diff --git a/README.md b/README.md index 9d8b7e1..fdc9483 100644 --- a/README.md +++ b/README.md @@ -124,16 +124,60 @@ docker-compose down # parar tudo ## šŸ—ŗļø Fases de implementação -| Fase | Status | O que fazer | -|------|--------|-------------| -| **1** | āœ… **CONCLUƍDA** | Setup + Docker + Models + Migrations + Seeds + Layout base | -| **2** | ā³ Pendente | Login por role + CRUD usuĆ”rios + pilares de preƧo + toggle tema | -| **3** | ā³ Pendente | Dashboard: cards grandes laranja/preto/branco + grĆ”fico Chart.js + cĆ”lculo ao vivo | -| **4** | āœ… **CONCLUƍDA** | Job Whenever (1h) + HistoricoEstimado + AuditoriaLog + API mĆ©tricas | -| **5** | āœ… **CONCLUƍDA** | Nova Consolidação + filtros + Wizard Passo 1 (selecionar motorista) | -| **6** | āœ… **CONCLUƍDA** | Toggles coloridos + aƧƵes em massa + barra progresso + Wizard Passos 2 e 3 (Stimulus) | -| **7** | āœ… **CONCLUƍDA** | PDFs Prawn: relatório individual + holerite com QR code + modal preview | -| **8** | āœ… **CONCLUƍDA** | Painel motorista + login PIN/QR + notificaƧƵes WhatsApp/email | +| Fase | Status | O que faz | +|------|--------|-----------| +| **1** | āœ… ConcluĆ­da | Setup + Docker + Models + Migrations + Seeds + Layout base | +| **2** | āœ… ConcluĆ­da *(corrigida)* | Login e-mail/PIN + CRUD usuĆ”rios + pilares de preƧo + toggle tema | +| **3** | āœ… ConcluĆ­da *(corrigida)* | Dashboard: cards + grĆ”fico Chart.js + ranking motoristas + navegação por mĆŖs | +| **4** | āœ… ConcluĆ­da | Job Whenever (1h) + HistoricoEstimado + AuditoriaLog + API mĆ©tricas | +| **5** | āœ… ConcluĆ­da | Nova Consolidação + filtros + Wizard Passo 1 | +| **6** | āœ… ConcluĆ­da | Toggles coloridos + aƧƵes em massa + Wizard Passos 2 e 3 (Stimulus) | +| **7** | āœ… ConcluĆ­da | PDFs Prawn: relatório + holerite com QR code + modal preview | +| **8** | āœ… ConcluĆ­da | Painel motorista + login PIN/QR + notificaƧƵes WhatsApp/email | + +**šŸŽ‰ PROJETO: 8 de 8 fases implementadas.** + +--- + +## šŸ”§ AnĆ”lise de integração (11/06/2026) — CorreƧƵes aplicadas + +As Fases 2/3 (commit `4724847`) foram desenvolvidas em paralelo Ć s Fases 4-8 (commits `90ed705` e `8b3d4bc`), e a mesclagem gerou **conflitos que quebravam a aplicação**. AnĆ”lise dos commits e correƧƵes: + +### šŸ”“ Problemas crĆ­ticos encontrados e corrigidos + +**1. Migration da Fase 2 quebrada** (`20260610_add_fase2_fields_to_users.rb`) +- Timestamp curto (8 dĆ­gitos) fazia ela rodar ANTES da `create_users` → erro "table does not exist" +- Adicionava coluna `ativo` que jĆ” existia → erro de coluna duplicada +- Criava `pin_acesso` duplicando o `pin_code` existente +- āœ… **Corrigida:** reescrita como `20260101000010_add_devise_trackable_to_users.rb` — só trackable/lockable, timestamp correto + +**2. Campo de PIN inconsistente** — Fase 2 usava `pin_acesso`, o model e as Fases 7/8 usam `pin_code`. PINs cadastrados no CRUD nĆ£o funcionariam no login. +- āœ… **Corrigido:** padronizado `pin_code` em todos os arquivos + +**3. Campo de nome inconsistente** — CRUD de usuĆ”rios usava `:name`, o schema usa `nome` → o CRUD quebrava ao salvar. +- āœ… **Corrigido:** padronizado `nome` + +**4. Controllers fora do namespace** — As rotas esperam `Admin::UsuariosController` e `Admin::ConfiguracoesController`, mas os controllers foram criados na raiz → `/admin/usuarios` dava "uninitialized constant" e os controllers ficavam inacessĆ­veis. +- āœ… **Corrigido:** movidos para `app/controllers/admin/` + views para `app/views/admin/` + paths atualizados (`admin_usuarios_path` etc.) + +**5. Dashboard (Fase 3) chamava mĆ©todos inexistentes** — `Entrega.do_mes` e `Configuracao.mapa_de_precos` foram sobrescritos pelo commit das Fases 4-6 → **a raiz do site quebrava** (root = dashboard#index). +- āœ… **Corrigido:** scope `do_mes` e mĆ©todo `mapa_de_precos` restaurados nos models, junto com `tipo_label`/`icone` usados pelas views de configuraƧƵes + +**6. AuditoriaLog com 2 assinaturas** — Fase 2 chamava `registrar(user, 'acao', ip)` posicional; o model usa keyword args → `ArgumentError` em login PIN, CRUD de usuĆ”rios e configuraƧƵes. +- āœ… **Corrigido:** todas as chamadas convertidas para a assinatura do model + +**7. Rotas/controllers ausentes** +- `Admin::AuditoriaLogsController` tinha rota mas nĆ£o existia → āœ… criado com view de listagem e filtros +- `toggle_tema` e `toggle_ativo` existiam nos controllers mas sem rota → āœ… rotas adicionadas +- Controller de configuraƧƵes usava campo `tipo` que nĆ£o existe (schema usa `chave`) → āœ… corrigido + +### 🟔 DuplicaƧƵes removidas (arquivos órfĆ£os) +- `app/controllers/motorista_controller.rb` + `app/views/motorista/index.html.erb` — a rota `/motorista` usa `Motorista::DashboardController` (Fase 8) +- `app/views/layouts/_sidebar.html.erb` — o layout renderiza `_navbar.html.erb` +- Seeds dos 3 motoristas de teste (JoĆ£o/1234, Maria/5678, Carlos/9012) restaurados — tinham sido sobrescritos + +### āš ļø Observação sobre login PIN duplicado +Existem **dois fluxos de login por PIN** funcionais: a aba PIN na tela Devise (`/auth/login`, Fase 2) e a tela dedicada (`/motorista/login`, Fase 8 — usada pelo QR Code do holerite). Ambos usam `pin_code` e funcionam; recomenda-se manter os dois (a tela dedicada Ć© melhor para mobile) ou unificar futuramente. ### šŸ“‚ Arquivos das Fases 4, 5 e 6 @@ -228,33 +272,35 @@ config/routes.rb # ATUALIZADO: /motorista/log 6. Logout → `/motorista/login` → entrar com PIN do motorista 7. Conferir cards de valores → baixar próprio holerite → sair -### ā–¶ļø Para continuar (faltam apenas Fases 2 e 3) +### ā–¶ļø Próximos passos (deploy) -Cole este contexto no inĆ­cio da conversa com o Claude: +O projeto estĆ” completo. Para colocar em produção: +```bash +# 1. Configurar .env com credenciais reais (DB_HOST do PostgreSQL existente) +cp .env.example .env && nano .env + +# 2. Subir e migrar +docker-compose up -d --build +docker-compose exec app bundle exec rails db:create db:migrate db:seed + +# 3. Ativar o cron do job de 1h +docker-compose exec app bundle exec whenever --update-crontab + +# 4. Testar o fluxo end-to-end (seção de teste acima) ``` -Continue o Sistema de Controle de Custos LogĆ­stica da Gade Hospitalar. -CHECKPOINT — FASES 1, 4, 5, 6, 7 e 8 CONCLUƍDAS: -- Rails 7+ com Docker, PostgreSQL externo, Tailwind (preto #0a0a0a / laranja #f97316) -- Models: Entrega (read-only db_reem_simplerout_2026), User (Devise+roles+pin_code - +login_token), Configuracao, Consolidacao (+route_ids), ConsolidacaoMotorista, - ConsolidacaoEntrega, HistoricoEstimado, AuditoriaLog — 9 migrations -- Fase 4: Whenever (1h) + job + rake historico:atualizar + API /api/v1/dashboard/metricas -- Fase 5: ConsolidacoesController (filtros, multi-select) + Wizard Passo 1 -- Fase 6: validar/classificar/classificar_em_massa/revisar + toggles + Stimulus -- Fase 7: PDFs Prawn (Pdf::RelatorioMotoristaPdf, Pdf::HoleritePdf com QR code) - + modal preview em consolidacoes/show -- Fase 8: login motorista por PIN (/motorista/login) e QR (/motorista/acesso/:token) - + painel motorista (2 cards + holerites) + NotificacaoService (Twilio/ActionMailer) +**Credenciais de teste (seeds):** -FALTAM SOMENTE: -- FASE 2: tela de login Devise estilizada + CRUD usuĆ”rios (admin/usuarios) + - CRUD pilares de preƧo (admin/configuracoes) + tela auditoria + toggle tema claro/escuro -- FASE 3: DashboardController + view com cards grandes (valor estimado, entregas - do dia/mĆŖs, motoristas ativos) + grĆ”fico Chart.js do historico_estimados -Consulte o README.md do repositório para a lista completa de arquivos. -``` +| UsuĆ”rio | Login | Senha/PIN | +|---------|-------|-----------| +| Admin | admin@gade.com | Gade@2026! | +| Gerente | gerente@gade.com | Gade@2026! | +| Motorista JoĆ£o Silva | PIN | 1234 | +| Motorista Maria Santos | PIN | 5678 | +| Motorista Carlos Souza | PIN | 9012 | + +āš ļø Altere as senhas padrĆ£o no primeiro acesso em produção. --- diff --git a/app/controllers/admin/auditoria_logs_controller.rb b/app/controllers/admin/auditoria_logs_controller.rb new file mode 100644 index 0000000..f8a95a4 --- /dev/null +++ b/app/controllers/admin/auditoria_logs_controller.rb @@ -0,0 +1,13 @@ +# app/controllers/admin/auditoria_logs_controller.rb +class Admin::AuditoriaLogsController < ApplicationController + def index + authorize AuditoriaLog, policy_class: ApplicationPolicy + + @logs = AuditoriaLog.recentes.limit(200) + @logs = @logs.por_user(params[:user_id]) if params[:user_id].present? + @logs = @logs.where(acao: params[:acao]) if params[:acao].present? + @logs = @logs.por_entidade(params[:entidade]) if params[:entidade].present? + + @usuarios = User.por_nome + end +end diff --git a/app/controllers/admin/configuracoes_controller.rb b/app/controllers/admin/configuracoes_controller.rb new file mode 100644 index 0000000..6477b5f --- /dev/null +++ b/app/controllers/admin/configuracoes_controller.rb @@ -0,0 +1,43 @@ +# app/controllers/configuracoes_controller.rb +class Admin::ConfiguracoesController < ApplicationController + before_action :set_configuracao, only: [:edit, :update] + + def index + authorize Configuracao + @configuracoes = Configuracao.all.order(:chave) + end + + def edit + authorize @configuracao + end + + def update + authorize @configuracao + + valor_anterior = @configuracao.valor + + if @configuracao.update(configuracao_params) + AuditoriaLog.registrar(user: current_user, acao: 'editar_preco', entidade: 'Configuracao', entidade_id: @configuracao.id, dados_novos: { detalhes: "#{@configuracao.chave}: R$ #{valor_anterior} → R$ #{@configuracao.valor}" }, request: request) + redirect_to admin_configuracoes_path, notice: "PreƧo de #{@configuracao.tipo_label} atualizado." + else + render :edit, status: :unprocessable_entity + end + end + + # POST /configuracoes/toggle_tema + def toggle_tema + skip_authorization + session[:tema] = session[:tema] == 'light' ? 'dark' : 'light' + redirect_back(fallback_location: dashboard_path) + end + + private + + def set_configuracao + @configuracao = Configuracao.find(params[:id]) + end + + def configuracao_params + params.require(:configuracao).permit(:valor, :descricao) + end +end diff --git a/app/controllers/admin/usuarios_controller.rb b/app/controllers/admin/usuarios_controller.rb new file mode 100644 index 0000000..1de528c --- /dev/null +++ b/app/controllers/admin/usuarios_controller.rb @@ -0,0 +1,84 @@ +# app/controllers/usuarios_controller.rb +class Admin::UsuariosController < ApplicationController + before_action :set_usuario, only: [:show, :edit, :update, :destroy, :toggle_ativo] + + def index + authorize User + @usuarios = policy_scope(User).order(:nome).page(params[:page]).per(20) + @roles = User.roles.keys + end + + def show + authorize @usuario + end + + def new + @usuario = User.new + authorize @usuario + end + + def create + @usuario = User.new(usuario_params) + authorize @usuario + + if @usuario.save + AuditoriaLog.registrar(user: current_user, acao: 'criar_usuario', entidade: 'User', dados_novos: { detalhes: "Criou usuĆ”rio #{@usuario.email} (#{@usuario.role})" }, request: request) + redirect_to admin_usuarios_path, notice: 'UsuĆ”rio criado com sucesso.' + else + render :new, status: :unprocessable_entity + end + end + + def edit + authorize @usuario + end + + def update + authorize @usuario + + if @usuario.update(usuario_params_update) + AuditoriaLog.registrar(user: current_user, acao: 'editar_usuario', entidade: 'User', dados_novos: { detalhes: "Editou usuĆ”rio #{@usuario.email}" }, request: request) + redirect_to admin_usuarios_path, notice: 'UsuĆ”rio atualizado.' + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + authorize @usuario + + if @usuario == current_user + redirect_to admin_usuarios_path, alert: 'VocĆŖ nĆ£o pode excluir sua própria conta.' + return + end + + @usuario.destroy + AuditoriaLog.registrar(user: current_user, acao: 'excluir_usuario', entidade: 'User', dados_novos: { detalhes: "Excluiu usuĆ”rio #{@usuario.email}" }, request: request) + redirect_to admin_usuarios_path, notice: 'UsuĆ”rio removido.' + end + + def toggle_ativo + authorize @usuario, :update? + @usuario.update!(ativo: !@usuario.ativo) + status = @usuario.ativo? ? 'ativado' : 'desativado' + AuditoriaLog.registrar(user: current_user, acao: "usuario_#{status}", entidade: \'User\', dados_novos: { detalhes: "#{@usuario.email} foi #{status}" }, request: request) + redirect_to admin_usuarios_path, notice: "UsuĆ”rio #{status} com sucesso." + end + + private + + def set_usuario + @usuario = User.find(params[:id]) + end + + def usuario_params + params.require(:user).permit(:nome, :email, :password, :password_confirmation, + :role, :pin_code, :ativo) + end + + def usuario_params_update + permitted = [:nome, :email, :role, :pin_code, :ativo] + permitted += [:password, :password_confirmation] if params[:user][:password].present? + params.require(:user).permit(permitted) + end +end diff --git a/app/controllers/users/sessions_controller.rb b/app/controllers/users/sessions_controller.rb index ea2dc18..edf3e97 100644 --- a/app/controllers/users/sessions_controller.rb +++ b/app/controllers/users/sessions_controller.rb @@ -41,11 +41,11 @@ class Users::SessionsController < Devise::SessionsController def handle_pin_login pin = params[:user][:pin].to_s.strip - user = User.find_by(pin_acesso: pin, role: 'motorista') + user = User.find_by(pin_code: pin, role: 'motorista') if user&.active? sign_in(user) - AuditoriaLog.registrar(user, 'login_pin', request.remote_ip) + AuditoriaLog.registrar(user: user, acao: 'login_pin', entidade: 'User', dados_novos: { detalhes: "" }, request: request) redirect_to motorista_path, notice: "Bem-vindo, #{user.nome_display}!" else flash.now[:alert] = 'PIN invĆ”lido ou motorista inativo.' diff --git a/app/models/configuracao.rb b/app/models/configuracao.rb index ccd8756..4b61c20 100644 --- a/app/models/configuracao.rb +++ b/app/models/configuracao.rb @@ -44,6 +44,45 @@ class Configuracao < ApplicationRecord valor('preco_desconto').to_f end + # Mapa usado pelo DashboardController (Fase 3) + def self.mapa_de_precos + { + entrega: preco_entrega, + retirada: preco_retirada, + bonus: preco_bonus, + desconto: preco_desconto + } + end + + LABELS = { + 'preco_entrega' => 'Entrega Normal', + 'preco_retirada' => 'Retirada', + 'preco_bonus' => 'BĆ“nus', + 'preco_desconto' => 'Desconto', + 'notificacao_whatsapp' => 'Notificação WhatsApp', + 'notificacao_email' => 'Notificação E-mail', + 'empresa_nome' => 'Nome da Empresa' + }.freeze + + ICONES = { + 'preco_entrega' => '🚚', + 'preco_retirada' => 'šŸ“¦', + 'preco_bonus' => '⭐', + 'preco_desconto' => 'āš ļø', + 'notificacao_whatsapp' => 'šŸ’¬', + 'notificacao_email' => 'āœ‰ļø', + 'empresa_nome' => 'šŸ¢' + }.freeze + + # Usados pelas views admin/configuracoes (Fase 2) + def tipo_label + LABELS[chave] || chave.humanize + end + + def icone + ICONES[chave] || 'āš™ļø' + end + def moeda? CHAVES_MOEDA.include?(chave) end diff --git a/app/models/entrega.rb b/app/models/entrega.rb index 7e18d34..1c4ed77 100644 --- a/app/models/entrega.rb +++ b/app/models/entrega.rb @@ -31,6 +31,10 @@ class Entrega < ApplicationRecord where(route_id: route_id) } + scope :do_mes, ->(data = Date.current) { + where(planned_date: data.beginning_of_month..data.end_of_month) + } + scope :da_conta_gade, -> { where(account_id: ENV.fetch('DB_EXISTING_ACCOUNT_ID', 95907).to_i) } diff --git a/app/views/admin/auditoria_logs/index.html.erb b/app/views/admin/auditoria_logs/index.html.erb new file mode 100644 index 0000000..7f5aaa8 --- /dev/null +++ b/app/views/admin/auditoria_logs/index.html.erb @@ -0,0 +1,43 @@ +<%# app/views/admin/auditoria_logs/index.html.erb %> +<% content_for :title, 'Auditoria' %> + +

šŸ” Auditoria

+ +<%= form_with url: admin_auditoria_logs_path, method: :get, + class: 'bg-[#1a1a1a] border border-[#2a2a2a] rounded-xl p-4 mb-6 flex flex-wrap gap-3' do %> + <%= select_tag :user_id, + options_from_collection_for_select(@usuarios, :id, :nome_display, params[:user_id]), + include_blank: 'Todos os usuÔrios', + class: 'bg-[#0a0a0a] border border-[#2a2a2a] text-white rounded-lg px-3 py-2.5' %> + <%= text_field_tag :acao, params[:acao], placeholder: 'Ação (ex: finalizar)', + class: 'bg-[#0a0a0a] border border-[#2a2a2a] text-white rounded-lg px-3 py-2.5' %> + <%= submit_tag 'Filtrar', class: 'bg-orange-500 hover:bg-orange-600 text-black font-bold px-5 rounded-lg cursor-pointer' %> +<% end %> + +
+ + + + + + + + + + + + <% @logs.each do |log| %> + + + + + + + + <% end %> + +
QuandoUsuÔrioAçãoEntidadeDetalhes
<%= l log.created_at, format: :short %><%= User.find_by(id: log.user_id)&.nome_display || "##{log.user_id}" %><%= log.acao %><%= log.entidade %><%= " ##{log.entidade_id}" if log.entidade_id %><%= log.dados_novos['detalhes'] || log.dados_novos.to_s.first(80) %>
+ <% if @logs.empty? %> +

Nenhum registro de auditoria encontrado.

+ <% end %> +
diff --git a/app/views/admin/configuracoes/edit.html.erb b/app/views/admin/configuracoes/edit.html.erb new file mode 100644 index 0000000..a84647e --- /dev/null +++ b/app/views/admin/configuracoes/edit.html.erb @@ -0,0 +1,58 @@ +<%# app/views/configuracoes/edit.html.erb %> +
+
+

+ <%= @configuracao.icone %> Editar: <%= @configuracao.tipo_label %> +

+

Atualize o valor do pilar de preƧo

+
+ + <%= render 'shared/flash' %> + + <%= form_with(model: @configuracao, url: admin_configuracao_path(@configuracao), method: :patch, + class: 'bg-[#1a1a1a] rounded-2xl border border-white/5 p-8 space-y-6') do |f| %> + + <% if @configuracao.errors.any? %> +
+ +
+ <% end %> + +
+ <%= f.label :valor, 'Valor (R$)', class: 'block text-sm font-medium text-gray-300 mb-1.5' %> +
+ R$ + <%= f.number_field :valor, + step: 0.01, + min: 0, + class: 'w-full pl-10 pr-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl + text-white text-xl font-bold focus:outline-none focus:border-[#f97316] + focus:ring-1 focus:ring-[#f97316] transition-colors', + placeholder: '0.00' %> +
+

Valor atual: <%= moeda(@configuracao.valor) %>

+
+ +
+ <%= f.label :descricao, 'Descrição (opcional)', class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.text_area :descricao, rows: 2, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1 + focus:ring-[#f97316] transition-colors resize-none', + placeholder: 'Ex: Entrega padrão para UBS e EMAD' %> +
+ +
+ <%= link_to 'Cancelar', admin_configuracoes_path, + class: 'px-6 py-3 text-gray-400 hover:text-white border border-white/10 + hover:border-white/20 rounded-xl transition-colors' %> + <%= f.submit 'Salvar PreƧo', + class: 'px-8 py-3 bg-[#f97316] hover:bg-orange-500 text-white font-semibold + rounded-xl transition-colors cursor-pointer min-h-[48px]' %> +
+ <% end %> +
diff --git a/app/views/admin/configuracoes/index.html.erb b/app/views/admin/configuracoes/index.html.erb new file mode 100644 index 0000000..2e184cb --- /dev/null +++ b/app/views/admin/configuracoes/index.html.erb @@ -0,0 +1,64 @@ +<%# app/views/configuracoes/index.html.erb %> +
+ +
+

ConfiguraƧƵes

+

Pilares de preço e parâmetros do sistema

+
+ + <%= render 'shared/flash' %> + + <%# Pilares de preƧo %> +
+

šŸ’° Pilares de PreƧo

+
+ <% @configuracoes.each do |cfg| %> +
+
+
<%= cfg.icone %>
+ <% if policy(cfg).edit? %> + <%= link_to edit_admin_configuracao_path(cfg), + class: 'opacity-0 group-hover:opacity-100 transition-opacity p-1.5 + text-gray-500 hover:text-white hover:bg-white/10 rounded-lg' do %> + + + + <% end %> + <% end %> +
+

<%= cfg.tipo_label %>

+

<%= moeda(cfg.valor) %>

+ <% if cfg.descricao.present? %> +

<%= cfg.descricao %>

+ <% end %> +
+ <% end %> +
+
+ + <%# InformaƧƵes do banco externo %> +
+

šŸ—„ļø Banco de Dados Externo

+
+
+

Tabela monitorada

+

db_reem_simplerout_2026

+
+
+

Account ID

+

95907 (Gade Hospitalar)

+
+
+

Atualização

+

A cada 1 hora

+
+
+

+ + + + Somente leitura — nunca alterar, deletar ou truncar esta tabela. +

+
+
diff --git a/app/views/admin/usuarios/_form.html.erb b/app/views/admin/usuarios/_form.html.erb new file mode 100644 index 0000000..de11cbd --- /dev/null +++ b/app/views/admin/usuarios/_form.html.erb @@ -0,0 +1,153 @@ +<%# app/views/usuarios/_form.html.erb %> +
+ +
+

+ <%= usuario.new_record? ? 'Novo UsuƔrio' : "Editar: #{usuario.nome}" %> +

+

+ <%= usuario.new_record? ? 'Preencha os dados para criar um novo acesso' : 'Atualize as informaƧƵes do usuƔrio' %> +

+
+ + <%= render 'shared/flash' %> + + <%= form_with(model: usuario, url: usuario.new_record? ? admin_usuarios_path : admin_usuario_path(usuario), + method: usuario.new_record? ? :post : :patch, + class: 'bg-[#1a1a1a] rounded-2xl border border-white/5 p-8 space-y-6') do |f| %> + + <% if usuario.errors.any? %> +
+

+ <%= pluralize(usuario.errors.count, 'erro', 'erros') %> encontrado<%= usuario.errors.count > 1 ? 's' : '' %>: +

+ +
+ <% end %> + +
+ <%# Nome %> +
+ <%= f.label :nome, 'Nome completo', class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.text_field :nome, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1 + focus:ring-[#f97316] transition-colors', + placeholder: 'João da Silva' %> +
+ + <%# Perfil %> +
+ <%= f.label :role, 'Perfil de acesso', class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.select :role, + options_for_select(role_options_for_select, usuario.role), + {}, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + focus:outline-none focus:border-[#f97316] focus:ring-1 focus:ring-[#f97316] + transition-colors cursor-pointer' %> +
+ + <%# Ativo toggle %> +
+
+ <%= f.label :ativo, 'UsuƔrio ativo', class: 'block text-sm font-medium text-gray-300' %> +

UsuÔrios inativos não conseguem fazer login

+
+ +
+
+ + <%# E-mail e senha (não motorista) %> +
+
+

Credenciais de acesso

+
+
+ <%= f.label :email, 'E-mail', class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.email_field :email, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1 + focus:ring-[#f97316] transition-colors', + placeholder: 'usuario@gade.com' %> +
+
+ <%= f.label :password, + usuario.new_record? ? 'Senha' : 'Nova senha (deixe em branco para manter)', + class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.password_field :password, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1 + focus:ring-[#f97316] transition-colors', + placeholder: '••••••••' %> +
+
+ <%= f.label :password_confirmation, 'Confirmar senha', + class: 'block text-sm font-medium text-gray-300 mb-1.5' %> + <%= f.password_field :password_confirmation, + class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white + placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1 + focus:ring-[#f97316] transition-colors', + placeholder: '••••••••' %> +
+
+
+
+ + <%# PIN (motorista) %> + + + <%# BotƵes %> +
+ <%= link_to 'Cancelar', admin_usuarios_path, + class: 'px-6 py-3 text-gray-400 hover:text-white border border-white/10 + hover:border-white/20 rounded-xl transition-colors' %> + <%= f.submit usuario.new_record? ? 'Criar UsuƔrio' : 'Salvar AlteraƧƵes', + class: 'px-8 py-3 bg-[#f97316] hover:bg-orange-500 text-white font-semibold + rounded-xl transition-colors cursor-pointer min-h-[48px]' %> +
+ <% end %> +
+ + diff --git a/app/views/admin/usuarios/edit.html.erb b/app/views/admin/usuarios/edit.html.erb new file mode 100644 index 0000000..8f44bbe --- /dev/null +++ b/app/views/admin/usuarios/edit.html.erb @@ -0,0 +1,2 @@ +<%# app/views/usuarios/edit.html.erb %> +<%= render 'form', usuario: @usuario %> diff --git a/app/views/admin/usuarios/index.html.erb b/app/views/admin/usuarios/index.html.erb new file mode 100644 index 0000000..8d49f99 --- /dev/null +++ b/app/views/admin/usuarios/index.html.erb @@ -0,0 +1,120 @@ +<%# app/views/usuarios/index.html.erb %> +
+ + <%# Header %> +
+
+

UsuƔrios

+

Gerencie o acesso ao sistema

+
+ <% if policy(User).create? %> + <%= link_to new_admin_usuario_path, + class: 'flex items-center gap-2 px-5 py-3 bg-[#f97316] hover:bg-orange-500 + text-white font-semibold rounded-xl transition-colors min-h-[48px]' do %> + + + + Novo UsuƔrio + <% end %> + <% end %> +
+ + <%# Flash %> + <%= render 'shared/flash' %> + + <%# Tabela %> +
+ + + + + + + + + + + + <% @usuarios.each do |usuario| %> + + + + + + + + <% end %> + + <% if @usuarios.empty? %> + + + + <% end %> + +
NomeE-mail / PINPerfilStatusAƧƵes
+
+
+ <%= usuario.nome.to_s[0].upcase %> +
+ <%= usuario.nome %> +
+
+ <% if usuario.motorista? && usuario.pin_code.present? %> +
PIN: ••••
+ <% else %> +
<%= usuario.email %>
+ <% end %> +
+ <%= badge_role(usuario.role) %> + + <%= badge_status_usuario(usuario.ativo?) %> + +
+ <% if policy(usuario).edit? %> + <%= link_to edit_admin_usuario_path(usuario), + class: 'p-2 text-gray-400 hover:text-white hover:bg-white/10 rounded-lg transition-colors', + title: 'Editar' do %> + + + + <% end %> + <% end %> + + <% if policy(usuario).toggle_ativo? %> + <%= button_to toggle_ativo_usuario_path(usuario), method: :post, + class: "p-2 rounded-lg transition-colors #{usuario.ativo? ? 'text-green-400 hover:bg-green-900/30' : 'text-red-400 hover:bg-red-900/30'}", + title: usuario.ativo? ? 'Desativar' : 'Ativar', + data: { confirm: "#{usuario.ativo? ? 'Desativar' : 'Ativar'} #{usuario.nome}?" } do %> + + + + <% end %> + <% end %> + + <% if policy(usuario).destroy? %> + <%= button_to admin_usuario_path(usuario), method: :delete, + class: 'p-2 text-gray-600 hover:text-red-400 hover:bg-red-900/20 rounded-lg transition-colors', + title: 'Excluir', + data: { confirm: "Excluir #{usuario.nome} permanentemente?" } do %> + + + + <% end %> + <% end %> +
+
+
šŸ‘„
+

Nenhum usuƔrio encontrado.

+
+ + <% if @usuarios.respond_to?(:total_pages) && @usuarios.total_pages > 1 %> +
+ <%= paginate @usuarios %> +
+ <% end %> +
+
diff --git a/app/views/admin/usuarios/new.html.erb b/app/views/admin/usuarios/new.html.erb new file mode 100644 index 0000000..d0c9862 --- /dev/null +++ b/app/views/admin/usuarios/new.html.erb @@ -0,0 +1,2 @@ +<%# app/views/usuarios/new.html.erb %> +<%= render 'form', usuario: @usuario %> diff --git a/config/routes.rb b/config/routes.rb index ce70f77..cba2dc2 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -44,9 +44,13 @@ Rails.application.routes.draw do # ConfiguraƧƵes (apenas admin/gerente) namespace :admin do - resources :usuarios, except: [:show] - resources :configuracoes, only: [:index, :update] - resources :auditoria_logs, only: [:index] + resources :usuarios, except: [:show] do + member { patch :toggle_ativo } + end + resources :configuracoes, only: [:index, :edit, :update] do + collection { post :toggle_tema } + end + resources :auditoria_logs, only: [:index] end # API interna — Dashboard mĆ©tricas diff --git a/db/migrate/20260101000010_add_devise_trackable_to_users.rb b/db/migrate/20260101000010_add_devise_trackable_to_users.rb new file mode 100644 index 0000000..bb8d135 --- /dev/null +++ b/db/migrate/20260101000010_add_devise_trackable_to_users.rb @@ -0,0 +1,20 @@ +# Migration corrigida da Fase 2: +# - Timestamp no padrĆ£o (roda DEPOIS da create_users) +# - Removidos pin_acesso e ativo (jĆ” existem como pin_code e ativo na create_users) +# - Mantidos apenas os campos Devise trackable + lockable +class AddDeviseTrackableToUsers < ActiveRecord::Migration[7.1] + def change + # Trackable + add_column :users, :sign_in_count, :integer, default: 0, null: false + add_column :users, :current_sign_in_at, :datetime + add_column :users, :last_sign_in_at, :datetime + add_column :users, :current_sign_in_ip, :string + add_column :users, :last_sign_in_ip, :string + + # Lockable + add_column :users, :failed_attempts, :integer, default: 0, null: false + add_column :users, :unlock_token, :string + add_column :users, :locked_at, :datetime + add_index :users, :unlock_token, unique: true + end +end diff --git a/db/seeds.rb b/db/seeds.rb index c7d8ab7..fed4106 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -45,3 +45,16 @@ puts "" puts "āœ… Seeds concluĆ­dos!" puts " Admin: admin@gade.com / Gade@2026!" puts " āš ļø ALTERE A SENHA DO ADMIN NO PRIMEIRO ACESSO!" + +# ── Motoristas de teste (Fase 2 — Victor) ──────────────────── +[ + { nome: 'JoĆ£o Silva', pin: '1234' }, + { nome: 'Maria Santos', pin: '5678' }, + { nome: 'Carlos Souza', pin: '9012' }, +].each do |m| + User.find_or_create_by!(nome: m[:nome], role: :motorista) do |u| + u.pin_code = m[:pin] + u.ativo = true + end + puts " āœ… Motorista: #{m[:nome]} / PIN: #{m[:pin]}" +end diff --git a/historico_commits.txt b/historico_commits.txt new file mode 100644 index 0000000..9142dfa --- /dev/null +++ b/historico_commits.txt @@ -0,0 +1,134 @@ +8b3d4bc Fases 7 e 8 — PDFs Prawn + QR + Painel Motorista + NotificaƧƵes + Gemfile | 6 +- + README.md | 92 +++++++++++++---- + app/controllers/consolidacoes_controller.rb | 46 ++++++++- + app/controllers/motorista/dashboard_controller.rb | 39 +++++++ + app/controllers/motorista/sessoes_controller.rb | 44 ++++++++ + app/mailers/application_mailer.rb | 5 + + app/mailers/consolidacao_mailer.rb | 14 +++ + app/models/user.rb | 5 + + app/services/notificacao_service.rb | 68 ++++++++++++ + app/services/pdf/base_pdf.rb | 68 ++++++++++++ + app/services/pdf/holerite_pdf.rb | 97 ++++++++++++++++++ + app/services/pdf/relatorio_motorista_pdf.rb | 77 ++++++++++++++ + .../consolidacao_mailer/pagamento_fechado.html.erb | 41 ++++++++ + app/views/consolidacoes/preview_holerite.html.erb | 63 ++++++++++++ + app/views/consolidacoes/show.html.erb | 114 +++++++++++++++++++++ + app/views/layouts/mailer.html.erb | 10 ++ + app/views/motorista/dashboard/index.html.erb | 73 +++++++++++++ + app/views/motorista/sessoes/new.html.erb | 75 ++++++++++++++ + config/initializers/smtp.rb | 17 +++ + config/routes.rb | 7 +- + .../20260101000009_add_login_token_to_users.rb | 6 ++ + 21 files changed, 943 insertions(+), 24 deletions(-) +90ed705 Fases 4, 5 e 6 — Job 1h + Auditoria + Consolidação + Wizard de validação + README.md | 240 ++++++++++----------- + app/controllers/api/v1/dashboard_controller.rb | 30 +++ + app/controllers/application_controller.rb | 26 ++- + app/controllers/concerns/auditavel.rb | 22 ++ + .../consolidacao_entregas_controller.rb | 168 +++++++++++++++ + app/controllers/consolidacoes_controller.rb | 131 +++++++++++ + app/helpers/application_helper.rb | 102 +++------ + app/javascript/controllers/validacao_controller.js | 145 +++++++++++++ + app/jobs/application_job.rb | 5 + + app/jobs/atualizar_historico_estimado_job.rb | 24 +++ + app/models/auditoria_log.rb | 31 +-- + app/models/configuracao.rb | 78 ++++--- + app/models/consolidacao.rb | 83 +++++-- + app/models/entrega.rb | 89 ++++++-- + app/models/user.rb | 76 ++++--- + app/policies/application_policy.rb | 41 +--- + app/policies/consolidacao_policy.rb | 15 ++ + app/policies/dashboard_policy.rb | 10 + + app/views/consolidacao_entregas/revisar.html.erb | 74 +++++++ + app/views/consolidacao_entregas/validar.html.erb | 166 ++++++++++++++ + app/views/consolidacoes/index.html.erb | 65 ++++++ + app/views/consolidacoes/new.html.erb | 89 ++++++++ + app/views/consolidacoes/wizard.html.erb | 91 ++++++++ + app/views/layouts/application.html.erb | 216 ++++++------------- + config/routes.rb | 82 ++++--- + config/schedule.rb | 12 ++ + ...0260101000008_add_route_ids_to_consolidacoes.rb | 6 + + db/seeds.rb | 101 +++------ + lib/tasks/historico.rake | 13 ++ + 29 files changed, 1616 insertions(+), 615 deletions(-) +b77fc01 Atualização README - Fase 2 e 3 + Projeto-Reem-Custo | 1 + + README.md | 189 ++++++++++++++++++++++++++++++++++------------------- + 2 files changed, 124 insertions(+), 66 deletions(-) +bd60e4c Atualizou o MD + README.md | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) +4724847 implantação da fase 2 e 3 + README_FASE2_3.md | 163 +++++ + app/controllers/application_controller.rb | 26 +- + app/controllers/configuracoes_controller.rb | 44 ++ + app/controllers/dashboard_controller.rb | 77 +++ + app/controllers/motorista_controller.rb | 42 ++ + app/controllers/users/sessions_controller.rb | 56 ++ + app/controllers/usuarios_controller.rb | 88 +++ + app/helpers/application_helper.rb | 102 ++- + app/models/auditoria_log.rb | 31 +- + app/models/configuracao.rb | 78 +-- + app/models/consolidacao.rb | 83 +-- + app/models/entrega.rb | 89 +-- + app/models/user.rb | 76 +-- + app/policies/application_policy.rb | 41 +- + app/policies/configuracao_policy.rb | 20 + + app/policies/user_policy.rb | 46 ++ + app/views/configuracoes/edit.html.erb | 58 ++ + app/views/configuracoes/index.html.erb | 64 ++ + app/views/dashboard/index.html.erb | 234 +++++++ + app/views/devise/sessions/new.html.erb | 231 +++++++ + app/views/layouts/_sidebar.html.erb | 64 ++ + app/views/layouts/application.html.erb | 216 ++++--- + app/views/motorista/index.html.erb | 96 +++ + app/views/shared/_flash.html.erb | 18 + + app/views/usuarios/_form.html.erb | 153 +++++ + app/views/usuarios/edit.html.erb | 2 + + app/views/usuarios/index.html.erb | 120 ++++ + app/views/usuarios/new.html.erb | 2 + + config/routes.rb | 76 ++- + db/migrate/20260610_add_fase2_fields_to_users.rb | 25 + + db/seeds.rb | 101 ++- + prompt_sistema_logistica_final.html | 771 +++++++++++++++++++++++ + setup_fase2_3.sh | 54 ++ + 33 files changed, 2916 insertions(+), 431 deletions(-) +d37237e Alteração de alguns arquivos para retirar do yaml o container Postgres pois ja tem um + .env.example | 24 +++--- + README.md | 210 +++++++++++++++++++++++++++++++++++++++-------------- + docker-compose.yml | 25 +------ + setup_git.sh | 13 ++-- + 4 files changed, 175 insertions(+), 97 deletions(-) +eb81286 Initial commit - Fase 1: Setup Rails + Docker + .env.example | 43 ++++++++ + .gitignore | 61 +++++++++++ + Dockerfile | 29 ++++++ + Gemfile | 55 ++++++++++ + README.md | 113 +++++++++++++++++++++ + app/controllers/application_controller.rb | 27 +++++ + app/helpers/application_helper.rb | 46 +++++++++ + app/models/auditoria_log.rb | 29 ++++++ + app/models/configuracao.rb | 55 ++++++++++ + app/models/consolidacao.rb | 75 ++++++++++++++ + app/models/consolidacao_entrega.rb | 32 ++++++ + app/models/consolidacao_motorista.rb | 29 ++++++ + app/models/entrega.rb | 88 ++++++++++++++++ + app/models/historico_estimado.rb | 32 ++++++ + app/models/user.rb | 69 +++++++++++++ + app/policies/application_policy.rb | 30 ++++++ + app/views/layouts/_navbar.html.erb | 92 +++++++++++++++++ + app/views/layouts/application.html.erb | 95 +++++++++++++++++ + config/routes.rb | 50 +++++++++ + db/migrate/20260101000001_create_users.rb | 27 +++++ + db/migrate/20260101000002_create_configuracoes.rb | 14 +++ + db/migrate/20260101000003_create_consolidacoes.rb | 23 +++++ + ...0260101000004_create_consolidacao_motoristas.rb | 17 ++++ + .../20260101000005_create_consolidacao_entregas.rb | 23 +++++ + .../20260101000006_create_historico_estimados.rb | 13 +++ + db/migrate/20260101000007_create_auditoria_logs.rb | 22 ++++ + db/seeds.rb | 47 +++++++++ + docker-compose.yml | 49 +++++++++ + setup_git.sh | 46 +++++++++ + tailwind.config.js | 59 +++++++++++ + 30 files changed, 1390 insertions(+) diff --git a/reem-notas.zip b/reem-notas.zip new file mode 100644 index 0000000..8ef1a8b Binary files /dev/null and b/reem-notas.zip differ