Compare commits
12 Commits
53341ac22e
...
teste
| Author | SHA256 | Date | |
|---|---|---|---|
| bd61b32edd | |||
| a08a0712f0 | |||
| 8e73bbe0ed | |||
| b55b602eb5 | |||
| 962f79266a | |||
| df9256c556 | |||
| 1dd2610c1f | |||
| 96b85adbe9 | |||
| bb9d55675a | |||
| 3f56e87a33 | |||
| 44ba0a93c6 | |||
| 07fda079aa |
6472
Imagens para correção /reem-notas-teste-app-1.html
Normal file
6472
Imagens para correção /reem-notas-teste-app-1.html
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
|||||||
,cubajr,cubajr,08.07.2026 10:01,file:///home/cubajr/.config/libreoffice/4;
|
|
||||||
BIN
Imagens para implantação /Imagem colada (2).png
Normal file
BIN
Imagens para implantação /Imagem colada (2).png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 299 KiB |
BIN
Imagens para implantação /Imagem colada (3).png
Normal file
BIN
Imagens para implantação /Imagem colada (3).png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 228 KiB |
BIN
Imagens para implantação /Imagem colada (4).png
Normal file
BIN
Imagens para implantação /Imagem colada (4).png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
BIN
Imagens para implantação /Imagem colada.png
Normal file
BIN
Imagens para implantação /Imagem colada.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 599 KiB |
48
README.md
48
README.md
@@ -1366,3 +1366,51 @@ docker compose up -d --build
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong>🔭 Roadmap — Integrações futuras com a API SimpliRoute (08/07/2026)</strong></summary>
|
||||||
|
|
||||||
|
Mapeamento completo da API do SimpliRoute (documentation.simpliroute.com) cruzado com o fluxo
|
||||||
|
do sistema. **Nada aqui está implementado** — são os próximos passos priorizados. A base
|
||||||
|
técnica já existe (`SimpliRoute::Client`, `SimpliRoute::PlanilhaCarga`, token via ENV):
|
||||||
|
cada item vira uma fase própria quando for priorizado.
|
||||||
|
|
||||||
|
### 1. 🚀 Carga direta no SimpliRoute (substitui o baixar/importar planilha)
|
||||||
|
`POST /v1/routes/visits/` aceita criação **em lote**: um botão "Subir para o SimpliRoute"
|
||||||
|
criaria as visitas da operação vigente direto pela API, com as mesmas regras da planilha
|
||||||
|
(título `NF {nf} - {nome}`, janelas 08:00–18:00, lat/long do mês anterior, etc.).
|
||||||
|
> ⚠️ **Pré-requisito que segura esta fase: consolidar os ENDEREÇOS antes da subida.**
|
||||||
|
- Anti-duplicação: conferir `reference` + `planned_date` antes de criar (reexecutar não duplica).
|
||||||
|
- Desfazer: `POST /v1/bulk/delete/visits/` permite implementar um "remover carga".
|
||||||
|
|
||||||
|
### 2. 🧾 Relatório de comprovantes de entrega (POD)
|
||||||
|
`GET /v1/plans/visits/{visit_id}/detail/` traz **foto, assinatura, hora e GPS** de cada
|
||||||
|
entrega → gerar PDF por operação/mês (reuso do padrão Prawn em `app/services/pdf/`).
|
||||||
|
Valor: faturamento com STS/prefeitura e defesa em disputas ("não recebi").
|
||||||
|
|
||||||
|
### 3. ⚡ Webhooks — painel em tempo real
|
||||||
|
`POST /v1/addons/webhooks/` com eventos `visit_checkout`, `route_started/finished`,
|
||||||
|
`on_its_way` → endpoint público autenticado no app grava o evento e o painel atualiza
|
||||||
|
**na hora**, sem esperar a sync de 30 min. Exige atenção à segurança (assinatura,
|
||||||
|
idempotência) e URL pública estável.
|
||||||
|
|
||||||
|
### 4. 📱 Aviso ao paciente via WhatsApp
|
||||||
|
Evento `on_its_way` + ETA da API + Twilio já existente (`NotificacaoService`):
|
||||||
|
"seu medicamento saiu para entrega". Reduz insucesso por **RESPONSÁVEL AUSENTE**
|
||||||
|
(motivo real da lista de observations).
|
||||||
|
|
||||||
|
### 5. 📺 Monitor de rotas ao vivo
|
||||||
|
`GET /v1/plans/{date}/vehicles/` + visitas por rota → tela "Operação de hoje" com cada
|
||||||
|
veículo, % concluído e atrasos (complementa o dashboard, que olha o passado).
|
||||||
|
|
||||||
|
### 6. 👷 Sincronização de motoristas/veículos
|
||||||
|
`GET /v1/accounts/drivers/` e `GET /v1/routes/vehicles/` ↔ usuários motoristas do sistema
|
||||||
|
(hoje o vínculo é o nome digitado — sujeito a divergência).
|
||||||
|
|
||||||
|
### 7. 📊 Datamart e 🏷️ tags/skills
|
||||||
|
Export paginado de analytics para enriquecer dashboards; tags/skills para classificar
|
||||||
|
visitas por tipo de material.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,17 @@ class Admin::EdicaoLancamentosController < ApplicationController
|
|||||||
notes: visita['notes'],
|
notes: visita['notes'],
|
||||||
checkout_time: visita['checkout_time'],
|
checkout_time: visita['checkout_time'],
|
||||||
checkout_latitude: visita['checkout_latitude'],
|
checkout_latitude: visita['checkout_latitude'],
|
||||||
checkout_longitude: visita['checkout_longitude']
|
checkout_longitude: visita['checkout_longitude'],
|
||||||
|
planned_date: visita['planned_date'],
|
||||||
|
contato: visita['contact_name'],
|
||||||
|
telefone: visita['contact_phone'],
|
||||||
|
# Fotos do card: fachada vem do rastreio (mesma foto do mapa de operações);
|
||||||
|
# pictures/assinatura vêm da API. Só URLs http(s) chegam ao <img>.
|
||||||
|
foto_fachada: url_imagem(entrega.try(:foto_da_fachada)),
|
||||||
|
pictures: Array(visita['pictures']).filter_map { |u| url_imagem(u) },
|
||||||
|
signature: url_imagem(visita['signature']),
|
||||||
|
motorista: entrega.driver,
|
||||||
|
veiculo: entrega.vehicle
|
||||||
},
|
},
|
||||||
motivos: motivos_seguros
|
motivos: motivos_seguros
|
||||||
}
|
}
|
||||||
@@ -59,20 +69,26 @@ class Admin::EdicaoLancamentosController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
# PATCH /admin/edicao_lancamento/atualizar
|
# PATCH /admin/edicao_lancamento/atualizar
|
||||||
|
# HTML: fluxo de form clássico (fallback). JSON: salvar-por-campo do card
|
||||||
|
# (click-to-edit) — o fetch manda visit_id + só o campo editado.
|
||||||
def atualizar
|
def atualizar
|
||||||
authorize :edicao_lancamento
|
authorize :edicao_lancamento
|
||||||
|
|
||||||
id = params[:visit_id].to_s.strip
|
id = params[:visit_id].to_s.strip
|
||||||
return redirect_to(admin_edicao_lancamento_path, alert: 'Visita não identificada.') if id.blank?
|
return responder_erro('Visita não identificada.') if id.blank?
|
||||||
|
|
||||||
anterior = client.visita(id)
|
anterior = client.visita(id)
|
||||||
attrs = mudancas(anterior)
|
attrs = mudancas(anterior)
|
||||||
|
|
||||||
|
# Confirmar um valor idêntico não é erro no inline edit — só não há o que fazer.
|
||||||
if attrs.empty?
|
if attrs.empty?
|
||||||
return redirect_to(admin_edicao_lancamento_path, alert: 'Nenhuma alteração informada.')
|
return respond_to do |format|
|
||||||
|
format.json { render json: { ok: true, campos: [], visita: {} } }
|
||||||
|
format.html { redirect_to admin_edicao_lancamento_path, alert: 'Nenhuma alteração informada.' }
|
||||||
|
end
|
||||||
end
|
end
|
||||||
if attrs['status'].present? && STATUS_VALIDOS.exclude?(attrs['status'])
|
if attrs['status'].present? && STATUS_VALIDOS.exclude?(attrs['status'])
|
||||||
return redirect_to(admin_edicao_lancamento_path, alert: 'Status inválido.')
|
return responder_erro('Status inválido.')
|
||||||
end
|
end
|
||||||
|
|
||||||
atualizada = client.atualizar_visita(id, attrs)
|
atualizada = client.atualizar_visita(id, attrs)
|
||||||
@@ -87,17 +103,41 @@ class Admin::EdicaoLancamentosController < ApplicationController
|
|||||||
request: request
|
request: request
|
||||||
)
|
)
|
||||||
|
|
||||||
|
respond_to do |format|
|
||||||
|
format.json do
|
||||||
|
render json: { ok: true, campos: attrs.keys, visita: atualizada.slice(*CAMPOS_EDITAVEIS) }
|
||||||
|
end
|
||||||
|
format.html do
|
||||||
redirect_to admin_edicao_lancamento_path,
|
redirect_to admin_edicao_lancamento_path,
|
||||||
notice: "Lançamento da NF #{atualizada['reference']} atualizado no SimpliRoute. " \
|
notice: "Lançamento da NF #{atualizada['reference']} atualizado no SimpliRoute. " \
|
||||||
'O painel refletirá na próxima sincronização.'
|
'O painel refletirá na próxima sincronização.'
|
||||||
|
end
|
||||||
|
end
|
||||||
rescue SimpliRoute::Error => e
|
rescue SimpliRoute::Error => e
|
||||||
redirect_to admin_edicao_lancamento_path, alert: "Não foi possível atualizar: #{e.message}"
|
responder_erro("Não foi possível atualizar: #{e.message}", status: :bad_gateway)
|
||||||
end
|
end
|
||||||
|
|
||||||
# GET /admin/edicao_lancamento/historico?visit_id=123 → JSON (best-effort).
|
# GET /admin/edicao_lancamento/historico?visit_id=123 → JSON com as DUAS fontes:
|
||||||
|
# o histórico da API do SimpliRoute (best-effort, costuma vir vazio) e a nossa
|
||||||
|
# trilha do AuditoriaLog (quem editou, quando, de→para).
|
||||||
def historico
|
def historico
|
||||||
authorize :edicao_lancamento
|
authorize :edicao_lancamento
|
||||||
render json: { ok: true, historico: client.historico(params[:visit_id]) }
|
|
||||||
|
id = params[:visit_id].to_s.strip
|
||||||
|
interno = AuditoriaLog.por_entidade('SimpliRoute::Visita')
|
||||||
|
.where(entidade_id: id)
|
||||||
|
.includes(:user).recentes.limit(50)
|
||||||
|
.map do |log|
|
||||||
|
{
|
||||||
|
usuario: log.user&.nome_display || '—',
|
||||||
|
acao: log.acao,
|
||||||
|
quando: log.created_at.in_time_zone.strftime('%d/%m/%Y %H:%M'),
|
||||||
|
de: log.dados_anteriores,
|
||||||
|
para: log.dados_novos
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: { ok: true, api: client.historico(id), interno: interno }
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
@@ -163,6 +203,21 @@ class Admin::EdicaoLancamentosController < ApplicationController
|
|||||||
render json: { ok: false, erro: msg }, status: status
|
render json: { ok: false, erro: msg }, status: status
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Erro do atualizar nos dois formatos (JSON p/ inline edit, HTML p/ fallback).
|
||||||
|
def responder_erro(msg, status: :unprocessable_entity)
|
||||||
|
respond_to do |format|
|
||||||
|
format.json { render json: { ok: false, erro: msg }, status: status }
|
||||||
|
format.html { redirect_to admin_edicao_lancamento_path, alert: msg }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Só aceita URL http(s) — evita injetar lixo no <img src> do card (mesmo
|
||||||
|
# filtro do foto_url do OperacaoMetricas).
|
||||||
|
def url_imagem(valor)
|
||||||
|
url = valor.to_s.strip
|
||||||
|
url.match?(%r{\Ahttps?://}i) ? url : nil
|
||||||
|
end
|
||||||
|
|
||||||
# Sem token não há o que fazer — avisa e volta.
|
# Sem token não há o que fazer — avisa e volta.
|
||||||
def garantir_configurado
|
def garantir_configurado
|
||||||
return if SimpliRoute.configurado?
|
return if SimpliRoute.configurado?
|
||||||
|
|||||||
@@ -165,6 +165,9 @@ class DashboardController < ApplicationController
|
|||||||
|
|
||||||
@pagamentos_feitos = pagos.includes(:consolidacao, :pagador).order(pago_em: :desc)
|
@pagamentos_feitos = pagos.includes(:consolidacao, :pagador).order(pago_em: :desc)
|
||||||
@pagamentos_pendentes = pendentes.includes(:consolidacao).order(consolidacao_id: :desc)
|
@pagamentos_pendentes = pendentes.includes(:consolidacao).order(consolidacao_id: :desc)
|
||||||
|
|
||||||
|
# Fluxo de pagamentos por dia (valor pago + acumulado) para o gráfico
|
||||||
|
@grafico_pagamentos_dia = build_grafico_pagamentos(pagos)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Visão financeira (custo) das consolidações finalizadas do período, já com o
|
# Visão financeira (custo) das consolidações finalizadas do período, já com o
|
||||||
@@ -241,6 +244,28 @@ class DashboardController < ApplicationController
|
|||||||
{ labels: labels, valores: valores, qtds: qtds }
|
{ labels: labels, valores: valores, qtds: qtds }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Valor pago por dia (pela data do pagamento) + acumulado no período,
|
||||||
|
# para o gráfico de fluxo de pagamentos.
|
||||||
|
def build_grafico_pagamentos(pagos)
|
||||||
|
dias = (@periodo_inicio..@periodo_fim).to_a
|
||||||
|
|
||||||
|
if dias.size <= MAX_DIAS_GRAFICO
|
||||||
|
soma = pagos.group("DATE(pago_em)").sum(:valor_total).transform_keys(&:to_s)
|
||||||
|
labels = dias.map { |d| d.strftime('%d/%m') }
|
||||||
|
chaves = dias.map(&:to_s)
|
||||||
|
else
|
||||||
|
soma = pagos.group("TO_CHAR(pago_em, 'YYYY-MM')").sum(:valor_total)
|
||||||
|
meses = meses_no_periodo
|
||||||
|
labels = meses.map { |m| Date.strptime(m, '%Y-%m').strftime('%m/%Y') }
|
||||||
|
chaves = meses
|
||||||
|
end
|
||||||
|
|
||||||
|
valores = chaves.map { |k| soma[k].to_f.round(2) }
|
||||||
|
acumulado = 0
|
||||||
|
{ labels: labels, valores: valores,
|
||||||
|
acumulado: valores.map { |v| (acumulado += v).round(2) } }
|
||||||
|
end
|
||||||
|
|
||||||
# Meses ("YYYY-MM") do início ao fim do período selecionado, inclusive.
|
# Meses ("YYYY-MM") do início ao fim do período selecionado, inclusive.
|
||||||
def meses_no_periodo
|
def meses_no_periodo
|
||||||
meses = []
|
meses = []
|
||||||
|
|||||||
@@ -131,8 +131,11 @@ module SimpliRoute
|
|||||||
valor.to_s.strip.gsub(/\s+/, ' ').upcase
|
valor.to_s.strip.gsub(/\s+/, ' ').upcase
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Coordenada como Float (com PONTO). O rastreio pode trazer texto com vírgula
|
||||||
|
# decimal ("-23,62"); coordenadas não usam separador de milhar, então trocar
|
||||||
|
# a vírgula por ponto é seguro e garante a saída numérica (ponto) no .xlsx.
|
||||||
def to_coord(valor)
|
def to_coord(valor)
|
||||||
Float(valor)
|
Float(valor.to_s.strip.tr(',', '.'))
|
||||||
rescue ArgumentError, TypeError
|
rescue ArgumentError, TypeError
|
||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
<%# app/views/admin/edicao_lancamentos/show.html.erb %>
|
<%# app/views/admin/edicao_lancamentos/show.html.erb %>
|
||||||
<div class="space-y-6" data-buscar-url="<%= buscar_admin_edicao_lancamento_path %>">
|
<%# Card estilizado com foto da fachada, edição inline (click-to-edit, salva por
|
||||||
|
campo direto na API do SimpliRoute) e histórico duplo (nosso AuditoriaLog +
|
||||||
|
/history/ da API). Os dados do card chegam via fetch (endpoint buscar). %>
|
||||||
|
<div class="space-y-6" id="edicao-app"
|
||||||
|
data-buscar-url="<%= buscar_admin_edicao_lancamento_path %>"
|
||||||
|
data-atualizar-url="<%= atualizar_admin_edicao_lancamento_path %>"
|
||||||
|
data-historico-url="<%= historico_admin_edicao_lancamento_path %>"
|
||||||
|
data-csrf="<%= form_authenticity_token %>"
|
||||||
|
data-motivos="<%= @motivos.to_json %>">
|
||||||
|
|
||||||
<%# Header %>
|
<%# Header %>
|
||||||
<div>
|
<div>
|
||||||
<h1 class="text-2xl font-bold text-white">Editar Lançamento</h1>
|
<h1 class="text-2xl font-bold text-white">Editar Lançamento</h1>
|
||||||
<p class="text-gray-400 text-sm mt-0.5">Corrige status, motivo e comentários de uma entrega direto no SimpliRoute</p>
|
<p class="text-gray-400 text-sm mt-0.5">Corrige status, motivo e dados de checkout de uma entrega direto no SimpliRoute</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<%# Flash %>
|
<%# Flash %>
|
||||||
@@ -13,9 +21,9 @@
|
|||||||
<%# Aviso de sincronização %>
|
<%# Aviso de sincronização %>
|
||||||
<div class="p-4 bg-amber-900/20 border border-amber-500/40 rounded-xl text-amber-200/90 text-sm flex items-start gap-2">
|
<div class="p-4 bg-amber-900/20 border border-amber-500/40 rounded-xl text-amber-200/90 text-sm flex items-start gap-2">
|
||||||
<span class="text-base leading-none">⚠️</span>
|
<span class="text-base leading-none">⚠️</span>
|
||||||
<p>As alterações são gravadas no <strong>SimpliRoute na hora</strong>, mas o painel e as
|
<p>As alterações são gravadas no <strong>SimpliRoute na hora</strong> (cada campo salva ao confirmar ✓),
|
||||||
consolidações só refletem <strong>após a próxima sincronização</strong> da base de rastreio.
|
mas o painel e as consolidações só refletem <strong>após a próxima sincronização</strong> da base de
|
||||||
Toda alteração fica registrada na auditoria.</p>
|
rastreio. Toda alteração fica registrada na auditoria.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<%# Busca por NF %>
|
<%# Busca por NF %>
|
||||||
@@ -35,156 +43,380 @@
|
|||||||
<p id="busca-loading" class="hidden mt-2 text-sm text-gray-400">Consultando SimpliRoute…</p>
|
<p id="busca-loading" class="hidden mt-2 text-sm text-gray-400">Consultando SimpliRoute…</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<%# Formulário de edição (oculto até achar a visita) %>
|
<%# Card do lançamento (preenchido via JS após a busca) %>
|
||||||
<%= form_with url: atualizar_admin_edicao_lancamento_path, method: :patch,
|
<div id="card" class="hidden bg-[#111] border border-white/5 rounded-2xl overflow-hidden">
|
||||||
html: { id: 'form-edicao', class: 'hidden bg-[#111] border border-white/5 rounded-2xl p-5 space-y-5' } do %>
|
|
||||||
<input type="hidden" name="visit_id" id="f-visit-id">
|
|
||||||
|
|
||||||
<%# Cabeçalho da visita (somente leitura) %>
|
<%# Header do card %>
|
||||||
<div class="border-b border-white/5 pb-4">
|
<div class="p-5 border-b border-white/5 flex flex-wrap items-start justify-between gap-3">
|
||||||
<p class="text-white font-semibold" id="f-titulo">—</p>
|
<div class="min-w-0">
|
||||||
<p class="text-gray-500 text-sm" id="f-endereco">—</p>
|
<div class="flex items-center gap-3 flex-wrap">
|
||||||
<p class="text-gray-600 text-xs mt-1">NF <span id="f-nf">—</span> · visita <span id="f-id">—</span></p>
|
<h2 id="c-titulo" class="text-white font-bold text-lg truncate">—</h2>
|
||||||
|
<span id="c-badge" class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-gray-800 text-gray-400">—</span>
|
||||||
</div>
|
</div>
|
||||||
|
<p id="c-endereco" class="text-gray-400 text-sm mt-1">—</p>
|
||||||
<div class="grid sm:grid-cols-2 gap-4">
|
<div class="flex flex-wrap gap-2 mt-2 text-xs text-gray-500">
|
||||||
<%# Status %>
|
<span class="px-2 py-0.5 rounded-full bg-white/5">NF <span id="c-nf">—</span></span>
|
||||||
<div>
|
<span class="px-2 py-0.5 rounded-full bg-white/5">Visita <span id="c-id">—</span></span>
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1.5">Status</label>
|
<span class="px-2 py-0.5 rounded-full bg-white/5">🚚 <span id="c-motorista">—</span></span>
|
||||||
<select name="status" id="f-status"
|
<span class="px-2 py-0.5 rounded-full bg-white/5">🚗 <span id="c-veiculo">—</span></span>
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-3 text-white
|
<span class="px-2 py-0.5 rounded-full bg-white/5">📞 <span id="c-telefone">—</span></span>
|
||||||
focus:outline-none focus:border-orange-500 min-h-[48px]">
|
|
||||||
<% { 'completed' => 'Completa', 'failed' => 'Falha', 'pending' => 'Pendente',
|
|
||||||
'partial' => 'Parcial', 'canceled' => 'Cancelada' }.each do |v, label| %>
|
|
||||||
<option value="<%= v %>"><%= label %></option>
|
|
||||||
<% end %>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<%# Motivo (só faz sentido em falha) %>
|
|
||||||
<div id="wrap-motivo">
|
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1.5">Motivo (insucesso)</label>
|
|
||||||
<select name="checkout_observation" id="f-motivo"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-3 text-white
|
|
||||||
focus:outline-none focus:border-orange-500 min-h-[48px]">
|
|
||||||
<option value="">— sem motivo —</option>
|
|
||||||
<% @motivos.each do |m| %>
|
|
||||||
<option value="<%= m['id'] %>"><%= m['label'] %></option>
|
|
||||||
<% end %>
|
|
||||||
</select>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<button id="btn-historico" type="button"
|
||||||
<%# Comentário livre %>
|
class="px-4 py-2.5 bg-[#1a1a1a] hover:bg-[#252525] border border-white/10 text-gray-200
|
||||||
<div>
|
text-sm font-semibold rounded-xl transition-colors whitespace-nowrap">
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1.5">Comentário do checkout</label>
|
🕑 Histórico
|
||||||
<textarea name="checkout_comment" id="f-comment" rows="2"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-3 text-white
|
|
||||||
placeholder-gray-600 focus:outline-none focus:border-orange-500"></textarea>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<%# Observações internas %>
|
|
||||||
<div>
|
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1.5">Observações (notes)</label>
|
|
||||||
<textarea name="notes" id="f-notes" rows="2"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-3 text-white
|
|
||||||
placeholder-gray-600 focus:outline-none focus:border-orange-500"></textarea>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<%# Data/geo do checkout (avançado) %>
|
|
||||||
<details class="rounded-xl border border-white/5 bg-[#0d0d0d] p-4">
|
|
||||||
<summary class="cursor-pointer text-sm text-gray-400">Data e localização do checkout (avançado)</summary>
|
|
||||||
<div class="grid sm:grid-cols-3 gap-4 mt-4">
|
|
||||||
<div>
|
|
||||||
<label class="block text-xs text-gray-400 mb-1.5">Data/hora</label>
|
|
||||||
<input type="datetime-local" name="checkout_time" id="f-checkout-time"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-2.5 text-white
|
|
||||||
focus:outline-none focus:border-orange-500">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-xs text-gray-400 mb-1.5">Latitude</label>
|
|
||||||
<input type="text" inputmode="decimal" name="checkout_latitude" id="f-lat"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-2.5 text-white
|
|
||||||
focus:outline-none focus:border-orange-500">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-xs text-gray-400 mb-1.5">Longitude</label>
|
|
||||||
<input type="text" inputmode="decimal" name="checkout_longitude" id="f-lng"
|
|
||||||
class="w-full bg-[#1a1a1a] border border-white/10 rounded-xl px-3 py-2.5 text-white
|
|
||||||
focus:outline-none focus:border-orange-500">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<div class="flex justify-end pt-2">
|
|
||||||
<button type="submit"
|
|
||||||
class="px-6 py-3 bg-green-600 hover:bg-green-500 text-white font-semibold rounded-xl
|
|
||||||
transition-colors min-h-[48px]">
|
|
||||||
Salvar no SimpliRoute
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<% end %>
|
|
||||||
|
<div class="grid lg:grid-cols-3 gap-0">
|
||||||
|
|
||||||
|
<%# Coluna esquerda — fotos %>
|
||||||
|
<div class="p-5 border-b lg:border-b-0 lg:border-r border-white/5 space-y-3">
|
||||||
|
<p class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Foto da fachada</p>
|
||||||
|
<div id="c-foto-wrap"></div>
|
||||||
|
<div id="c-extras-wrap" class="hidden">
|
||||||
|
<p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mt-4 mb-2">Fotos do SimpliRoute</p>
|
||||||
|
<div id="c-extras" class="grid grid-cols-3 gap-2"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<%# Coluna direita — campos click-to-edit %>
|
||||||
|
<div class="lg:col-span-2 p-5">
|
||||||
|
<p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
|
||||||
|
Dados do lançamento <span class="normal-case font-normal text-gray-600">— clique num valor para editar</span>
|
||||||
|
</p>
|
||||||
|
<div id="c-campos" class="grid sm:grid-cols-2 gap-3"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<%# Modal de histórico %>
|
||||||
|
<div id="modal-hist" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
<div id="modal-hist-overlay" class="absolute inset-0 bg-black/70"></div>
|
||||||
|
<div class="relative bg-[#151515] border border-white/10 rounded-2xl w-full max-w-2xl max-h-[85vh] flex flex-col">
|
||||||
|
<div class="flex items-center justify-between p-4 border-b border-white/5">
|
||||||
|
<h3 class="text-white font-bold">🕑 Histórico de alterações</h3>
|
||||||
|
<button id="modal-hist-fechar" type="button"
|
||||||
|
class="w-9 h-9 rounded-lg bg-white/5 hover:bg-white/10 text-gray-300">✕</button>
|
||||||
|
</div>
|
||||||
|
<div id="modal-hist-corpo" class="p-4 overflow-y-auto space-y-5 text-sm">
|
||||||
|
<p class="text-gray-400">Carregando…</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
const wrap = document.querySelector('[data-buscar-url]');
|
const app = document.getElementById('edicao-app');
|
||||||
const buscarU = wrap.dataset.buscarUrl;
|
const URLS = {
|
||||||
const campo = document.getElementById('campo-nf');
|
buscar: app.dataset.buscarUrl,
|
||||||
const btn = document.getElementById('btn-buscar');
|
atualizar: app.dataset.atualizarUrl,
|
||||||
const erro = document.getElementById('busca-erro');
|
historico: app.dataset.historicoUrl
|
||||||
const loading = document.getElementById('busca-loading');
|
};
|
||||||
const form = document.getElementById('form-edicao');
|
const CSRF = app.dataset.csrf;
|
||||||
|
const MOTIVOS = JSON.parse(app.dataset.motivos || '[]');
|
||||||
|
|
||||||
const set = (id, v) => { document.getElementById(id).value = (v ?? ''); };
|
let visita = null; // estado atual do lançamento carregado
|
||||||
const txt = (id, v) => { document.getElementById(id).textContent = (v ?? '—'); };
|
|
||||||
|
|
||||||
function toggleMotivo() {
|
// ── Config dos campos editáveis ─────────────────────────────
|
||||||
const falha = document.getElementById('f-status').value === 'failed';
|
const STATUS = {
|
||||||
document.getElementById('wrap-motivo').style.opacity = falha ? '1' : '0.45';
|
completed: { label: 'Completa', cls: 'bg-green-600 text-white', icone: '✅' },
|
||||||
}
|
failed: { label: 'Falha', cls: 'bg-red-600 text-white', icone: '❌' },
|
||||||
document.getElementById('f-status').addEventListener('change', toggleMotivo);
|
pending: { label: 'Pendente', cls: 'bg-yellow-500 text-black', icone: '🕗' },
|
||||||
|
partial: { label: 'Parcial', cls: 'bg-blue-600 text-white', icone: '◐' },
|
||||||
|
canceled: { label: 'Cancelada', cls: 'bg-gray-700 text-gray-300', icone: '🚫' }
|
||||||
|
};
|
||||||
|
const CAMPOS = [
|
||||||
|
{ campo: 'status', label: 'Status', tipo: 'status' },
|
||||||
|
{ campo: 'checkout_observation', label: 'Motivo (insucesso)', tipo: 'motivo' },
|
||||||
|
{ campo: 'checkout_comment', label: 'Comentário do checkout', tipo: 'textarea', col2: true },
|
||||||
|
{ campo: 'notes', label: 'Observações (notes)', tipo: 'textarea', col2: true },
|
||||||
|
{ campo: 'checkout_time', label: 'Data/hora do checkout', tipo: 'datetime' },
|
||||||
|
{ campo: 'checkout_latitude', label: 'Latitude', tipo: 'texto' },
|
||||||
|
{ campo: 'checkout_longitude', label: 'Longitude', tipo: 'texto' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const esc = s => String(s ?? '').replace(/[&<>"']/g,
|
||||||
|
m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
|
||||||
|
|
||||||
|
const motivoLabel = uuid => (MOTIVOS.find(m => m.id === uuid) || {}).label || null;
|
||||||
|
|
||||||
|
// ── Busca por NF ────────────────────────────────────────────
|
||||||
|
const campoNf = document.getElementById('campo-nf');
|
||||||
|
const erroEl = document.getElementById('busca-erro');
|
||||||
|
const loadEl = document.getElementById('busca-loading');
|
||||||
|
const cardEl = document.getElementById('card');
|
||||||
|
|
||||||
async function buscar() {
|
async function buscar() {
|
||||||
const nf = campo.value.trim();
|
const nf = campoNf.value.trim();
|
||||||
erro.classList.add('hidden');
|
erroEl.classList.add('hidden');
|
||||||
if (!nf) { erro.textContent = 'Informe o número da NF.'; erro.classList.remove('hidden'); return; }
|
if (!nf) { mostrarErroBusca('Informe o número da NF.'); return; }
|
||||||
|
|
||||||
loading.classList.remove('hidden');
|
loadEl.classList.remove('hidden');
|
||||||
form.classList.add('hidden');
|
cardEl.classList.add('hidden');
|
||||||
try {
|
try {
|
||||||
const resp = await fetch(buscarU + '?nf=' + encodeURIComponent(nf), { headers: { 'Accept': 'application/json' } });
|
const resp = await fetch(URLS.buscar + '?nf=' + encodeURIComponent(nf), { headers: { 'Accept': 'application/json' } });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (!data.ok) { mostrarErroBusca(data.erro || 'Não foi possível localizar a entrega.'); return; }
|
||||||
|
visita = data.visita;
|
||||||
|
renderCard();
|
||||||
|
cardEl.classList.remove('hidden');
|
||||||
|
} catch (e) {
|
||||||
|
mostrarErroBusca('Erro de conexão ao buscar a NF.');
|
||||||
|
} finally {
|
||||||
|
loadEl.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function mostrarErroBusca(msg) { erroEl.textContent = msg; erroEl.classList.remove('hidden'); }
|
||||||
|
|
||||||
|
document.getElementById('btn-buscar').addEventListener('click', buscar);
|
||||||
|
campoNf.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); buscar(); } });
|
||||||
|
|
||||||
|
// ── Card ────────────────────────────────────────────────────
|
||||||
|
function renderCard() {
|
||||||
|
const v = visita;
|
||||||
|
document.getElementById('c-titulo').textContent = v.titulo || '—';
|
||||||
|
document.getElementById('c-endereco').textContent = v.endereco || '—';
|
||||||
|
document.getElementById('c-nf').textContent = v.nf ?? '—';
|
||||||
|
document.getElementById('c-id').textContent = v.id ?? '—';
|
||||||
|
document.getElementById('c-motorista').textContent = v.motorista || '—';
|
||||||
|
document.getElementById('c-veiculo').textContent = v.veiculo || '—';
|
||||||
|
document.getElementById('c-telefone').textContent = v.telefone || '—';
|
||||||
|
renderBadge();
|
||||||
|
renderFotos();
|
||||||
|
renderCampos();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBadge() {
|
||||||
|
const cfg = STATUS[visita.status] || { label: visita.status || '—', cls: 'bg-gray-800 text-gray-400', icone: '❓' };
|
||||||
|
const b = document.getElementById('c-badge');
|
||||||
|
b.className = 'inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold ' + cfg.cls;
|
||||||
|
b.textContent = cfg.icone + ' ' + cfg.label;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderFotos() {
|
||||||
|
const wrap = document.getElementById('c-foto-wrap');
|
||||||
|
if (visita.foto_fachada) {
|
||||||
|
wrap.innerHTML =
|
||||||
|
'<a href="' + esc(visita.foto_fachada) + '" target="_blank" rel="noopener" title="Abrir em tamanho real">' +
|
||||||
|
'<img src="' + esc(visita.foto_fachada) + '" alt="Fachada" loading="lazy" ' +
|
||||||
|
'class="w-full h-52 object-cover rounded-xl border border-white/10 hover:opacity-90 transition-opacity">' +
|
||||||
|
'</a>';
|
||||||
|
} else {
|
||||||
|
wrap.innerHTML =
|
||||||
|
'<div class="w-full h-52 rounded-xl border border-dashed border-white/10 flex items-center justify-center ' +
|
||||||
|
'text-gray-600 text-sm">📷 Sem foto da fachada para esta entrega</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
const extras = [...(visita.pictures || [])];
|
||||||
|
if (visita.signature) extras.push(visita.signature);
|
||||||
|
const extrasWrap = document.getElementById('c-extras-wrap');
|
||||||
|
const grid = document.getElementById('c-extras');
|
||||||
|
if (extras.length) {
|
||||||
|
grid.innerHTML = extras.map(u =>
|
||||||
|
'<a href="' + esc(u) + '" target="_blank" rel="noopener">' +
|
||||||
|
'<img src="' + esc(u) + '" loading="lazy" class="w-full h-16 object-cover rounded-lg border border-white/10 hover:opacity-90">' +
|
||||||
|
'</a>').join('');
|
||||||
|
extrasWrap.classList.remove('hidden');
|
||||||
|
} else {
|
||||||
|
extrasWrap.classList.add('hidden');
|
||||||
|
grid.innerHTML = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Campos click-to-edit ────────────────────────────────────
|
||||||
|
function valorExibicao(def) {
|
||||||
|
const v = visita[def.campo];
|
||||||
|
if (def.tipo === 'status') return (STATUS[v] || {}).label || v || '—';
|
||||||
|
if (def.tipo === 'motivo') return v ? (motivoLabel(v) || v) : '— sem motivo —';
|
||||||
|
if (def.tipo === 'datetime') {
|
||||||
|
if (!v) return '—';
|
||||||
|
const s = String(v);
|
||||||
|
return s.slice(8, 10) + '/' + s.slice(5, 7) + '/' + s.slice(0, 4) + ' ' + s.slice(11, 16);
|
||||||
|
}
|
||||||
|
return (v === null || v === undefined || v === '') ? '—' : String(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCampos() {
|
||||||
|
const grid = document.getElementById('c-campos');
|
||||||
|
grid.innerHTML = '';
|
||||||
|
CAMPOS.forEach(def => {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'campo group bg-[#1a1a1a] border border-white/5 rounded-xl px-4 py-3 cursor-pointer ' +
|
||||||
|
'hover:border-orange-500/50 transition-colors' + (def.col2 ? ' sm:col-span-2' : '');
|
||||||
|
div.dataset.campo = def.campo;
|
||||||
|
pintarExibicao(div, def);
|
||||||
|
grid.appendChild(div);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function pintarExibicao(div, def, flash) {
|
||||||
|
div.innerHTML =
|
||||||
|
'<p class="text-xs text-gray-500 mb-0.5">' + esc(def.label) + '</p>' +
|
||||||
|
'<div class="flex items-start justify-between gap-2">' +
|
||||||
|
'<p class="texto-valor text-sm text-white break-words min-h-[20px]">' + esc(valorExibicao(def)) + '</p>' +
|
||||||
|
'<span class="text-gray-600 group-hover:text-orange-400 text-sm" title="Editar">✏️</span>' +
|
||||||
|
'</div>';
|
||||||
|
div.onclick = () => abrirEdicao(div, def);
|
||||||
|
if (flash) {
|
||||||
|
div.classList.add('ring-2', 'ring-green-500/70');
|
||||||
|
setTimeout(() => div.classList.remove('ring-2', 'ring-green-500/70'), 1200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function abrirEdicao(div, def) {
|
||||||
|
div.onclick = null;
|
||||||
|
div.classList.remove('cursor-pointer');
|
||||||
|
const atual = visita[def.campo];
|
||||||
|
|
||||||
|
let editorHtml;
|
||||||
|
const base = 'w-full bg-[#111] border border-orange-500/60 rounded-lg px-2.5 py-2 text-sm text-white focus:outline-none';
|
||||||
|
if (def.tipo === 'status') {
|
||||||
|
editorHtml = '<select class="ed ' + base + '">' +
|
||||||
|
Object.entries(STATUS).map(([v, c]) =>
|
||||||
|
'<option value="' + v + '"' + (v === atual ? ' selected' : '') + '>' + c.label + '</option>').join('') +
|
||||||
|
'</select>';
|
||||||
|
} else if (def.tipo === 'motivo') {
|
||||||
|
editorHtml = '<select class="ed ' + base + '">' +
|
||||||
|
'<option value="">— sem motivo —</option>' +
|
||||||
|
MOTIVOS.map(m =>
|
||||||
|
'<option value="' + esc(m.id) + '"' + (m.id === atual ? ' selected' : '') + '>' + esc(m.label) + '</option>').join('') +
|
||||||
|
'</select>';
|
||||||
|
} else if (def.tipo === 'textarea') {
|
||||||
|
editorHtml = '<textarea rows="2" class="ed ' + base + '">' + esc(atual ?? '') + '</textarea>';
|
||||||
|
} else if (def.tipo === 'datetime') {
|
||||||
|
const valor = atual ? String(atual).slice(0, 16) : '';
|
||||||
|
editorHtml = '<input type="datetime-local" value="' + esc(valor) + '" class="ed ' + base + '">';
|
||||||
|
} else {
|
||||||
|
editorHtml = '<input type="text" value="' + esc(atual ?? '') + '" class="ed ' + base + '">';
|
||||||
|
}
|
||||||
|
|
||||||
|
div.innerHTML =
|
||||||
|
'<p class="text-xs text-orange-400 mb-1">' + esc(def.label) + '</p>' +
|
||||||
|
editorHtml +
|
||||||
|
'<div class="flex items-center gap-2 mt-2">' +
|
||||||
|
'<button type="button" class="btn-ok px-3 py-1.5 bg-green-600 hover:bg-green-500 text-white text-xs font-bold rounded-lg">✓ Salvar</button>' +
|
||||||
|
'<button type="button" class="btn-cancelar px-3 py-1.5 bg-white/5 hover:bg-white/10 text-gray-300 text-xs rounded-lg">✕ Cancelar</button>' +
|
||||||
|
'<span class="msg-salvando hidden text-xs text-gray-400">Salvando…</span>' +
|
||||||
|
'</div>' +
|
||||||
|
'<p class="msg-erro hidden mt-1.5 text-xs text-red-400"></p>';
|
||||||
|
|
||||||
|
const ed = div.querySelector('.ed');
|
||||||
|
ed.focus();
|
||||||
|
|
||||||
|
const cancelar = () => pintarExibicao(div, def) || div.classList.add('cursor-pointer');
|
||||||
|
div.querySelector('.btn-cancelar').onclick = e => { e.stopPropagation(); cancelar(); };
|
||||||
|
div.querySelector('.btn-ok').onclick = e => { e.stopPropagation(); salvar(div, def, ed.value); };
|
||||||
|
ed.addEventListener('keydown', e => {
|
||||||
|
if (e.key === 'Escape') cancelar();
|
||||||
|
if (e.key === 'Enter' && def.tipo !== 'textarea') { e.preventDefault(); salvar(div, def, ed.value); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function salvar(div, def, valor) {
|
||||||
|
const msgErro = div.querySelector('.msg-erro');
|
||||||
|
const msgSalvando = div.querySelector('.msg-salvando');
|
||||||
|
msgErro.classList.add('hidden');
|
||||||
|
msgSalvando.classList.remove('hidden');
|
||||||
|
try {
|
||||||
|
const body = { visit_id: visita.id };
|
||||||
|
body[def.campo] = valor;
|
||||||
|
const resp = await fetch(URLS.atualizar, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'X-CSRF-Token': CSRF
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
});
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (!data.ok) {
|
if (!data.ok) {
|
||||||
erro.textContent = data.erro || 'Não foi possível localizar a entrega.';
|
msgErro.textContent = data.erro || 'Erro ao salvar.';
|
||||||
erro.classList.remove('hidden');
|
msgErro.classList.remove('hidden');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const v = data.visita;
|
// Atualiza o estado local com o que a API confirmou (ou mantém o atual
|
||||||
set('f-visit-id', v.id);
|
// quando o valor não mudou — campos: []).
|
||||||
txt('f-titulo', v.titulo);
|
if (data.campos && data.campos.length) Object.assign(visita, data.visita);
|
||||||
txt('f-endereco', v.endereco);
|
pintarExibicao(div, def, data.campos && data.campos.length > 0);
|
||||||
txt('f-nf', v.nf);
|
div.classList.add('cursor-pointer');
|
||||||
txt('f-id', v.id);
|
if (def.campo === 'status') renderBadge();
|
||||||
set('f-status', v.status || 'completed');
|
|
||||||
set('f-motivo', v.checkout_observation || '');
|
|
||||||
set('f-comment', v.checkout_comment || '');
|
|
||||||
set('f-notes', v.notes || '');
|
|
||||||
set('f-lat', v.checkout_latitude ?? '');
|
|
||||||
set('f-lng', v.checkout_longitude ?? '');
|
|
||||||
// ISO -> valor de datetime-local (YYYY-MM-DDTHH:MM)
|
|
||||||
set('f-checkout-time', v.checkout_time ? String(v.checkout_time).slice(0, 16) : '');
|
|
||||||
toggleMotivo();
|
|
||||||
form.classList.remove('hidden');
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
erro.textContent = 'Erro de conexão ao buscar a NF.';
|
msgErro.textContent = 'Erro de conexão ao salvar.';
|
||||||
erro.classList.remove('hidden');
|
msgErro.classList.remove('hidden');
|
||||||
} finally {
|
} finally {
|
||||||
loading.classList.add('hidden');
|
msgSalvando.classList.add('hidden');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
btn.addEventListener('click', buscar);
|
// ── Histórico (modal) ───────────────────────────────────────
|
||||||
campo.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); buscar(); } });
|
const modal = document.getElementById('modal-hist');
|
||||||
|
const corpo = document.getElementById('modal-hist-corpo');
|
||||||
|
|
||||||
|
function fecharModal() { modal.classList.add('hidden'); }
|
||||||
|
document.getElementById('modal-hist-fechar').onclick = fecharModal;
|
||||||
|
document.getElementById('modal-hist-overlay').onclick = fecharModal;
|
||||||
|
document.addEventListener('keydown', e => { if (e.key === 'Escape') fecharModal(); });
|
||||||
|
|
||||||
|
document.getElementById('btn-historico').addEventListener('click', async () => {
|
||||||
|
if (!visita) return;
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
corpo.innerHTML = '<p class="text-gray-400">Carregando…</p>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch(URLS.historico + '?visit_id=' + encodeURIComponent(visita.id),
|
||||||
|
{ headers: { 'Accept': 'application/json' } });
|
||||||
|
const data = await resp.json();
|
||||||
|
corpo.innerHTML = htmlHistorico(data);
|
||||||
|
} catch (e) {
|
||||||
|
corpo.innerHTML = '<p class="text-red-400">Erro ao carregar o histórico.</p>';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function nomeCampo(campo) {
|
||||||
|
const def = CAMPOS.find(c => c.campo === campo);
|
||||||
|
return def ? def.label : campo;
|
||||||
|
}
|
||||||
|
function fmtValor(campo, valor) {
|
||||||
|
if (valor === null || valor === undefined || valor === '') return '—';
|
||||||
|
if (campo === 'checkout_observation') return motivoLabel(valor) || valor;
|
||||||
|
if (campo === 'status') return (STATUS[valor] || {}).label || valor;
|
||||||
|
return String(valor);
|
||||||
|
}
|
||||||
|
|
||||||
|
function htmlHistorico(data) {
|
||||||
|
let html = '<div>' +
|
||||||
|
'<p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">📒 Nosso sistema (auditoria)</p>';
|
||||||
|
const interno = (data.interno || []);
|
||||||
|
if (!interno.length) {
|
||||||
|
html += '<p class="text-gray-500">Nenhuma alteração registrada pelo sistema.</p>';
|
||||||
|
} else {
|
||||||
|
html += interno.map(l => {
|
||||||
|
const mudancas = Object.keys(l.para || {}).map(campo =>
|
||||||
|
'<li class="text-gray-300"><span class="text-gray-500">' + esc(nomeCampo(campo)) + ':</span> ' +
|
||||||
|
'<span class="text-red-300/80 line-through">' + esc(fmtValor(campo, (l.de || {})[campo])) + '</span>' +
|
||||||
|
' → <span class="text-green-300">' + esc(fmtValor(campo, l.para[campo])) + '</span></li>').join('');
|
||||||
|
return '<div class="bg-[#1a1a1a] border border-white/5 rounded-xl p-3 mb-2">' +
|
||||||
|
'<div class="flex items-center justify-between text-xs text-gray-500 mb-1.5">' +
|
||||||
|
'<span>👤 ' + esc(l.usuario) + '</span><span>' + esc(l.quando) + '</span>' +
|
||||||
|
'</div>' +
|
||||||
|
'<ul class="space-y-0.5 text-xs">' + (mudancas || '<li class="text-gray-500">—</li>') + '</ul>' +
|
||||||
|
'</div>';
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
html += '</div><div>' +
|
||||||
|
'<p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">🌐 SimpliRoute (API)</p>';
|
||||||
|
const api = (data.api || []);
|
||||||
|
if (!api.length) {
|
||||||
|
html += '<p class="text-gray-500">Sem registros de histórico na API do SimpliRoute.</p>';
|
||||||
|
} else {
|
||||||
|
html += '<pre class="bg-[#1a1a1a] border border-white/5 rounded-xl p-3 text-xs text-gray-300 overflow-x-auto">' +
|
||||||
|
esc(JSON.stringify(api, null, 2)) + '</pre>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
return html;
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -204,9 +204,9 @@
|
|||||||
<%# GRÁFICO + MOTORISTAS (lado a lado no desktop) %>
|
<%# GRÁFICO + MOTORISTAS (lado a lado no desktop) %>
|
||||||
<div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
|
<div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
|
||||||
|
|
||||||
<%# Gráfico de linha diário (Chart.js) %>
|
<%# Gráficos diários (Chart.js) — flex-col p/ preencher a altura do card de motoristas %>
|
||||||
<div class="xl:col-span-2 bg-[#1a1a1a] rounded-2xl border border-white/5 p-6">
|
<div class="xl:col-span-2 bg-[#1a1a1a] rounded-2xl border border-white/5 p-6 flex flex-col">
|
||||||
<div class="flex items-center justify-between mb-6">
|
<div class="flex flex-wrap items-center justify-between gap-2 mb-6">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-lg font-semibold text-white">Evolução do custo</h2>
|
<h2 class="text-lg font-semibold text-white">Evolução do custo</h2>
|
||||||
<p class="text-gray-400 text-sm">Valor estimado por dia no período<%= ' · operação filtrada' if @operacao_filtro.present? %></p>
|
<p class="text-gray-400 text-sm">Valor estimado por dia no período<%= ' · operação filtrada' if @operacao_filtro.present? %></p>
|
||||||
@@ -215,9 +215,39 @@
|
|||||||
<span class="inline-block w-3 h-0.5 bg-[#f97316] rounded"></span> Valor (R$)
|
<span class="inline-block w-3 h-0.5 bg-[#f97316] rounded"></span> Valor (R$)
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="relative h-64">
|
<div class="relative flex-1 min-h-56">
|
||||||
<canvas id="grafico-diario"></canvas>
|
<canvas id="grafico-diario"></canvas>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<%# Pagamentos por dia (fluxo de caixa) — quando o dinheiro saiu de fato %>
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2 mt-6 mb-4 pt-6 border-t border-white/5">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-lg font-semibold text-white">Pagamentos por dia</h2>
|
||||||
|
<p class="text-gray-400 text-sm">Valor pago aos motoristas por data de pagamento</p>
|
||||||
|
</div>
|
||||||
|
<% if @pag_pago_qtd.positive? %>
|
||||||
|
<div class="flex flex-wrap items-center gap-3 text-xs text-gray-400">
|
||||||
|
<span class="flex items-center gap-1.5"><span class="inline-block w-3 h-2 bg-green-500 rounded-sm"></span> Pago no dia</span>
|
||||||
|
<span class="flex items-center gap-1.5"><span class="inline-block w-3 h-0.5 bg-gray-300 rounded"></span> Acumulado</span>
|
||||||
|
</div>
|
||||||
|
<% end %>
|
||||||
|
</div>
|
||||||
|
<% if @pag_pago_qtd.positive? %>
|
||||||
|
<div class="relative flex-1 min-h-48">
|
||||||
|
<canvas id="grafico-pagamentos-dia"></canvas>
|
||||||
|
</div>
|
||||||
|
<% else %>
|
||||||
|
<div class="flex-1 min-h-48 flex flex-col items-center justify-center text-gray-400">
|
||||||
|
<div class="text-3xl mb-2">💸</div>
|
||||||
|
<p class="text-sm">Nenhum pagamento realizado neste período</p>
|
||||||
|
<% if @pag_pend_valor.positive? %>
|
||||||
|
<p class="text-xs mt-1">
|
||||||
|
<span class="text-yellow-500 font-semibold"><%= moeda(@pag_pend_valor) %></span>
|
||||||
|
aguardando pagamento (<%= @pag_pend_qtd %> motorista(s))
|
||||||
|
</p>
|
||||||
|
<% end %>
|
||||||
|
</div>
|
||||||
|
<% end %>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<%# Top motoristas %>
|
<%# Top motoristas %>
|
||||||
@@ -348,9 +378,9 @@
|
|||||||
<th class="py-2 pl-3 font-medium text-right">Valor</th>
|
<th class="py-2 pl-3 font-medium text-right">Valor</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody id="pagamentos-feitos-tbody">
|
||||||
<% @pagamentos_feitos.each do |cm| %>
|
<% @pagamentos_feitos.each do |cm| %>
|
||||||
<tr class="border-b border-white/5">
|
<tr class="border-b border-white/5 pagamento-feito-row">
|
||||||
<td class="py-2.5 pr-3 text-gray-300 whitespace-nowrap"><%= l cm.pago_em.to_date, format: :short %></td>
|
<td class="py-2.5 pr-3 text-gray-300 whitespace-nowrap"><%= l cm.pago_em.to_date, format: :short %></td>
|
||||||
<td class="py-2.5 px-3 text-white"><%= cm.motorista_nome %></td>
|
<td class="py-2.5 px-3 text-white"><%= cm.motorista_nome %></td>
|
||||||
<td class="py-2.5 px-3">
|
<td class="py-2.5 px-3">
|
||||||
@@ -364,6 +394,10 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="pagamentos-feitos-paginacao" class="flex items-center justify-between mt-3 hidden">
|
||||||
|
<p class="text-gray-400 text-xs" id="pagamentos-feitos-info"></p>
|
||||||
|
<div class="flex gap-1" id="pagamentos-feitos-abas"></div>
|
||||||
|
</div>
|
||||||
<% else %>
|
<% else %>
|
||||||
<p class="text-gray-400 text-sm py-3">Nenhum pagamento realizado neste período.</p>
|
<p class="text-gray-400 text-sm py-3">Nenhum pagamento realizado neste período.</p>
|
||||||
<% end %>
|
<% end %>
|
||||||
@@ -382,9 +416,9 @@
|
|||||||
<th class="py-2 pl-3 font-medium text-right">Valor</th>
|
<th class="py-2 pl-3 font-medium text-right">Valor</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody id="pagamentos-pendentes-tbody">
|
||||||
<% @pagamentos_pendentes.each do |cm| %>
|
<% @pagamentos_pendentes.each do |cm| %>
|
||||||
<tr class="border-b border-white/5">
|
<tr class="border-b border-white/5 pagamento-pendente-row">
|
||||||
<td class="py-2.5 pr-3 text-white"><%= cm.motorista_nome %></td>
|
<td class="py-2.5 pr-3 text-white"><%= cm.motorista_nome %></td>
|
||||||
<td class="py-2.5 px-3">
|
<td class="py-2.5 px-3">
|
||||||
<%= link_to cm.consolidacao.nome, consolidacao_path(cm.consolidacao),
|
<%= link_to cm.consolidacao.nome, consolidacao_path(cm.consolidacao),
|
||||||
@@ -396,6 +430,10 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="pagamentos-pendentes-paginacao" class="flex items-center justify-between mt-3 hidden">
|
||||||
|
<p class="text-gray-400 text-xs" id="pagamentos-pendentes-info"></p>
|
||||||
|
<div class="flex gap-1" id="pagamentos-pendentes-abas"></div>
|
||||||
|
</div>
|
||||||
<% else %>
|
<% else %>
|
||||||
<p class="text-gray-400 text-sm py-3">Nenhuma pendência no período. 🎉</p>
|
<p class="text-gray-400 text-sm py-3">Nenhuma pendência no período. 🎉</p>
|
||||||
<% end %>
|
<% end %>
|
||||||
@@ -473,6 +511,60 @@
|
|||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<%# Paginação client-side das tabelas de pagamentos (10 por página) %>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
function paginarTabela(prefixo, classeLinha, rotulo) {
|
||||||
|
const tbody = document.getElementById(prefixo + '-tbody');
|
||||||
|
const nav = document.getElementById(prefixo + '-paginacao');
|
||||||
|
if (!tbody || !nav || nav.dataset.iniciado) return;
|
||||||
|
nav.dataset.iniciado = '1';
|
||||||
|
|
||||||
|
const porPagina = 10;
|
||||||
|
const linhas = Array.from(tbody.querySelectorAll('.' + classeLinha));
|
||||||
|
const paginas = Math.ceil(linhas.length / porPagina);
|
||||||
|
if (paginas <= 1) return;
|
||||||
|
|
||||||
|
const abas = document.getElementById(prefixo + '-abas');
|
||||||
|
const info = document.getElementById(prefixo + '-info');
|
||||||
|
nav.classList.remove('hidden');
|
||||||
|
|
||||||
|
function mostrarPagina(p) {
|
||||||
|
linhas.forEach(function (tr, i) {
|
||||||
|
tr.style.display = (i >= (p - 1) * porPagina && i < p * porPagina) ? '' : 'none';
|
||||||
|
});
|
||||||
|
const de = (p - 1) * porPagina + 1;
|
||||||
|
const ate = Math.min(p * porPagina, linhas.length);
|
||||||
|
info.textContent = de + '–' + ate + ' de ' + linhas.length + ' ' + rotulo;
|
||||||
|
abas.querySelectorAll('button').forEach(function (b) {
|
||||||
|
const ativa = Number(b.dataset.pagina) === p;
|
||||||
|
b.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ' +
|
||||||
|
(ativa ? 'bg-[#f97316] text-white'
|
||||||
|
: 'bg-[#0a0a0a] text-gray-400 border border-white/5 hover:text-white');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let p = 1; p <= paginas; p++) {
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.type = 'button';
|
||||||
|
btn.textContent = p;
|
||||||
|
btn.dataset.pagina = p;
|
||||||
|
btn.addEventListener('click', function () { mostrarPagina(p); });
|
||||||
|
abas.appendChild(btn);
|
||||||
|
}
|
||||||
|
mostrarPagina(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function initPaginacaoPagamentos() {
|
||||||
|
paginarTabela('pagamentos-feitos', 'pagamento-feito-row', 'pagamentos');
|
||||||
|
paginarTabela('pagamentos-pendentes', 'pagamento-pendente-row', 'pendências');
|
||||||
|
}
|
||||||
|
|
||||||
|
initPaginacaoPagamentos();
|
||||||
|
document.addEventListener('turbo:load', initPaginacaoPagamentos);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
<%# Filtro de operação — submete o form ao marcar/desmarcar %>
|
<%# Filtro de operação — submete o form ao marcar/desmarcar %>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
@@ -564,6 +656,82 @@
|
|||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<%# Fluxo de pagamentos: barras (pago no dia) + linha (acumulado no período) %>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
const ctx = document.getElementById('grafico-pagamentos-dia');
|
||||||
|
if (!ctx || typeof Chart === 'undefined') return;
|
||||||
|
Chart.getChart(ctx)?.destroy();
|
||||||
|
|
||||||
|
const labels = <%= raw @grafico_pagamentos_dia[:labels].to_json %>;
|
||||||
|
const valores = <%= raw @grafico_pagamentos_dia[:valores].to_json %>;
|
||||||
|
const acumulado = <%= raw @grafico_pagamentos_dia[:acumulado].to_json %>;
|
||||||
|
|
||||||
|
const brl = (v) => `R$ ${v.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||||
|
|
||||||
|
new Chart(ctx, {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: labels,
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'Pago no dia',
|
||||||
|
data: valores,
|
||||||
|
backgroundColor: 'rgba(34, 197, 94, 0.65)',
|
||||||
|
hoverBackgroundColor: '#22c55e',
|
||||||
|
borderRadius: 4,
|
||||||
|
borderSkipped: false,
|
||||||
|
maxBarThickness: 28,
|
||||||
|
order: 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Acumulado',
|
||||||
|
data: acumulado,
|
||||||
|
type: 'line',
|
||||||
|
borderColor: '#d1d5db',
|
||||||
|
borderWidth: 2,
|
||||||
|
borderDash: [5, 4],
|
||||||
|
pointRadius: 0,
|
||||||
|
pointHoverRadius: 4,
|
||||||
|
tension: 0.3,
|
||||||
|
order: 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
interaction: { mode: 'index', intersect: false },
|
||||||
|
plugins: {
|
||||||
|
legend: { display: false },
|
||||||
|
tooltip: {
|
||||||
|
backgroundColor: '#0a0a0a',
|
||||||
|
borderColor: '#22c55e',
|
||||||
|
borderWidth: 1,
|
||||||
|
titleColor: '#9ca3af',
|
||||||
|
bodyColor: '#ffffff',
|
||||||
|
padding: 12,
|
||||||
|
callbacks: {
|
||||||
|
label: (c) => ` ${c.dataset.label}: ${brl(c.parsed.y)}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
grid: { display: false, drawBorder: false },
|
||||||
|
ticks: { color: '#6b7280', font: { size: 11 }, maxTicksLimit: 10 }
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
beginAtZero: true,
|
||||||
|
grid: { color: 'rgba(255,255,255,0.04)', drawBorder: false },
|
||||||
|
ticks: { color: '#6b7280', font: { size: 11 }, callback: (v) => `R$ ${v.toFixed(0)}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
<%# Rosca de pagamentos (pago x a pagar, por valor) %>
|
<%# Rosca de pagamentos (pago x a pagar, por valor) %>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
|||||||
@@ -80,7 +80,10 @@
|
|||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body class="bg-[#0a0a0a] text-white min-h-screen">
|
<%# overflow-x-hidden: conteúdo largo demais não pode criar scroll horizontal na
|
||||||
|
página (aparecia como uma barra laranja "quebrando" o rodapé no celular);
|
||||||
|
tabelas largas já rolam nos próprios contêineres overflow-x-auto. %>
|
||||||
|
<body class="bg-[#0a0a0a] text-white min-h-screen overflow-x-hidden">
|
||||||
|
|
||||||
<%# ── Animação de abertura (uma vez, logo após o login) ── %>
|
<%# ── Animação de abertura (uma vez, logo após o login) ── %>
|
||||||
<% if @mostrar_splash %>
|
<% if @mostrar_splash %>
|
||||||
|
|||||||
@@ -40,13 +40,17 @@ Rails.application.configure do
|
|||||||
|
|
||||||
p.font_src :self, :data, "https://fonts.gstatic.com"
|
p.font_src :self, :data, "https://fonts.gstatic.com"
|
||||||
|
|
||||||
# Imagens: data/blob (QR base64, canvas dos gráficos), ícones do Leaflet e
|
# Imagens: data/blob (QR base64, canvas dos gráficos), ícones do Leaflet,
|
||||||
# tiles do mapa (ArcGIS World Imagery + OpenStreetMap).
|
# tiles do mapa (ArcGIS World Imagery + OpenStreetMap) e as FOTOS DA FACHADA
|
||||||
|
# do popup do mapa de operações — hospedadas no S3 do SimpliRoute
|
||||||
|
# (ex.: simpli-visit-images.s3.amazonaws.com). Sem o host da Amazon o CSP
|
||||||
|
# enforcing bloqueava a foto ("Refused to load the image ... img-src").
|
||||||
p.img_src :self, :data, :blob,
|
p.img_src :self, :data, :blob,
|
||||||
"https://unpkg.com",
|
"https://unpkg.com",
|
||||||
"https://cdn.jsdelivr.net",
|
"https://cdn.jsdelivr.net",
|
||||||
"https://server.arcgisonline.com",
|
"https://server.arcgisonline.com",
|
||||||
"https://*.tile.openstreetmap.org"
|
"https://*.tile.openstreetmap.org",
|
||||||
|
"https://*.amazonaws.com"
|
||||||
|
|
||||||
p.connect_src :self
|
p.connect_src :self
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -32,7 +32,12 @@ services:
|
|||||||
# O passo do cron é "best-effort": se o crontab/cron não estiver disponível
|
# O passo do cron é "best-effort": se o crontab/cron não estiver disponível
|
||||||
# (ex.: imagem antiga sem o pacote `cron`), apenas avisa no log e SEGUE —
|
# (ex.: imagem antiga sem o pacote `cron`), apenas avisa no log e SEGUE —
|
||||||
# nunca impede o Rails de subir. (Requer rebuild: docker compose up -d --build)
|
# nunca impede o Rails de subir. (Requer rebuild: docker compose up -d --build)
|
||||||
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails db:prepare && { bundle exec whenever --update-crontab && cron || echo '[boot] AVISO cron/crontab indisponivel (rode com --build), seguindo sem agendamento'; } && bundle exec rails s -b 0.0.0.0"
|
# `bundle check || bundle install`: os gems ficam num VOLUME nomeado
|
||||||
|
# (bundle_cache) que persiste e SOMBREIA os gems da imagem — então adicionar
|
||||||
|
# uma gem nova ao Gemfile não chega no container só com `up`/`--build`. Este
|
||||||
|
# passo instala o que faltar no volume no boot (idempotente e rápido quando já
|
||||||
|
# está tudo instalado), evitando o Bundler::GemNotFound ao subir.
|
||||||
|
command: bash -c "rm -f tmp/pids/server.pid && (bundle check || bundle install) && bundle exec rails db:prepare && { bundle exec whenever --update-crontab && cron || echo '[boot] AVISO cron/crontab indisponivel (rode com --build), seguindo sem agendamento'; } && bundle exec rails s -b 0.0.0.0"
|
||||||
# O banco PostgreSQL já existe externamente.
|
# O banco PostgreSQL já existe externamente.
|
||||||
# Configure DB_HOST no .env com o IP/hostname do seu servidor PostgreSQL.
|
# Configure DB_HOST no .env com o IP/hostname do seu servidor PostgreSQL.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user