summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/cycle_analytics.js.es6
blob: da473a9bffc21e8b3ee19e5af83e0f5a0078a263 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//= require vue

((global) => {

  const COOKIE_NAME = 'cycle_analytics_help_dismissed';
  const store = gl.cycleAnalyticsStore = {
    isLoading: true,
    hasError: false,
    isHelpDismissed: Cookies.get(COOKIE_NAME),
    analytics: {}
  };

  gl.CycleAnalytics = class CycleAnalytics {
    constructor() {
      const that = this;

      this.vue = new Vue({
        el: '#cycle-analytics',
        name: 'CycleAnalytics',
        created: this.fetchData(),
        data: store,
        methods: {
          dismissLanding() {
            that.dismissLanding();
          }
        }
      });
    }

    fetchData(options) {
      store.isLoading = true;
      options = options || { startDate: 30 };

      $.ajax({
        url: $('#cycle-analytics').data('request-path'),
        method: 'GET',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          cycle_analytics: {
            start_date: options.startDate
          }
        }
      }).done((data) => {
        this.decorateData(data);
        this.initDropdown();
      })
      .error((data) => {
        this.handleError(data);
      })
      .always(() => {
        store.isLoading = false;
      })
    }

    decorateData(data) {
      data.summary = data.summary || [];
      data.stats = data.stats || [];

      data.summary.forEach((item) => {
        item.value = item.value || '-';
      });

      data.stats.forEach((item) => {
        item.value = item.value || '- - -';
      });

      store.analytics = data;
    }

    handleError(data) {
      store.hasError = true;
      new Flash('There was an error while fetching cycle analytics data.', 'alert');
    }

    dismissLanding() {
      store.isHelpDismissed = true;
      Cookies.set(COOKIE_NAME, true, {
        path: gon.relative_url_root || '/'
      });
    }

    initDropdown() {
      const $dropdown = $('.js-ca-dropdown');
      const $label = $dropdown.find('.dropdown-label');

      $dropdown.find('li a').off('click').on('click', (e) => {
        e.preventDefault();
        const $target = $(e.currentTarget);
        const value = $target.data('value');

        $label.text($target.text().trim());
        this.fetchData({ startDate: value });
      })
    }

  }

})(window.gl || (window.gl = {}));