# app/models/entrega.rb # # Model de LEITURA para a tabela existente da Gade Hospitalar. # NUNCA criar migration para esta tabela. # NUNCA executar INSERT, UPDATE, DELETE ou DROP nesta tabela. # class Entrega < ApplicationRecord self.table_name = 'db_reem_simplerout_2026' self.primary_key = 'tracking_id' # Apenas leitura — segurança contra mutações acidentais def readonly? true end # ── Scopes ────────────────────────────────────────────────── scope :concluidas, -> { where(status: 'completed') } scope :com_checkin, -> { where.not(checkin: nil) } scope :pagas, -> { concluidas.com_checkin } scope :pendentes, -> { where.not(status: 'completed') } scope :no_periodo, ->(inicio, fim) { where(planned_date: inicio.to_date..fim.to_date) } scope :do_motorista, ->(nome) { where(driver: nome) } scope :da_rota, ->(route_id) { where(route_id: route_id) } scope :da_conta_gade, -> { where(account_id: ENV.fetch('DB_EXISTING_ACCOUNT_ID', 95907).to_i) } # ── Métodos de classe ──────────────────────────────────────── # Lista motoristas únicos (para selects, consolidações) def self.motoristas_ativos(inicio: nil, fim: nil) base = da_conta_gade base = base.no_periodo(inicio, fim) if inicio && fim base.distinct.order(:driver).pluck(:driver).compact.reject(&:empty?) end # Lista rotas únicas (route_id → descrição) def self.rotas_unicas(inicio: nil, fim: nil) base = da_conta_gade base = base.no_periodo(inicio, fim) if inicio && fim base.distinct.pluck(:route_id).compact end # Contagem de entregas pagas para cálculo estimado def self.contar_pagas(inicio:, fim:, motorista: nil, route_id: nil) base = pagas.da_conta_gade.no_periodo(inicio, fim) base = base.do_motorista(motorista) if motorista.present? base = base.da_rota(route_id) if route_id.present? base.count end # ── Helpers de instância ───────────────────────────────────── def numero_nf reference_id end def local contact_name.presence || address end def concluida? status == 'completed' end def checkin_registrado? checkin.present? end def elegivel_pagamento? concluida? && checkin_registrado? end def atraso_minutos return 0 unless delay.present? delay.to_s.split(':').then { |h, m, _s| h.to_i * 60 + m.to_i } end end