# -*- encoding : utf-8 -*-
class Admin::NavisionController < ApplicationController
  layout "admin"
  before_action :auth_admin, :only => :index
  
  before_action :admin_space
  
  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", "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 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 << 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_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 = true
      @table_header = ["compte comptable", "compte tiers", "tiers","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 true #ExportHist.new(:piece => e["No_"]).save
            i+= 1
            e["Désignation"] = e["Libellé écriture"] if !e["Désignation"]
        
            #TTC
            line = []
            line << "41100000"
            line << e["Buy-from Contact No_"]
            line << e["Pay-to Name"]
            line << d.to_date
            line << e["Vendor Invoice No_"]
            line << e["Job No_"]
            line << "FA "+e["Pay-to Name"].to_s
      
            if true
              if @credit
                line << ('%.2f' % e["Amount incl_ VAT"]).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
                  cpt = cpt_co.purchase_account
                else
                  cpt = li["Shortcut Dimension 2 Code"]
                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
                  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] += (li["Amount Including VAT"].to_s.to_f - li["Amount"].to_s.to_f)
              
              
              
  
             
            
            
              end
            end
          
            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["Vendor Invoice No_"]
                line << e["Job No_"]
                line << "FA "+e["Pay-to Name"].to_s
                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
    
  
      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 file
    send_file "private_medias/exports/#{params[:id]}.xlsx"
  end
end
