alertRulesList.tsx 11 KB

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