# -*- encoding : utf-8 -*-
class Admin::NavisionController < ApplicationController
  layout "admin"
  before_action :auth_admin, :only => :index
  
  before_action :admin_space
  
  
  def import_projets
    @client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
    @result = @client.execute("SELECT TOP 50000 * FROM dbo.[JIPE$Job]")
    #Project Principal
    #render :inline => @result.count.to_s
  end
  
  
  def import_clients
    @client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
    @result = @client.execute("SELECT TOP 50000 * FROM dbo.[JIPE$Customer]")
    #render :inline => @result.count.to_s
  end
  
  
  def import_fournisseurs
    @client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
    @result = @client.execute("SELECT TOP 50000 * FROM dbo.[JIPE$Vendor]")
    #render :inline => @result.count.to_s
  end
  
  def import_produits
    @client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
    @result = @client.execute("SELECT TOP 50000 * FROM dbo.[JIPE$Item]")
    #render :inline => @result.count.to_s
  end
  
  
  def admin_space
    @admin_space = "export_compta"
  end
  
  def index
    
  end
  
  def export_sale
    
  end
  
  def get_purchase_account
    
    render :inline => "done"
    
  end
  
  
  def export_a_sale
    
    
    if params[:start_at].to_s != "" and params[:stop_at].to_s != ""
      require 'csv'
      
      i = 0
    
      @filename = "AvoirsVentes"
    
    
      start_at = Date.parse(params[:start_at]).strftime("%Y-%m-%d")
      end_at = Date.parse(params[:stop_at]).strftime("%Y-%m-%d")
    
    
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Sales Cr_Memo Header] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <=  '#{end_at}';")
      r.count
    
      @credit = false
      @table_header = ["compte comptable", "compte client", "client","date", "numero piece","N° projet","libellé",  "débit", "crédit"] 

      @table = []
      r.cancel
      r.each do |e|


        d = Date.parse(e["Document Date"].to_s)

        if d >= Date.parse("2019/06/01")
          if ExportHist.new(:piece => e["No_"]).save
            
            i+= 1
            
            e["Désignation"] = e["Posting Description"] if !e["Désignation"]
        
          
          
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Sales Cr_Memo Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            cpts = {}
          
            tot_ttc = 0.0
          
            l.each do |li|
            
            
              if li["Amount Including VAT"].to_f != 0.0
              
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"]).first
              
                if cpt_co
                  if cpt_co.sale_account?
                    cpt = cpt_co.sale_account
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                else
                  cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  SComptaAccount.create(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"])
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || 0.0
              
                cpts[cpt] += li["Amount"]
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  if sca.sale_account.to_s != ""
                    vat += sca.sale_account.to_s
                  else
                    vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                  end
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                  vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                end
              
              
                cpts[vat] = cpts[vat] || 0.0
              
                tot_ttc += li["Amount Including VAT"].to_s.to_f
              
                cpts[vat] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
              
              
  
             
            
            
              end
            end
          
            #TTC
            line = []
            line << "41100000"
            line << e["Bill-to Customer No_"]
            line << e["Bill-to Name"]
            line << d.to_date
            line << e["No_"]
            line << e["Job No_"]
            line << e["Posting Description"]
          
            e["Amount incl_ VAT"] = 10.0
          
            if true
              if @credit
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            cpts.each do |key,value|
              if value.to_f != 0.0
                line = []
                line << key
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << e["No_"]
                line << e["Job No_"]
                line << e["Posting Description"]
                if @credit
                  line << ""
                  line << ('%.2f' % value).to_s.sub(".",",")
                else
                  line << ('%.2f' % value).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end
    

      xlsx_package = Axlsx::Package.new
      wb = xlsx_package.workbook
      wb.add_worksheet(name: "import") do |sheet|
        sheet.add_row @table_header
        @table.each do |tr|
          sheet.add_row tr
        end
      end

      directory_name = "exports"
      Dir.mkdir("private_medias/#{directory_name}") unless File.exists?("private_medias/#{directory_name}")

      xlsx_package.serialize("private_medias/#{directory_name}/#{@filename}-#{start_at}-#{end_at}--#{Time.now.to_s.to_slug}-----#{i}-lignes.xlsx")  
      
      
    else
      
    end
    
  end
  
  
  def export_sale
    
   
    if params[:start_at].to_s != "" and params[:stop_at].to_s != ""
      require 'csv'
      
      i = 0
    
      @filename = "Ventes"
    
    
      start_at = Date.parse(params[:start_at]).strftime("%Y-%m-%d")
      end_at = Date.parse(params[:stop_at]).strftime("%Y-%m-%d")
    
    
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Sales Invoice Header] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <=  '#{end_at}';")
      r.count
    
      @credit = true
      @table_header = ["compte comptable", "compte client", "client","date","echeance", "numero piece","N° projet","libellé",  "débit", "crédit"] 

      @table = []
      r.cancel
      r.each do |e|


        d = Date.parse(e["Document Date"].to_s)
        due_date = Date.parse(e["Due Date"].to_s)

        if d >= Date.parse("2019/06/01")
          if ExportHist.new(:piece => e["No_"]).save
            
            i+= 1
            
            e["Désignation"] = e["Posting Description"] if !e["Désignation"]
        
          
          
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Sales Invoice Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            cpts = {}
          
            tot_ttc = 0.0
          
            l.each do |li|
            
            
              if li["Amount Including VAT"].to_f != 0.0
              
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"]).first
              
                if cpt_co
                  if cpt_co.sale_account?
                    cpt = cpt_co.sale_account
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                else
                  cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  SComptaAccount.create(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"])
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || 0.0
              
                cpts[cpt] += li["Amount"]
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  if sca.sale_account.to_s != ""
                    vat += sca.sale_account.to_s
                  else
                    vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                  end
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                  vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                end
              
              
                cpts[vat] = cpts[vat] || 0.0
              
                tot_ttc += li["Amount Including VAT"].to_s.to_f
              
                cpts[vat] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
              
              
  
             
            
            
              end
            end
          
            #TTC
            line = []
            line << "41100000"
            line << e["Bill-to Customer No_"]
            line << e["Bill-to Name"]
            line << d.to_date
            line << due_date.to_date
            
            
            line << e["No_"]
            line << e["Job No_"]
            line << e["Posting Description"]
          
            e["Amount incl_ VAT"] = 10.0
          
            if true
              if @credit
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            cpts.each do |key,value|
              if value.to_f != 0.0
                line = []
                line << key
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << due_date.to_date
                line << e["No_"]
                line << e["Job No_"]
                line << e["Posting Description"]
                if @credit
                  line << ""
                  line << ('%.2f' % value).to_s.sub(".",",")
                else
                  line << ('%.2f' % value).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end
    

      xlsx_package = Axlsx::Package.new
      wb = xlsx_package.workbook
      wb.add_worksheet(name: "import") do |sheet|
        sheet.add_row @table_header
        @table.each do |tr|
          sheet.add_row tr
        end
      end

      directory_name = "exports"
      Dir.mkdir("private_medias/#{directory_name}") unless File.exists?("private_medias/#{directory_name}")

      xlsx_package.serialize("private_medias/#{directory_name}/#{@filename}-#{start_at}-#{end_at}--#{Time.now.to_s.to_slug}-----#{i}-lignes.xlsx")  
      
      
    else
      
    end
    
  end
  
  def export_purchase
    
    if params[:start_at].to_s != "" and params[:stop_at].to_s != ""
    
      require 'csv'
    
      i = 0
    
      @filename = "Achats"
    
      start_at = Date.parse(params[:start_at]).strftime("%Y-%m-%d")
      end_at = Date.parse(params[:stop_at]).strftime("%Y-%m-%d")
    
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Purch_ Inv_ Header] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <  '#{end_at}';")
      r.count
    
      @credit = false
      @table_header = ["compte comptable","code", "zone", "compte tiers", "tiers","date", "echeance", "numero piece","N° projet","libellé",  "débit", "crédit"] 
      @table = []
      r.cancel
      r.each do |e|


        d = Date.parse(e["Document Date"].to_s)
        due_date = Date.parse(e["Due Date"].to_s)
        if d >= Date.parse("2019/06/01")
          if ExportHist.new(:piece => e["No_"]).save
            i+= 1
            #e["Désignation"] = e["Libellé écriture"] if !e["Désignation"]
        
            #TTC
            line = []
            line << "40100000"
            line << ""
            line << ""
            line << e["Buy-from Vendor No_"]
            line << e["Pay-to Name"]
            line << d.to_date
            line << due_date.to_date
            line << e["Vendor Invoice No_"]
            line << e["Job No_"]
            line << e["Posting Description"].to_s
      
            if true
              if @credit or e["Amount incl_ VAT"].to_f < 0
                line << ('%.2f' % e["Amount incl_ VAT"]).to_f.abs.to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % e["Amount incl_ VAT"]).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Purch_ Inv_ Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            puts "SELECT TOP 1000 * FROM dbo.[JIPE$Purch_ Inv_ Line] WHERE [Document No_] = '#{e["No_"]}';"
            puts l.count
          
            cpts = {}
          
            l.each do |li|
            
            
              if li["Amount Including VAT"].to_f != 0.0
              
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => "FRANCE").first
              
                if cpt_co and cpt_co.purchase_account?
                  cpt = cpt_co.purchase_account
                else
                  if li["Shortcut Dimension 2 Code"].to_s == ""
                    cpt = "60100000"
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || [0.0, [], []]
              
                cpts[cpt][0] += li["Amount"]
                
                cpts[cpt][1] << li["Shortcut Dimension 2 Code"].to_s+" - "+ActionController::Base.helpers.number_to_currency(li["Amount"].to_f) 
                
                cpts[cpt][2] << li["VAT Bus_ Posting Group"].to_s
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  vat += sca.purchase_account.to_s
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                end
              
              
                cpts[vat] = cpts[vat] || [0.0, [], []]
              
                cpts[vat][0] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
                cpts[vat][1] << li["VAT Prod_ Posting Group"].to_s+" - "+ActionController::Base.helpers.number_to_currency(li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
                
                cpts[vat][2] << li["VAT Bus_ Posting Group"].to_s
              
              
  
             
            
            
              end
            end
          
            cpts.sort.each do |key,value|
              if value[0].to_f != 0.0
                line = []
                line << key
                line << value[1].uniq.join(" ||| ").to_s
                line << value[2].uniq.join(" ||| ").to_s
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << due_date.to_date
                line << e["Vendor Invoice No_"]
                line << e["Job No_"]
                line << e["Posting Description"].to_s
                if @credit or value[0].to_f < 0
                  line << ""
                  line << ('%.2f' % value[0].abs).to_s.sub(".",",")
                else
                  line << ('%.2f' % value[0]).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end
    
  
      if true
  
        xlsx_package = Axlsx::Package.new
        wb = xlsx_package.workbook
        wb.add_worksheet(name: "import") do |sheet|
          sheet.add_row @table_header
          @table.each do |tr|
            sheet.add_row tr
          end
        end
  
        directory_name = "exports"
        Dir.mkdir("private_medias/#{directory_name}") unless File.exists?("private_medias/#{directory_name}")
  
        xlsx_package.serialize("private_medias/#{directory_name}/#{@filename}-#{start_at}-#{end_at}--#{Time.now.to_s.to_slug}-----#{i}-lignes.xlsx")  
    
      end
      
    else
      
    end
    
  end
  
  
  
  
  
  
  
  
  
  
  def export_a_purchase
    
    if params[:start_at].to_s != "" and params[:stop_at].to_s != ""
    
      require 'csv'
    
      i = 0
    
      @filename = "AvoirsAchats"
    
      start_at = Date.parse(params[:start_at]).strftime("%Y-%m-%d")
      end_at = Date.parse(params[:stop_at]).strftime("%Y-%m-%d")
    
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Purch_ Cr_ Memo Hdr_] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <  '#{end_at}';")
      r.count
    
      @credit = true
      @table_header = ["compte comptable","code", "zone", "compte tiers", "tiers","date", "echeance", "numero piece","N° projet","libellé",  "débit", "crédit"] 
      @table = []
      r.cancel
      r.each do |e|


        d = Date.parse(e["Document Date"].to_s)
        due_date = Date.parse(e["Due Date"].to_s)
        if d >= Date.parse("2019/06/01")
          if ExportHist.new(:piece => e["No_"]).save
            i+= 1
            #e["Désignation"] = e["Libellé écriture"] if !e["Désignation"]
        
            #TTC
            line = []
            line << "40100000"
            line << e["Buy-from Vendor No_"]
            line << e["Pay-to Name"]
            line << d.to_date
            line << due_date.to_date
            line << e["No_"]
            line << e["Job No_"]
            line << e["Posting Description"].to_s
      
            if true
              if @credit or e["Amount incl_ VAT"].to_f < 0
                line << ('%.2f' % e["Amount incl_ VAT"]).to_f.abs.to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % e["Amount incl_ VAT"]).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Purch_ Cr_ Memo Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            puts "SELECT TOP 1000 * FROM dbo.[JIPE$Purch_ Cr_ Memo Line] WHERE [Document No_] = '#{e["No_"]}';"
            puts l.count
          
            cpts = {}
          
            l.each do |li|
            
            
              if li["Amount Including VAT"].to_f != 0.0
              
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => "FRANCE").first
              
                if cpt_co and cpt_co.purchase_account?
                  cpt = cpt_co.purchase_account
                else
                  if li["Shortcut Dimension 2 Code"].to_s == ""
                    if e["Job No_"].to_s != ""
                      cpt = "60101000"
                    else
                      cpt = "60100000"
                    end
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || [0.0, li["Shortcut Dimension 2 Code"], li["VAT Bus_ Posting Group"]]
              
                cpts[cpt][0] += li["Amount"]
                
                cpts[cpt][1] += " | "+li["Shortcut Dimension 2 Code"].to_s
                
                cpts[cpt][2] += " | "+li["VAT Bus_ Posting Group"].to_s
                
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  vat += sca.purchase_account.to_s
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                end
              
              
                cpts[vat] = cpts[vat] || [0.0, li["VAT Prod_ Posting Group"], li["VAT Bus_ Posting Group"]]
              
                cpts[vat][0] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
                cpts[vat][1] += " | "+li["Shortcut Dimension 2 Code"].to_s
                
                cpts[vat][2] += " | "+li["VAT Bus_ Posting Group"].to_s
              
              
  
             
            
            
              end
            end
          
            cpts.each do |key,value|
              if value[0].to_f != 0.0
                line = []
                line << key
                line << value[1].to_s
                line << value[2].to_s
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << due_date.to_date
                line << e["Vendor Invoice No_"]
                line << e["Job No_"]
                line << e["Posting Description"].to_s
                if @credit or value[0].to_f < 0
                  line << ""
                  line << ('%.2f' % value[0].abs).to_s.sub(".",",")
                else
                  line << ('%.2f' % value[0]).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end
    
  
      if true
  
        xlsx_package = Axlsx::Package.new
        wb = xlsx_package.workbook
        wb.add_worksheet(name: "import") do |sheet|
          sheet.add_row @table_header
          @table.each do |tr|
            sheet.add_row tr
          end
        end
  
        directory_name = "exports"
        Dir.mkdir("private_medias/#{directory_name}") unless File.exists?("private_medias/#{directory_name}")
  
        xlsx_package.serialize("private_medias/#{directory_name}/#{@filename}-#{start_at}-#{end_at}--#{Time.now.to_s.to_slug}-----#{i}-lignes.xlsx")  
    
      end
      
    else
      
    end
    
  end
  
  
  
  
  
  
  
  def export_sale_s
    
    PriceDocument.all.each do |pd|
      pd.destroy
    end
    
    if true # params[:start_at].to_s != "" and params[:stop_at].to_s != ""
      require 'csv'
      
      i = 0
    
      @filename = "Ventes"
    
    
      start_at = Date.parse("2019-06-01").strftime("%Y-%m-%d")
      end_at = Date.parse("2020-04-15").strftime("%Y-%m-%d")
    
    
      puts start_at
      puts end_at
      puts "AH"
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Sales Invoice Header] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <=  '#{end_at}';")
      r.count
    
      @credit = true
      @table_header = ["compte comptable", "compte client", "client","date","echeance", "numero piece","N° projet","libellé",  "débit", "crédit"] 

      @table = []
      r.cancel
      r.each do |e|

        puts "B"
        
        d = Date.parse(e["Document Date"].to_s)
        due_date = Date.parse(e["Due Date"].to_s)

        if true #d >= Date.parse("2019/06/01")
          if true #ExportHist.new(:piece => e["No_"]).save
            
            @price_document = PriceDocument.new(:price_document_type_id => 1, :d_number => e["No_"])
            
            @price_document.s_project = SProject.where(:p_number => e["Job No_"]).first
            
            
            i+= 1
            
            e["Désignation"] = e["Posting Description"] if !e["Désignation"]
            
            @price_document.price_line_block = PriceLineBlock.new(:movement_type => "cred")
  
            @price_document.date = d.to_date
            @price_document.price_line_block.p_customer = PCustomer.where(:code => e["Bill-to Customer No_"]).first
            @price_document.p_customer = @price_document.price_line_block.p_customer
            
            
            @price_document.price_line_block.customer_ref =  e["Order No_ Customer"]
            
            @price_document.price_line_block.customer_ref += " "+e["Your Reference"].to_s if e["Your Reference"].to_s != ""
            
            
            @price_document.price_line_block.ct_payment_end_at = e["Due Date"]
            @price_document.nav_due_date = e["Due Date"]
            
            @price_document.nav_oder_no_customer = e["Order No_ Customer"]
            
            
            @price_document.nav_location_code = e["Location Code"]
            @price_document.nav_shortcut_dimension_1_code = e["Shortcut Dimension 1 Code"]
            @price_document.nav_customer_posting_group = e["Customer Posting Group"]
            @price_document.nav_payment_method_code = e["Payment Method Code"]
            
            @p_payment_type = PPaymentType.where(:code => e["Payment Method Code"]).first
            
            @price_document.price_line_block.p_payment_type = @p_payment_type
            
            
            @price_document.nav_your_references = e["Your Reference"]
            @price_document.nav_bill_name = e["Bill-to Name"]
            @price_document.nav_bill_name_2 = e["Bill-to Name 2"]
            @price_document.nav_bill_address = e["Bill-to Address"]
            @price_document.nav_bill_address_2 = e["Bill-to Address 2"]
            @price_document.nav_bill_post_code = e["Bill-to Post Code"]
            @price_document.nav_bill_city = e["Bill-to City"]
            
            @price_document.nav_ship_name = e["Ship-to Name"]
            @price_document.nav_ship_name_2 = e["Ship-to Name 2"]
            @price_document.nav_ship_address = e["Ship-to Address"]
            @price_document.nav_ship_address_2 = e["Ship-to Address 2"]
            @price_document.nav_ship_post_code = e["Ship-to Post Code"]
            @price_document.nav_ship_city = e["Ship-to City"]
            
            
            if @price_document.p_customer
            
              bill_particular = Particular.where(:owner_type => "PCustomer", :owner_id => @price_document.p_customer.id,:organisation => @price_document.nav_bill_name, :name => @price_document.nav_bill_name_2, :address_2 => @price_document.nav_bill_address, :address_3 => @price_document.nav_bill_address_2, :cp => @price_document.nav_bill_post_code, :city => @price_document.nav_bill_city).first
            
            
              if !bill_particular
              
                bill_particular = Particular.create(:imported => true, :owner_type => "PCustomer", :owner_id => @price_document.p_customer.id,:organisation => @price_document.nav_bill_name, :name => @price_document.nav_bill_name_2, :address_2 => @price_document.nav_bill_address, :address_3 => @price_document.nav_bill_address_2, :cp => @price_document.nav_bill_post_code, :city => @price_document.nav_bill_city)
              end
 
              @price_document.price_line_block.particular_bill_id = bill_particular.id
            
              @price_document.particular_bill_id = @price_document.price_line_block.particular_bill_id
            
              send_particular = Particular.where(:owner_type => "PCustomer", :owner_id => @price_document.p_customer.id,:organisation => @price_document.nav_ship_name, :name => @price_document.nav_ship_name_2, :address_2 => @price_document.nav_ship_address, :address_3 => @price_document.nav_ship_address_2, :cp => @price_document.nav_ship_post_code, :city => @price_document.nav_ship_city).first
            
            
              if !send_particular
              
                send_particular = Particular.create(:imported => true, :owner_type => "PCustomer", :owner_id => @price_document.p_customer.id,:organisation => @price_document.nav_ship_name, :name => @price_document.nav_ship_name_2, :address_2 => @price_document.nav_ship_address, :address_3 => @price_document.nav_ship_address_2, :cp => @price_document.nav_ship_post_code, :city => @price_document.nav_ship_city)
              end
 
              @price_document.price_line_block.particular_send_id = send_particular.id
              
              @price_document.particular_send_id = @price_document.price_line_block.particular_send_id
            
            end
            
            
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Sales Invoice Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            cpts = {}
          
            tot_ttc = 0.0
          
            l.each do |li|
            
            
              if true #li["Amount Including VAT"].to_f != 0.0
                p_product_cat = nil
                if li["Shortcut Dimension 2 Code"].to_s != ""
                  
                  p_product_cat = PProductCat.where(:code => li["Shortcut Dimension 2 Code"]).first
                  
                  p_product_cat = PProductCat.create(:code => li["Shortcut Dimension 2 Code"]) if !p_product_cat
                    
                  
                  
                  
                end
                p_product_cat_id = nil
                p_product_cat_id = p_product_cat.id if p_product_cat
                
                line = @price_document.price_line_block.price_lines.new(:ct_p_product_cat_id => p_product_cat_id, :nav_line_no => li["Line No_"], :nav_unit_of_measure => li["Unit of Measure"], :nav_unit_of_measure_code => li[""], :nav_shortcut_dimension_2_code => li["Shortcut Dimension 2 Code"], :nav_gen_bus_posting_group => li["Gen_ Bus_ Posting Group"], :nav_gen_posting_group => li["Gen_ Prod_ Posting Group"], :nav_vat_prod_posting_group => li["VAT Prod_ Posting Group"], :ct_p_product_cat_id => (PProductCat.where(:code => li["Shortcut Dimension 2 Code"]).first ? PProductCat.where(:code => li["Shortcut Dimension 2 Code"]).first.id : nil),:p_product_ref => PProductRef.where(:ref => li["Item No_"]).first ,:ct_u_price_ht => li["Amount"], :qte => li["Quantity"], :ct_title => li["Description"], :ac_tva_account_value => li["VAT %"])
                
                
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"]).first
              
                if cpt_co
                  if cpt_co.sale_account?
                    cpt = cpt_co.sale_account
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                else
                  cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  SComptaAccount.create(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"])
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || 0.0
              
                cpts[cpt] += li["Amount"]
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  if sca.sale_account.to_s != ""
                    vat += sca.sale_account.to_s
                  else
                    vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                  end
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                  vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                end
              
              
                cpts[vat] = cpts[vat] || 0.0
              
                tot_ttc += li["Amount Including VAT"].to_s.to_f
              
                cpts[vat] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
              
              
  
             
            
            
              end
            end
          
            puts "TEST"
            puts @price_document.save
            puts @price_document.errors.messages
            
            #break if i > 30
            
            
            #TTC
            line = []
            line << "41100000"
            line << e["Bill-to Customer No_"]
            line << e["Bill-to Name"]
            line << d.to_date
            line << due_date.to_date
            
            
            line << e["No_"]
            line << e["Job No_"]
            line << e["Posting Description"]
          
            e["Amount incl_ VAT"] = 10.0
          
            if true
              if @credit
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            cpts.each do |key,value|
              if value.to_f != 0.0
                line = []
                line << key
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << due_date.to_date
                line << e["No_"]
                line << e["Job No_"]
                line << e["Posting Description"]
                if @credit
                  line << ""
                  line << ('%.2f' % value).to_s.sub(".",",")
                else
                  line << ('%.2f' % value).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end

    else
      
    end
    
    render :inline => "ok"
    
  end
  
  
  
  def export_a_sale_s
    
    #PriceDocument.all.each do |pd|
    #  pd.destroy
    #end
    
    if true # params[:start_at].to_s != "" and params[:stop_at].to_s != ""
      require 'csv'
      
      i = 0
    
      @filename = "Ventes"
    
    
      start_at = Date.parse("2019-06-01").strftime("%Y-%m-%d")
      end_at = Date.parse("2020-03-30").strftime("%Y-%m-%d")
    
    
      puts start_at
      puts end_at
      puts "AH"
    
      client = TinyTds::Client.new(username: 'test', password: '@Chatenois!2017', host: '40.89.153.193', appname: "SQL4PS" , port: 1534, database: "JIPE")
      r = client.execute("SELECT TOP 500 * FROM dbo.[JIPE$Sales Cr_Memo Header] WHERE [Document Date] >= '#{start_at}' AND [Document Date] <=  '#{end_at}';")
      r.count
    
      @credit = true
      @table_header = ["compte comptable", "compte client", "client","date","echeance", "numero piece","N° projet","libellé",  "débit", "crédit"] 

      @table = []
      r.cancel
      r.each do |e|

        puts "B"
        
        d = Date.parse(e["Document Date"].to_s)
        due_date = Date.parse(e["Due Date"].to_s)

        if true #d >= Date.parse("2019/06/01")
          if true #ExportHist.new(:piece => e["No_"]).save
            
            @price_document = PriceDocument.new(:price_document_type_id => 2, :d_number => e["No_"])
            
            @price_document.s_project = SProject.where(:p_number => e["Job No_"]).first
            
            
            i+= 1
            
            e["Désignation"] = e["Posting Description"] if !e["Désignation"]
            
            @price_document.price_line_block = PriceLineBlock.new(:movement_type => "deb")
  
            @price_document.date = d.to_date
            @price_document.price_line_block.p_customer = PCustomer.where(:code => e["Bill-to Customer No_"]).first
            @price_document.p_customer = @price_document.price_line_block.p_customer
            @price_document.price_line_block.particular_send_id = @price_document.price_line_block.p_customer.particular.id
            @price_document.price_line_block.particular_bill_id = @price_document.price_line_block.p_customer.particular.id
            
            
            
            
            l = client.execute("SELECT TOP 1000 * FROM dbo.[JIPE$Sales Cr_Memo Line] WHERE [Document No_] = '#{e["No_"]}';")
            l.count
            l.cancel
          
            cpts = {}
          
            tot_ttc = 0.0
          
            l.each do |li|
            
            
              if li["Amount Including VAT"].to_f != 0.0
                line = @price_document.price_line_block.price_lines.new(:ct_u_price_ht => li["Amount"], :qte => li["Quantity"], :ct_title => li["Description"], :ac_tva_account_value => li["VAT %"])
                
                
                cpt_co = SComptaAccount.where(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"]).first
              
                if cpt_co
                  if cpt_co.sale_account?
                    cpt = cpt_co.sale_account
                  else
                    cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  end
                else
                  cpt = li["Shortcut Dimension 2 Code"] + " " + li["VAT Bus_ Posting Group"]
                  SComptaAccount.create(:code => li["Shortcut Dimension 2 Code"], :zone => li["VAT Bus_ Posting Group"])
                end
              
                if cpt == "60101000"
                  if e["Job No_"].to_s != ""
                    cpt = "60101000"
                  else
                    cpt = "60100000"
                  end
                  
                end
              
                cpts[cpt] = cpts[cpt] || 0.0
              
                cpts[cpt] += li["Amount"]
              
              
                vat = "" # li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                if sca = SComptaAccount.where(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"]).first
                  if sca.sale_account.to_s != ""
                    vat += sca.sale_account.to_s
                  else
                    vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                  end
                else
                  SComptaAccount.create(:code => li["VAT Prod_ Posting Group"], :zone => li["VAT Bus_ Posting Group"])
                  vat +=li["VAT Prod_ Posting Group"]+" "+li["VAT Bus_ Posting Group"]
                end
              
              
                cpts[vat] = cpts[vat] || 0.0
              
                tot_ttc += li["Amount Including VAT"].to_s.to_f
              
                cpts[vat] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
              
              
  
             
            
            
              end
            end
          
            puts "TEST"
            puts @price_document.save
            puts @price_document.errors.messages
            
            #break if i > 30
            
            
            #TTC
            line = []
            line << "41100000"
            line << e["Bill-to Customer No_"]
            line << e["Bill-to Name"]
            line << d.to_date
            line << due_date.to_date
            
            
            line << e["No_"]
            line << e["Job No_"]
            line << e["Posting Description"]
          
            e["Amount incl_ VAT"] = 10.0
          
            if true
              if @credit
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
                line << ""
              else
                line << ""
                line << ('%.2f' % tot_ttc).to_s.sub(".",",")
              end
            end
  
            @table << line
          
            cpts.each do |key,value|
              if value.to_f != 0.0
                line = []
                line << key
                line << "" #e["N° client à facturer"]
                line << e["Pay-to Name"]
                line << d.to_date
                line << due_date.to_date
                line << e["No_"]
                line << e["Job No_"]
                line << e["Posting Description"]
                if @credit
                  line << ""
                  line << ('%.2f' % value).to_s.sub(".",",")
                else
                  line << ('%.2f' % value).to_s.sub(".",",")
                  line << ""
                end

                @table << line
              end
            
            end
          
      
          
          end
        else
        
        end
    
      end

    else
      
    end
    
    render :inline => "ok"
    
  end
  
  
  
  
  
  
  
  
  
  def file
    send_file "private_medias/exports/#{params[:id]}.xlsx"
  end
end
