Commit cce39124 authored by Ezekiel Kigbo's avatar Ezekiel Kigbo Committed by Brandon Labuschagne

Adds a vuex store for project VSA

parent af930550
export const DEFAULT_DAYS_TO_DISPLAY = 30;
import createFlash from '~/flash';
import axios from '~/lib/utils/axios_utils';
import { __ } from '~/locale';
import { DEFAULT_DAYS_TO_DISPLAY } from '../constants';
import * as types from './mutation_types';
export const fetchCycleAnalyticsData = ({
state: { requestPath, startDate },
dispatch,
commit,
}) => {
commit(types.REQUEST_CYCLE_ANALYTICS_DATA);
return axios
.get(requestPath, {
params: { 'cycle_analytics[start_date]': startDate },
})
.then(({ data }) => commit(types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS, data))
.then(() => dispatch('setSelectedStage'))
.then(() => dispatch('fetchStageData'))
.catch(() => {
commit(types.RECEIVE_CYCLE_ANALYTICS_DATA_ERROR);
createFlash({
message: __('There was an error while fetching value stream analytics data.'),
});
});
};
export const fetchStageData = ({ state: { requestPath, selectedStage, startDate }, commit }) => {
commit(types.REQUEST_STAGE_DATA);
return axios
.get(`${requestPath}/events/${selectedStage.name}.json`, {
params: { 'cycle_analytics[start_date]': startDate },
})
.then(({ data }) => commit(types.RECEIVE_STAGE_DATA_SUCCESS, data))
.catch(() => commit(types.RECEIVE_STAGE_DATA_ERROR));
};
export const setSelectedStage = ({ commit, state: { stages } }, selectedStage = null) => {
const stage = selectedStage || stages[0];
commit(types.SET_SELECTED_STAGE, stage);
};
export const setDateRange = ({ commit }, { startDate = DEFAULT_DAYS_TO_DISPLAY }) =>
commit(types.SET_DATE_RANGE, { startDate });
export const initializeVsa = ({ commit, dispatch }, initialData = {}) => {
commit(types.INITIALIZE_VSA, initialData);
return dispatch('fetchCycleAnalyticsData');
};
/**
* While we are in the process implementing group level features at the project level
* we will use a simplified vuex store for the project level, eventually this can be
* replaced with the store at ee/app/assets/javascripts/analytics/cycle_analytics/store/index.js
* once we have enough of the same features implemented across the project and group level
*/
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import mutations from './mutations';
import state from './state';
Vue.use(Vuex);
export default () =>
new Vuex.Store({
actions,
mutations,
state,
});
export const INITIALIZE_VSA = 'INITIALIZE_VSA';
export const SET_SELECTED_STAGE = 'SET_SELECTED_STAGE';
export const SET_DATE_RANGE = 'SET_DATE_RANGE';
export const REQUEST_CYCLE_ANALYTICS_DATA = 'REQUEST_CYCLE_ANALYTICS_DATA';
export const RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS = 'RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS';
export const RECEIVE_CYCLE_ANALYTICS_DATA_ERROR = 'RECEIVE_CYCLE_ANALYTICS_DATA_ERROR';
export const REQUEST_STAGE_DATA = 'REQUEST_STAGE_DATA';
export const RECEIVE_STAGE_DATA_SUCCESS = 'RECEIVE_STAGE_DATA_SUCCESS';
export const RECEIVE_STAGE_DATA_ERROR = 'RECEIVE_STAGE_DATA_ERROR';
import { decorateData, decorateEvents } from '../utils';
import * as types from './mutation_types';
export default {
[types.INITIALIZE_VSA](state, { requestPath }) {
state.requestPath = requestPath;
},
[types.SET_SELECTED_STAGE](state, stage) {
state.isLoadingStage = true;
state.selectedStage = stage;
state.isLoadingStage = false;
},
[types.SET_DATE_RANGE](state, { startDate }) {
state.startDate = startDate;
},
[types.REQUEST_CYCLE_ANALYTICS_DATA](state) {
state.isLoading = true;
state.stages = [];
state.hasError = false;
},
[types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS](state, data) {
state.isLoading = false;
const { stages, summary } = decorateData(data);
state.stages = stages;
state.summary = summary;
state.hasError = false;
},
[types.RECEIVE_CYCLE_ANALYTICS_DATA_ERROR](state) {
state.isLoading = false;
state.stages = [];
state.hasError = true;
},
[types.REQUEST_STAGE_DATA](state) {
state.isLoadingStage = true;
state.isEmptyStage = false;
state.selectedStageEvents = [];
state.hasError = false;
},
[types.RECEIVE_STAGE_DATA_SUCCESS](state, { events = [] }) {
const { selectedStage } = state;
state.isLoadingStage = false;
state.isEmptyStage = !events.length;
state.selectedStageEvents = decorateEvents(events, selectedStage);
state.hasError = false;
},
[types.RECEIVE_STAGE_DATA_ERROR](state) {
state.isLoadingStage = false;
state.isEmptyStage = true;
state.selectedStageEvents = [];
state.hasError = true;
},
};
import { DEFAULT_DAYS_TO_DISPLAY } from '../constants';
export default () => ({
requestPath: '',
startDate: DEFAULT_DAYS_TO_DISPLAY,
stages: [],
summary: [],
analytics: [],
stats: [],
selectedStage: {},
selectedStageEvents: [],
medians: {},
hasError: false,
isLoading: false,
isLoadingStage: false,
isEmptyStage: false,
});
import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils';
import { dasherize } from '~/lib/utils/text_utility';
import { __ } from '../locale';
import DEFAULT_EVENT_OBJECTS from './default_event_objects';
const EMPTY_STAGE_TEXTS = {
issue: __(
'The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.',
),
plan: __(
'The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.',
),
code: __(
'The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.',
),
test: __(
'The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.',
),
review: __(
'The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.',
),
staging: __(
'The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.',
),
};
/**
* These `decorate` methods will be removed when me migrate to the
* new table layout https://gitlab.com/gitlab-org/gitlab/-/issues/326704
*/
const mapToEvent = (event, stage) => {
return convertObjectPropsToCamelCase(
{
...DEFAULT_EVENT_OBJECTS[stage.slug],
...event,
},
{ deep: true },
);
};
export const decorateEvents = (events, stage) => events.map((event) => mapToEvent(event, stage));
const mapToStage = (permissions, item) => {
const slug = dasherize(item.name.toLowerCase());
return {
...item,
slug,
active: false,
isUserAllowed: permissions[slug],
emptyStageText: EMPTY_STAGE_TEXTS[slug],
component: `stage-${slug}-component`,
};
};
const mapToSummary = ({ value, ...rest }) => ({ ...rest, value: value || '-' });
export const decorateData = (data = {}) => {
const { permissions, stats, summary } = data;
return {
stages: stats?.map((item) => mapToStage(permissions, item)) || [],
summary: summary?.map((item) => mapToSummary(item)) || [],
};
};
import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils';
export const summary = [
{ value: '20', title: 'New Issues' },
{ value: null, title: 'Commits' },
{ value: null, title: 'Deploys' },
{ value: null, title: 'Deployment Frequency', unit: 'per day' },
];
const issueStage = {
title: 'Issue',
name: 'issue',
legend: '',
description: 'Time before an issue gets scheduled',
value: null,
};
const planStage = {
title: 'Plan',
name: 'plan',
legend: '',
description: 'Time before an issue starts implementation',
value: 'about 21 hours',
};
const codeStage = {
title: 'Code',
name: 'code',
legend: '',
description: 'Time until first merge request',
value: '2 days',
};
const testStage = {
title: 'Test',
name: 'test',
legend: '',
description: 'Total test time for all commits/merges',
value: 'about 5 hours',
};
const reviewStage = {
title: 'Review',
name: 'review',
legend: '',
description: 'Time between merge request creation and merge/close',
value: null,
};
const stagingStage = {
title: 'Staging',
name: 'staging',
legend: '',
description: 'From merge request merge until deploy to production',
value: '2 days',
};
export const selectedStage = {
...issueStage,
value: null,
active: false,
isUserAllowed: true,
emptyStageText:
'The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.',
component: 'stage-issue-component',
slug: 'issue',
};
export const stats = [issueStage, planStage, codeStage, testStage, reviewStage, stagingStage];
export const permissions = {
issue: true,
plan: true,
code: true,
test: true,
review: true,
staging: true,
};
export const rawData = {
summary,
stats,
permissions,
};
export const convertedData = {
stages: [
selectedStage,
{
...planStage,
active: false,
isUserAllowed: true,
emptyStageText:
'The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.',
component: 'stage-plan-component',
slug: 'plan',
},
{
...codeStage,
active: false,
isUserAllowed: true,
emptyStageText:
'The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.',
component: 'stage-code-component',
slug: 'code',
},
{
...testStage,
active: false,
isUserAllowed: true,
emptyStageText:
'The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.',
component: 'stage-test-component',
slug: 'test',
},
{
...reviewStage,
active: false,
isUserAllowed: true,
emptyStageText:
'The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.',
component: 'stage-review-component',
slug: 'review',
},
{
...stagingStage,
active: false,
isUserAllowed: true,
emptyStageText:
'The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.',
component: 'stage-staging-component',
slug: 'staging',
},
],
summary: [
{ value: '20', title: 'New Issues' },
{ value: '-', title: 'Commits' },
{ value: '-', title: 'Deploys' },
{ value: '-', title: 'Deployment Frequency', unit: 'per day' },
],
};
export const rawEvents = [
{
title: 'Brockfunc-1617160796',
author: {
id: 275,
name: 'VSM User4',
username: 'vsm-user-4-1617160796',
state: 'active',
avatar_url:
'https://www.gravatar.com/avatar/6a6f5480ae582ba68982a34169420747?s=80&d=identicon',
web_url: 'http://gdk.test:3001/vsm-user-4-1617160796',
show_status: false,
path: '/vsm-user-4-1617160796',
},
iid: '16',
total_time: { days: 1, hours: 9 },
created_at: 'about 1 month ago',
url: 'http://gdk.test:3001/vsa-life/ror-project-vsa/-/issues/16',
short_sha: 'some_sha',
commit_url: 'some_commit_url',
},
{
title: 'Subpod-1617160796',
author: {
id: 274,
name: 'VSM User3',
username: 'vsm-user-3-1617160796',
state: 'active',
avatar_url:
'https://www.gravatar.com/avatar/fde853fc3ab7dc552e649dcb4fcf5f7f?s=80&d=identicon',
web_url: 'http://gdk.test:3001/vsm-user-3-1617160796',
show_status: false,
path: '/vsm-user-3-1617160796',
},
iid: '20',
total_time: { days: 2, hours: 18 },
created_at: 'about 1 month ago',
url: 'http://gdk.test:3001/vsa-life/ror-project-vsa/-/issues/20',
},
];
export const convertedEvents = rawEvents.map((ev) =>
convertObjectPropsToCamelCase(ev, { deep: true }),
);
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import testAction from 'helpers/vuex_action_helper';
import * as actions from '~/cycle_analytics/store/actions';
import httpStatusCodes from '~/lib/utils/http_status';
import { selectedStage } from '../mock_data';
const mockRequestPath = 'some/cool/path';
const mockStartDate = 30;
describe('Project Value Stream Analytics actions', () => {
let state;
let mock;
beforeEach(() => {
state = {};
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
state = {};
});
it.each`
action | type | payload | expectedActions
${'initializeVsa'} | ${'INITIALIZE_VSA'} | ${{ requestPath: mockRequestPath }} | ${['fetchCycleAnalyticsData']}
${'setDateRange'} | ${'SET_DATE_RANGE'} | ${{ startDate: 30 }} | ${[]}
${'setSelectedStage'} | ${'SET_SELECTED_STAGE'} | ${{ selectedStage }} | ${[]}
`(
'$action should dispatch $expectedActions and commit $type',
({ action, type, payload, expectedActions }) =>
testAction({
action: actions[action],
state,
payload,
expectedMutations: [
{
type,
payload,
},
],
expectedActions: expectedActions.map((a) => ({ type: a })),
}),
);
describe('fetchCycleAnalyticsData', () => {
beforeEach(() => {
state = { requestPath: mockRequestPath };
mock = new MockAdapter(axios);
mock.onGet(mockRequestPath).reply(httpStatusCodes.OK);
});
it(`dispatches the 'setSelectedStage' and 'fetchStageData' actions`, () =>
testAction({
action: actions.fetchCycleAnalyticsData,
state,
payload: {},
expectedMutations: [
{ type: 'REQUEST_CYCLE_ANALYTICS_DATA' },
{ type: 'RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS' },
],
expectedActions: [{ type: 'setSelectedStage' }, { type: 'fetchStageData' }],
}));
describe('with a failing request', () => {
beforeEach(() => {
state = { requestPath: mockRequestPath };
mock = new MockAdapter(axios);
mock.onGet(mockRequestPath).reply(httpStatusCodes.BAD_REQUEST);
});
it(`commits the 'RECEIVE_CYCLE_ANALYTICS_DATA_ERROR' mutation`, () =>
testAction({
action: actions.fetchCycleAnalyticsData,
state,
payload: {},
expectedMutations: [
{ type: 'REQUEST_CYCLE_ANALYTICS_DATA' },
{ type: 'RECEIVE_CYCLE_ANALYTICS_DATA_ERROR' },
],
expectedActions: [],
}));
});
});
describe('fetchStageData', () => {
const mockStagePath = `${mockRequestPath}/events/${selectedStage.name}.json`;
beforeEach(() => {
state = {
requestPath: mockRequestPath,
startDate: mockStartDate,
selectedStage,
};
mock = new MockAdapter(axios);
mock.onGet(mockStagePath).reply(httpStatusCodes.OK);
});
it(`commits the 'RECEIVE_STAGE_DATA_SUCCESS' mutation`, () =>
testAction({
action: actions.fetchStageData,
state,
payload: {},
expectedMutations: [{ type: 'REQUEST_STAGE_DATA' }, { type: 'RECEIVE_STAGE_DATA_SUCCESS' }],
expectedActions: [],
}));
describe('with a failing request', () => {
beforeEach(() => {
state = {
requestPath: mockRequestPath,
startDate: mockStartDate,
selectedStage,
};
mock = new MockAdapter(axios);
mock.onGet(mockStagePath).reply(httpStatusCodes.BAD_REQUEST);
});
it(`commits the 'RECEIVE_STAGE_DATA_ERROR' mutation`, () =>
testAction({
action: actions.fetchStageData,
state,
payload: {},
expectedMutations: [{ type: 'REQUEST_STAGE_DATA' }, { type: 'RECEIVE_STAGE_DATA_ERROR' }],
expectedActions: [],
}));
});
});
});
import * as types from '~/cycle_analytics/store/mutation_types';
import mutations from '~/cycle_analytics/store/mutations';
import { selectedStage, rawEvents, convertedEvents, rawData, convertedData } from '../mock_data';
let state;
const mockRequestPath = 'fake/request/path';
const mockStartData = '2021-04-20';
describe('Project Value Stream Analytics mutations', () => {
beforeEach(() => {
state = {};
});
afterEach(() => {
state = null;
});
it.each`
mutation | stateKey | value
${types.SET_SELECTED_STAGE} | ${'isLoadingStage'} | ${false}
${types.REQUEST_CYCLE_ANALYTICS_DATA} | ${'isLoading'} | ${true}
${types.REQUEST_CYCLE_ANALYTICS_DATA} | ${'stages'} | ${[]}
${types.REQUEST_CYCLE_ANALYTICS_DATA} | ${'hasError'} | ${false}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS} | ${'isLoading'} | ${false}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS} | ${'hasError'} | ${false}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_ERROR} | ${'isLoading'} | ${false}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_ERROR} | ${'hasError'} | ${true}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_ERROR} | ${'stages'} | ${[]}
${types.REQUEST_STAGE_DATA} | ${'isLoadingStage'} | ${true}
${types.REQUEST_STAGE_DATA} | ${'isEmptyStage'} | ${false}
${types.REQUEST_STAGE_DATA} | ${'hasError'} | ${false}
${types.REQUEST_STAGE_DATA} | ${'selectedStageEvents'} | ${[]}
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${'isLoadingStage'} | ${false}
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${'selectedStageEvents'} | ${[]}
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${'hasError'} | ${false}
${types.RECEIVE_STAGE_DATA_ERROR} | ${'isLoadingStage'} | ${false}
${types.RECEIVE_STAGE_DATA_ERROR} | ${'selectedStageEvents'} | ${[]}
${types.RECEIVE_STAGE_DATA_ERROR} | ${'hasError'} | ${true}
${types.RECEIVE_STAGE_DATA_ERROR} | ${'isEmptyStage'} | ${true}
`('$mutation will set $stateKey to $value', ({ mutation, stateKey, value }) => {
mutations[mutation](state, {});
expect(state).toMatchObject({ [stateKey]: value });
});
it.each`
mutation | payload | stateKey | value
${types.INITIALIZE_VSA} | ${{ requestPath: mockRequestPath }} | ${'requestPath'} | ${mockRequestPath}
${types.SET_SELECTED_STAGE} | ${selectedStage} | ${'selectedStage'} | ${selectedStage}
${types.SET_DATE_RANGE} | ${{ startDate: mockStartData }} | ${'startDate'} | ${mockStartData}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS} | ${rawData} | ${'stages'} | ${convertedData.stages}
${types.RECEIVE_CYCLE_ANALYTICS_DATA_SUCCESS} | ${rawData} | ${'summary'} | ${convertedData.summary}
`(
'$mutation with $payload will set $stateKey to $value',
({ mutation, payload, stateKey, value }) => {
mutations[mutation](state, payload);
expect(state).toMatchObject({ [stateKey]: value });
},
);
describe('with a stage selected', () => {
beforeEach(() => {
state = {
selectedStage,
};
});
it.each`
mutation | payload | stateKey | value
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${{ events: [] }} | ${'isEmptyStage'} | ${true}
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${{ events: rawEvents }} | ${'selectedStageEvents'} | ${convertedEvents}
${types.RECEIVE_STAGE_DATA_SUCCESS} | ${{ events: rawEvents }} | ${'isEmptyStage'} | ${false}
`(
'$mutation with $payload will set $stateKey to $value',
({ mutation, payload, stateKey, value }) => {
mutations[mutation](state, payload);
expect(state).toMatchObject({ [stateKey]: value });
},
);
});
});
import { decorateEvents, decorateData } from '~/cycle_analytics/utils';
import { selectedStage, rawData, convertedData, rawEvents } from './mock_data';
describe('Value stream analytics utils', () => {
describe('decorateEvents', () => {
const [result] = decorateEvents(rawEvents, selectedStage);
const eventKeys = Object.keys(result);
const authorKeys = Object.keys(result.author);
it('will return the same number of events', () => {
expect(decorateEvents(rawEvents, selectedStage).length).toBe(rawEvents.length);
});
it('will set all the required event fields', () => {
['totalTime', 'author', 'createdAt', 'shortSha', 'commitUrl'].forEach((key) => {
expect(eventKeys).toContain(key);
});
['webUrl', 'avatarUrl'].forEach((key) => {
expect(authorKeys).toContain(key);
});
});
it('will remove unused fields', () => {
['total_time', 'created_at', 'short_sha', 'commit_url'].forEach((key) => {
expect(eventKeys).not.toContain(key);
});
['web_url', 'avatar_url'].forEach((key) => {
expect(authorKeys).not.toContain(key);
});
});
});
describe('decorateData', () => {
const result = decorateData(rawData);
it('returns the summary data', () => {
expect(result.summary).toEqual(convertedData.summary);
});
it('returns the stages data', () => {
expect(result.stages).toEqual(convertedData.stages);
});
it('returns each of the default value stream stages', () => {
const stages = result.stages.map(({ name }) => name);
['issue', 'plan', 'code', 'test', 'review', 'staging'].forEach((stageName) => {
expect(stages).toContain(stageName);
});
});
it('returns `-` for summary data that has no value', () => {
const singleSummaryResult = decorateData({
stats: [],
permissions: { issue: true },
summary: [{ value: null, title: 'Commits' }],
});
expect(singleSummaryResult.summary).toEqual([{ value: '-', title: 'Commits' }]);
});
it('returns additional fields for each stage', () => {
const singleStageResult = decorateData({
stats: [{ name: 'issue', value: null }],
permissions: { issue: false },
});
const stage = singleStageResult.stages[0];
const txt =
'The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.';
expect(stage).toMatchObject({
active: false,
isUserAllowed: false,
emptyStageText: txt,
slug: 'issue',
component: 'stage-issue-component',
});
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment