<commit_before>import * as d3 from 'd3'
import * as dc from 'dc'
import crossfilter from 'crossfilter2'
import moment from 'moment'
import { d3locale } from 'lib/shared'
import 'jsgrid'

window.GobiertoBudgets.InvoicesController = (function() {

  function InvoicesController() {}

  // Global variables
  var data, ndx, _r, _tabledata, _empty, dataEndpoint, _chartdata = {}, $tableHTML = {};

  InvoicesController.prototype.show = function() {
    $tableHTML = $("#providers-table");

    dataEndpoint = "/presupuestos/proveedores-facturas.csv"

    let municipalityId = window.populateData.municipalityId;
    let maxYearUrl = dataEndpoint + '?filter_by_location_id='+municipalityId+'&sort_desc_by=date&limit=1';
    let minYearUrl = dataEndpoint + '?filter_by_location_id='+municipalityId+'&sort_asc_by=date&limit=1';

    // Get the dates
    let getYear = function (url) {
      return new Promise((resolve) => {
        d3.csv(url)
          .header('authorization', 'Bearer ' + window.populateData.token)
          .get(function(error, csv) {
            if (error) throw error;

            resolve(moment(_.map(csv, 'date')[0]).year())
          });
      })
    }

    // Insert the buttons to the DOM
    Promise.all([getYear(maxYearUrl), getYear(minYearUrl)]).then((range) => {
      const $dropdownContent = $('[data-dropdown]:not(.js-dropdown)')
      for (var i = range[0]; i >= range[1]; i--) {
        $('<button class="button-grouped button-compact sort-G" data-toggle="' + i + '">' + i + '</button>')
          .appendTo($dropdownContent)
          .bind('click', btnOnClickExtended);
      }
    })

    // Click event handler
    let btnOnClick = function(e) {
      var filter = $(e.target).attr('data-toggle');

      // Reset all buttons
      $('.sort-G').removeClass('active');
      $('.sort-G[data-toggle="' + filter + '"]').addClass('active');

      // Reset dropdown
      const $dropdownText = $('[data-dropdown].js-dropdown')
      let tpl = `${I18n.t('gobierto_budgets.providers.index.previous')}&nbsp;<small>&#9660;</small>`
      $dropdownText.html(tpl);

      // Hide dropdown always
      const $dropdownContent = $('[data-dropdown]:not(.js-dropdown)')
      $dropdownContent.addClass('hidden')

      // Hide table to show spinner
      $tableHTML.addClass('hidden');

      $('html, body').animate({
        scrollTop: $('#invoices-filters').offset().top
      }, 500);

      getData(filter);
    }

    // Extend btnOnClick functionality just for dynamic content (Promise)
    // In order to avoid mix logic with old features, since jQuery appendTo method must bind the event itself
    let btnOnClickExtended = function (e) {
      // Call original function
      btnOnClick.call(this, e)

      // Run concrete stuff
      const $dropdownText = $('[data-dropdown].js-dropdown')
      let tpl = `${$(e.target).attr('data-toggle')}&nbsp;<small>&#9660;</small>`
      $dropdownText.html(tpl);
    }

    $('#invoices-filters .sort-G').on('click', btnOnClick);

    getData('3m');
  };

  function getData(filter) {
    var dateRange;

    if (filter === '3m'){
      dateRange = moment().subtract(3, 'month').format('YYYYMMDD') + '-' + moment().format('YYYYMMDD');
    } else if (filter === '12m'){
      dateRange = moment().subtract(1, 'year').format('YYYYMMDD') + '-' + moment().format('YYYYMMDD');
    } else {
      var d1 = new Date(filter, 0, 1);
      var d2 = new Date(filter, 11, 31);
      dateRange = moment(d1).format('YYYYMMDD') + '-' + moment(d2).format('YYYYMMDD');
    }

    var municipalityId = window.populateData.municipalityId;
    var url = dataEndpoint + '?filter_by_location_id='+municipalityId+'&date_date_range='+dateRange+'&sort_asc_by=date&except_columns=_id,invoice_id,payment_date,location_id,province_id,autonomous_region_id';

    // Show spinner
    $(".js-toggle-overlay").addClass('is-active');

    d3.csv(url)
      .header('authorization', 'Bearer ' + window.populateData.token)
      .get(function(error, csv) {
        if (error) throw error;

        // Hide spinner
        $(".js-toggle-overlay").removeClass('is-active');
        // Show table again
        $tableHTML.removeClass('hidden');

        data = _.filter(csv, _callback(filter));

        if (!data.length) {
          // disable empty filter
          $('#invoices-filters button[data-toggle=' + filter + ']').prop('disabled', true)

          // if there's no data, get all available filters and trigger a new one
          let filters = [];
          $('#invoices-filters button[data-toggle]').each(function() { filters.push($(this).attr('data-toggle')) });
          let previousFilter = (filters.indexOf(filter) > 0) ? filters[filters.indexOf(filter) - 1] : alert(I18n.t('gobierto_budgets.invoices.show.empty'))

          // trigger another filter automatically
          $('#invoices-filters button[data-toggle=' + previousFilter + ']').trigger('click');
          return
        }

        _r = {
          domain: [501, 1001, 5001, 10001, 15001],
          range: [0, 1, 2, 3, 4, 5]
        };
        var rangeFormat = d3.scaleThreshold().domain(_r.domain).range(_r.range);
        var intl = new Intl.DateTimeFormat(I18n.locale); // Improve performance
<commit_msg>Update invoices_controller.js<commit_after>import * as d3 from 'd3'
import * as dc from 'dc'
import crossfilter from 'crossfilter2'
import moment from 'moment'
import { d3locale } from 'lib/shared'
import 'jsgrid'

window.GobiertoBudgets.InvoicesController = (function() {

  function InvoicesController() {}

  // Global variables
  var data, ndx, _r, _tabledata, _empty, dataEndpoint, _chartdata = {}, $tableHTML = {};

  InvoicesController.prototype.show = function() {
    $tableHTML = $("#providers-table");

    dataEndpoint = "/presupuestos/proveedores-facturas.csv"

    let municipalityId = window.populateData.municipalityId;
    let maxYearUrl = dataEndpoint + '?filter_by_location_id='+municipalityId+'&sort_desc_by=date&limit=1';
    let minYearUrl = dataEndpoint + '?filter_by_location_id='+municipalityId+'&sort_asc_by=date&limit=1';

    // Get the dates
    let getYear = function (url) {
      return new Promise((resolve) => {
        d3.csv(url)
          .header('authorization', 'Bearer ' + window.populateData.token)
          .get(function(error, csv) {
            if (error) throw error;

            resolve(moment(_.map(csv, 'date')[0]).year())
          });
      })
    }

    // Insert the buttons to the DOM
    Promise.all([getYear(minYearUrl), getYear(maxYearUrl)]).then((range) => {
      const $dropdownContent = $('[data-dropdown]:not(.js-dropdown)')
      for (var i = range[0]; i <= range[1]; i++) {
        $('<button class="button-grouped button-compact sort-G" data-toggle="' + i + '">' + i + '</button>')
          .appendTo($dropdownContent)
          .bind('click', btnOnClickExtended);
      }
    })

    // Click event handler
    let btnOnClick = function(e) {
      var filter = $(e.target).attr('data-toggle');

      // Reset all buttons
      $('.sort-G').removeClass('active');
      $('.sort-G[data-toggle="' + filter + '"]').addClass('active');

      // Reset dropdown
      const $dropdownText = $('[data-dropdown].js-dropdown')
      let tpl = `${I18n.t('gobierto_budgets.providers.index.previous')}&nbsp;<small>&#9660;</small>`
      $dropdownText.html(tpl);

      // Hide dropdown always
      const $dropdownContent = $('[data-dropdown]:not(.js-dropdown)')
      $dropdownContent.addClass('hidden')

      // Hide table to show spinner
      $tableHTML.addClass('hidden');

      $('html, body').animate({
        scrollTop: $('#invoices-filters').offset().top
      }, 500);

      getData(filter);
    }

    // Extend btnOnClick functionality just for dynamic content (Promise)
    // In order to avoid mix logic with old features, since jQuery appendTo method must bind the event itself
    let btnOnClickExtended = function (e) {
      // Call original function
      btnOnClick.call(this, e)

      // Run concrete stuff
      const $dropdownText = $('[data-dropdown].js-dropdown')
      let tpl = `${$(e.target).attr('data-toggle')}&nbsp;<small>&#9660;</small>`
      $dropdownText.html(tpl);
    }

    $('#invoices-filters .sort-G').on('click', btnOnClick);

    getData('3m');
  };

  function getData(filter) {
    var dateRange;

    if (filter === '3m'){
      dateRange = moment().subtract(3, 'month').format('YYYYMMDD') + '-' + moment().format('YYYYMMDD');
    } else if (filter === '12m'){
      dateRange = moment().subtract(1, 'year').format('YYYYMMDD') + '-' + moment().format('YYYYMMDD');
    } else {
      var d1 = new Date(filter, 0, 1);
      var d2 = new Date(filter, 11, 31);
      dateRange = moment(d1).format('YYYYMMDD') + '-' + moment(d2).format('YYYYMMDD');
    }

    var municipalityId = window.populateData.municipalityId;
    var url = dataEndpoint + '?filter_by_location_id='+municipalityId+'&date_date_range='+dateRange+'&sort_asc_by=date&except_columns=_id,invoice_id,payment_date,location_id,province_id,autonomous_region_id';

    // Show spinner
    $(".js-toggle-overlay").addClass('is-active');

    d3.csv(url)
      .header('authorization', 'Bearer ' + window.populateData.token)
      .get(function(error, csv) {
        if (error) throw error;

        // Hide spinner
        $(".js-toggle-overlay").removeClass('is-active');
        // Show table again
        $tableHTML.removeClass('hidden');

        data = _.filter(csv, _callback(filter));

        // enable empty filter
        $('#invoices-filters button[data-toggle=' + filter + ']').prop('disabled', false)

        if (!data.length) {
          // disable empty filter
          $('#invoices-filters button[data-toggle=' + filter + ']').prop('disabled', true)

          // if there's no data, get all available filters and trigger a new one
          let filters = [];
          $('#invoices-filters button[data-toggle]').each(function() { filters.push($(this).attr('data-toggle')) });
          let previousFilter = (filters.indexOf(filter) > 0) ? filters[filters.indexOf(filter) - 1] : alert(I18n.t('gobierto_budgets.invoices.show.empty'))

          // trigger another filter automatically
          $('#invoices-filters button[data-toggle=' + previousFilter + ']').trigger('click');
          return
        }

        _r = {
          domain: [501, 1001, 5001, 10001, 15001],
          range: [0, 1, 2, 3, 4, 5]
        };
        var rangeFormat = d3.scaleThreshold().domain(_r.domain).range(_r.range);
        var intl = new Intl.DateTimeFormat(I18n.locale); // Improve performance

{'fraction_non_alphanumeric': 0.1662259161314696, 'fraction_numerical': 0.013978088401964487, 'mean_word_length': 3.026235741444867, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6742476', 'n_tokens_mistral': 3451, 'n_tokens_neox': 3282, 'n_words': 673}