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/project';
  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 {CombinedAlerts} from '../../types';
  35. import {AlertRuleType, CombinedAlertType} 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. const DataConsentBanner = HookOrDefault({
  51. hookName: 'component:data-consent-banner',
  52. defaultComponent: null,
  53. });
  54. function AlertRulesList() {
  55. const location = useLocation();
  56. const router = useRouter();
  57. const api = useApi();
  58. const queryClient = useQueryClient();
  59. const organization = useOrganization();
  60. useRouteAnalyticsEventNames('alert_rules.viewed', 'Alert Rules: Viewed');
  61. useRouteAnalyticsParams({
  62. sort: Array.isArray(location.query.sort)
  63. ? location.query.sort.join(',')
  64. : location.query.sort,
  65. });
  66. // Fetch alert rules
  67. const {
  68. data: ruleListResponse = [],
  69. refetch,
  70. getResponseHeader,
  71. isLoading,
  72. isError,
  73. } = useApiQuery<Array<CombinedAlerts | 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: CombinedAlerts,
  102. ownerValue: string
  103. ) => {
  104. // TODO(davidenwang): Once we have edit apis for uptime alerts, fill this in
  105. if (rule.type === CombinedAlertType.UPTIME) {
  106. return;
  107. }
  108. const endpoint =
  109. rule.type === 'alert_rule'
  110. ? `/organizations/${organization.slug}/alert-rules/${rule.id}`
  111. : `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`;
  112. const updatedRule = {...rule, owner: ownerValue};
  113. api.request(endpoint, {
  114. method: 'PUT',
  115. data: updatedRule,
  116. success: () => {
  117. addMessage(t('Updated alert rule'), 'success');
  118. },
  119. error: () => {
  120. addMessage(t('Unable to save change'), 'error');
  121. },
  122. });
  123. };
  124. const handleDeleteRule = async (projectId: string, rule: CombinedAlerts) => {
  125. const deleteEndpoints = {
  126. [CombinedAlertType.ISSUE]: `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`,
  127. [CombinedAlertType.METRIC]: `/organizations/${organization.slug}/alert-rules/${rule.id}/`,
  128. [CombinedAlertType.UPTIME]: `/projects/${organization.slug}/${projectId}/uptime/${rule.id}/`,
  129. };
  130. try {
  131. await api.requestPromise(deleteEndpoints[rule.type], {method: 'DELETE'});
  132. setApiQueryData<Array<CombinedAlerts | 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(
  146. ruleList.flatMap(rule =>
  147. rule.type === CombinedAlertType.UPTIME ? [rule.projectSlug] : rule.projects
  148. )
  149. );
  150. const ruleListPageLinks = getResponseHeader?.('Link');
  151. const sort: {asc: boolean; field: SortField} = {
  152. asc: location.query.asc === '1',
  153. field: (location.query.sort as SortField) || defaultSort,
  154. };
  155. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  156. const isAlertRuleSort =
  157. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  158. const sortArrow = (
  159. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  160. );
  161. return (
  162. <Fragment>
  163. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug} />
  164. <PageFiltersContainer>
  165. <AlertHeader router={router} activeTab="rules" />
  166. <Layout.Body>
  167. <Layout.Main fullWidth>
  168. <DataConsentBanner source="alerts" />
  169. <FilterBar
  170. location={location}
  171. onChangeFilter={handleChangeFilter}
  172. onChangeSearch={handleChangeSearch}
  173. />
  174. <StyledPanelTable
  175. isLoading={isLoading}
  176. isEmpty={ruleList.length === 0 && !isError}
  177. emptyMessage={t('No alert rules found for the current query.')}
  178. headers={[
  179. <StyledSortLink
  180. key="name"
  181. role="columnheader"
  182. aria-sort={
  183. sort.field !== 'name' ? 'none' : sort.asc ? 'ascending' : 'descending'
  184. }
  185. to={{
  186. pathname: location.pathname,
  187. query: {
  188. ...currentQuery,
  189. // sort by name should start by ascending on first click
  190. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  191. sort: 'name',
  192. },
  193. }}
  194. >
  195. {t('Alert Rule')} {sort.field === 'name' ? sortArrow : null}
  196. </StyledSortLink>,
  197. <StyledSortLink
  198. key="status"
  199. role="columnheader"
  200. aria-sort={
  201. !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
  202. }
  203. to={{
  204. pathname: location.pathname,
  205. query: {
  206. ...currentQuery,
  207. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  208. sort: ['incident_status', 'date_triggered'],
  209. },
  210. }}
  211. >
  212. {t('Status')} {isAlertRuleSort ? sortArrow : null}
  213. </StyledSortLink>,
  214. t('Project'),
  215. t('Team'),
  216. t('Actions'),
  217. ]}
  218. >
  219. {isError ? (
  220. <StyledLoadingError
  221. message={t('There was an error loading alerts.')}
  222. onRetry={refetch}
  223. />
  224. ) : null}
  225. <VisuallyCompleteWithData
  226. id="AlertRules-Body"
  227. hasData={ruleList.length > 0}
  228. >
  229. <Projects orgId={organization.slug} slugs={projectsFromResults}>
  230. {({initiallyLoaded, projects}) =>
  231. ruleList.map(rule => {
  232. const isIssueAlertInstance = isIssueAlert(rule);
  233. const keyPrefix = isIssueAlertInstance
  234. ? AlertRuleType.ISSUE
  235. : AlertRuleType.METRIC;
  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. `;