alertRulesList.tsx 12 KB

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