alertRulesList.tsx 10 KB

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