Skip to content

Commit

Permalink
ADM-928:[frontend]refactor: update code style and add features (#1433)
Browse files Browse the repository at this point in the history
* ADM-928:[frontend]refactor: update code style

* ADM-928:[frontend]refactor: update rejected and fulfilled constants

* fix(e2e): rename

* fix(e2e): refactor

* fix(e2e): format

---------

Co-authored-by: guzhongren <guzhongren@live.cn>
  • Loading branch information
weiraneve and guzhongren authored May 8, 2024
1 parent 827d783 commit 07b1c57
Show file tree
Hide file tree
Showing 15 changed files with 61 additions and 82 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { nextStep, updateFailedTimeRange } from '@src/context/stepper/StepperSlice';
import DateRangeViewer from '@src/components/Common/DateRangeViewer';
import { formatDateToTimestampString } from '@src/utils/util';
import { DateRange } from '@src/context/config/configSlice';
import { setupStore } from '@test/utils/setupStoreUtil';
import { render, screen } from '@testing-library/react';
Expand Down Expand Up @@ -62,17 +63,21 @@ describe('DateRangeViewer', () => {
});

it('should show priority high icon when click expand button and step number is 1', async () => {
const failedTimeRanges = ['1706716800000'];
const failedTimeRangeList = [formatDateToTimestampString('2024-02-01T00:00:00.000+08:00')];
store.dispatch(nextStep());
store.dispatch(updateFailedTimeRange(failedTimeRanges));
store.dispatch(updateFailedTimeRange(failedTimeRangeList));
const { getByLabelText } = setup(mockDateRanges);

await userEvent.click(getByLabelText('expandMore'));

expect(screen.getByTestId('PriorityHighIcon')).toBeInTheDocument();
});

it('should not show priority high icon when click expand button and step number is 0', async () => {
const { getByLabelText } = setup(mockDateRanges);

await userEvent.click(getByLabelText('expandMore'));

expect(screen.queryByTestId('PriorityHighIcon')).not.toBeInTheDocument();
});
});
16 changes: 8 additions & 8 deletions frontend/__tests__/context/stepperSlice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ describe('stepper reducer', () => {
{
stepNumber: 0,
timeStamp: 0,
shouldMetricsLoad: true,
failedTimeRange: [],
shouldMetricsLoaded: true,
failedTimeRangeList: [],
},
nextStep(),
);
Expand All @@ -34,8 +34,8 @@ describe('stepper reducer', () => {
{
stepNumber: 0,
timeStamp: 0,
shouldMetricsLoad: true,
failedTimeRange: [],
shouldMetricsLoaded: true,
failedTimeRangeList: [],
},
backStep(),
);
Expand All @@ -48,8 +48,8 @@ describe('stepper reducer', () => {
{
stepNumber: 2,
timeStamp: 0,
shouldMetricsLoad: true,
failedTimeRange: [],
shouldMetricsLoaded: true,
failedTimeRangeList: [],
},
backStep(),
);
Expand All @@ -63,8 +63,8 @@ describe('stepper reducer', () => {
{
stepNumber: 2,
timeStamp: 0,
shouldMetricsLoad: true,
failedTimeRange: [],
shouldMetricsLoaded: true,
failedTimeRangeList: [],
},
updateTimeStamp(mockTime),
);
Expand Down
2 changes: 1 addition & 1 deletion frontend/jest.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"globalSetup": "./global-setup.ts",
"setupFiles": ["./jest.polyfills.ts"],
"setupFilesAfterEnv": ["<rootDir>/__tests__/setupTests.ts"],
"testEnvironment": "<rootDir>/jsdom.extended.ts",
"testEnvironment": "jsdom",
"testRegex": "/__tests__/.*(test|spec)\\.(jsx?|tsx?|ts?)$",
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"],
"moduleNameMapper": {
Expand Down
25 changes: 0 additions & 25 deletions frontend/jsdom.extended.ts

This file was deleted.

8 changes: 4 additions & 4 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
"lint": "eslint -c .eslintrc.json ./ && prettier --check ./",
"fix": "eslint -c .eslintrc.json --fix && npx prettier --write . --ignore-unknown",
"audit": "npx audit-ci@^6 --config ./audit-ci.jsonc",
"test": "jest --env=jsdom",
"test:watch": "jest --env=jsdom --watchAll",
"coverage": "jest --env=jsdom --watchAll=false --coverage",
"coverage:silent": "jest --env=jsdom --watchAll=false --coverage --silent",
"test": "jest",
"test:watch": "jest --watchAll",
"coverage": "jest --watchAll=false --coverage",
"coverage:silent": "jest --watchAll=false --coverage --silent",
"pre-e2e": "./scripts/generate-config-files.sh",
"e2e": "pnpm exec playwright test",
"e2e:major": "pnpm run pre-e2e && pnpm exec playwright test /major-path --project='Google Chrome'",
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/components/Common/DateRangeViewer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type Props = {
const DateRangeViewer = ({ dateRangeList, changeDateRange, selectedDateRange, disabledAll = true }: Props) => {
const [showMoreDateRange, setShowMoreDateRange] = useState(false);
const DateRangeExpandRef = useRef<HTMLDivElement>(null);
const failedTimeRange = useAppSelector(selectFailedTimeRange);
const failedTimeRangeList = useAppSelector(selectFailedTimeRange);
const stepNumber = useAppSelector(selectStepNumber);

const handleClickOutside = useCallback((event: MouseEvent) => {
Expand All @@ -52,7 +52,9 @@ const DateRangeViewer = ({ dateRangeList, changeDateRange, selectedDateRange, di
<DateRangeExpandContainer ref={ref}>
{dateRangeList.map((dateRange) => {
const disabled = dateRange.disabled || disabledAll;
const hasMetricsError = failedTimeRange.includes(formatDateToTimestampString(dateRange.startDate as string));
const hasMetricsError = failedTimeRangeList.includes(
formatDateToTimestampString(dateRange.startDate as string),
);
return (
<SingleDateRange
disabled={disabled}
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/constants/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export const REPORT_PAGE_TYPE = {
DORA: 'DoraReport',
};

export const REJECTED = 'rejected';
export const FULFILLED = 'fulfilled';

export const SHOW_MORE = 'show more >';
export const BACK = 'Back';
export const RETRY = 'retry';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { DateRangePicker } from '@src/containers/ConfigStep/DateRangePicker/Date
import { ADD_TIME_RANGE_BUTTON_TEXT, MAX_TIME_RANGE_AMOUNT } from '@src/constants/resources';
import { BASIC_INFO_ERROR_MESSAGE } from '@src/containers/ConfigStep/Form/literal';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { updateShouldMetricsLoad } from '@src/context/stepper/StepperSlice';
import { updateShouldMetricsLoaded } from '@src/context/stepper/StepperSlice';
import { useAppDispatch, useAppSelector } from '@src/hooks/useAppDispatch';
import { AddButton } from '@src/components/Common/AddButtonOneLine';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
Expand Down Expand Up @@ -56,7 +56,7 @@ export const DateRangePickerGroup = ({ onError }: TProps) => {
const dispatchUpdateConfig = () => {
dispatch(updateShouldGetBoardConfig(true));
dispatch(updateShouldGetPipelineConfig(true));
dispatch(updateShouldMetricsLoad(true));
dispatch(updateShouldMetricsLoaded(true));
};

const addRangeHandler = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { useGetMetricsStepsEffect } from '@src/hooks/useGetMetricsStepsEffect';
import { addNotification } from '@src/context/notification/NotificationSlice';
import { uniqPipelineListCrews, updateResponseCrews } from '@src/utils/util';
import { MESSAGE, NO_PIPELINE_STEP_ERROR } from '@src/constants/resources';
import { shouldMetricsLoad } from '@src/context/stepper/StepperSlice';
import { shouldMetricsLoaded } from '@src/context/stepper/StepperSlice';
import { ErrorNotification } from '@src/components/ErrorNotification';
import { METRICS_DATA_FAIL_STATUS } from '@src/constants/commons';
import { useAppDispatch, useAppSelector } from '@src/hooks';
Expand Down Expand Up @@ -73,7 +73,7 @@ export const PipelineMetricSelection = ({
const pipelineNameWarningMessage = selectPipelineNameWarningMessage(storeContext, id);
const stepWarningMessage = selectStepWarningMessage(storeContext, id);
const [isShowNoStepWarning, setIsShowNoStepWarning] = useState(false);
const shouldLoad = useAppSelector(shouldMetricsLoad);
const shouldLoad = useAppSelector(shouldMetricsLoaded);
const pipelineList = useAppSelector(selectPipelineList);
const shouldGetPipelineConfig = useAppSelector(selectShouldGetPipelineConfig);
const isLoadingRef = useRef(false);
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/containers/MetricsStep/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
import { DeploymentFrequencySettings } from '@src/containers/MetricsStep/DeploymentFrequencySettings';
import { addNotification, closeAllNotifications } from '@src/context/notification/NotificationSlice';
import { Classification } from '@src/containers/MetricsStep/Classification';
import { shouldMetricsLoad } from '@src/context/stepper/StepperSlice';
import { shouldMetricsLoaded } from '@src/context/stepper/StepperSlice';
import DateRangeViewer from '@src/components/Common/DateRangeViewer';
import { useGetBoardInfoEffect } from '@src/hooks/useGetBoardInfo';
import { combineBoardInfo, sortDateRanges } from '@src/utils/util';
Expand Down Expand Up @@ -69,7 +69,7 @@ const MetricsStep = () => {
cycleTimeSettingsType === CYCLE_TIME_SETTINGS_TYPES.BY_COLUMN &&
cycleTimeSettings.filter((e) => e.value === DONE).length > 1;
const { getBoardInfo, isLoading, errorMessage, boardInfoFailedStatus } = useGetBoardInfoEffect();
const shouldLoad = useAppSelector(shouldMetricsLoad);
const shouldLoad = useAppSelector(shouldMetricsLoaded);
const shouldGetBoardConfig = useAppSelector(selectShouldGetBoardConfig);

const getInfo = useCallback(
Expand Down
28 changes: 14 additions & 14 deletions frontend/src/context/stepper/StepperSlice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import type { RootState } from '@src/store';
export interface StepState {
stepNumber: number;
timeStamp: number;
shouldMetricsLoad: boolean;
failedTimeRange: string[];
shouldMetricsLoaded: boolean;
failedTimeRangeList: string[];
}

const initialState: StepState = {
stepNumber: 0,
timeStamp: 0,
shouldMetricsLoad: true,
failedTimeRange: [],
shouldMetricsLoaded: true,
failedTimeRangeList: [],
};

export const stepperSlice = createSlice({
Expand All @@ -25,34 +25,34 @@ export const stepperSlice = createSlice({
state.timeStamp = initialState.timeStamp;
},
nextStep: (state) => {
if (state.shouldMetricsLoad && state.stepNumber === 0) {
state.failedTimeRange = [];
if (state.shouldMetricsLoaded && state.stepNumber === 0) {
state.failedTimeRangeList = [];
}
state.shouldMetricsLoad = true;
state.shouldMetricsLoaded = true;
state.stepNumber += 1;
},
backStep: (state) => {
state.shouldMetricsLoad = false;
state.shouldMetricsLoaded = false;
state.stepNumber = state.stepNumber === ZERO ? ZERO : state.stepNumber - 1;
},
updateShouldMetricsLoad: (state, action) => {
state.shouldMetricsLoad = action.payload;
updateShouldMetricsLoaded: (state, action) => {
state.shouldMetricsLoaded = action.payload;
},
updateTimeStamp: (state, action) => {
state.timeStamp = action.payload;
},
updateFailedTimeRange: (state, action) => {
state.failedTimeRange = state.failedTimeRange.concat(action.payload);
state.failedTimeRangeList = state.failedTimeRangeList.concat(action.payload);
},
},
});

export const { resetStep, nextStep, backStep, updateShouldMetricsLoad, updateTimeStamp, updateFailedTimeRange } =
export const { resetStep, nextStep, backStep, updateShouldMetricsLoaded, updateTimeStamp, updateFailedTimeRange } =
stepperSlice.actions;

export const selectStepNumber = (state: RootState) => state.stepper.stepNumber;
export const selectTimeStamp = (state: RootState) => state.stepper.timeStamp;
export const shouldMetricsLoad = (state: RootState) => state.stepper.shouldMetricsLoad;
export const selectFailedTimeRange = (state: RootState) => state.stepper.failedTimeRange;
export const shouldMetricsLoaded = (state: RootState) => state.stepper.shouldMetricsLoaded;
export const selectFailedTimeRange = (state: RootState) => state.stepper.failedTimeRangeList;

export default stepperSlice.reducer;
8 changes: 4 additions & 4 deletions frontend/src/hooks/useGetBoardInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const useGetBoardInfoEffect = (): useGetBoardInfoInterface => {
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState({});
const [boardInfoFailedStatus, setBoardInfoFailedStatus] = useState(METRICS_DATA_FAIL_STATUS.NOT_FAILED);
const localFailedTimeRange: string[] = [];
const localFailedTimeRangeList: string[] = [];

const getBoardInfo = async (data: BoardInfoConfigDTO) => {
setIsLoading(true);
Expand Down Expand Up @@ -103,15 +103,15 @@ export const useGetBoardInfoEffect = (): useGetBoardInfoInterface => {
if (!res.data) {
errorCount++;
localBoardInfoFailedStatus = METRICS_DATA_FAIL_STATUS.PARTIAL_FAILED_NO_CARDS;
localFailedTimeRange.push(formatDateToTimestampString(info.startDate as string));
localFailedTimeRangeList.push(formatDateToTimestampString(info.startDate as string));
setBoardInfoFailedStatus(METRICS_DATA_FAIL_STATUS.PARTIAL_FAILED_NO_CARDS);
}
return res;
})
.catch((err) => {
errorCount++;
localBoardInfoFailedStatus = boardInfoPartialFailedStatusMapping(err?.code);
localFailedTimeRange.push(formatDateToTimestampString(info.startDate as string));
localFailedTimeRangeList.push(formatDateToTimestampString(info.startDate as string));
setBoardInfoFailedStatus(localBoardInfoFailedStatus);
return err;
});
Expand All @@ -135,7 +135,7 @@ export const useGetBoardInfoEffect = (): useGetBoardInfoInterface => {
})
.finally(() => {
setIsLoading(false);
dispatch(updateFailedTimeRange(localFailedTimeRange));
dispatch(updateFailedTimeRange(localFailedTimeRangeList));
});
}
};
Expand Down
14 changes: 7 additions & 7 deletions frontend/src/hooks/useGetMetricsStepsEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { updateShouldRetryPipelineConfig } from '@src/context/Metrics/metricsSli
import { IStepsParams, IStepsRes, metricsClient } from '@src/clients/MetricsClient';
import { METRICS_DATA_FAIL_STATUS, DURATION } from '@src/constants/commons';
import { updateFailedTimeRange } from '@src/context/stepper/StepperSlice';
import { FULFILLED, MESSAGE, REJECTED } from '@src/constants/resources';
import { useAppDispatch } from '@src/hooks/useAppDispatch';
import { TimeoutError } from '@src/errors/TimeoutError';
import { MESSAGE } from '@src/constants/resources';
import { useState } from 'react';

export interface useGetMetricsStepsEffectInterface {
Expand Down Expand Up @@ -47,10 +47,10 @@ export const useGetMetricsStepsEffect = (): useGetMetricsStepsEffectInterface =>
return metricsClient.getSteps(param, organizationId, buildId, pipelineType, token);
}),
);
const hasRejected = allStepsRes.some((stepInfo) => stepInfo.status === 'rejected');
const hasFulfilled = allStepsRes.some((stepInfo) => stepInfo.status === 'fulfilled');
const hasRejected = allStepsRes.some((stepInfo) => stepInfo.status === REJECTED);
const hasFulfilled = allStepsRes.some((stepInfo) => stepInfo.status === FULFILLED);
const rejectedIndices = allStepsRes.reduce((indices: number[], stepInfo, index) => {
if (stepInfo.status === 'rejected') {
if (stepInfo.status === REJECTED) {
indices.push(index);
}
return indices;
Expand All @@ -60,15 +60,15 @@ export const useGetMetricsStepsEffect = (): useGetMetricsStepsEffectInterface =>
if (!hasRejected) {
setStepFailedStatus(METRICS_DATA_FAIL_STATUS.NOT_FAILED);
} else if (hasRejected && hasFulfilled) {
const rejectedStep = allStepsRes.find((stepInfo) => stepInfo.status === 'rejected');
const rejectedStep = allStepsRes.find((stepInfo) => stepInfo.status === REJECTED);
if ((rejectedStep as PromiseRejectedResult).reason.code == 400) {
setStepFailedStatus(METRICS_DATA_FAIL_STATUS.PARTIAL_FAILED_4XX);
} else {
setStepFailedStatus(METRICS_DATA_FAIL_STATUS.PARTIAL_FAILED_TIMEOUT);
}
}
setIsLoading(false);
if (allStepsRes.every((stepInfo) => stepInfo.status === 'rejected')) {
if (allStepsRes.every((stepInfo) => stepInfo.status === REJECTED)) {
if (isAllTimeoutError(allStepsRes)) {
dispatch(updateShouldRetryPipelineConfig(true));
setErrorMessageAndTime(pipelineType, TIMEOUT);
Expand All @@ -79,7 +79,7 @@ export const useGetMetricsStepsEffect = (): useGetMetricsStepsEffectInterface =>
}

return allStepsRes
.filter((stepInfo) => stepInfo.status === 'fulfilled')
.filter((stepInfo) => stepInfo.status === FULFILLED)
.map((stepInfo) => (stepInfo as PromiseFulfilledResult<IStepsRes>).value)
.reduce(
(accumulator, currentValue) => {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/hooks/useGetPipelineToolInfoEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import { pipelineToolClient, IGetPipelineToolInfoResult } from '@src/clients/pipeline/PipelineToolClient';
import { selectShouldGetPipelineConfig, updatePipelineSettings } from '@src/context/Metrics/metricsSlice';
import { clearMetricsPipelineFormMeta } from '@src/context/meta/metaSlice';
import { shouldMetricsLoad } from '@src/context/stepper/StepperSlice';
import { shouldMetricsLoaded } from '@src/context/stepper/StepperSlice';
import { useEffect, useState, useRef, useCallback } from 'react';
import { useAppDispatch, useAppSelector } from '@src/hooks';

Expand All @@ -29,7 +29,7 @@ export const useGetPipelineToolInfoEffect = (): IUseVerifyPipeLineToolStateInter
const [info, setInfo] = useState<IGetPipelineToolInfoResult>(defaultInfoStructure);
const isProjectCreated = useAppSelector(selectIsProjectCreated);
const restoredPipelineTool = useAppSelector(selectPipelineTool);
const shouldLoad = useAppSelector(shouldMetricsLoad);
const shouldLoad = useAppSelector(shouldMetricsLoaded);
const shouldGetPipelineConfig = useAppSelector(selectShouldGetPipelineConfig);
const [isFirstFetch, setIsFirstFetch] = useState(shouldGetPipelineConfig);

Expand Down
8 changes: 1 addition & 7 deletions frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,6 @@
"types": ["node", "vite-plugin-pwa/react", "jest"]
},
"include": ["src", "__tests__", "e2e", "*.ts"],
"exclude": [
"__tests__/__mocks__/svgTransformer.ts",
"package.json",
"pnpm-lock.yaml",
"jsdom.extended.ts",
"jest.polyfills.ts"
],
"exclude": ["__tests__/__mocks__/svgTransformer.ts", "package.json", "pnpm-lock.yaml", "jest.polyfills.ts"],
"references": [{ "path": "./tsconfig.node.json" }, { "path": "./tsconfig.scripts.json" }]
}

0 comments on commit 07b1c57

Please sign in to comment.