alertRulesList.tsx 10 KB

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