alertRulesList.tsx 12 KB

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