class OrderHist < ApplicationRecord
  has_many :order_hist_lines
  
  belongs_to :p_customer
  belongs_to :p_commercial
  belongs_to :p_payment_type
  
  acts_as_sorting :fields => {
    #:id => {:name => "Id", :reorder => true},
    :p_customer_id => {:name => "Client", :reorder => true},
    :numerofacture => {:name => "Numéro facture", :reorder => true},
  
    :montant_ht => {:name => "Montant HT", :reorder => true, :as => :currency},
    :montant_ht_remise => {:name => "Montant HT remisé", :reorder => true, :as => :currency},
    
    
    #:date_modification => {:name => "", :reorder => true},
    :date_facture => {:name => "Date facture", :reorder => true, :as => :date},
    #:colisage => {:name => "", :reorder => true},
    #:nbr_colis => {:name => "", :reorder => true},
   
    :p_payment_type_id => {:name => "Type de paiement", :reorder => true},
    #:echeance_nbr_jour => {:name => "Nbr jours paiement", :reorder => true},
    #:code_commercial => {:name => "Code commercial", :reorder => true},
    :p_commercial_id => {:name => "Commercial", :reorder => true},
    
    
    :actions => {:name => "Actions"}
    
  }
  
  
  before_save do
  
    incremental = [ :montant_ht, :montant_ht_remise]
  
    incremental.each do |c|
      eval "self.#{c.to_s} = self.order_hist_lines.sum(:#{c.to_s})"
    end
    
    incremental = [ :montant_ht_com, :cout_achat_ht, :marge_brut_hors_remise, :marge_brut_remise, :marge_net, :marge_brut_hors_remise_pa, :marge_brut_remise_pa, :marge_net_ht_pa]
  
    incremental.each do |c|
      eval "self.#{c.to_s} = self.order_hist_lines.sum(:cc_#{c.to_s})"
    end
    
    
  end
end
