Skip to content

feat(mute-metric-alerts): Add mute button to metric alerts page #50967

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions static/app/components/alerts/snoozeAlert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ type Props = {
}) => void;
projectSlug: string;
ruleActionCategory: RuleActionsCategories;
ruleId: string;
type: 'issue' | 'metric';
ruleId?: string;
};

function SnoozeAlert({
Expand All @@ -33,19 +34,22 @@ function SnoozeAlert({
ruleId,
ruleActionCategory,
hasAccess,
type,
}: Props) {
const organization = useOrganization();
const api = useApi();
const location = useLocation();

const [disabled, setDisabled] = useState(false);

const alertPath = type === 'issue' ? 'rules' : 'alert-rules';

const handleMute = useCallback(
async (target: 'me' | 'everyone', autoMute = false) => {
setDisabled(true);
try {
await api.requestPromise(
`/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/snooze/`,
`/projects/${organization.slug}/${projectSlug}/${alertPath}/${ruleId}/snooze/`,
{
method: 'POST',
data: {
Expand Down Expand Up @@ -87,6 +91,7 @@ function SnoozeAlert({
organization.slug,
projectSlug,
ruleId,
alertPath,
]
);

Expand All @@ -95,7 +100,7 @@ function SnoozeAlert({

try {
await api.requestPromise(
`/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/snooze/`,
`/projects/${organization.slug}/${projectSlug}/${alertPath}/${ruleId}/snooze/`,
{
method: 'DELETE',
}
Expand Down
19 changes: 2 additions & 17 deletions static/app/views/alerts/rules/issue/details/ruleDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import useOrganization from 'sentry/utils/useOrganization';
import useProjects from 'sentry/utils/useProjects';
import {findIncompatibleRules} from 'sentry/views/alerts/rules/issue';
import {ALERT_DEFAULT_CHART_PERIOD} from 'sentry/views/alerts/rules/metric/details/constants';
import {getRuleActionCategory} from 'sentry/views/alerts/rules/utils';

import {IssueAlertDetailsChart} from './alertChart';
import AlertRuleIssuesList from './issuesList';
Expand Down Expand Up @@ -69,23 +70,6 @@ const getIssueAlertDetailsQueryKey = ({
{query: {expand: 'lastTriggered'}},
];

function getRuleActionCategory(rule: IssueAlertRule) {
const numDefaultActions = rule.actions.filter(
action => action.id === 'sentry.mail.actions.NotifyEmailAction'
).length;

switch (numDefaultActions) {
// Are all actions default actions?
case rule.actions.length:
return RuleActionsCategories.ALL_DEFAULT;
// Are none of the actions default actions?
case 0:
return RuleActionsCategories.NO_DEFAULT;
default:
return RuleActionsCategories.SOME_DEFAULT;
}
}

function AlertRuleDetails({params, location, router}: AlertRuleDetailsProps) {
const queryClient = useQueryClient();
const organization = useOrganization();
Expand Down Expand Up @@ -314,6 +298,7 @@ function AlertRuleDetails({params, location, router}: AlertRuleDetailsProps) {
projectSlug={projectSlug}
ruleActionCategory={ruleActionCategory}
hasAccess={hasAccess}
type="issue"
/>
)}
</Access>
Expand Down
21 changes: 21 additions & 0 deletions static/app/views/alerts/rules/metric/details/body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import Placeholder from 'sentry/components/placeholder';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {Organization, Project} from 'sentry/types';
import {RuleActionsCategories} from 'sentry/types/alerts';
import MetricHistory from 'sentry/views/alerts/rules/metric/details/metricHistory';
import {Dataset, MetricRule, TimePeriod} from 'sentry/views/alerts/rules/metric/types';
import {extractEventTypeFilterFromRule} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
import {getAlertRuleActionCategory} from 'sentry/views/alerts/rules/utils';

import {AlertRuleStatus, Incident} from '../../../types';
import {isCrashFreeAlert} from '../utils/isCrashFreeAlert';
Expand Down Expand Up @@ -158,6 +160,9 @@ export default class DetailsBody extends Component<Props> {
...(rule.timeWindow > 1 ? {[TimePeriod.FOURTEEN_DAYS]: t('Last 14 days')} : {}),
};

const isSnoozed = rule.snooze;
const ruleActionCategory = getAlertRuleActionCategory(rule);

return (
<Fragment>
{selectedIncident &&
Expand All @@ -172,6 +177,22 @@ export default class DetailsBody extends Component<Props> {
)}
<Layout.Body>
<Layout.Main>
{isSnoozed && (
<Alert showIcon>
{ruleActionCategory === RuleActionsCategories.NO_DEFAULT
? tct(
"[creator] muted this alert so these notifications won't be sent in the future.",
{creator: rule.snoozeCreatedBy}
)
: tct(
"[creator] muted this alert[forEveryone]so you won't get these notifications in the future.",
{
creator: rule.snoozeCreatedBy,
forEveryone: rule.snoozeForEveryone ? ' for everyone ' : ' ',
}
)}
Comment on lines +187 to +193
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dumb question but wouldn't metric alerts always be for everyone or are we looking for specific email my team -> this user is muted

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2023-06-15 at 12 31 25 PM

you can set it to email a user or yeah if it's a team it emails each user in the team and one person can mute it for themselves.

</Alert>
)}
<StyledPageTimeRangeSelector
organization={organization}
relative={timePeriod.period ?? ''}
Expand Down
34 changes: 33 additions & 1 deletion static/app/views/alerts/rules/metric/details/header.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import isPropValid from '@emotion/is-prop-valid';
import styled from '@emotion/styled';

import Access from 'sentry/components/acl/access';
import SnoozeAlert from 'sentry/components/alerts/snoozeAlert';
import Breadcrumbs from 'sentry/components/breadcrumbs';
import {Button} from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
Expand All @@ -10,17 +12,29 @@ import {IconCopy, IconEdit} from 'sentry/icons';
import {t} from 'sentry/locale';
import {Organization, Project} from 'sentry/types';
import {MetricRule} from 'sentry/views/alerts/rules/metric/types';
import {getAlertRuleActionCategory} from 'sentry/views/alerts/rules/utils';

import {isIssueAlert} from '../../../utils';

type Props = {
hasMetricRuleDetailsError: boolean;
onSnooze: (nextState: {
snooze: boolean;
snoozeCreatedBy?: string;
snoozeForEveryone?: boolean;
}) => void;
organization: Organization;
project?: Project;
rule?: MetricRule;
};

function DetailsHeader({hasMetricRuleDetailsError, rule, organization, project}: Props) {
function DetailsHeader({
hasMetricRuleDetailsError,
rule,
organization,
project,
onSnooze,
}: Props) {
const isRuleReady = !!rule && !hasMetricRuleDetailsError;
const ruleTitle = rule && !hasMetricRuleDetailsError ? rule.name : '';
const settingsLink =
Expand All @@ -39,6 +53,9 @@ function DetailsHeader({hasMetricRuleDetailsError, rule, organization, project}:
},
};

const hasSnoozeFeature = organization.features.includes('mute-metric-alerts');
const isSnoozed = rule?.snooze ?? false;

return (
<Layout.Header>
<Layout.HeaderContent>
Expand All @@ -62,6 +79,21 @@ function DetailsHeader({hasMetricRuleDetailsError, rule, organization, project}:
</Layout.HeaderContent>
<Layout.HeaderActions>
<ButtonBar gap={1}>
{hasSnoozeFeature && rule && project && (
<Access access={['alerts:write']}>
{({hasAccess}) => (
<SnoozeAlert
isSnoozed={isSnoozed}
onSnooze={onSnooze}
ruleId={rule.id}
projectSlug={project.slug}
ruleActionCategory={getAlertRuleActionCategory(rule)}
hasAccess={hasAccess}
type="metric"
/>
)}
</Access>
)}
<Button size="sm" icon={<IconCopy />} to={duplicateLink}>
{t('Duplicate')}
</Button>
Expand Down
54 changes: 53 additions & 1 deletion static/app/views/alerts/rules/metric/details/index.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {initializeOrg} from 'sentry-test/initializeOrg';
import {act, render, screen} from 'sentry-test/reactTestingLibrary';
import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';

import ProjectsStore from 'sentry/stores/projectsStore';
import {trackAnalytics} from 'sentry/utils/analytics';
Expand Down Expand Up @@ -129,4 +129,56 @@ describe('MetricAlertDetails', () => {
expect(incidentMock).toHaveBeenCalled();
expect(issuesRequest).toHaveBeenCalled();
});

it('renders mute button for metric alert', async () => {
const {routerContext, organization, router} = initializeOrg({
organization: {features: ['mute-metric-alerts']},
});
const incident = TestStubs.Incident();
const rule = TestStubs.MetricRule({
projects: [project.slug],
latestIncident: incident,
});

MockApiClient.addMockResponse({
url: `/organizations/org-slug/alert-rules/${rule.id}/`,
body: rule,
});
MockApiClient.addMockResponse({
url: `/organizations/org-slug/incidents/`,
body: [incident],
});

const postRequest = MockApiClient.addMockResponse({
url: `/projects/${organization.slug}/${project.slug}/alert-rules/${rule.id}/snooze/`,
method: 'POST',
});
const deleteRequest = MockApiClient.addMockResponse({
url: `/projects/${organization.slug}/${project.slug}/alert-rules/${rule.id}/snooze/`,
method: 'DELETE',
});

render(
<MetricAlertDetails
organization={organization}
route={{}}
router={router}
routes={router.routes}
routeParams={router.params}
location={router.location}
params={{ruleId: rule.id}}
/>,
{context: routerContext, organization}
);

expect(await screen.findByText('Mute for me')).toBeInTheDocument();

await userEvent.click(screen.getByRole('button', {name: 'Mute for me'}));
expect(postRequest).toHaveBeenCalledTimes(1);

expect(await screen.findByText('Unmute')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', {name: 'Unmute'}));

expect(deleteRequest).toHaveBeenCalledTimes(1);
});
});
16 changes: 16 additions & 0 deletions static/app/views/alerts/rules/metric/details/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,21 @@ class MetricAlertDetails extends Component<Props, State> {
};
}

onSnooze = ({
snooze,
snoozeCreatedBy,
snoozeForEveryone,
}: {
snooze: boolean;
snoozeCreatedBy?: string;
snoozeForEveryone?: boolean;
}) => {
if (this.state.rule) {
const rule = {...this.state.rule, snooze, snoozeCreatedBy, snoozeForEveryone};
this.setState({rule});
}
};

fetchData = async () => {
const {
api,
Expand Down Expand Up @@ -230,6 +245,7 @@ class MetricAlertDetails extends Component<Props, State> {
organization={organization}
rule={rule}
project={project}
onSnooze={this.onSnooze}
/>
<DetailsBody
{...this.props}
Expand Down
3 changes: 3 additions & 0 deletions static/app/views/alerts/rules/metric/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export interface SavedMetricRule extends UnsavedMetricRule {
dateModified: string;
id: string;
name: string;
snooze: boolean;
status: number;
createdBy?: {email: string; id: number; name: string} | null;
errors?: {detail: string}[];
Expand All @@ -111,6 +112,8 @@ export interface SavedMetricRule extends UnsavedMetricRule {
*/
latestIncident?: Incident | null;
originalAlertRuleId?: number | null;
snoozeCreatedBy?: string;
snoozeForEveryone?: boolean;
}

export type MetricRule = Partial<SavedMetricRule> & UnsavedMetricRule;
Expand Down
35 changes: 35 additions & 0 deletions static/app/views/alerts/rules/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import IdBadge from 'sentry/components/idBadge';
import {t} from 'sentry/locale';
import {Organization, Project} from 'sentry/types';
import {IssueAlertRule, RuleActionsCategories} from 'sentry/types/alerts';
import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
import {MetricRule} from 'sentry/views/alerts/rules/metric/types';

export function getProjectOptions({
organization,
Expand Down Expand Up @@ -62,3 +64,36 @@ function renderIdBadge(project: Project) {
/>
);
}

export function getRuleActionCategory(rule: IssueAlertRule) {
const numDefaultActions = rule.actions.filter(
action => action.id === 'sentry.mail.actions.NotifyEmailAction'
).length;

switch (numDefaultActions) {
// Are all actions default actions?
case rule.actions.length:
return RuleActionsCategories.ALL_DEFAULT;
// Are none of the actions default actions?
case 0:
return RuleActionsCategories.NO_DEFAULT;
default:
return RuleActionsCategories.SOME_DEFAULT;
}
}

export function getAlertRuleActionCategory(rule: MetricRule) {
const actions = rule.triggers.map(trigger => trigger.actions).flat();
const numDefaultActions = actions.filter(action => action.type === 'email').length;

switch (numDefaultActions) {
// Are all actions default actions?
case actions.length:
return RuleActionsCategories.ALL_DEFAULT;
// Are none of the actions default actions?
case 0:
return RuleActionsCategories.NO_DEFAULT;
default:
return RuleActionsCategories.SOME_DEFAULT;
}
}