alertRulesList.tsx 10 KB

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