alertRulesList.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import {
  5. addErrorMessage,
  6. addMessage,
  7. addSuccessMessage,
  8. } from 'sentry/actionCreators/indicator';
  9. import HookOrDefault from 'sentry/components/hookOrDefault';
  10. import * as Layout from 'sentry/components/layouts/thirds';
  11. import Link from 'sentry/components/links/link';
  12. import LoadingError from 'sentry/components/loadingError';
  13. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  14. import Pagination from 'sentry/components/pagination';
  15. import {PanelTable} from 'sentry/components/panels/panelTable';
  16. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  17. import {IconArrow} from 'sentry/icons';
  18. import {t} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import type {Project} from 'sentry/types/project';
  21. import {defined} from 'sentry/utils';
  22. import {uniq} from 'sentry/utils/array/uniq';
  23. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  24. import Projects from 'sentry/utils/projects';
  25. import type {ApiQueryKey} from 'sentry/utils/queryClient';
  26. import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
  27. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  28. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  29. import useApi from 'sentry/utils/useApi';
  30. import {useLocation} from 'sentry/utils/useLocation';
  31. import useOrganization from 'sentry/utils/useOrganization';
  32. import useRouter from 'sentry/utils/useRouter';
  33. import {MetricsRemovedAlertsWidgetsAlert} from '../../../metrics/metricsRemovedAlertsWidgetsAlert';
  34. import FilterBar from '../../filterBar';
  35. import type {CombinedAlerts} from '../../types';
  36. import {AlertRuleType, CombinedAlertType} from '../../types';
  37. import {getTeamParams, isIssueAlert} from '../../utils';
  38. import AlertHeader from '../header';
  39. import RuleListRow from './row';
  40. type SortField = 'date_added' | 'name' | ['incident_status', 'date_triggered'];
  41. const defaultSort: SortField = ['incident_status', 'date_triggered'];
  42. function getAlertListQueryKey(orgSlug: string, query: Location['query']): ApiQueryKey {
  43. const queryParams = {...query};
  44. queryParams.expand = ['latestIncident', 'lastTriggered'];
  45. queryParams.team = getTeamParams(queryParams.team!);
  46. if (!queryParams.sort) {
  47. queryParams.sort = defaultSort;
  48. }
  49. return [`/organizations/${orgSlug}/combined-rules/`, {query: queryParams}];
  50. }
  51. const DataConsentBanner = HookOrDefault({
  52. hookName: 'component:data-consent-banner',
  53. defaultComponent: null,
  54. });
  55. function AlertRulesList() {
  56. const location = useLocation();
  57. const router = useRouter();
  58. const api = useApi();
  59. const queryClient = useQueryClient();
  60. const organization = useOrganization();
  61. useRouteAnalyticsEventNames('alert_rules.viewed', 'Alert Rules: Viewed');
  62. useRouteAnalyticsParams({
  63. sort: Array.isArray(location.query.sort)
  64. ? location.query.sort.join(',')
  65. : location.query.sort,
  66. });
  67. // Fetch alert rules
  68. const {
  69. data: ruleListResponse = [],
  70. refetch,
  71. getResponseHeader,
  72. isPending,
  73. isError,
  74. } = useApiQuery<Array<CombinedAlerts | null>>(
  75. getAlertListQueryKey(organization.slug, location.query),
  76. {
  77. staleTime: 0,
  78. }
  79. );
  80. const handleChangeFilter = (activeFilters: string[]) => {
  81. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  82. router.push({
  83. pathname: location.pathname,
  84. query: {
  85. ...currentQuery,
  86. team: activeFilters.length > 0 ? activeFilters : '',
  87. },
  88. });
  89. };
  90. const handleChangeSearch = (name: string) => {
  91. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  92. router.push({
  93. pathname: location.pathname,
  94. query: {
  95. ...currentQuery,
  96. name,
  97. },
  98. });
  99. };
  100. const handleOwnerChange = (
  101. projectId: string,
  102. rule: CombinedAlerts,
  103. ownerValue: string
  104. ) => {
  105. // TODO(davidenwang): Once we have edit apis for uptime alerts, fill this in
  106. if (rule.type === CombinedAlertType.UPTIME) {
  107. return;
  108. }
  109. const endpoint =
  110. rule.type === 'alert_rule'
  111. ? `/organizations/${organization.slug}/alert-rules/${rule.id}`
  112. : `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`;
  113. const updatedRule = {...rule, owner: ownerValue};
  114. api.request(endpoint, {
  115. method: 'PUT',
  116. data: updatedRule,
  117. success: () => {
  118. addMessage(t('Updated alert rule'), 'success');
  119. },
  120. error: () => {
  121. addMessage(t('Unable to save change'), 'error');
  122. },
  123. });
  124. };
  125. const handleDeleteRule = async (projectId: string, rule: CombinedAlerts) => {
  126. const deleteEndpoints = {
  127. [CombinedAlertType.ISSUE]: `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`,
  128. [CombinedAlertType.METRIC]: `/organizations/${organization.slug}/alert-rules/${rule.id}/`,
  129. [CombinedAlertType.UPTIME]: `/projects/${organization.slug}/${projectId}/uptime/${rule.id}/`,
  130. };
  131. try {
  132. await api.requestPromise(deleteEndpoints[rule.type], {method: 'DELETE'});
  133. setApiQueryData<Array<CombinedAlerts | null>>(
  134. queryClient,
  135. getAlertListQueryKey(organization.slug, location.query),
  136. data => data?.filter(r => r?.id !== rule.id && r?.type !== rule.type)
  137. );
  138. refetch();
  139. addSuccessMessage(t('Deleted rule'));
  140. } catch (_err) {
  141. addErrorMessage(t('Error deleting rule'));
  142. }
  143. };
  144. const hasEditAccess = organization.access.includes('alerts:write');
  145. const ruleList = ruleListResponse.filter(defined);
  146. const projectsFromResults = uniq(
  147. ruleList.flatMap(rule =>
  148. rule.type === CombinedAlertType.UPTIME ? [rule.projectSlug] : rule.projects
  149. )
  150. );
  151. const ruleListPageLinks = getResponseHeader?.('Link');
  152. const sort: {asc: boolean; field: SortField} = {
  153. asc: location.query.asc === '1',
  154. field: (location.query.sort as SortField) || defaultSort,
  155. };
  156. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  157. const isAlertRuleSort =
  158. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  159. const sortArrow = (
  160. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  161. );
  162. return (
  163. <Fragment>
  164. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug} />
  165. <PageFiltersContainer>
  166. <AlertHeader router={router} activeTab="rules" />
  167. <Layout.Body>
  168. <Layout.Main fullWidth>
  169. <MetricsRemovedAlertsWidgetsAlert organization={organization} />
  170. <DataConsentBanner source="alerts" />
  171. <FilterBar
  172. location={location}
  173. onChangeFilter={handleChangeFilter}
  174. onChangeSearch={handleChangeSearch}
  175. />
  176. <StyledPanelTable
  177. isLoading={isPending}
  178. isEmpty={ruleList.length === 0 && !isError}
  179. emptyMessage={t('No alert rules found for the current query.')}
  180. headers={[
  181. <StyledSortLink
  182. key="name"
  183. role="columnheader"
  184. aria-sort={
  185. sort.field !== 'name' ? 'none' : sort.asc ? 'ascending' : 'descending'
  186. }
  187. to={{
  188. pathname: location.pathname,
  189. query: {
  190. ...currentQuery,
  191. // sort by name should start by ascending on first click
  192. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  193. sort: 'name',
  194. },
  195. }}
  196. >
  197. {t('Alert Rule')} {sort.field === 'name' ? sortArrow : null}
  198. </StyledSortLink>,
  199. <StyledSortLink
  200. key="status"
  201. role="columnheader"
  202. aria-sort={
  203. !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
  204. }
  205. to={{
  206. pathname: location.pathname,
  207. query: {
  208. ...currentQuery,
  209. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  210. sort: ['incident_status', 'date_triggered'],
  211. },
  212. }}
  213. >
  214. {t('Status')} {isAlertRuleSort ? sortArrow : null}
  215. </StyledSortLink>,
  216. t('Project'),
  217. t('Team'),
  218. t('Actions'),
  219. ]}
  220. >
  221. {isError ? (
  222. <StyledLoadingError
  223. message={t('There was an error loading alerts.')}
  224. onRetry={refetch}
  225. />
  226. ) : null}
  227. <VisuallyCompleteWithData
  228. id="AlertRules-Body"
  229. hasData={ruleList.length > 0}
  230. >
  231. <Projects orgId={organization.slug} slugs={projectsFromResults}>
  232. {({initiallyLoaded, projects}) =>
  233. ruleList.map(rule => {
  234. const isIssueAlertInstance = isIssueAlert(rule);
  235. const keyPrefix = isIssueAlertInstance
  236. ? AlertRuleType.ISSUE
  237. : rule.type === CombinedAlertType.UPTIME
  238. ? AlertRuleType.UPTIME
  239. : AlertRuleType.METRIC;
  240. return (
  241. <RuleListRow
  242. // Metric and issue alerts can have the same id
  243. key={`${keyPrefix}-${rule.id}`}
  244. projectsLoaded={initiallyLoaded}
  245. projects={projects as Project[]}
  246. rule={rule}
  247. orgId={organization.slug}
  248. onOwnerChange={handleOwnerChange}
  249. onDelete={handleDeleteRule}
  250. hasEditAccess={hasEditAccess}
  251. />
  252. );
  253. })
  254. }
  255. </Projects>
  256. </VisuallyCompleteWithData>
  257. </StyledPanelTable>
  258. <Pagination
  259. pageLinks={ruleListPageLinks}
  260. onCursor={(cursor, path, _direction) => {
  261. let team = currentQuery.team;
  262. // Keep team parameter, but empty to remove parameters
  263. if (!team || team.length === 0) {
  264. team = '';
  265. }
  266. router.push({
  267. pathname: path,
  268. query: {...currentQuery, team, cursor},
  269. });
  270. }}
  271. />
  272. </Layout.Main>
  273. </Layout.Body>
  274. </PageFiltersContainer>
  275. </Fragment>
  276. );
  277. }
  278. export default AlertRulesList;
  279. const StyledLoadingError = styled(LoadingError)`
  280. grid-column: 1 / -1;
  281. margin-bottom: ${space(4)};
  282. border-radius: 0;
  283. border-width: 1px 0;
  284. `;
  285. const StyledSortLink = styled(Link)`
  286. color: inherit;
  287. display: flex;
  288. align-items: center;
  289. gap: ${space(0.5)};
  290. :hover {
  291. color: inherit;
  292. }
  293. `;
  294. const StyledPanelTable = styled(PanelTable)`
  295. @media (min-width: ${p => p.theme.breakpoints.small}) {
  296. overflow: initial;
  297. }
  298. grid-template-columns: minmax(250px, 4fr) auto auto 60px auto;
  299. white-space: nowrap;
  300. font-size: ${p => p.theme.fontSizeMedium};
  301. `;