Corrige dashboard por período, CRUD de usuário, PDFs e paginação na revisão

- Dashboard: no_periodo passa a cobrir o dia inteiro (planned_date é timestamp),
  corrigindo período que zerava ao terminar no dia dos dados
- Dashboard: card de consolidações filtra por sobreposição de datas (não created_at)
- Usuários: adiciona helper role_options_for_select (corrige edição/criação)
- Consolidação: set_consolidacao nas actions de PDF/preview (corrige
  Pundit::NotDefinedError em Relatório Individual, Gerar Holerite e Preview)
- Revisão: paginação com Pagy (20/página + seletor 20/50/100)
- Nova consolidação: veículos filtrados pelo(s) motorista(s) no período
This commit is contained in:
2026-06-16 14:45:06 -03:00
parent aad167873f
commit fedf5bfcc9
17 changed files with 14917 additions and 24 deletions

View File

@@ -0,0 +1,252 @@
<!DOCTYPE html>
<html lang="pt-BR" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="V0huiUnnR6iuZZliHnfydw0_28pJd5ho66yiE1jO186V5ffx6xm7oL5TuqTEwVv9v-9pxKKkTDbXwLQRAdLL3w">
<title>teste | Reem Logística</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
brand: {
preto: '#0a0a0a',
'preto-card': '#1a1a1a',
laranja: '#f97316',
'laranja-escuro': '#ea580c',
branco: '#ffffff',
}
}
}
}
}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
body { font-family: 'Inter', sans-serif; }
/* Scrollbar tema escuro */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: #0a0a0a; }
::-webkit-scrollbar-thumb { background: #f97316; border-radius: 3px; }
/* Loading spinner laranja */
.spinner {
border: 3px solid #1a1a1a;
border-top-color: #f97316;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<script type="importmap" data-turbo-track="reload">{
"imports": {
"application": "/assets/application-09caced1.js",
"@hotwired/turbo-rails": "/assets/turbo.min-86bf8853.js",
"@hotwired/stimulus": "/assets/stimulus.min-7ea3d58b.js",
"@hotwired/stimulus-loading": "/assets/stimulus-loading-25917588.js",
"controllers/application": "/assets/controllers/application-75a69c37.js",
"controllers": "/assets/controllers/index-dfefe98d.js",
"controllers/validacao_controller": "/assets/controllers/validacao_controller-3ce614b7.js"
}
}</script>
<link rel="modulepreload" href="/assets/application-09caced1.js">
<link rel="modulepreload" href="/assets/turbo.min-86bf8853.js">
<link rel="modulepreload" href="/assets/stimulus.min-7ea3d58b.js">
<link rel="modulepreload" href="/assets/stimulus-loading-25917588.js">
<link rel="modulepreload" href="/assets/controllers/application-75a69c37.js">
<link rel="modulepreload" href="/assets/controllers/index-dfefe98d.js">
<link rel="modulepreload" href="/assets/controllers/validacao_controller-3ce614b7.js">
<script type="module">import "application"</script>
</head>
<body class="bg-[#0a0a0a] text-white min-h-screen">
<div id="sidebar-overlay"
class="fixed inset-0 bg-black/70 z-30 hidden md:hidden"
onclick="toggleSidebar()"></div>
<aside id="sidebar"
class="fixed top-0 left-0 h-full w-64 bg-[#111111] border-r border-[#2a2a2a] z-40
transform -translate-x-full md:translate-x-0 transition-transform duration-300">
<div class="flex items-center gap-3 px-6 py-5 border-b border-[#2a2a2a]">
<div class="w-9 h-9 bg-orange-500 rounded-lg flex items-center justify-center font-black text-black text-lg">G</div>
<div>
<p class="font-bold text-white text-sm leading-tight">Reem Transporte</p>
<p class="text-orange-500 text-xs">Logística</p>
</div>
</div>
<div class="px-6 py-4 border-b border-[#2a2a2a]">
<p class="text-xs text-gray-500 mb-1">Logado como</p>
<p class="text-white font-semibold text-sm truncate">Administrador Gade</p>
<span class="inline-block mt-1 px-2 py-0.5 text-xs rounded-full
bg-orange-500 text-black">
Administrador
</span>
</div>
<nav class="px-3 py-4 space-y-1 flex-1 overflow-y-auto">
<a class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] text-gray-400 hover:bg-[#1a1a1a] hover:text-white" href="/dashboard">📊 Dashboard</a>
<a class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] text-gray-400 hover:bg-[#1a1a1a] hover:text-white" href="/consolidacoes">📦 Consolidações</a>
<div class="pt-4 mt-4 border-t border-[#2a2a2a]">
<p class="px-3 text-xs text-gray-600 uppercase tracking-wider mb-2">Administração</p>
<a class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] text-gray-400 hover:bg-[#1a1a1a] hover:text-white" href="/admin/usuarios">👥 Usuários</a>
<a class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] text-gray-400 hover:bg-[#1a1a1a] hover:text-white" href="/admin/configuracoes">⚙️ Configurações</a>
<a class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all min-h-[44px] text-gray-400 hover:bg-[#1a1a1a] hover:text-white" href="/admin/auditoria_logs">🔍 Auditoria</a>
</div>
</nav>
<div class="px-6 py-4 border-t border-[#2a2a2a]">
<a data-turbo-method="delete" data-turbo-confirm="Deseja sair?" class="flex items-center gap-2 text-gray-400 hover:text-red-400 text-sm transition-colors" href="/auth/logout">
<span>🚪</span> Sair
</a> </div>
</aside>
<header class="md:hidden fixed top-0 left-0 right-0 z-30 bg-[#111111] border-b border-[#2a2a2a] px-4 py-3 flex items-center justify-between">
<button onclick="toggleSidebar()"
class="text-orange-500 text-2xl min-h-[48px] min-w-[48px] flex items-center justify-center">
</button>
<div class="flex items-center gap-2">
<div class="w-7 h-7 bg-orange-500 rounded flex items-center justify-center font-black text-black text-sm">G</div>
<span class="font-bold text-white text-sm">Reem Logística</span>
</div>
<div class="w-12"></div>
</header>
<div class="h-14 md:hidden"></div>
<script>
function toggleSidebar() {
const s = document.getElementById('sidebar');
const o = document.getElementById('sidebar-overlay');
s.classList.toggle('-translate-x-full');
o.classList.toggle('hidden');
}
</script>
<main class="ml-0 md:ml-64 p-4 md:p-8 min-h-screen">
<div class="max-w-4xl mx-auto">
<div class="mb-6">
<a class="text-gray-500 hover:text-orange-500 text-sm" href="/consolidacoes">← Consolidações</a>
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mt-2">
<div>
<div class="flex items-center gap-3">
<h1 class="text-2xl font-bold text-white">teste</h1>
<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-yellow-500 text-black">📝 Rascunho</span>
</div>
<p class="text-gray-400 text-sm mt-1">
📅 01/02/2026 → 28/02/2026
· Criada por Administrador Gade
</p>
</div>
<div class="flex gap-2">
<a class="bg-orange-500 hover:bg-orange-600 text-black font-bold px-5 py-3 rounded-lg min-h-[48px] flex items-center" href="/consolidacoes/3/wizard">✏️ Continuar validação</a>
<form class="button_to" method="post" action="/consolidacoes/3/arquivar"><button data-turbo-confirm="Arquivar esta consolidação? Ela não será excluída, apenas movida para o arquivo." class="text-gray-400 hover:text-white border border-[#2a2a2a] px-4 py-3 rounded-lg min-h-[48px]" type="submit">📁 Arquivar</button><input type="hidden" name="authenticity_token" value="bFgW-DhUfHVabQb6YBBZhcI6kTfr6RY-m2AcIg74Too_85JbSI2x1yKmq7VymjoA3QnfDb2v-F5VSGRHh8Q_DQ" autocomplete="off" /></form>
</div>
</div>
</div>
<div class="bg-[#1a1a1a] border border-orange-500 rounded-xl p-6 mb-6 text-center">
<p class="text-gray-400 text-sm">Valor total da consolidação</p>
<p class="text-orange-500 font-black text-4xl">R$ 5265,00</p>
</div>
<h2 class="text-white font-bold text-lg mb-3">👥 Motoristas</h2>
<div class="space-y-3">
<div class="bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl p-5">
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<p class="text-white font-bold text-lg">Bruno Corgozinho</p>
<p class="text-orange-500 font-black text-xl">R$ 5265,00</p>
</div>
<div class="flex flex-wrap gap-2">
<button onclick="abrirPreview('/consolidacoes/3/preview_holerite?motorista=Bruno+Corgozinho')"
class="bg-[#0a0a0a] hover:bg-[#2a2a2a] text-white border border-orange-500 font-semibold px-4 py-3 rounded-lg text-sm min-h-[48px]">
👁️ Ver antes de gerar
</button>
<a class="bg-orange-800 hover:bg-orange-700 text-white font-semibold px-4 py-3 rounded-lg text-sm min-h-[48px] flex items-center" href="/consolidacoes/3/gerar_pdf_relatorio?motorista=Bruno+Corgozinho">📄 Relatório Individual</a>
<a class="bg-orange-500 hover:bg-orange-600 text-black font-bold px-4 py-3 rounded-lg text-sm min-h-[48px] flex items-center" href="/consolidacoes/3/gerar_pdf_holerite?motorista=Bruno+Corgozinho">🧾 Gerar Holerite</a>
</div>
</div>
</div>
</div>
</div>
<div id="modal-preview" class="fixed inset-0 bg-black/80 z-50 hidden items-center justify-center p-4">
<div class="bg-[#1a1a1a] border border-[#2a2a2a] rounded-2xl max-w-2xl w-full max-h-[85vh] flex flex-col">
<div class="flex items-center justify-between px-6 py-4 border-b border-[#2a2a2a]">
<h3 class="text-white font-bold">👁️ Pré-visualização do Holerite</h3>
<button onclick="fecharPreview()" class="text-gray-400 hover:text-white text-2xl min-w-[44px] min-h-[44px]"></button>
</div>
<div id="modal-preview-conteudo" class="overflow-y-auto p-6 flex-1">
<div class="flex justify-center py-10"><div class="spinner w-10 h-10"></div></div>
</div>
<div class="flex gap-3 px-6 py-4 border-t border-[#2a2a2a]">
<a id="modal-confirmar" href="#"
class="flex-1 bg-orange-500 hover:bg-orange-600 text-black font-bold py-3 rounded-lg text-center min-h-[48px] flex items-center justify-center">
✓ Confirmar e baixar PDF
</a>
<button onclick="fecharPreview()"
class="px-6 py-3 text-gray-400 hover:text-white border border-[#2a2a2a] rounded-lg min-h-[48px]">
← Voltar
</button>
</div>
</div>
</div>
<script>
async function abrirPreview(url) {
const modal = document.getElementById('modal-preview');
const conteudo = document.getElementById('modal-preview-conteudo');
modal.classList.remove('hidden');
modal.classList.add('flex');
conteudo.innerHTML = '<div class="flex justify-center py-10"><div class="spinner w-10 h-10"></div></div>';
const resp = await fetch(url);
conteudo.innerHTML = await resp.text();
// O link de confirmar aponta para o PDF do mesmo motorista
document.getElementById('modal-confirmar').href =
url.replace('preview_holerite', 'gerar_pdf_holerite');
}
function fecharPreview() {
const modal = document.getElementById('modal-preview');
modal.classList.add('hidden');
modal.classList.remove('flex');
}
</script>
</main>
<script>
setTimeout(() => {
['flash-notice', 'flash-alert'].forEach(id => {
const el = document.getElementById(id);
if (el) el.style.transition = 'opacity 0.5s', el.style.opacity = '0',
setTimeout(() => el.remove(), 500);
});
}, 4000);
</script>
<script async nonce="" type="text/javascript" id="mini-profiler" src="/mini-profiler-resources/includes.js?v=e0bcc9ce0ae3bb5d6b736b6f282f601f" data-css-url="/mini-profiler-resources/includes.css?v=e0bcc9ce0ae3bb5d6b736b6f282f601f" data-version="e0bcc9ce0ae3bb5d6b736b6f282f601f" data-path="/mini-profiler-resources/" data-current-id="5vfdctp5mnyu0tdtx94a" data-ids="5vfdctp5mnyu0tdtx94a,md2esz0jc4j57ce236e8" data-horizontal-position="left" data-vertical-position="top" data-trivial="false" data-children="false" data-max-traces="20" data-controls="false" data-total-sql-count="false" data-authorized="true" data-toggle-shortcut="alt+p" data-start-hidden="false" data-collapse-results="true" data-html-container="body" data-hidden-custom-fields="" data-turbo-permanent="false"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

View File

@@ -1,6 +1,7 @@
# app/controllers/application_controller.rb # app/controllers/application_controller.rb
class ApplicationController < ActionController::Base class ApplicationController < ActionController::Base
include Pundit::Authorization include Pundit::Authorization
include Pagy::Backend
before_action :authenticate_user! before_action :authenticate_user!
before_action :set_tema before_action :set_tema

View File

@@ -125,15 +125,19 @@ class ConsolidacaoEntregasController < ApplicationController
authorize @consolidacao, :show? authorize @consolidacao, :show?
@motorista = params[:motorista] @motorista = params[:motorista]
@classificacoes = @consolidacao.consolidacao_entregas todas = @consolidacao.consolidacao_entregas.where(motorista_nome: @motorista)
.where(motorista_nome: @motorista)
.order(:created_at)
# reorder(nil): GROUP BY tipo + ORDER BY created_at é inválido no PostgreSQL # Agregados calculados sobre o conjunto COMPLETO (não só a página exibida)
@resumo = @classificacoes.reorder(nil).group(:tipo).count @resumo = todas.group(:tipo).count
@total = @classificacoes.sum do |c| @total = todas.sum do |c|
c.tipo == 'desconto' ? -c.valor_aplicado : c.valor_aplicado c.tipo == 'desconto' ? -c.valor_aplicado : c.valor_aplicado
end end
@total_pilares = todas.count
@total_classificadas = todas.distinct.count(:tracking_id)
# Paginação só da tabela exibida — 20 padrão, com seletor 20/50/100
@por_pagina = [20, 50, 100].include?(params[:por_pagina].to_i) ? params[:por_pagina].to_i : 20
@pagy, @classificacoes = pagy(todas.order(:created_at), limit: @por_pagina)
# Próximo motorista pendente (para botão "Próximo Motorista") # Próximo motorista pendente (para botão "Próximo Motorista")
nomes_completos = @consolidacao.consolidacao_motoristas.map(&:motorista_nome) nomes_completos = @consolidacao.consolidacao_motoristas.map(&:motorista_nome)

View File

@@ -2,7 +2,9 @@
class ConsolidacoesController < ApplicationController class ConsolidacoesController < ApplicationController
include Auditavel include Auditavel
before_action :set_consolidacao, only: %i[show edit update destroy finalizar arquivar wizard] before_action :set_consolidacao,
only: %i[show edit update destroy finalizar arquivar wizard
preview_holerite gerar_pdf_relatorio gerar_pdf_holerite]
# GET /consolidacoes — lista com filtros # GET /consolidacoes — lista com filtros
def index def index
@@ -65,6 +67,17 @@ class ConsolidacoesController < ApplicationController
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
# GET /consolidacoes/veiculos_disponiveis?motoristas[]=X&inicio=&fim=
# Lista (JSON) os veículos usados pelos motoristas selecionados no período —
# alimenta o filtro dinâmico de veículos no formulário de nova consolidação.
def veiculos_disponiveis
authorize Consolidacao, :new?
veiculos = Entrega.veiculos_de_motoristas(
params[:motoristas], inicio: params[:inicio], fim: params[:fim]
)
render json: { veiculos: veiculos }
end
# GET /consolidacoes/:id — visão geral # GET /consolidacoes/:id — visão geral
def show def show
authorize @consolidacao authorize @consolidacao

View File

@@ -72,8 +72,10 @@ class DashboardController < ApplicationController
# Evolução diária no período (para Chart.js) # Evolução diária no período (para Chart.js)
@grafico_diario = build_grafico_diario(entregas, config[:entrega]) @grafico_diario = build_grafico_diario(entregas, config[:entrega])
# Consolidações criadas no período # Consolidações cujo período (data_inicio..data_fim) cruza o período do dashboard
@consolidacoes_mes = Consolidacao.ativas.where(created_at: @periodo_inicio.beginning_of_day..@periodo_fim.end_of_day) # — independe de quando foram criadas (created_at).
@consolidacoes_mes = Consolidacao.ativas
.where('data_inicio <= ? AND data_fim >= ?', @periodo_fim, @periodo_inicio)
@consolidacoes_abertas = @consolidacoes_mes.where(status: :rascunho).count @consolidacoes_abertas = @consolidacoes_mes.where(status: :rascunho).count
@consolidacoes_fechadas = @consolidacoes_mes.where(status: :finalizada).count @consolidacoes_fechadas = @consolidacoes_mes.where(status: :finalizada).count

View File

@@ -1,5 +1,12 @@
# app/helpers/application_helper.rb # app/helpers/application_helper.rb
module ApplicationHelper module ApplicationHelper
include Pagy::Frontend
# Opções [label, valor] para o select de perfil de usuário (form de usuário)
def role_options_for_select
User::ROLES_LABEL.map { |value, label| [label, value] }
end
# Link de navegação com estado ativo # Link de navegação com estado ativo
def nav_link_to(label, path, **opts) def nav_link_to(label, path, **opts)
active = current_page?(path) active = current_page?(path)

View File

@@ -20,8 +20,11 @@ class Entrega < ApplicationRecord
scope :pagas, -> { concluidas.com_checkout } scope :pagas, -> { concluidas.com_checkout }
scope :pendentes, -> { where.not(status: 'completed') } scope :pendentes, -> { where.not(status: 'completed') }
# planned_date é timestamp: usamos o dia inteiro do limite superior para não
# descartar as entregas do último dia do período (causava dashboard zerado e
# subcontagem de elegíveis nas consolidações).
scope :no_periodo, ->(inicio, fim) { scope :no_periodo, ->(inicio, fim) {
where(planned_date: inicio.to_date..fim.to_date) where(planned_date: inicio.to_date.beginning_of_day..fim.to_date.end_of_day)
} }
scope :do_motorista, ->(nome) { scope :do_motorista, ->(nome) {
@@ -65,6 +68,17 @@ class Entrega < ApplicationRecord
base.distinct.order(:vehicle).pluck(:vehicle).compact.reject(&:empty?) base.distinct.order(:vehicle).pluck(:vehicle).compact.reject(&:empty?)
end end
# Veículos usados pelo(s) motorista(s) selecionado(s) no período — alimenta o
# filtro dinâmico de veículos na criação de consolidação.
def self.veiculos_de_motoristas(motoristas, inicio: nil, fim: nil)
nomes = Array(motoristas).reject(&:blank?)
return [] if nomes.empty?
base = da_conta_gade.where(driver: nomes)
base = base.no_periodo(inicio, fim) if inicio.present? && fim.present?
base.distinct.order(:vehicle).pluck(:vehicle).compact.reject(&:empty?)
end
# Contagem de entregas pagas para cálculo estimado # Contagem de entregas pagas para cálculo estimado
def self.contar_pagas(inicio:, fim:, motorista: nil, vehicle: nil) def self.contar_pagas(inicio:, fim:, motorista: nil, vehicle: nil)
base = pagas.da_conta_gade.no_periodo(inicio, fim) base = pagas.da_conta_gade.no_periodo(inicio, fim)

View File

@@ -30,11 +30,24 @@
<div class="bg-[#1a1a1a] border border-orange-500 rounded-xl p-6 mb-6 text-center"> <div class="bg-[#1a1a1a] border border-orange-500 rounded-xl p-6 mb-6 text-center">
<p class="text-gray-400 text-sm mb-1">Total a pagar — <%= @motorista %></p> <p class="text-gray-400 text-sm mb-1">Total a pagar — <%= @motorista %></p>
<p class="text-orange-500 font-black text-4xl"><%= moeda(@total) %></p> <p class="text-orange-500 font-black text-4xl"><%= moeda(@total) %></p>
<p class="text-gray-500 text-xs mt-1"><%= @classificacoes.map(&:tracking_id).uniq.size %> entregas classificadas (<%= @classificacoes.size %> pilares)</p> <p class="text-gray-500 text-xs mt-1"><%= @total_classificadas %> entregas classificadas (<%= @total_pilares %> pilares)</p>
</div> </div>
<%# Seletor de itens por página %>
<form method="get" action="<%= revisar_consolidacao_consolidacao_entregas_path(@consolidacao) %>"
class="flex items-center justify-end gap-2 mb-2">
<input type="hidden" name="motorista" value="<%= @motorista %>">
<label class="text-gray-400 text-sm">Itens por página</label>
<select name="por_pagina" onchange="this.form.submit()"
class="bg-[#1a1a1a] border border-[#2a2a2a] text-white rounded-lg px-3 py-2 text-sm focus:border-orange-500 focus:outline-none cursor-pointer">
<% [20, 50, 100].each do |n| %>
<option value="<%= n %>" <%= 'selected' if @por_pagina == n %>><%= n %></option>
<% end %>
</select>
</form>
<%# Detalhe das classificações %> <%# Detalhe das classificações %>
<div class="bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl overflow-hidden mb-6"> <div class="bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl overflow-hidden mb-4">
<table class="w-full text-sm"> <table class="w-full text-sm">
<thead class="bg-[#0a0a0a] text-gray-400"> <thead class="bg-[#0a0a0a] text-gray-400">
<tr> <tr>
@@ -61,6 +74,37 @@
</table> </table>
</div> </div>
<%# Navegação de páginas %>
<% if @pagy.pages > 1 %>
<% pag = ->(p) { revisar_consolidacao_consolidacao_entregas_path(@consolidacao, motorista: @motorista, por_pagina: @por_pagina, page: p) } %>
<nav class="flex items-center justify-center gap-1.5 mb-6 flex-wrap">
<% if @pagy.prev %>
<%= link_to '', pag.call(@pagy.prev),
class: 'min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg border border-[#2a2a2a] text-white hover:border-orange-500' %>
<% else %>
<span class="min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg border border-[#2a2a2a] text-gray-700"></span>
<% end %>
<% @pagy.series.each do |item| %>
<% if item == :gap %>
<span class="px-2 text-gray-500">…</span>
<% elsif item.is_a?(String) %>
<span class="min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg bg-orange-500 text-black font-bold"><%= item %></span>
<% else %>
<%= link_to item, pag.call(item),
class: 'min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg border border-[#2a2a2a] text-white hover:border-orange-500' %>
<% end %>
<% end %>
<% if @pagy.next %>
<%= link_to '', pag.call(@pagy.next),
class: 'min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg border border-[#2a2a2a] text-white hover:border-orange-500' %>
<% else %>
<span class="min-w-[40px] min-h-[40px] flex items-center justify-center rounded-lg border border-[#2a2a2a] text-gray-700"></span>
<% end %>
</nav>
<% end %>
<%# Ações finais %> <%# Ações finais %>
<div class="flex flex-col md:flex-row gap-3"> <div class="flex flex-col md:flex-row gap-3">
<% if @proximo %> <% if @proximo %>

View File

@@ -63,21 +63,15 @@
</div> </div>
</div> </div>
<%# Veículos — multi-select opcional %> <%# Veículos — multi-select opcional (filtrado pelo motorista + período) %>
<div> <div>
<label class="block text-white font-semibold mb-2"> <label class="block text-white font-semibold mb-2">
Veículos <span class="text-gray-500 font-normal text-sm">(opcional — filtra entregas por veículo)</span> Veículos <span class="text-gray-500 font-normal text-sm">(opcional — só os veículos usados pelo(s) motorista(s) no período)</span>
</label> </label>
<div class="bg-[#0a0a0a] border border-[#2a2a2a] rounded-lg p-3 max-h-48 overflow-y-auto space-y-1"> <div id="veiculos-lista"
<% if @veiculos.blank? %> data-url="<%= veiculos_disponiveis_consolidacoes_path %>"
<p class="text-gray-500 text-sm px-2 py-2">Nenhum veículo encontrado no período.</p> class="bg-[#0a0a0a] border border-[#2a2a2a] rounded-lg p-3 max-h-48 overflow-y-auto space-y-1">
<% end %> <p class="text-gray-500 text-sm px-2 py-2">Selecione um motorista para listar os veículos.</p>
<% @veiculos.each do |v| %>
<label class="flex items-center gap-2 text-white hover:bg-[#1a1a1a] rounded px-2 py-2 cursor-pointer text-sm min-h-[44px]">
<%= check_box_tag 'consolidacao[vehicle_ids][]', v, false, class: 'rounded text-orange-500 bg-[#1a1a1a] border-[#2a2a2a]', id: nil %>
<%= v %>
</label>
<% end %>
</div> </div>
</div> </div>
@@ -90,3 +84,82 @@
</div> </div>
<% end %> <% end %>
</div> </div>
<script>
(function () {
const lista = document.getElementById('veiculos-lista');
if (!lista) return;
const url = lista.dataset.url;
const dataIni = document.getElementById('consolidacao_data_inicio');
const dataFim = document.getElementById('consolidacao_data_fim');
// Mantém os veículos que já estavam marcados ao recarregar a lista.
function veiculosMarcados() {
return Array.from(lista.querySelectorAll('input[name="consolidacao[vehicle_ids][]"]:checked'))
.map(c => c.value);
}
function motoristasSelecionados() {
return Array.from(document.querySelectorAll('.chk-motorista:checked')).map(c => c.value);
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function renderVeiculos(veiculos, marcados) {
if (!veiculos.length) {
lista.innerHTML = '<p class="text-gray-500 text-sm px-2 py-2">Nenhum veículo encontrado para este(s) motorista(s) no período.</p>';
return;
}
lista.innerHTML = veiculos.map(function (v) {
const checked = marcados.includes(v) ? 'checked' : '';
const val = escapeHtml(v);
return '<label class="flex items-center gap-2 text-white hover:bg-[#1a1a1a] rounded px-2 py-2 cursor-pointer text-sm min-h-[44px]">' +
'<input type="checkbox" name="consolidacao[vehicle_ids][]" value="' + val + '" ' + checked +
' class="rounded text-orange-500 bg-[#1a1a1a] border-[#2a2a2a]">' + val + '</label>';
}).join('');
}
let controller = null;
async function atualizarVeiculos() {
const motoristas = motoristasSelecionados();
const marcados = veiculosMarcados();
if (!motoristas.length) {
lista.innerHTML = '<p class="text-gray-500 text-sm px-2 py-2">Selecione um motorista para listar os veículos.</p>';
return;
}
const params = new URLSearchParams();
motoristas.forEach(m => params.append('motoristas[]', m));
if (dataIni && dataIni.value) params.append('inicio', dataIni.value);
if (dataFim && dataFim.value) params.append('fim', dataFim.value);
if (controller) controller.abort();
controller = new AbortController();
try {
const resp = await fetch(url + '?' + params.toString(), {
headers: { 'Accept': 'application/json' },
signal: controller.signal
});
const data = await resp.json();
renderVeiculos(data.veiculos || [], marcados);
} catch (e) {
if (e.name !== 'AbortError') {
lista.innerHTML = '<p class="text-red-400 text-sm px-2 py-2">Erro ao carregar veículos.</p>';
}
}
}
document.addEventListener('change', function (e) {
if (e.target.classList.contains('chk-motorista')) atualizarVeiculos();
});
if (dataIni) dataIni.addEventListener('change', atualizarVeiculos);
if (dataFim) dataFim.addEventListener('change', atualizarVeiculos);
// Estado inicial (caso o form volte com motoristas já marcados após erro de validação)
if (motoristasSelecionados().length) atualizarVeiculos();
})();
</script>

View File

@@ -0,0 +1,7 @@
# config/initializers/pagy.rb
require 'pagy/extras/overflow'
# Página fora do intervalo cai na última página (evita erro ao trocar itens/página).
Pagy::DEFAULT[:overflow] = :last_page
# Itens por página padrão.
Pagy::DEFAULT[:limit] = 20

View File

@@ -25,6 +25,10 @@ Rails.application.routes.draw do
# Consolidações # Consolidações
resources :consolidacoes do resources :consolidacoes do
collection do
get :veiculos_disponiveis # JSON — veículos do(s) motorista(s) no período (form nova consolidação)
end
member do member do
get :wizard # Passo 1 — selecionar motorista get :wizard # Passo 1 — selecionar motorista
post :finalizar post :finalizar