alertRulesList.tsx 11 KB

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