:javascript
  function number_checkbox_checked(checkboxclass, labelclass) {
    const checkboxChecked = $(`.${checkboxclass}:checked`);
    $(`.${labelclass}`).append('<p>('+checkboxChecked.length+')</p>')
  }

  function on_load(itemlist) {
    var list = $(`.${itemlist}`),
    origOrder = list.children();

    var i, checked = document.createDocumentFragment(),
        unchecked = document.createDocumentFragment();
    for (i = 0; i < origOrder.length; i++) {
        if (origOrder[i].getElementsByTagName("input")[0].checked) {
            checked.appendChild(origOrder[i]);
        } else {
            unchecked.appendChild(origOrder[i]);
        }
    }
    list.append(checked).append(unchecked);

  }

  function move_on_top_of_the_list(itemlist) {
    var list = $(`.${itemlist}`),
    origOrder = list.children();

    list.on("click", ":checkbox", function() {
      var i, checked = document.createDocumentFragment(),
          unchecked = document.createDocumentFragment();
      for (i = 0; i < origOrder.length; i++) {
          if (origOrder[i].getElementsByTagName("input")[0].checked) {
              checked.appendChild(origOrder[i]);
          } else {
              unchecked.appendChild(origOrder[i]);
          }
      }
      list.append(checked).append(unchecked);

    });
  }

  window.onload = function() {
    on_load("productCheck");
    on_load("salesCheck");
    on_load("productcatCheck");
    on_load("brandCheck");
    on_load("clientsCheck");
  };


-if current_admin.has_permission?("stats-avec-marges") or current_admin.has_permission?("stats-commercial")
  .qi_header

    %h1
      Tableaux de bord

      %span
        Commercial
      -if params[:p_commercial_id].to_s != "" and @p_commercial = PCommercial.where(:id => params[:p_commercial_id]).first
        %span=@p_commercial.long_name

      -if params[:p_customer_id].to_s != "" and @p_customer = PCustomer.where(:id => params[:p_customer_id]).first
        %span=@p_customer.show_name

  -if @current_p_commercial_id.present?
    .row
      .col-xl-12.col-xxl-12.d-flex
        .w-100
          .row
            .col-sm-3
              .card
                .card-body
                  .row
                    .col.mt-0
                      %h5.card-title Chiffre d'affaires / N-1 de l'entreprise
                    .col-auto
                      .avatar
                        .avatar-title.rounded-circle.bg-primary-dark
                          .align-middle=ic :euro
                  %h1.display-5.mt-2.mb-4
                    .row
                      .col-sm-6
                        Commercial :
                        %br
                        -(@periode_ca = (@periode_lines.sum(:tot_amount_ht)))
                        -(@past_periode_ca = (@past_periode_lines.sum(:tot_amount_ht)))
                        ="(#{number_to_percentage((@percent_periode_ca = (@periode_ca/@past_periode_ca)*100.0), :precision => 2)})"
                      .col-sm-6
                        Entreprise :
                        %br
                        -(periode_ca = (@gen_periode_lines.sum(:tot_amount_ht)))
                        -(past_periode_ca = (@gen_past_periode_lines.sum(:tot_amount_ht)))
                        ="(#{number_to_percentage((percent_periode_ca = (periode_ca/past_periode_ca)*100.0), :precision => 2)})"
                  Soit
                  -if @percent_periode_ca < percent_periode_ca
                    %span.text-danger
                      ="(#{number_to_percentage((@percent_periode_ca - percent_periode_ca ), :precision => 2)})"
                  -else
                    %span.text-success
                      ="(#{number_to_percentage((@percent_periode_ca - percent_periode_ca ), :precision => 2)})"
                  d'écart
            .col-sm-3
              .card
                .card-body
                  .row
                    .col.mt-0
                      %h5.card-title Prix moyen au kilo de l'entreprise
                    .col-auto
                      .avatar
                        .avatar-title.rounded-circle.bg-primary-dark
                          .align-middle=ic :"balance-scale-right"
                  %h1.display-5.mt-2.mb-4
                    .row
                      .col-sm-6
                        Commercial :
                        %br
                        -@ca_produits_degrade = @periode_lines.where("title not in(?)", ["Remise pied de page","Frais de port"]).sum(:tot_amount_ht)
                        -@periode_tot_weight = @periode_lines.sum(:weight_tot).to_i
                        =number_to_currency(((@periode_tot_weight.to_f != 0.0 ? @periode_avg_price_per_kg = @ca_produits_degrade / @periode_tot_weight : 0.0)), :precision => 2)
                        ="/ Kg"
                      .col-sm-6
                        Entreprise :
                        %br
                        -ca_produits_degrade = @gen_periode_lines.where("title not in(?)", ["Remise pied de page","Frais de port"]).sum(:tot_amount_ht)
                        -periode_tot_weight = @gen_periode_lines.sum(:weight_tot).to_i
                        =number_to_currency(((@periode_tot_weight.to_f != 0.0 ? periode_avg_price_per_kg = ca_produits_degrade / periode_tot_weight : 0.0)), :precision => 2)
                        ="/ Kg"
                  Soit
                  -if @periode_avg_price_per_kg != nil
                    -if @periode_avg_price_per_kg < periode_avg_price_per_kg
                      %span.text-danger
                        ="(#{number_to_currency((@periode_avg_price_per_kg - periode_avg_price_per_kg ), :precision => 2)})"
                    -else
                      %span.text-success
                        ="(#{number_to_currency((@periode_avg_price_per_kg - periode_avg_price_per_kg ), :precision => 2)})"
                    d'écart
            .col-sm-3
              .card
                .card-body
                  .row
                    .col.mt-0
                      %h5.card-title Délais de paiement moyen
                    .col-auto
                      .avatar
                        .avatar-title.rounded-circle.bg-primary-dark
                          .align-middle=ic :calendar
                  %h1.display-5.mt-2.mb-4
                    .row
                      .col-sm-6
                        Commercial :
                        %br
                        =@payment_avg = (@periode_price_documents.where("cc_solded_nbr_days is not NULL").average(:cc_solded_nbr_days)).to_i
                        jours
                      .col-sm-6
                        Entreprise :
                        %br
                        =payment_avg = (@gen_periode_price_documents.where("cc_solded_nbr_days is not NULL").average(:cc_solded_nbr_days)).to_i
                        jours
                  Soit
                  -if @payment_avg > payment_avg
                    %span.text-danger
                      =@payment_avg - payment_avg
                  -else
                    %span.text-success
                      =@payment_avg - payment_avg
                  jours d'écart

            -objective_done = number_to_currency (@periode_lines.sum(:tot_amount_ht)), :precision => 0
            -objective = PCommercialObjective.where(:start_at => @start.to_date).where(p_commercial_id: @current_p_commercial_id).each do |objective|
            -objective_todo = number_to_currency (objective.total_ca), :precision => 0

              .col-sm-3{ :class => ("d-none" if params[:s_brand_ids].present? || params[:p_product_ref_ids].present? || params[:p_product_cat_ids].present? || params[:p_customer_ids].present?)}
                .card
                  .card-body
                    .row
                      .col.mt-0
                        %h5.card-title Objectifs
                      .col-auto
                        .avatar
                          .avatar-title.rounded-circle.bg-primary-dark
                            .align-middle=ic :bullseye
                    %h1.display-5.mt-2.mb-4
                      .row
                        .col-sm-6
                          A réaliser:
                          %br
                            =objective_todo
                        .col-sm-6
                          Réalisé :
                          -if objective_done >= objective_todo
                            %br
                              .text-success
                                =objective_done
                          -else
                            %br
                              .text-danger
                                =objective_done



  .qi_search_row
    =form_tag "", :method => "get",  :onsubmit => "" do

      .right
        =submit_tag "Afficher", :class => "btn btn-primary"

      %table.qi_search_row_top
        %tr
          %td{:style => "vertical-align:center;"}
            Début
          %td{:style => "vertical-align:center;"}
            .input-group
              =text_field_tag :start, params[:start],:class => "form-control datepicker", :placeholder => "Début"
              %span.input-group-addon.btn{:onclick => "$(this).prev('input').val('');"}

          %td
            Fin
          %td
            .input-group
              =text_field_tag :stop, params[:stop],:class => "form-control datepicker", :placeholder => "Fin"
              %span.input-group-addon.btn{:onclick => "$(this).prev('input').val('');"}

      %table.qi_search_row_top
        / -if @current_p_commercial_id.present?
        %tr
          %td{:style => "width:25%;", :class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
            %strong Commerciaux :
            #checkAllSales
              %label Tout séléctionner
              <input type="checkbox" name="checkall" id="checkallsales"</input>
              %label{:class => "countSales"}

            .check_box_search_index
              <input type="text" class="check_box_search_input" placeholder="Recherche"></input>
              .check_box_search_index_inner.salesCheck
                -if @current_p_commercial_id.present? && @current_p_commercial_id != nil
                  -@current_p_commercial_id.each do |pdt|
                    %p
                      = label_tag "p_commercial_ids_"+pdt.id.to_s do
                        = check_box_tag :"p_commercial_ids[]", pdt.id, {:id => "p_commercial_ids_#{pdt.id}"}
                        = pdt.name
                -else
                  -PCommercial.all.each do |pdt|
                    %p

                      = label_tag "p_commercial_ids_"+pdt.id.to_s do
                        = check_box_tag :"p_commercial_ids[]", pdt.id, (true if params[:p_commercial_ids].include?(pdt.id.to_s)), {:id => "p_commercial_ids_#{pdt.id}", :class => "checkSales"}
                        = pdt.long_name
          :javascript
            $("#checkallsales").change(function () {
              $("input:checkbox.checkSales").prop('checked',this.checked);
            });

            number_checkbox_checked("checkSales", "countSales")

            move_on_top_of_the_list("salesCheck")

          %td{:style => "width:25%;"}
            %strong Produits :
            #checkAllProducts
              %label Tout séléctionner
              <input type="checkbox" name="checkall" id="checkallproducts"</input>
              %label{:class => "countProducts"}

            .check_box_search_index
              <input type="text" class="check_box_search_input" placeholder="Recherche"></input>
              .check_box_search_index_inner.productCheck

                -PProductRef.all.each do |pdt|
                  %p{:class => "products" }
                    = label_tag "p_product_ref_ids_"+pdt.id.to_s  do
                      = check_box_tag :"p_product_ref_ids[]", pdt.id, (true if params[:p_product_ref_ids].include?(pdt.id.to_s)), {:id => "p_product_ref_ids_#{pdt.id}", :class => "checkProducts", }
                      = pdt.cc_name

          :javascript
            $("#checkallproducts").change(function () {
              $("input:checkbox.checkProducts").prop('checked',this.checked);
            });

            number_checkbox_checked("checkProducts", "countProducts")

            move_on_top_of_the_list("productCheck")


          %td{:style => "width:25%;"}
            %strong Clients :
            #checkAllClients
              %label Tout séléctionner
              <input type="checkbox" name="checkall" id="checkallclients"</input>
              %label{:class => "countClients"}

            .check_box_search_index
              <input type="text" class="check_box_search_input" placeholder="Recherche"></input>
              .check_box_search_index_inner.clientsCheck
                -st = StatLine.group(:p_customer_id).order(:p_customer_name)
                -if current_admin.p_commercial
                  -st = st.where(:p_customer_id => current_admin.p_commercial.p_customers.ids)
                -st.all.each do |pdt|
                  -if pdt.p_customer_name?
                    %p
                      = label_tag "p_customer_ids_"+pdt.p_customer_id.to_s do
                        = check_box_tag :"p_customer_ids[]", pdt.p_customer_id, (true if params[:p_customer_ids].include?(pdt.p_customer_id.to_s)), {:id => "p_customer_ids_#{pdt.p_customer_id}", :class => "checkClients"}
                        = "#{pdt.p_customer_code} #{pdt.p_customer_name}"
          :javascript
            $("#checkallclients").change(function () {
              $("input:checkbox.checkClients").prop('checked',this.checked);
            });

            number_checkbox_checked("checkClients", "countClients")

            move_on_top_of_the_list("clientsCheck")

          %td{:style => "width:25%;"}
            %strong Catégorie produits :
            #checkAllProductCat
              %label Tout séléctionner
              <input type="checkbox" name="checkall" id="checkallproductcat"</input>
              %label{:class => "countProductCat"}

            .check_box_search_index
              <input type="text" class="check_box_search_input" placeholder="Recherche"></input>
              .check_box_search_index_inner.productCatCheck
                -if @current_p_commercial_id.present? && @current_p_commercial_id != nil
                  -PProductCat.where(commercial_show: true).all.each do |pdt|
                    %p
                      = label_tag "p_product_cat_ids_"+pdt.id.to_s  do
                        = check_box_tag :"p_product_cat_ids[]", pdt.id, (true if params[:p_product_cat_ids].include?(pdt.id.to_s)), {:id => "p_product_cat_ids_#{pdt.id}", :class => "checkProductCat"}
                        = pdt.name

                -else
                  -PProductCat.all.each do |pdt|
                    %p
                      = label_tag "p_product_cat_ids_"+pdt.id.to_s  do
                        = check_box_tag :"p_product_cat_ids[]", pdt.id, (true if params[:p_product_cat_ids].include?(pdt.id.to_s)), {:id => "p_product_cat_ids_#{pdt.id}", :class => "checkProductCat"}
                        = pdt.name
          :javascript
            $("#checkallproductcat").change(function () {
              $("input:checkbox.checkProductCat").prop('checked',this.checked);
            });

            number_checkbox_checked("checkProductCat", "countProductCat")

            move_on_top_of_the_list("productCatCheck")

          %td{:style => "width:25%;"}
            %strong Marques :
            #checkAllBrands
              %label Tout séléctionner
              <input type="checkbox" name="checkall" id="checkallbrands"</input>
              %label{:class => "countBrands"}

            .check_box_search_index
              <input type="text" class="check_box_search_input" placeholder="Recherche"></input>
              .check_box_search_index_inner.brandCheck

                -SBrand.all.each do |pdt|
                  %p{:class => "brands"}
                    = label_tag "s_brand_ids_"+pdt.id.to_s  do
                      = check_box_tag :"s_brand_ids[]", pdt.id, (true if params[:s_brand_ids].include?(pdt.id.to_s)), {:id => "s_brand_ids_#{pdt.id}", :class => "checkBrands"};
                      = pdt.name



          :javascript
            $("#checkallbrands").change(function () {
              $("input:checkbox.checkBrands").prop('checked',this.checked);
            });

            number_checkbox_checked("checkBrands", "countBrands")



            move_on_top_of_the_list("brandCheck")


        :scss
          .check_box_search_index_inner{
            height:150px;
            overflow:auto;
            white-space: normal !important;
            p{
              margin:0;


            }
          }

          .qi_search_row{
            td{
              vertical-align :top;
            }
          }

        :javascript
          $(".check_box_search_input").on("keyup", function() {
              var value = $(this).val();

              $(this).closest(".check_box_search_index").find("p").each(function(index) {


                      $row = $(this);

                      var text = $row.text();

                      if (text.toUpperCase().search(value.toUpperCase()) != -1) {
                          $row.show();
                      }
                      else {
                          $row.hide();
                      }

              });
          });


  .qi_row
    %main
      %div


        .card
          .card-header

            %h5.card-title.mb-0 CA
          .card-body




            .align-self-center.w-100
              .py-3
                .chart.chart-xs
                  %canvas#chartjs-ca




            -ca = []
            -ca_past = []
            -ca_labels = []

            -start_date = @start.beginning_of_month

            -while start_date < @stop
              -ca << @periode_lines.where("date >= ? and date <= ?", start_date.beginning_of_month, start_date.end_of_month).sum(:tot_amount_ht)
              -ca_past << @past_periode_lines.where("date >= ? and date <= ?", (start_date - 1.year).beginning_of_month, (start_date - 1.year).end_of_month).sum(:tot_amount_ht)
              -ca_labels << l(start_date, :format => "%b")
              -start_date = start_date + 1.month




            :javascript
              $(function() {
              	// Bar chart
              	new Chart(document.getElementById("chartjs-ca"), {
              		type: "line",
              		data: {
              			labels: #{raw(ca_labels.to_s)},
              			datasets: [
                      {
                        label: "N-1",
                				backgroundColor: "transparent",
                				borderColor: "#718197",
                				hoverBackgroundColor: "#718197",
                				hoverBorderColor: "#718197",
                				data: #{raw(ca_past.to_s)},
                				barPercentage: .75,
                				categoryPercentage: .5

                			},
                      {
                      label: "N",
              				backgroundColor: "transparent",
              				borderColor: "#57a36d",
              				hoverBackgroundColor: "#57a36d",
              				hoverBorderColor: "#57a36d",
              				data: #{raw(ca.to_s)},
              				barPercentage: .75,
              				categoryPercentage: .5

              			}



                  ]

              		},
              		options: {
              			maintainAspectRatio: false,
              			legend: {
              				display: true
              			},
              			scales: {
              				yAxes: [{
              					gridLines: {
              						display: false
              					},
              					stacked: false,

              				}],
              				xAxes: [{
              					stacked: false,
              					gridLines: {
              						color: "transparent"
              					}
              				}]
              			}
              		}
              	});
              });

        .row
          .col-xl-6.col-xxl-6.d-flex
            .w-100
              .row
                .col-sm-6
                  .card
                    .card-body
                      .row
                        .col.mt-0
                          %h5.card-title Chiffre d'affaires net produits
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :euro
                      %h1.display-5.mt-2.mb-4
                        =number_to_currency (@periode_ca = (@periode_lines.sum(:tot_amount_ht))), :precision => 0
                        ="/"
                        %br
                        %span{:style => "font-size:0.8em;"}
                          =number_to_currency (@past_periode_ca = (@past_periode_lines.sum(:tot_amount_ht))), :precision => 0

                          ="(#{number_to_percentage((@percent_periode_ca = (@periode_ca/@past_periode_ca)*100.0), :precision => 2)})"

                      .mb-0
                        Dont
                        %span.text-danger{:class => ("d-none" if @periode_lines.where(:title =>"Remise pied de page").sum(:tot_amount_ht) <= 0 && @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                          =number_to_currency @periode_lines.where(:title =>"Remise pied de page").sum(:tot_amount_ht), :precision => 0
                          de remise pied de page et
                        %span.text-success
                          =number_to_currency @periode_lines.where(:title =>"Frais de port").sum(:tot_amount_ht), :precision => 0
                        de frais de port



                  .card
                    .card-body{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                      .row
                        .col.mt-0
                          %h5.card-title Marge
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :euro
                      %h1.display-5.mt-2.mb-4
                        =number_to_currency (@periode_marge = (@periode_lines.sum(:marge_ht))), :precision => 0
                        -if (n = @periode_price_documents.where(:price_document_type_id => [4]).where(:cost_ok => false).count) > 0
                          =link_to admin_price_documents_path(:start => params[:start], :stop => params[:stop], :price_document_type_ids => [4], :search => {:cost_ok => "Non"})  do
                            %span.red{:style => "font-size:0.5em;"}
                              =ic :warning
                              =n
                        ="/"
                        %br
                        %span{:style => "font-size:0.8em;"}
                          =number_to_currency (@past_periode_marge = (@past_periode_lines.sum(:marge_ht))), :precision => 0
                          -if (n = @past_periode_price_documents.where(:price_document_type_id => [4]).where(:cost_ok => false).count) > 0
                            =ic :warning
                            =n
                          ="(#{number_to_percentage((@percent_vs_periode_marge = (@periode_marge/@past_periode_marge)*100.0), :precision => 2)})"

                      .mb-0
                        Marge générale sur la période
                        =number_to_percentage((@percent_periode_marge = (@periode_marge/@periode_ca)*100.0), :precision => 2)
                        (sur n-1
                        =number_to_percentage((@past_percent_periode_marge = (@past_periode_marge/@past_periode_ca)*100.0), :precision => 2)
                        =")"




                  .card{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                    .card-body
                      .row
                        .col.mt-0
                          %h5.card-title Chiffre d'affaire brut
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :euro
                      %h1.display-5.mt-2.mb-4
                        =number_to_currency (@ca_produits = @periode_lines.sum(:tot_line_ht)), :precision => 0


                .col-sm-6
                  .card
                    .card-body

                      .row
                        .col.mt-0
                          %h5.card-title Chiffre d'affaire net
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :euro
                      %h1.display-5.mt-2.mb-4
                        =number_to_currency (@ca_produits_degrade = @periode_lines.where("title not in(?)", ["Remise pied de page","Frais de port"]).sum(:tot_amount_ht)), :precision => 0


                      .mb_0
                        Soit
                        %span.text-danger
                          -@ca_produits = @periode_lines.sum(:tot_line_ht)
                          =number_to_currency(@remises = (@ca_produits - @ca_produits_degrade), :precision => 0)
                        \(
                        %span.text-danger=number_to_percentage((@remises / @ca_produits)*100.0, :precision => 2)
                        \)
                        de remises




                  .card
                    .card-header

                      %h5.card-title.mb-0 Répartition familles produits
                    .card-body.d-flex
                      .align-self-center.w-100
                        .py-3
                          .chart.chart-xs
                            %canvas#chartjs-dashboard-pie
                        -if false
                          %table.table.mb-0
                            %tbody
                              %tr
                                %td
                                  %i.fas.fa-circle.text-primary.fa-fw
                                  Chrome
                                %td.text-right 4401
                              %tr
                                %td
                                  %i.fas.fa-circle.text-warning.fa-fw
                                  Firefox
                                %td.text-right 4003
                              %tr
                                %td
                                  %i.fas.fa-circle.text-danger.fa-fw
                                  IE
                                %td.text-right 1589




          .col-xl-6.col-xxl-6.d-flex
            .w-100
              .row



                .col-sm-6
                  .card
                    .card-body
                      .row
                        .col.mt-0
                          %h5.card-title Poids
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :"balance-scale-right"
                      %h1.display-5.mt-2.mb-4
                        =number_to_currency ((@periode_tot_weight = @periode_lines.sum(:weight_tot)).to_i), :precision => 0, :unit => "Kg"

                      .mb-0
                        %span.text-success
                          %i.mdi.mdi-arrow-bottom-right
                          =number_to_currency(((@periode_tot_weight.to_f != 0.0 ? @periode_avg_price_per_kg = @ca_produits_degrade / @periode_tot_weight : 0.0)), :precision => 2)
                          ="/ Kg"
                        ca moyen / kilo


                  .card
                    .card-header

                      %h5.card-title.mb-0 Paiements à venir
                    .card-body
                      -@periode_payment_retard = @periode_price_documents.where(:cc_solded => false).where("cc_payment_end_at < ?", Date.today).sum(:cc_tot_amount_ht)

                      -@periode_payment_a_venir_30_j = @periode_price_documents.where(:cc_solded => false).where("cc_payment_end_at >= ? and cc_payment_end_at < ?", Date.today, (Date.today + 30.days)).sum(:cc_tot_amount_ht)

                      -@periode_payment_a_venir_plus_30_j = @periode_price_documents.where(:cc_solded => false).where("cc_payment_end_at >= ?", (Date.today + 30.days)).sum(:cc_tot_amount_ht)


                      -treso = []
                      -treso_labels = []

                      -treso << (@periode_payment_retard * -1).to_f
                      -treso_labels << "En retard"


                      -treso << @periode_payment_a_venir_30_j.to_f
                      -treso_labels << "30 jours"

                      -treso << @periode_payment_a_venir_plus_30_j.to_f
                      -treso_labels << "+ de 30 jours"






                      .align-self-center.w-100
                        .py-3
                          .chart.chart-xs
                            %canvas#chartjs-dashboard-bar-alt





                .col-sm-6



                  .card
                    .card-body
                      .row
                        -if params[:p_commercial_ids].size > 0
                          -@all_customers_rows = PCustomer.where(:p_commercial_id => params[:p_commercial_ids])
                          -@all_customers = @all_customers_rows.count
                        -else
                          -@all_customers = PCustomer.count
                          -@all_customers_rows = PCustomer.all
                        .col.mt-0
                          %h5.card-title
                            =@all_customers
                            Clients
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :"users"
                      %h1.display-5.mt-2.mb-4

                      -if params[:p_customer_ids] and params[:p_customer_ids].size > 0
                        -@periode_nbr_clients_actifs = (@periode_lines.group(:p_customer_id).map{|a| a.p_customer_id}).reject { |e| e.to_s.empty? }.uniq.length
                        -@tot_customs = PCustomer.where(id: params[:p_customer_ids]).ids
                        -@all_customers = PCustomer.where(id: params[:p_customer_ids]).count
                        -@tot_clients_inactifs = (@tot_customs - @periode_lines.group(:p_customer_id).map{|p| p.p_customer_id}.uniq)
                        -@all_customers_rows = @all_customers_rows.where(id: params[:p_customer_ids])
                      -else
                        -@tot_clients_inactifs = (@all_customers_rows.ids - (@periode_lines.group(:p_customer_id).map{|a| a.p_customer_id}).reject { |e| e.to_s.empty? }.uniq )


                        -@periode_nbr_clients_actifs = (@periode_lines.group(:p_customer_id).map{|a| a.p_customer_id}).reject { |e| e.to_s.empty? }.uniq.length
                        / -@clients_inactifs = []
                        / -@periode_nbr_clients_inactifs = params[:p_customer_ids].each do |a|
                        /   -@clients_inactifs << PCustomer.where(id: a, enabled: false)

                        / -@tot_clients_inactifs = (@clients_inactifs.length - @periode_nbr_clients_actifs)

                      %div{:style => "font-size:0.7em;float:right"}
                        =link_to admin_p_customers_path(:p_customer_ids => (@all_customers_rows.ids - (@periode_lines.group(:p_customer_id).map{|a| a.p_customer_id}).uniq )), :method => :patch do
                          =@tot_clients_inactifs.length
                          inactifs

                      %div{:style => "font-size:0.7em"}
                        =@periode_nbr_clients_actifs
                        actifs


                      - @active_customers = ((@periode_nbr_clients_actifs.to_f / @all_customers.to_f)*100)



                      .progress
                        .progress-bar.bg-success-dark{"aria-valuemax" => "100", "aria-valuemin" => "0", "aria-valuenow" => "43", :role => "progressbar", :style => "width: #{@active_customers.to_i}%;"}=number_to_percentage @active_customers.to_i, :precision => 0
                        .progress-bar.bg-danger-dark{"aria-valuemax" => "100", "aria-valuemin" => "0", "aria-valuenow" => "43", :role => "progressbar", :style => "width: #{100.0 - (@active_customers.to_i)}%;"}=number_to_percentage((100.0 - @active_customers.to_i), :precision => 0)


                      -@new_customer = @all_customers_rows.where("created_at > ?", @start).count

                      %br
                      %div{:style => "font-size:0.6em;float:right"}



                        =@past_customers = @all_customers - @new_customer
                        Historiques


                      %div{:style => "font-size:0.6em"}
                        =@new_customer
                        Nouveaux


                      - @new_customers_percent = ((@new_customer.to_f / @all_customers.to_f)*100).to_i



                      .progress
                        .progress-bar.bg-success-dark{"aria-valuemax" => "100", "aria-valuemin" => "0", "aria-valuenow" => "43", :role => "progressbar", :style => "width: #{@new_customers_percent.to_i}%;"}=number_to_percentage @new_customers_percent.to_i, :precision => 0
                        .progress-bar.bg-primary-dark{"aria-valuemax" => "100", "aria-valuemin" => "0", "aria-valuenow" => "43", :role => "progressbar", :style => "width: #{100.0 - (@new_customers_percent.to_i)}%;"}=number_to_percentage((100.0 - @new_customers_percent.to_i), :precision => 0)



                      =#number_to_percentage (@active_customers = ((@periode_nbr_clients_actifs.to_f / @all_customers.to_f)*100)), :precision => 0


                      .mb-0
                        %span.text-success
                          %i.mdi.mdi-arrow-bottom-right
                          =number_to_currency((@periode_avg_ca_per_customer = @ca_produits_degrade / @periode_nbr_clients_actifs.to_f), :precision => 0)

                        ca moyen / clients

                      .mb-0
                        Dont
                        %span.text-warning
                          %i.mdi.mdi-arrow-bottom-right
                          =PCustomer.where(disabled_raison: "n'existe plus" ).count

                        clients qui n'existent plus


                  .card
                    .card-body
                      .row
                        .col.mt-0
                          %h5.card-title Délais de paiement moyen
                        .col-auto
                          .avatar
                            .avatar-title.rounded-circle.bg-primary-dark
                              .align-middle=ic :"calendar"
                      %h1.display-5.mt-2.mb-4
                        =(@payment_avg = @periode_price_documents.where("cc_solded_nbr_days is not NULL").average(:cc_solded_nbr_days)).to_i
                        jours
                      .mb-0










        -if true
          -params[:tab] = params[:tab] || "p_product_cats"
          .tab
            %ul.nav.nav-tabs{:role => "tablist"}

              -if !@current_p_commercial_id or @current_p_commercial_id == nil
                %li.nav-item
                  =link_to params.permit!.merge({:tab => "p_commercials"}), :class => "nav-link "+("active" if params[:tab] == "p_commercials").to_s do
                    Commerciaux
              %li.nav-item
                =link_to params.permit!.merge({:tab => "p_customers"}), :class => "nav-link "+("active" if params[:tab] == "p_customers").to_s do
                  Clients
              %li.nav-item
                =link_to params.permit!.merge({:tab => "inactive_p_customers"}), :class => "nav-link "+("active" if params[:tab] == "inactive_p_customers").to_s do
                  Clients inactifs

              %li.nav-item
                =link_to params.permit!.merge({:tab => "p_product_cats"}), :class => "nav-link "+("active" if params[:tab] == "p_product_cats").to_s do
                  Catégories produits

              %li.nav-item
                =link_to params.permit!.merge({:tab => "p_product_refs"}), :class => "nav-link "+("active" if params[:tab] == "p_product_refs").to_s do
                  Produits

              %li.nav-item
                =link_to params.permit!.merge({:tab => "s_brand"}), :class => "nav-link "+("active" if params[:tab] == "s_brand").to_s do
                  Marques
              -if current_admin.p_commercial
                %li.nav-item{ :class => ("d-none" if params[:s_brand_ids].present? || params[:p_product_ref_ids].present? || params[:p_product_cat_ids].present? || params[:p_customer_ids].present?)}
                  =link_to params.permit!.merge({:tab => "p_commercial_objectives"}), :class => "nav-link "+("active" if params[:tab] == "p_commercial_objectives").to_s do
                    Objectifs


            .tab-content
              -if params[:tab] == "p_commercials"
                #tab-3.tab-pane.active{:role => "tabpanel"}
                  %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?) }
                    %thead
                      %tr
                        %th Commercial
                        %th.numeraire CA
                        %th.numeraire CA N-1
                        %th.numeraire Poids

                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Marge

                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Ecart marge


                        %th.numeraire Prix moyen / Kg

                        %th.numeraire Ecart prix moyen / prix moyen

                        %th.numeraire Nbr client actifs
                        %th.numeraire Nbr clients

                        %th.numeraire Moyenne CA client
                        %th.numeraire Ecart
                        %th.numeraire Moyenne de délais de paiement

                        %th

                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(cc_tot_amount_ht) AS cc_tot_amount_ht, SUM(cc_weight_tot) AS cc_weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("cc_tot_amount_ht DESC").each do |ppp|



                      -results = @periode_lines.select("p_commercial_id AS p_commercial_id, SUM(tot_amount_ht) AS tot_amount_ht, (SELECT SUM(tot_amount_ht) FROM stat_lines plb WHERE id IN(#{@past_periode_lines.ids.to_s.gsub('[', '').gsub(']', '')}) and p_commercial_id = stat_lines.p_commercial_id) AS past_tot_amount_ht, ((SUM(tot_amount_ht)/#{@ca_produits_degrade}) * 100.0) as ca_percent, ((SUM(marge_ht)/SUM(tot_amount_ht)) * 100.0) as marge_percent, (((SUM(marge_ht)/SUM(tot_amount_ht)) * 100.0)) - #{@percent_periode_marge} as ecart_marge_percent, SUM(weight_tot) AS weight_tot, ((SUM(weight_tot)/#{@periode_tot_weight}) * 100.0) as weight_tot_percent , SUM(weight_tot) AS weight_tot, (SUM(tot_amount_ht) / SUM(weight_tot)) AS price_per_kg, (#{@periode_avg_price_per_kg}) AS avg_price_per_kg, ((SUM(tot_amount_ht) / SUM(weight_tot)) - #{@periode_avg_price_per_kg}) AS ecart_avg_price_per_kg, (#{@periode_avg_ca_per_customer}) as periode_avg_ca_per_customer").group(:p_commercial_id).order("tot_amount_ht DESC")


                      -results.each do |ppp|
                        %tr
                          %td
                            -ppr = PCommercial.where(:id => ppp.p_commercial_id).first
                            =link_to ppr.long_name, admin_p_commercial_path(ppr) if ppr

                          %td.numeraire
                            =number_to_currency ppp.tot_amount_ht, :precision => 0


                            =percentage_jauge(ppp.ca_percent, 5.0 )

                          %td.numeraire
                            =number_to_currency ppp.past_tot_amount_ht, :precision => 0
                            =percentage_jauge((ppp.tot_amount_ht / ppp.past_tot_amount_ht) * 100.0, 1.0, @percent_periode_ca, "success", "warning") if ppp.past_tot_amount_ht




                          %td.numeraire
                            =number_to_currency ppp.weight_tot, :unit => "Kg", :precision => 0
                            =percentage_jauge(ppp.weight_tot_percent, 5.0 )

                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                            -if ppr
                              -m = (@periode_lines.where(:p_commercial_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_commercial_id => ppr.id).sum(:tot_amount_ht))*100.0
                              =number_to_currency ((@periode_lines.where(:p_commercial_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_commercial_id => ppr.id).sum(:tot_amount_ht)) * ppp.price_per_kg.to_f), :precision => 3

                              =percentage_jauge(m)


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                            =number_to_percentage(m.to_f - @percent_periode_marge.to_f, :precision => 2)




                          %td.numeraire
                            =number_to_currency(ppp.price_per_kg)


                          %td.numeraire

                            -if ppp.ecart_avg_price_per_kg.to_f > 0.0
                              .text-success=number_to_currency(ppp.ecart_avg_price_per_kg)
                            -else
                              .text-danger=number_to_currency(ppp.ecart_avg_price_per_kg)


                          %td.numeraire
                            =n = @periode_lines.where(:p_commercial_id => ppp.p_commercial_id).group(:p_customer_id).count().length
                            -if ppr

                              =percentage_jauge((n.to_f / ppr.p_customers.count.to_f) * 100.0, 1.0, @active_customers, "success", "warning") if ppp.past_tot_amount_ht




                          %td.numeraire
                            =ppr.p_customers.count if ppr
                          %td.numeraire
                            =number_to_currency (ppp.tot_amount_ht / @periode_lines.where(:p_commercial_id => ppp.p_commercial_id).group(:p_customer_id).count().length.to_f), :precision => 0

                          %td.numeraire
                            -ecart_commercial_ca = (ppp.tot_amount_ht / @periode_lines.where(:p_commercial_id => ppp.p_commercial_id).group(:p_customer_id).count().length.to_f) - ppp.periode_avg_ca_per_customer
                            -if ecart_commercial_ca.to_f > 0.0
                              .text-success=number_to_currency(ecart_commercial_ca, :precision => 0)

                            -else
                              .text-danger=number_to_currency(ecart_commercial_ca, :precision => 0)

                          %td.numeraire
                            -n = (@periode_price_documents.where(:p_commercial_id => ppr.id).where("cc_solded_nbr_days is not NULL").average(:cc_solded_nbr_days)).to_i if ppr
                            =color_scale(n,@payment_avg, 7, "#28a745", "red")

                          %td
                            =link_to i(:"bar-chart"), params.permit!.merge({:p_commercial_id => ppr.id, :p_customer_id => nil, :p_product_ref_id => nil}) if ppr


              -if params[:tab] == "p_product_refs"
                #tab-1.tab-pane.active{:role => "tabpanel"}
                  %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?) }
                    %thead
                      %tr
                        %th Produit
                        %th.numeraire CA
                        %th.numeraire CA N-1
                        %th.numeraire Poids
                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Marge
                        -if false
                          %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Ecart marge
                        %th.numeraire Prix moyen / Kg produit
                        %th.numeraire Prix moyen / Kg
                        %th.numeraire Ecart prix moyen / prix moyen
                        %th

                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(tot_amount_ht) AS tot_amount_ht, SUM(weight_tot) AS weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("tot_amount_ht DESC").each do |ppp|



                      -results = @periode_lines.select("p_product_ref_id, SUM(tot_amount_ht) AS tot_amount_ht,"+("(SELECT SUM(tot_amount_ht) FROM stat_lines plb WHERE id IN(#{@past_periode_lines.ids.to_s.gsub('[', '').gsub(']', '')}) and p_product_ref_id = stat_lines.p_product_ref_id) AS past_tot_amount_ht," if @past_periode_lines.ids.size > 0).to_s+" ((SUM(tot_amount_ht)/#{@ca_produits}) * 100.0) as ca_percent, SUM(weight_tot) AS weight_tot, ((SUM(weight_tot)/#{@periode_tot_weight}) * 100.0) as weight_tot_percent , (SUM(tot_amount_ht) / SUM(weight_tot)) AS price_per_kg, (#{@periode_avg_price_per_kg}) AS avg_price_per_kg, ((SUM(tot_amount_ht) / SUM(weight_tot)) - #{@periode_avg_price_per_kg}) AS ecart_avg_price_per_kg").group(:p_product_ref_id).order("tot_amount_ht DESC")


                      -results.each do |ppp|
                        %tr
                          %td
                            -ppr = PProductRef.where(:id => ppp.p_product_ref_id).first
                            =link_to ppr.name, edit_admin_p_product_path(ppr.p_product) if ppr and ppr.p_product

                          %td.numeraire
                            =number_to_currency ppp.tot_amount_ht, :precision => 0
                            =percentage_jauge(ppp.ca_percent, 5.0 )


                          %td.numeraire
                            -if @past_periode_lines.ids.size > 0
                              =number_to_currency ppp.past_tot_amount_ht, :precision => 0
                              =percentage_jauge((ppp.tot_amount_ht / ppp.past_tot_amount_ht) * 100.0) if ppp.past_tot_amount_ht


                          %td.numeraire
                            =number_to_currency ppp.weight_tot, :unit => "Kg", :precision => 0
                            =percentage_jauge(ppp.weight_tot_percent, 5.0 )


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                            -if ppr
                              -m = (@periode_lines.where(:p_product_ref_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_product_ref_id => ppr.id).sum(:tot_amount_ht))*100.0

                              =number_to_currency ((@periode_lines.where(:p_product_ref_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_product_ref_id => ppr.id).sum(:tot_amount_ht)) * ppp.price_per_kg.to_f), :precision => 3
                              =percentage_jauge(m)


                          -if false
                            %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                              =number_to_percentage(m.to_f - @percent_periode_marge.to_f, :precision => 2)





                          %td.numeraire
                            =number_to_currency(ppp.price_per_kg)

                          %td.numeraire
                            =#number_to_currency(ppp.avg_price_per_kg)

                          %td.numeraire

                            -if ppp.ecart_avg_price_per_kg.to_f > 0.0
                              .text-success=number_to_currency(ppp.ecart_avg_price_per_kg)
                            -else
                              .text-danger=number_to_currency(ppp.ecart_avg_price_per_kg)

                          %td
                            =link_to i(:"bar-chart"), params.permit!.merge({:p_commercial_id => nil, :p_customer_id => nil, :p_product_ref_id => ppr.id}) if ppr



              -if params[:tab] == "inactive_p_customers"
                #tab-2.tab-pane.active{:role => "tabpanel"}


                  %table#inactive_p_customers_table.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?) }
                    %thead
                      %tr
                        %th Client
                        %th Commercial
                        %th Client bloqué ?
                        %th Raison du blocage

                        %th.numeraire CA N-1



                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(cc_tot_amount_ht) AS cc_tot_amount_ht, SUM(cc_weight_tot) AS cc_weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("cc_tot_amount_ht DESC").each do |ppp|



                      -if params[:p_customer_ids] and params[:p_customer_ids].size > 0
                        -@actifs_customs = @periode_lines.group(:p_customer_id).map{|p| p.p_customer_id}.uniq
                        -@tot_customs = PCustomer.where(id: params[:p_customer_ids]).ids
                        -@inactif_customs = (@tot_customs - @actifs_customs)
                      -else
                        -@inactif_customs = (@all_customers_rows.ids - (@periode_lines.group(:p_customer_id).map{|a| a.p_customer_id}).reject { |e| e.to_s.empty? }.uniq )



                      -PCustomer.where(:id => @inactif_customs).all.each do |p_customer|


                        %tr
                          %td

                            =link_to p_customer.show_name, admin_p_customer_path(p_customer)

                          %td
                            -ppc = PCommercial.where(:id => p_customer.p_commercial_id).first if p_customer
                            =link_to ppc.long_name, admin_p_commercial_path(ppc) if ppc

                          %td
                            -if !p_customer.enabled
                              Bloqué

                          %td
                            -if !p_customer.enabled
                              =p_customer.disabled_raison


                          %td.numeraire=number_to_currency @past_periode_lines.where(:p_customer_id => p_customer.id).sum(:tot_amount_ht)










              -if params[:tab] == "p_customers"
                #tab-2.tab-pane.active{:role => "tabpanel"}
                  %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?) }
                    %thead
                      %tr
                        %th Client
                        %th Commercial
                        %th.numeraire CA
                        %th.numeraire CA N-1
                        %th.numeraire Poids
                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Marge

                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Ecart marge
                        %th.numeraire Prix moyen / Kg produit
                        %th.numeraire Prix moyen / Kg
                        %th.numeraire Ecart prix moyen / prix moyen
                        %th.numeraire Moyenne délais de paiement
                        %th Client bloqué ?
                        %th Raison du blocage
                        %th

                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(cc_tot_amount_ht) AS cc_tot_amount_ht, SUM(cc_weight_tot) AS cc_weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("cc_tot_amount_ht DESC").each do |ppp|



                      -results = @periode_lines.select("p_customer_id, SUM(tot_amount_ht) AS tot_amount_ht, SUM(tot_amount_ht) AS tot_amount_ht, (SELECT SUM(tot_amount_ht) FROM stat_lines plb WHERE id IN(#{@past_periode_lines.ids.to_s.gsub('[', '').gsub(']', '')}) and p_customer_id = stat_lines.p_customer_id) AS past_tot_amount_ht, ((SUM(tot_amount_ht)/#{@ca_produits}) * 100.0) as ca_percent, SUM(weight_tot) AS weight_tot, ((SUM(weight_tot)/#{@periode_tot_weight}) * 100.0) as weight_tot_percent , (SUM(tot_amount_ht) / SUM(weight_tot)) AS price_per_kg, (#{@periode_avg_price_per_kg}) AS avg_price_per_kg, ((SUM(tot_amount_ht) / SUM(weight_tot)) - #{@periode_avg_price_per_kg}) AS ecart_avg_price_per_kg").group(:p_customer_id).order("tot_amount_ht DESC")


                      -results.each do |ppp|
                        %tr
                          %td
                            -ppr = PCustomer.where(:id => ppp.p_customer_id).first
                            =link_to ppr.show_name, admin_p_customer_path(ppr) if ppr

                          %td
                            -ppc = PCommercial.where(:id => ppr.p_commercial_id).first if ppr
                            =link_to ppc.long_name, admin_p_commercial_path(ppc) if ppr and ppc


                          %td.numeraire
                            =number_to_currency ppp.tot_amount_ht, :precision => 0
                            =percentage_jauge(ppp.ca_percent, 20.0 )

                          %td.numeraire
                            =number_to_currency ppp.past_tot_amount_ht, :precision => 0
                            =percentage_jauge((ppp.tot_amount_ht / ppp.past_tot_amount_ht) * 100.0) if ppp.past_tot_amount_ht





                          %td.numeraire
                            =number_to_currency ppp.weight_tot, :unit => "Kg", :precision => 0
                            =percentage_jauge(ppp.weight_tot_percent, 20.0 )


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                            -if ppr
                              -m = (@periode_lines.where(:p_customer_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_customer_id => ppr.id).sum(:tot_amount_ht))*100.0
                              =number_to_currency ((@periode_lines.where(:p_customer_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_customer_id => ppr.id).sum(:tot_amount_ht)) * ppp.price_per_kg.to_f), :precision => 3

                              =percentage_jauge(m)


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}
                            =number_to_percentage(m.to_f - @percent_periode_marge.to_f, :precision => 2)

                          %td.numeraire
                            =number_to_currency(ppp.price_per_kg)

                          %td.numeraire
                            =number_to_currency(ppp.avg_price_per_kg)

                          %td.numeraire

                            -if ppp.ecart_avg_price_per_kg.to_f > 0.0
                              .text-success=number_to_currency(ppp.ecart_avg_price_per_kg)
                            -else
                              .text-danger=number_to_currency(ppp.ecart_avg_price_per_kg)

                          %td.numeraire
                            =(@periode_price_documents.where(:p_customer_id => ppr.id).where("cc_solded_nbr_days is not NULL").average(:cc_solded_nbr_days)).to_i if ppr

                          %td
                            -if ppr and !ppr.enabled
                              Bloqué

                          %td
                            -if ppr and !ppr.enabled
                              =ppr.disabled_raison

                          %td
                            =link_to i(:"bar-chart"), params.permit!.merge({:p_commercial_id => nil, :p_customer_id => ppr.id, :p_product_ref_id => nil}) if ppr



              -if true
                #tab-4.tab-pane{:role => "tabpanel", :class => ("active" if params[:tab] == "p_product_cats")}
                  %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?), :data => {:title => "categories-produits"}}
                    %thead
                      %tr
                        %th Catégorie produit
                        %th.numeraire CA
                        %th.numeraire CA N-1
                        %th.numeraire Poids
                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Marge

                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Ecart marge
                        %th.numeraire Prix moyen / Kg produit

                        %th.numeraire Ecart prix moyen / prix moyen
                        -if false
                          %th.numeraire CA Moyen / clients général
                        %th.numeraire Nbr Clients
                        %th.numeraire CA Moyen famille / client

                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(cc_tot_amount_ht) AS cc_tot_amount_ht, SUM(cc_weight_tot) AS cc_weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("cc_tot_amount_ht DESC").each do |ppp|


                      -pie_label = []
                      -pie_data = []





                      -results = @periode_lines.select("p_product_cat_id, SUM(tot_amount_ht) AS tot_amount_ht, "+("(SELECT SUM(tot_amount_ht) FROM stat_lines plb WHERE id IN(#{@past_periode_lines.ids.to_s.gsub('[', '').gsub(']', '')}) and p_product_cat_id = stat_lines.p_product_cat_id) AS past_tot_amount_ht, " if @past_periode_lines.ids.size > 0).to_s+"((SUM(tot_amount_ht)/#{@ca_produits}) * 100.0) as ca_percent, SUM(weight_tot) AS weight_tot, "+("((SUM(weight_tot)/#{@periode_tot_weight}) * 100.0) as weight_tot_percent , " if @periode_tot_weight != 0.0).to_s+"(SUM(tot_amount_ht) / SUM(weight_tot)) AS price_per_kg, (#{@periode_avg_price_per_kg}) AS avg_price_per_kg, ((SUM(tot_amount_ht) / SUM(weight_tot)) - #{@periode_avg_price_per_kg}) AS ecart_avg_price_per_kg, (#{@periode_avg_ca_per_customer}) as periode_avg_ca_per_customer").group(:p_product_cat_id).order("tot_amount_ht DESC")


                      -results.each do |ppp|
                        %tr
                          %td
                            -ppr = PProductCat.where(:id => ppp.p_product_cat_id).first
                            =link_to ppr.name, admin_p_commercial_path(ppr) if ppr
                            -pie_label << ppr.name if ppr


                          -pie_data << ppp.tot_amount_ht.to_f if ppr

                          %td.numeraire
                            =number_to_currency ppp.tot_amount_ht, :precision => 0
                            =percentage_jauge(ppp.ca_percent, 2.0 )

                          %td.numeraire
                            -if defined?(past_tot_amount_ht)
                              =number_to_currency ppp.past_tot_amount_ht, :precision => 0
                              =percentage_jauge((ppp.tot_amount_ht / ppp.past_tot_amount_ht) * 100.0) if ppp.past_tot_amount_ht



                          %td.numeraire
                            =number_to_currency ppp.weight_tot, :unit => "Kg", :precision => 0
                            =percentage_jauge(ppp.weight_tot_percent, 2.0 )

                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}


                            -if ppr
                              -m = (@periode_lines.where(:p_product_cat_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_product_cat_id => ppr.id).sum(:tot_amount_ht))*100.0

                              =number_to_currency ((@periode_lines.where(:p_product_cat_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:p_product_cat_id => ppr.id).sum(:tot_amount_ht)) * ppp.price_per_kg.to_f), :precision => 3

                              =percentage_jauge(m)


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}

                            =number_to_percentage(m.to_f - @percent_periode_marge.to_f, :precision => 3)




                          %td.numeraire
                            =number_to_currency(ppp.price_per_kg, :precision => 3)


                          %td.numeraire

                            -if ppp.ecart_avg_price_per_kg.to_f > 0.0
                              .text-success=number_to_currency(ppp.ecart_avg_price_per_kg)
                            -else
                              .text-danger=number_to_currency(ppp.ecart_avg_price_per_kg)



                          %td.numeraire
                            =nbr_customers = @periode_lines.where(:p_product_cat_id => ppp.p_product_cat_id).group(:p_customer_id).count().length
                          %td.numeraire
                            =number_to_currency (ppp.tot_amount_ht / nbr_customers.to_f), :precision => 0
              -if true
                #tab-4.tab-pane{:role => "tabpanel", :class => ("active" if params[:tab] == "s_brand")}
                  %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?), :data => {:title => "marques"}}
                    %thead
                      %tr
                        %th Marques
                        %th.numeraire CA
                        %th.numeraire CA N-1
                        %th.numeraire Poids
                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Marge

                        %th.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)} Ecart marge
                        %th.numeraire Prix moyen / Kg produit

                        %th.numeraire Ecart prix moyen / prix moyen
                        -if false
                          %th.numeraire CA Moyen / clients général
                        %th.numeraire Nbr Clients
                        %th.numeraire CA Moyen famille / client

                    %tbody
                      /* 11:18:50 localhost presta_app */ SELECT COUNT(1) FROM `order_hist_lines`;

                      -#@periode_price_lines.select("p_product_ref_id, SUM(cc_tot_amount_ht) AS cc_tot_amount_ht, SUM(cc_weight_tot) AS cc_weight_tot, ((SELECT weight FROM `p_product_refs` WHERE id = price_lines.p_product_ref_id )) AS price_per_kg").group(:p_product_ref_id).order("cc_tot_amount_ht DESC").each do |ppp|


                      -#pie_label = []
                      -#pie_data = []





                      -results = @periode_lines.select("s_brand_id, SUM(tot_amount_ht) AS tot_amount_ht, "+("(SELECT SUM(tot_amount_ht) FROM stat_lines plb WHERE id IN(#{@past_periode_lines.ids.to_s.gsub('[', '').gsub(']', '')}) and s_brand_id = stat_lines.s_brand_id) AS past_tot_amount_ht, " if @past_periode_lines.ids.size > 0).to_s+"((SUM(tot_amount_ht)/#{@ca_produits}) * 100.0) as ca_percent, SUM(weight_tot) AS weight_tot, "+("((SUM(weight_tot)/#{@periode_tot_weight}) * 100.0) as weight_tot_percent , " if @periode_tot_weight != 0.0).to_s+"(SUM(tot_amount_ht) / SUM(weight_tot)) AS price_per_kg, (#{@periode_avg_price_per_kg}) AS avg_price_per_kg, ((SUM(tot_amount_ht) / SUM(weight_tot)) - #{@periode_avg_price_per_kg}) AS ecart_avg_price_per_kg, (#{@periode_avg_ca_per_customer}) as periode_avg_ca_per_customer").group(:s_brand_id).order("tot_amount_ht DESC")


                      -results.each do |ppp|
                        %tr
                          %td
                            -ppr = SBrand.where(:id => ppp.s_brand_id).first

                            =link_to ppr.name, admin_p_commercial_path(ppr) if ppr
                            -#pie_label << ppr.name if ppr


                          -#pie_data << ppp.tot_amount_ht.to_f if ppr

                          %td.numeraire
                            =number_to_currency ppp.tot_amount_ht, :precision => 0
                            =percentage_jauge(ppp.ca_percent, 2.0 )

                          %td.numeraire
                            -if defined?(past_tot_amount_ht)
                              =number_to_currency ppp.past_tot_amount_ht, :precision => 0
                              =percentage_jauge((ppp.tot_amount_ht / ppp.past_tot_amount_ht) * 100.0) if ppp.past_tot_amount_ht



                          %td.numeraire
                            =number_to_currency ppp.weight_tot, :unit => "Kg", :precision => 0
                            =percentage_jauge(ppp.weight_tot_percent, 2.0 )

                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}


                            -if ppr
                              -m = (@periode_lines.where(:s_brand_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:s_brand_id => ppr.id).sum(:tot_amount_ht))*100.0

                              =number_to_currency ((@periode_lines.where(:s_brand_id => ppr.id).sum(:marge_ht)/@periode_lines.where(:s_brand_id => ppr.id).sum(:tot_amount_ht)) * ppp.price_per_kg.to_f), :precision => 3

                              =percentage_jauge(m)


                          %td.numeraire{:class => ("d-none" if @current_p_commercial_id.present? && @current_p_commercial_id != nil)}

                            =number_to_percentage(m.to_f - @percent_periode_marge.to_f, :precision => 3)




                          %td.numeraire
                            =number_to_currency(ppp.price_per_kg, :precision => 3)


                          %td.numeraire

                            -if ppp.ecart_avg_price_per_kg.to_f > 0.0
                              .text-success=number_to_currency(ppp.ecart_avg_price_per_kg)
                            -else
                              .text-danger=number_to_currency(ppp.ecart_avg_price_per_kg)



                          %td.numeraire
                            =nbr_customers = @periode_lines.where(:s_brand_id => ppp.s_brand_id).group(:p_customer_id).count().length
                          %td.numeraire
                            =number_to_currency (ppp.tot_amount_ht / nbr_customers.to_f), :precision => 0

              -if true
                -if (current_admin.p_commercial)
                  #tab-4.tab-pane{:role => "tabpanel", :class => ("active" if params[:tab] == "p_commercial_objectives")}
                    %table#datatables-dashboard-traffic.table.table-striped.my-0.table-hover{:class => ("export_table" if @current_p_commercial_id.blank?), :data => {:title => "objectifs"}}
                      
                      -if @start.month == 5 and @start.day == 1
                        -trim_start_date = Date.parse("#{@start.year}/#{@start.month}/#{@start.day}")
                      
                        -p_commercial_objective = PCommercialObjective.where(:start_at => trim_start_date).where(:p_commercial_id => params[:p_commercial_ids]).first
                        -if p_commercial_objective
                          -tot_trim = {}
                      
                          -next_year_trim_start_date = trim_start_date + 1.year
                          -i = 1
                          %th
                            Période
                          %th
                            Objectif CA
                          %th
                            Objectif Poids
                          %th
                            Réalisé CA
                          %th
                            Réalisé poids
                          -while trim_start_date < next_year_trim_start_date
                            - trim_end_date = trim_start_date + (3.month - 1.day)
                            - tr_array = []


                            -start_month_date = trim_start_date

                            -tot = {:ca => 0.0, :weight => 0.0}

                            -tot_ca = 0.0
                            -tot_weight = 0.0



                            -while start_month_date <= trim_end_date
                              -end_month_date = start_month_date.end_of_month
                              -p_commercial_object_month = p_commercial_objective.p_commercial_object_months.where(start_at: start_month_date).first

                              -tr_array << capture do
                                -month_periode_lines = StatLine.where("date >= ? and date <= ?", start_month_date, end_month_date).where(p_commercial_id: p_commercial_objective.p_commercial_id)
                                -month_ca_done = month_periode_lines.sum(:tot_amount_ht).round(0)
                                -month_weight_done = month_periode_lines.sum(:weight_tot).round(0)
                                %tr{:class => "tr_trim_#{i}", :style => ("display:none;" if i != 1)}
                                  %td

                                    =l(start_month_date, :format => "%B").capitalize

                                  %td
                                    -tot[:ca] += p_commercial_object_month.ca_total_ca
                                    =number_to_currency(p_commercial_object_month.ca_total_ca)

                                  %td
                                    -tot[:weight] += p_commercial_object_month.ca_total_weight
                                    =p_commercial_object_month.ca_total_weight.to_i
                                    Kg

                                  %td
                                    =number_to_currency month_ca_done, :precision => 0

                                  %td
                                    =month_weight_done.to_i
                                    Kg


                              -start_month_date = start_month_date + 1.month




                            %tr
                              -trim_periode_lines = StatLine.where("date >= ? and date <= ?", trim_start_date, trim_end_date).where(p_commercial_id: p_commercial_objective.p_commercial_id)
                              -trim_ca_done = trim_periode_lines.sum(:tot_amount_ht).round(0)
                              -trim_weight_done = trim_periode_lines.sum(:weight_tot).round(0)
                              %td
                                =link_to "+", "#", :onclick => "$('.tr_trim_#{i}').toggle();return false;"
                                %strong
                                  Trimestre
                                  = i
                                  du
                                  =l trim_start_date
                                  au

                                  =l trim_end_date

                              %td
                                -r = 0.0
                                -p_commercial_objective.p_commercial_object_months.where("start_at >= ? and start_at <= ?", trim_start_date, trim_end_date).each do |pcom|
                                  -r = r + pcom.ca_total_ca
                                =number_to_currency r

                              / %td
                              /   =number_to_currency tot[:ca]

                              %td
                                = tot[:weight].to_i
                                Kg

                              %td
                                =number_to_currency trim_ca_done, :precision => 0

                              %td
                                =trim_weight_done.to_i
                                Kg

                            -tr_array.each do |tr|
                              =raw tr


                            -trim_start_date = trim_start_date + 3.month
                            -i += 1


                          .thead
                            %tr
                              %th
                                =link_to "+", "#", :onclick => "$('.brands_objectives').toggle();return false;"
                                Marque
                              %th
                                Objectif CA
                              %th
                                Objectif Poids
                              %th
                                Réalisé CA
                              %th
                                Réalisé poids

                          -p_commercial_object_brand = PCommercialObjectBrand.where(p_commercial_id: params[:p_commercial_ids], commercial_show: true).all.each do |object_brand|
                            -brand_start_date = p_commercial_objective.start_at
                            -brand_end_date = p_commercial_objective.end_at
                            -brand_periode_lines = StatLine.where("date >= ? and date <= ?", brand_start_date, brand_end_date).where(p_commercial_id: p_commercial_objective.id, s_brand_id: object_brand.s_brand_id)
                            -brand_ca_done = trim_periode_lines.sum(:tot_amount_ht)
                            -brand_weight_done = trim_periode_lines.sum(:weight_tot)
                            %tbody
                              %tr{:class => "brands_objectives", :style => "display:none;"}
                                %td
                                  =object_brand.s_brand.name
                                %td
                                  =number_to_currency object_brand.ca_total_ca
                                %td
                                  =object_brand.ca_total_weight
                                  Kg
                                %td
                                  =number_to_currency brand_ca_done, :precision => 0
                                %td
                                  =brand_weight_done.to_i
                                  Kg






                        -if false
                          -PCommercialObjective.where(:p_commercial_id => params[:p_commercial_ids]).each do |p_commercial_objective|
                            -@t1 = p_commercial_objective.p_commercial_object_months.where(start_at: ["01/05/2020", "01/06/2020", "01/07/2020"])
                            -@t2 = p_commercial_objective.p_commercial_object_months.where(start_at: ["01/08/2021", "01/09/2021", "01/10/2021"])
                            -@t2 = p_commercial_objective.p_commercial_object_months.where(start_at: ["01/11/2021", "01/12/2021", "01/01/2022"])
                            -@t2 = p_commercial_objective.p_commercial_object_months.where(start_at: ["01/02/2022", "01/03/2022", "01/04/2022"])

                            %thead
                              %tr
                                %th{:scope => "col"}
                                  ID
                                %th{:scope => "col"}
                                  Objectif (%)
                                %th{:scope => "col"}
                                  Date de début
                                %th{:scope => "col"}
                                  Date de fin
                                %th{:scope => "col"}
                                  A réaliser
                                %th{:scope => "col"}
                                  Réalisé


                            %tbody
                              %tr
                                %th{:scope => "col"}

                                %td
                                  =object_month.objective_percent
                                  (%)
                                %td
                                  =object_month.start_at
                                %td
                                  =object_month.end_at
                                %td
                                  #{@month_ca_todo}

                                -if @month_ca_todo >= @month_ca_done
                                  %td.text-danger
                                    #{@month_ca_done}
                                -else
                                  %td.text-success
                                  #{@month_ca_done}



                            -@t1.each do |object_month|

                              -@month_start = object_month.start_at
                              -@month_stop = object_month.end_at

                              %tr
                                %td
                                  =@month_start

                                %td
                                  =@month_stop

                              -@month_periode_lines = StatLine.where("date >= ? and date <= ?", @month_start, @month_stop)
                              -@month_periode_lines = @month_periode_lines.where(p_commercial_id: object_month.p_commercial_id)
                              -@month_ca_todo = number_to_currency (p_commercial_objective.total_ca * object_month.objective_percent) / 100
                              -@month_ca_done = number_to_currency (@month_periode_lines.sum(:tot_amount_ht)), :precision => 0

                              %tbody
                                %tr
                                  %th{:scope => "col"}
                                    =object_month.id
                                  %td
                                    =object_month.objective_percent
                                    (%)
                                  %td
                                    =object_month.start_at
                                  %td
                                    =object_month.end_at
                                  %td
                                    #{@month_ca_todo}

                                  -if @month_ca_todo >= @month_ca_done
                                    %td.text-danger
                                      #{@month_ca_done}
                                  -else
                                    %td.text-success
                                    #{@month_ca_done}


  -pie_data.to_s

  :javascript
    $(function() {
    	var mapData = {
    		"US": 298,
    		"SA": 200,
    		"DE": 220,
    		"FR": 540,
    		"CN": 120,
    		"AU": 760,
    		"BR": 550,
    		"IN": 200,
    		"GB": 120,
    	};
    	$('#world_map').vectorMap({
    		map: 'world_mill',
    		backgroundColor: "transparent",
    		zoomOnScroll: false,
    		regionStyle: {
    			initial: {
    				fill: '#e4e4e4',
    				"fill-opacity": 0.9,
    				stroke: 'none',
    				"stroke-width": 0,
    				"stroke-opacity": 0
    			}
    		},
    		series: {
    			regions: [{
    				values: mapData,
    				scale: [window.theme.primary],
    				normalizeFunction: 'polynomial'
    			}]
    		},
    	});
    	setTimeout(function() {
    		$(window).trigger('resize');
    	}, 350)
    })
  :javascript
    $(function() {
    	// Pie chart
    	new Chart(document.getElementById("chartjs-dashboard-pie"), {
    		type: 'pie',
    		data: {
    			labels: #{raw(pie_label.to_s)},
    			datasets: [{
    				data: #{raw(pie_data.to_s)},
    				backgroundColor: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],
    				borderColor: "transparent"
    			}]
    		},
    		options: {
    			responsive: !window.MSInputMethodContext,
    			maintainAspectRatio: false,
    			legend: {
    				display: false
    			},
    			cutoutPercentage: 75
    		}
    	});
    });
  :javascript
    $(function() {
    	// Radar chart
    	new Chart(document.getElementById("chartjs-dashboard-radar"), {
    		type: "radar",
    		data: {
    			labels: ["Technology", "Sports", "Media", "Gaming", "Arts"],
    			datasets: [{
    				label: "Interests",
    				backgroundColor: "rgba(0, 123, 255, 0.2)",
    				borderColor: "#2979ff",
    				pointBackgroundColor: "#2979ff",
    				pointBorderColor: "#fff",
    				pointHoverBackgroundColor: "#fff",
    				pointHoverBorderColor: "#2979ff",
    				data: [70, 53, 82, 60, 33]
    			}]
    		},
    		options: {
    			maintainAspectRatio: false,
    			legend: {
    				display: false
    			}
    		}
    	});
    });






  :javascript
    $(function() {
    	// Bar chart
    	new Chart(document.getElementById("chartjs-dashboard-bar-alt"), {
    		type: "bar",
    		data: {
    			labels: #{raw(treso_labels.to_s)},
    			datasets: [{

    				backgroundColor: ["#dd6b5a", "#f6c143", "#57a36d"],
    				borderColor: window.theme.primary,
    				hoverBackgroundColor: ["#dd6b5a", "#f6c143", "#57a36d"],
    				hoverBorderColor: window.theme.primary,
    				data: #{raw(treso.to_s)},
    				barPercentage: .75,
    				categoryPercentage: .5

    			}]
    		},
    		options: {
    			maintainAspectRatio: false,
    			legend: {
    				display: false
    			},
    			scales: {
    				yAxes: [{
    					gridLines: {
    						display: false
    					},
    					stacked: false,

    				}],
    				xAxes: [{
    					stacked: false,
    					gridLines: {
    						color: "transparent"
    					}
    				}]
    			}
    		}
    	});
    });


  -if false
    :javascript
      $(function() {
      	// Bar chart
      	new Chart(document.getElementById("chartjs-dashboard-bar-alt"), {
      		type: "bar",
      		data: {
      			labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
      			datasets: [{
      				label: "Last year",
      				backgroundColor: window.theme.primary,
      				borderColor: window.theme.primary,
      				hoverBackgroundColor: window.theme.primary,
      				hoverBorderColor: window.theme.primary,
      				data: [54, 67, 41, 55, 62, 45, 55, 73, 60, 76, 48, 79],
      				barPercentage: .75,
      				categoryPercentage: .5
      			}, {
      				label: "This year",
      				backgroundColor: "#E8EAED",
      				borderColor: "#E8EAED",
      				hoverBackgroundColor: "#E8EAED",
      				hoverBorderColor: "#E8EAED",
      				data: [69, 66, 24, 48, 52, 51, 44, 53, 62, 79, 51, 68],
      				barPercentage: .75,
      				categoryPercentage: .5
      			}]
      		},
      		options: {
      			maintainAspectRatio: false,
      			legend: {
      				display: false
      			},
      			scales: {
      				yAxes: [{
      					gridLines: {
      						display: false
      					},
      					stacked: false,
      					ticks: {
      						stepSize: 20
      					}
      				}],
      				xAxes: [{
      					stacked: false,
      					gridLines: {
      						color: "transparent"
      					}
      				}]
      			}
      		}
      	});
      });



:javascript
  $('.export_table').DataTable( {
      dom: 'Bfrtip',
      ordering: false,
    paging: false,
    searching:false,
      buttons: [
          {
            extend: 'excelHtml5',
            text:'Export Excel',
            filename: 'export-basic-#{Time.now.strftime("%Y-%m-%d-%H-%m-%S")}',
            title:''
          },
          {
            extend: 'csv',
            text:'Export CSV',
            filename: 'export-basic-#{Time.now.strftime("%Y-%m-%d-%H-%m-%S")}',
            title:''
          }
      ]
  } );

:scss
  .dataTables_info{
    display:none;
  }
