All files / app/assets/javascripts/analytics/usage_trends/components usage_trends_count_chart.vue

97.67% Statements 42/43
75% Branches 15/20
96.43% Functions 27/28
97.67% Lines 42/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207  2x 2x 2x   2x         2x 2x 2x   2x                                                                           16x             18x     60x     36x     36x       2x     24x     16x   12x 12x 24x           9x           9x 9x                                       16x 16x 16x     16x             14x 14x           14x 14x 4x                                       8x         2x 2x 2x   4x 4x               2x 2x 2x         2x         102x                                        
<script>
import { GlAlert } from '@gitlab/ui';
import { GlLineChart } from '@gitlab/ui/dist/charts';
import * as Sentry from '@sentry/browser';
import { some, every } from 'lodash';
import {
  differenceInMonths,
  formatDateAsMonth,
  getDayDifference,
} from '~/lib/utils/datetime_utility';
import ChartSkeletonLoader from '~/vue_shared/components/resizable_chart/skeleton_loader.vue';
import { TODAY, START_DATE } from '../constants';
import { getAverageByMonth, getEarliestDate, generateDataKeys } from '../utils';
 
const QUERY_DATA_KEY = 'usageTrendsMeasurements';
 
export default {
  name: 'UsageTrendsCountChart',
  components: {
    GlLineChart,
    GlAlert,
    ChartSkeletonLoader,
  },
  startDate: START_DATE,
  endDate: TODAY,
  props: {
    chartTitle: {
      type: String,
      required: true,
    },
    loadChartErrorMessage: {
      type: String,
      required: true,
    },
    noDataMessage: {
      type: String,
      required: true,
    },
    xAxisTitle: {
      type: String,
      required: true,
    },
    yAxisTitle: {
      type: String,
      required: true,
    },
    queries: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      errors: { ...generateDataKeys(this.queries, '') },
      ...generateDataKeys(this.queries, []),
    };
  },
  computed: {
    errorMessages() {
      return Object.values(this.errors);
    },
    isLoading() {
      return some(this.$apollo.queries, (query) => query?.loading);
    },
    allQueriesFailed() {
      return every(this.errorMessages, (message) => message.length);
    },
    hasLoadingErrors() {
      return some(this.errorMessages, (message) => message.length);
    },
    errorMessage() {
      // show the generic loading message if all requests fail
      return this.allQueriesFailed ? this.loadChartErrorMessage : this.errorMessages.join('\n\n');
    },
    hasEmptyDataSet() {
      return this.chartData.every(({ data }) => data.length === 0);
    },
    totalDaysToShow() {
      return getDayDifference(this.$options.startDate, this.$options.endDate);
    },
    chartData() {
      const options = { shouldRound: true };
      return this.queries.map(({ identifier, title }) => ({
        name: title,
        data: getAverageByMonth(this[identifier]?.nodes, options),
      }));
    },
    range() {
      return {
        min: this.$options.startDate,
        max: this.$options.endDate,
      };
    },
    chartOptions() {
      const { endDate, startDate } = this.$options;
      return {
        xAxis: {
          ...this.range,
          name: this.xAxisTitle,
          type: 'time',
          splitNumber: differenceInMonths(startDate, endDate) + 1,
          axisLabel: {
            interval: 0,
            showMinLabel: false,
            showMaxLabel: false,
            align: 'right',
            formatter: formatDateAsMonth,
          },
        },
        yAxis: {
          name: this.yAxisTitle,
        },
      };
    },
  },
  created() {
    this.queries.forEach(({ query, identifier, loadError }) => {
      this.$apollo.addSmartQuery(identifier, {
        query,
        variables() {
          return {
            identifier,
            first: this.totalDaysToShow,
            after: null,
          };
        },
        update(data) {
          const { nodes = [], pageInfo } = data[QUERY_DATA_KEY] || {};
          return {
            nodes,
            pageInfo,
          };
        },
        result() {
          const { pageInfo, nodes } = this[identifier];
          if (pageInfo?.hasNextPage && this.calculateDaysToFetch(getEarliestDate(nodes)) > 0) {
            this.fetchNextPage({
              query: this.$apollo.queries[identifier],
              errorMessage: loadError,
              pageInfo,
              identifier,
            });
          }
        },
        error(error) {
          this.handleError({
            message: loadError,
            identifier,
            error,
          });
        },
      });
    });
  },
  methods: {
    calculateDaysToFetch(firstDataPointDate = null) {
      return firstDataPointDate
        ? Math.max(0, getDayDifference(this.$options.startDate, new Date(firstDataPointDate)))
        : 0;
    },
    handleError({ identifier, error, message }) {
      this.loadingError = true;
      this.errors = { ...this.errors, [identifier]: message };
      Sentry.captureException(error);
    },
    fetchNextPage({ query, pageInfo, identifier, errorMessage }) {
      query
        .fetchMore({
          variables: {
            identifier,
            first: this.calculateDaysToFetch(getEarliestDate(this[identifier].nodes)),
            after: pageInfo.endCursor,
          },
          updateQuery: (previousResult, { fetchMoreResult }) => {
            const { nodes, ...rest } = fetchMoreResult[QUERY_DATA_KEY];
            const { nodes: previousNodes } = previousResult[QUERY_DATA_KEY];
            return {
              [QUERY_DATA_KEY]: { ...rest, nodes: [...previousNodes, ...nodes] },
            };
          },
        })
        .catch((error) => this.handleError({ identifier, error, message: errorMessage }));
    },
  },
};
</script>
<template>
  <div>
    <h3>{{ chartTitle }}</h3>
    <gl-alert v-if="hasLoadingErrors" variant="danger" :dismissible="false" class="gl-mt-3">
      {{ errorMessage }}
    </gl-alert>
    <div v-if="!allQueriesFailed">
      <chart-skeleton-loader v-if="isLoading" />
      <gl-alert v-else-if="hasEmptyDataSet" variant="info" :dismissible="false" class="gl-mt-3">
        {{ noDataMessage }}
      </gl-alert>
      <gl-line-chart
        v-else
        :option="chartOptions"
        :include-legend-avg-max="true"
        :data="chartData"
      />
    </div>
  </div>
</template>