class AddReliquatFdpToPriceLineBlock < ActiveRecord::Migration[6.0]
  def change
    add_column :price_line_blocks, :reliquat_fdp_ht, :decimal,   :precision => 14,   :scale => 2
    
    
    PriceLineBlock.find_each do |plb|
      plb.save
    end
  
    PriceLine.find_each do |pl|
      if pl.ac_price_u_ht
        pl.bk_price_ht = pl.ac_price_u_ht
      end
      pl.save
    end
  
    
    
    PriceLineBlock.where(:archived => true).find_each do |plb|
      if first = plb.price_lines.order('ac_discount_market_percent DESC').first
        plb.ac_customer_market_discount_percent = first.discount_market_percent
        plb.cc_customer_market_discount_percent = first.discount_market_percent
        plb.save
      end
    end
    
    
    PriceDocument.where(:cc_label => ["Bon de livraison", "Facture", "Avoir"]).find_each do |pd|
      if pd.ref_element_type == "PCustomerSheet" and pcs = pd.ref_element and !pd.bon_de_commande_id
        puts pd.id
        if bc = pcs.price_documents.where(:cc_label => "Bon de commande").first
          pd.bon_de_commande_id = bc.id
          pd.save
          pd.price_line_block.save
        end
      end
      
      pd.price_line_block.bk_tot_fdp_ht = pd.price_line_block.cc_tot_fdp_ht if !pd.price_line_block.bk_tot_fdp_ht
      pd.save
      
    end
    
    
    
    
    
    
    PriceDocument.where(:cc_label => ["Facture", "Avoir"] ).find_each do |pd|
      if pd.ref_element_type == "PCustomerSheet" and pcs = pd.ref_element
        puts pd.id
        if bc = pcs.price_documents.where(:cc_label => "Bon de livraison").first
          pd.bon_de_livraison_id = bc.id
          pd.save
          pd.price_line_block.save
        end
      end
      
    end
      
    PriceDocument.where(:cc_label => ["Avoir"] ).find_each do |pd|
      if pd.ref_element_type == "PCustomerSheet" and pcs = pd.ref_element
        puts pd.id
        if bc = pcs.price_documents.where(:cc_label => "Facture").first
          pd.facture_id = bc.id
          pd.save
          pd.price_line_block.save
        end
      end
      
    end
    
  end
end
