alertRulesList.tsx 12 KB

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