alertRulesList.tsx 11 KB

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