Skip to content

Commit

Permalink
Fix/cr should activate disabled lag free (#3826)
Browse files Browse the repository at this point in the history
<!-- Thanks for creating a PR! To make it easier for reviewers and
everyone else to understand what your changes relate to, please add some
relevant content to the headings below. Feel free to ignore or delete
sections that you don't think are relevant. Thank you! ❤️ -->

- Adds change request option to activate disabled strategies UI
- Fixes Disable strategy bug (onSuggestDisable)

## About the changes
<!-- Describe the changes introduced. What are they and why are they
being introduced? Feel free to also add screenshots or steps to view the
changes if they're visual. -->

<!-- Does it close an issue? Multiple? -->
Closes #

<!-- (For internal contributors): Does it relate to an issue on public
roadmap? -->
<!--
Relates to [roadmap](https://github.com/orgs/Unleash/projects/10) item:
#
-->

### Important files
<!-- PRs can contain a lot of changes, but not all changes are equally
important. Where should a reviewer start looking to get an overview of
the changes? Are any files particularly important? -->


## Discussion points
<!-- Anything about the PR you'd like to discuss before it gets merged?
Got any questions or doubts? -->

---------

Signed-off-by: andreas-unleash <andreas@getunleash.ai>
  • Loading branch information
andreas-unleash committed May 23, 2023
1 parent 6b21a8b commit 8aadbc8
Show file tree
Hide file tree
Showing 13 changed files with 312 additions and 259 deletions.
4 changes: 2 additions & 2 deletions frontend/cypress/integration/import/import.spec.ts
Expand Up @@ -120,8 +120,8 @@ describe('imports', () => {
cy.get(
"[data-testid='feature-toggle-status'] input[type='checkbox']:checked"
)
.closest('div')
.contains('development');
.invoke('attr', 'aria-label')
.should('eq', 'development');
cy.contains('50%');
});
});
Expand Up @@ -86,8 +86,6 @@ export const StrategyTooltipLink: FC<IStrategyTooltipLinkProps> = ({
<Truncated>
<Typography component="s" color="text.secondary">
{previousTitle}
PREVIOUS consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</Typography>{' '}
</Truncated>
}
Expand All @@ -103,9 +101,6 @@ export const StrategyTooltipLink: FC<IStrategyTooltipLinkProps> = ({
<Typography component="span">
{change.payload.title ||
formatStrategyName(change.payload.name)}
lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua.
</Typography>
</TooltipLink>
</Truncated>
Expand Down
@@ -0,0 +1,55 @@
import { screen } from '@testing-library/react';
import { render } from 'utils/testRenderer';
import { testServerRoute, testServerSetup } from 'utils/testServer';
import { DisableEnableStrategyDialog } from './DisableEnableStrategyDialog';

const server = testServerSetup();

const defaultProps = {
isOpen: true,
onClose: () => {},
onConfirm: () => {},
projectId: 'project1',
featureId: 'feature1',
environmentId: 'env1',
strategy: {
id: 'some-id',
name: 'flexibleRollout',
constraints: [],
parameters: {
rollout: '50%',
stickiness: 'default',
},
},
};

test('should render disable dialog in regular mode', async () => {
testServerRoute(server, '/api/admin/ui-config', {});
testServerRoute(server, '/api/admin/projects/project1', {});

render(<DisableEnableStrategyDialog {...defaultProps} />);

expect(
screen.queryByText('Change requests are enabled for this environment.')
).not.toBeInTheDocument();
expect(
screen.getByText('Are you sure you want to disable this strategy?')
).toBeInTheDocument();
});

test('should render enable dialog in regular mode', async () => {
testServerRoute(server, '/api/admin/ui-config', {});
testServerRoute(server, '/api/admin/projects/project1', {});

const props = {
...defaultProps,
strategy: { ...defaultProps.strategy, disabled: true },
};

render(<DisableEnableStrategyDialog {...props} />);

expect(
screen.queryByText('Change requests are enabled for this environment.')
).not.toBeInTheDocument();
expect(screen.getByText('Enable strategy')).toBeInTheDocument();
});
Expand Up @@ -18,7 +18,9 @@ export const DisableEnableStrategyDialog = ({
const { projectId, environmentId } = props;
const { isChangeRequestConfigured } = useChangeRequestsEnabled(projectId);
const isChangeRequest = isChangeRequestConfigured(environmentId);
const { onSuggestEnable } = useSuggestEnableDisable({ ...props });
const { onSuggestEnable, onSuggestDisable } = useSuggestEnableDisable({
...props,
});
const { onEnable, onDisable } = useEnableDisable({ ...props });
const disabled = Boolean(props.strategy?.disabled);

Expand All @@ -28,7 +30,7 @@ export const DisableEnableStrategyDialog = ({
if (disabled) {
onSuggestEnable();
} else {
onSuggestEnable();
onSuggestDisable();
}
} else {
if (disabled) {
Expand Down Expand Up @@ -70,8 +72,8 @@ export const DisableEnableStrategyDialog = ({
}
elseShow={
<Alert severity="error">
Enabling the strategy will change which users receive
access to the feature.
{disabled ? 'Enabling' : 'Disabling'} the strategy will
change which users receive access to the feature.
</Alert>
}
/>
Expand Down
Expand Up @@ -20,7 +20,10 @@ import {
UPDATE_FEATURE_STRATEGY,
} from '@server/types/permissions';
import { useHasProjectEnvironmentAccess } from 'hooks/useHasAccess';
import { STRATEGY_FORM_REMOVE_ID } from 'utils/testIds';
import {
STRATEGY_FORM_REMOVE_ID,
STRATEGY_REMOVE_MENU_BTN,
} from 'utils/testIds';

export interface IRemoveStrategyMenuProps {
projectId: string;
Expand Down Expand Up @@ -74,6 +77,7 @@ const MenuStrategyRemove = ({
aria-controls={open ? 'actions-menu' : undefined}
aria-haspopup="true"
aria-expanded={open ? 'true' : undefined}
data-testid={STRATEGY_REMOVE_MENU_BTN}
>
<MoreVertIcon sx={{ width: 32, height: 32 }} />
</IconButton>
Expand Down
@@ -1,21 +1,10 @@
import { ENVIRONMENT_STRATEGY_ERROR } from 'constants/apiErrors';
import useFeatureApi from 'hooks/api/actions/useFeatureApi/useFeatureApi';
import { useFeature } from 'hooks/api/getters/useFeature/useFeature';
import useToast from 'hooks/useToast';
import { IFeatureEnvironment } from 'interfaces/featureToggle';
import PermissionSwitch from 'component/common/PermissionSwitch/PermissionSwitch';
import { UPDATE_FEATURE_ENVIRONMENT } from 'component/providers/AccessProvider/permissions';
import { formatUnknownError } from 'utils/formatUnknownError';
import { useRequiredPathParam } from 'hooks/useRequiredPathParam';
import { useChangeRequestToggle } from 'hooks/useChangeRequestToggle';
import { ChangeRequestDialogue } from 'component/changeRequest/ChangeRequestConfirmDialog/ChangeRequestConfirmDialog';
import { UpdateEnabledMessage } from 'component/changeRequest/ChangeRequestConfirmDialog/ChangeRequestMessages/UpdateEnabledMessage';
import { useChangeRequestsEnabled } from 'hooks/useChangeRequestsEnabled';
import { styled } from '@mui/material';
import StringTruncator from 'component/common/StringTruncator/StringTruncator';
import { FeatureOverviewSidePanelEnvironmentHider } from './FeatureOverviewSidePanelEnvironmentHider';
import { useState } from 'react';
import { EnableEnvironmentDialog } from './EnableEnvironmentDialog';
import { FeatureToggleSwitch } from 'component/project/Project/ProjectFeatureToggles/FeatureToggleSwitch/FeatureToggleSwitch';

const StyledContainer = styled('div')(({ theme }) => ({
marginLeft: theme.spacing(-1.5),
Expand Down Expand Up @@ -53,98 +42,7 @@ export const FeatureOverviewSidePanelEnvironmentSwitch = ({

const projectId = useRequiredPathParam('projectId');
const featureId = useRequiredPathParam('featureId');
const { toggleFeatureEnvironmentOn, toggleFeatureEnvironmentOff } =
useFeatureApi();
const { feature, refetchFeature } = useFeature(projectId, featureId);
const { setToastData, setToastApiError } = useToast();
const { isChangeRequestConfigured } = useChangeRequestsEnabled(projectId);
const {
onChangeRequestToggle,
onChangeRequestToggleClose,
onChangeRequestToggleConfirm,
changeRequestDialogDetails,
} = useChangeRequestToggle(projectId);

const [showEnabledDialog, setShowEnabledDialog] = useState(false);
const disabledStrategiesCount = environment.strategies.filter(
strategy => strategy.disabled
).length;
const handleToggleEnvironmentOn = async (
shouldActivateDisabled = false
) => {
try {
await toggleFeatureEnvironmentOn(
projectId,
featureId,
name,
shouldActivateDisabled
);
setToastData({
type: 'success',
title: `Available in ${name}`,
text: `${featureId} is now available in ${name} based on its defined strategies.`,
});
refetchFeature();
if (callback) {
callback();
}
} catch (error: unknown) {
if (
error instanceof Error &&
error.message === ENVIRONMENT_STRATEGY_ERROR
) {
showInfoBox();
} else {
setToastApiError(formatUnknownError(error));
}
}
};

const handleToggleEnvironmentOff = async () => {
try {
await toggleFeatureEnvironmentOff(projectId, featureId, name);
setToastData({
type: 'success',
title: `Unavailable in ${name}`,
text: `${featureId} is unavailable in ${name} and its strategies will no longer have any effect.`,
});
refetchFeature();
if (callback) {
callback();
}
} catch (error: unknown) {
setToastApiError(formatUnknownError(error));
}
};

const toggleEnvironment = async (e: React.ChangeEvent) => {
if (isChangeRequestConfigured(name)) {
e.preventDefault();
onChangeRequestToggle(featureId, name, !enabled);
return;
}
if (enabled) {
await handleToggleEnvironmentOff();
return;
}

if (featureHasOnlyDisabledStrategies()) {
setShowEnabledDialog(true);
} else {
await handleToggleEnvironmentOn();
}
};

const featureHasOnlyDisabledStrategies = () => {
const featureEnvironment = feature?.environments?.find(
env => env.name === name
);
return (
featureEnvironment?.strategies &&
featureEnvironment?.strategies?.length > 0 &&
featureEnvironment?.strategies?.every(strategy => strategy.disabled)
);
};

const defaultContent = (
<>
Expand All @@ -155,30 +53,21 @@ export const FeatureOverviewSidePanelEnvironmentSwitch = ({
</>
);

const onActivateStrategies = async () => {
await handleToggleEnvironmentOn(true);
setShowEnabledDialog(false);
};

const onAddDefaultStrategy = async () => {
await handleToggleEnvironmentOn();
setShowEnabledDialog(false);
const handleToggle = () => {
refetchFeature();
if (callback) callback();
};

return (
<StyledContainer>
<StyledLabel>
<PermissionSwitch
tooltip={
enabled
? `Disable feature in ${name}`
: `Enable feature in ${name}`
}
permission={UPDATE_FEATURE_ENVIRONMENT}
<FeatureToggleSwitch
featureId={feature.name}
projectId={projectId}
checked={enabled}
onChange={toggleEnvironment}
environmentId={name}
environmentName={environment.name}
onToggle={handleToggle}
onError={showInfoBox}
value={enabled}
/>
{children ?? defaultContent}
</StyledLabel>
Expand All @@ -187,27 +76,6 @@ export const FeatureOverviewSidePanelEnvironmentSwitch = ({
hiddenEnvironments={hiddenEnvironments}
setHiddenEnvironments={setHiddenEnvironments}
/>
<ChangeRequestDialogue
isOpen={changeRequestDialogDetails.isOpen}
onClose={onChangeRequestToggleClose}
environment={changeRequestDialogDetails?.environment}
onConfirm={onChangeRequestToggleConfirm}
messageComponent={
<UpdateEnabledMessage
enabled={changeRequestDialogDetails?.enabled!}
featureName={changeRequestDialogDetails?.featureName!}
environment={changeRequestDialogDetails.environment!}
/>
}
/>
<EnableEnvironmentDialog
isOpen={showEnabledDialog}
onClose={() => setShowEnabledDialog(false)}
environment={name}
disabledStrategiesCount={disabledStrategiesCount}
onActivateDisabledStrategies={onActivateStrategies}
onAddDefaultStrategy={onAddDefaultStrategy}
/>
</StyledContainer>
);
};

0 comments on commit 8aadbc8

Please sign in to comment.