2022-11-02 07:34:14 +01:00
|
|
|
import { useCallback, useState } from 'react';
|
|
|
|
import useToast from 'hooks/useToast';
|
|
|
|
import { formatUnknownError } from 'utils/formatUnknownError';
|
|
|
|
import { useChangeRequestApi } from './api/actions/useChangeRequestApi/useChangeRequestApi';
|
2022-11-23 13:45:19 +01:00
|
|
|
import { usePendingChangeRequests } from './api/getters/usePendingChangeRequests/usePendingChangeRequests';
|
2022-11-02 07:34:14 +01:00
|
|
|
|
|
|
|
export const useChangeRequestToggle = (project: string) => {
|
|
|
|
const { setToastData, setToastApiError } = useToast();
|
2022-11-30 12:04:29 +01:00
|
|
|
const { addChange } = useChangeRequestApi();
|
2022-11-23 13:45:19 +01:00
|
|
|
const { refetch: refetchChangeRequests } =
|
|
|
|
usePendingChangeRequests(project);
|
2022-11-02 07:34:14 +01:00
|
|
|
|
|
|
|
const [changeRequestDialogDetails, setChangeRequestDialogDetails] =
|
|
|
|
useState<{
|
|
|
|
enabled?: boolean;
|
|
|
|
featureName?: string;
|
|
|
|
environment?: string;
|
|
|
|
isOpen: boolean;
|
|
|
|
}>({ isOpen: false });
|
|
|
|
|
|
|
|
const onChangeRequestToggle = useCallback(
|
|
|
|
(featureName: string, environment: string, enabled: boolean) => {
|
|
|
|
setChangeRequestDialogDetails({
|
|
|
|
featureName,
|
|
|
|
environment,
|
|
|
|
enabled,
|
|
|
|
isOpen: true,
|
|
|
|
});
|
|
|
|
},
|
|
|
|
[]
|
|
|
|
);
|
|
|
|
|
|
|
|
const onChangeRequestToggleClose = useCallback(() => {
|
2022-11-29 13:34:30 +01:00
|
|
|
setChangeRequestDialogDetails(prev => ({ ...prev, isOpen: false }));
|
2022-11-02 07:34:14 +01:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
const onChangeRequestToggleConfirm = useCallback(async () => {
|
|
|
|
try {
|
2022-11-30 12:04:29 +01:00
|
|
|
await addChange(project, changeRequestDialogDetails.environment!, {
|
|
|
|
feature: changeRequestDialogDetails.featureName!,
|
|
|
|
action: 'updateEnabled',
|
|
|
|
payload: {
|
|
|
|
enabled: Boolean(changeRequestDialogDetails.enabled),
|
|
|
|
},
|
|
|
|
});
|
2022-11-02 07:34:14 +01:00
|
|
|
refetchChangeRequests();
|
2022-11-29 13:34:30 +01:00
|
|
|
setChangeRequestDialogDetails(prev => ({ ...prev, isOpen: false }));
|
2022-11-02 07:34:14 +01:00
|
|
|
setToastData({
|
|
|
|
type: 'success',
|
|
|
|
title: 'Changes added to the draft!',
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
setToastApiError(formatUnknownError(error));
|
2022-11-29 13:34:30 +01:00
|
|
|
setChangeRequestDialogDetails(prev => ({ ...prev, isOpen: false }));
|
2022-11-02 07:34:14 +01:00
|
|
|
}
|
2022-11-30 12:04:29 +01:00
|
|
|
}, [addChange]);
|
2022-11-02 07:34:14 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
onChangeRequestToggle,
|
|
|
|
onChangeRequestToggleClose,
|
|
|
|
onChangeRequestToggleConfirm,
|
|
|
|
changeRequestDialogDetails,
|
|
|
|
};
|
|
|
|
};
|