index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import {Component} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import flatten from 'lodash/flatten';
  5. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import * as Layout from 'sentry/components/layouts/thirds';
  8. import ExternalLink from 'sentry/components/links/externalLink';
  9. import Link from 'sentry/components/links/link';
  10. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  11. import Pagination from 'sentry/components/pagination';
  12. import {PanelTable} from 'sentry/components/panels';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {IconArrow} from 'sentry/icons';
  15. import {t, tct} from 'sentry/locale';
  16. import {Organization, PageFilters, Project} from 'sentry/types';
  17. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  18. import Projects from 'sentry/utils/projects';
  19. import Teams from 'sentry/utils/teams';
  20. import withPageFilters from 'sentry/utils/withPageFilters';
  21. import FilterBar from '../filterBar';
  22. import AlertHeader from '../list/header';
  23. import {CombinedMetricIssueAlerts} from '../types';
  24. import {getTeamParams, isIssueAlert} from '../utils';
  25. import RuleListRow from './row';
  26. const DOCS_URL = 'https://docs.sentry.io/product/alerts-notifications/metric-alerts/';
  27. type Props = RouteComponentProps<{orgId: string}, {}> & {
  28. organization: Organization;
  29. selection: PageFilters;
  30. };
  31. type State = {
  32. ruleList?: CombinedMetricIssueAlerts[];
  33. teamFilterSearch?: string;
  34. };
  35. class AlertRulesList extends AsyncComponent<Props, State & AsyncComponent['state']> {
  36. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  37. const {params, location} = this.props;
  38. const {query} = location;
  39. query.expand = ['latestIncident'];
  40. query.team = getTeamParams(query.team);
  41. if (!query.sort) {
  42. query.sort = ['incident_status', 'date_triggered'];
  43. }
  44. return [
  45. [
  46. 'ruleList',
  47. `/organizations/${params && params.orgId}/combined-rules/`,
  48. {
  49. query,
  50. },
  51. ],
  52. ];
  53. }
  54. handleChangeFilter = (_sectionId: string, activeFilters: Set<string>) => {
  55. const {router, location} = this.props;
  56. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  57. const teams = [...activeFilters];
  58. router.push({
  59. pathname: location.pathname,
  60. query: {
  61. ...currentQuery,
  62. team: teams.length ? teams : '',
  63. },
  64. });
  65. };
  66. handleChangeSearch = (name: string) => {
  67. const {router, location} = this.props;
  68. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  69. router.push({
  70. pathname: location.pathname,
  71. query: {
  72. ...currentQuery,
  73. name,
  74. },
  75. });
  76. };
  77. handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
  78. const {params} = this.props;
  79. const {orgId} = params;
  80. const alertPath = isIssueAlert(rule) ? 'rules' : 'alert-rules';
  81. try {
  82. await this.api.requestPromise(
  83. `/projects/${orgId}/${projectId}/${alertPath}/${rule.id}/`,
  84. {
  85. method: 'DELETE',
  86. }
  87. );
  88. this.reloadData();
  89. } catch (_err) {
  90. addErrorMessage(t('Error deleting rule'));
  91. }
  92. };
  93. renderLoading() {
  94. return this.renderBody();
  95. }
  96. renderList() {
  97. const {
  98. params: {orgId},
  99. location,
  100. organization,
  101. router,
  102. } = this.props;
  103. const {loading, ruleList = [], ruleListPageLinks} = this.state;
  104. const {query} = location;
  105. const allProjectsFromIncidents = new Set(
  106. flatten(ruleList?.map(({projects}) => projects))
  107. );
  108. const sort: {
  109. asc: boolean;
  110. field: 'date_added' | 'name' | ['incident_status', 'date_triggered'];
  111. } = {
  112. asc: query.asc === '1',
  113. field: query.sort || 'date_added',
  114. };
  115. const {cursor: _cursor, page: _page, ...currentQuery} = query;
  116. const isAlertRuleSort =
  117. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  118. const sortArrow = (
  119. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  120. );
  121. return (
  122. <StyledLayoutBody>
  123. <Layout.Main fullWidth>
  124. <FilterBar
  125. location={location}
  126. onChangeFilter={this.handleChangeFilter}
  127. onChangeSearch={this.handleChangeSearch}
  128. />
  129. <Teams provideUserTeams>
  130. {({initiallyLoaded: loadedTeams, teams}) => (
  131. <StyledPanelTable
  132. headers={[
  133. <StyledSortLink
  134. key="name"
  135. role="columnheader"
  136. aria-sort={
  137. sort.field !== 'name'
  138. ? 'none'
  139. : sort.asc
  140. ? 'ascending'
  141. : 'descending'
  142. }
  143. to={{
  144. pathname: location.pathname,
  145. query: {
  146. ...currentQuery,
  147. // sort by name should start by ascending on first click
  148. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  149. sort: 'name',
  150. },
  151. }}
  152. >
  153. {t('Alert Rule')} {sort.field === 'name' && sortArrow}
  154. </StyledSortLink>,
  155. <StyledSortLink
  156. key="status"
  157. role="columnheader"
  158. aria-sort={
  159. !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
  160. }
  161. to={{
  162. pathname: location.pathname,
  163. query: {
  164. ...currentQuery,
  165. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  166. sort: ['incident_status', 'date_triggered'],
  167. },
  168. }}
  169. >
  170. {t('Status')} {isAlertRuleSort && sortArrow}
  171. </StyledSortLink>,
  172. t('Project'),
  173. t('Team'),
  174. <StyledSortLink
  175. key="dateAdded"
  176. role="columnheader"
  177. aria-sort={
  178. sort.field !== 'date_added'
  179. ? 'none'
  180. : sort.asc
  181. ? 'ascending'
  182. : 'descending'
  183. }
  184. to={{
  185. pathname: location.pathname,
  186. query: {
  187. ...currentQuery,
  188. asc: sort.field === 'date_added' && !sort.asc ? '1' : undefined,
  189. sort: 'date_added',
  190. },
  191. }}
  192. >
  193. {t('Created')} {sort.field === 'date_added' && sortArrow}
  194. </StyledSortLink>,
  195. t('Actions'),
  196. ]}
  197. isLoading={loading || !loadedTeams}
  198. isEmpty={ruleList?.length === 0}
  199. emptyMessage={t('No alert rules found for the current query.')}
  200. emptyAction={
  201. <EmptyStateAction>
  202. {tct('Learn more about [link:Alerts]', {
  203. link: <ExternalLink href={DOCS_URL} />,
  204. })}
  205. </EmptyStateAction>
  206. }
  207. >
  208. <Projects orgId={orgId} slugs={Array.from(allProjectsFromIncidents)}>
  209. {({initiallyLoaded, projects}) =>
  210. ruleList.map(rule => (
  211. <RuleListRow
  212. // Metric and issue alerts can have the same id
  213. key={`${isIssueAlert(rule) ? 'metric' : 'issue'}-${rule.id}`}
  214. projectsLoaded={initiallyLoaded}
  215. projects={projects as Project[]}
  216. rule={rule}
  217. orgId={orgId}
  218. onDelete={this.handleDeleteRule}
  219. organization={organization}
  220. userTeams={new Set(teams.map(team => team.id))}
  221. />
  222. ))
  223. }
  224. </Projects>
  225. </StyledPanelTable>
  226. )}
  227. </Teams>
  228. <Pagination
  229. pageLinks={ruleListPageLinks}
  230. onCursor={(cursor, path, _direction) => {
  231. let team = currentQuery.team;
  232. // Keep team parameter, but empty to remove parameters
  233. if (!team || team.length === 0) {
  234. team = '';
  235. }
  236. router.push({
  237. pathname: path,
  238. query: {...currentQuery, team, cursor},
  239. });
  240. }}
  241. />
  242. </Layout.Main>
  243. </StyledLayoutBody>
  244. );
  245. }
  246. renderBody() {
  247. const {params, organization, router} = this.props;
  248. const {orgId} = params;
  249. return (
  250. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  251. <PageFiltersContainer
  252. organization={organization}
  253. showDateSelector={false}
  254. showEnvironmentSelector={false}
  255. hideGlobalHeader
  256. >
  257. <AlertHeader organization={organization} router={router} activeTab="rules" />
  258. {this.renderList()}
  259. </PageFiltersContainer>
  260. </SentryDocumentTitle>
  261. );
  262. }
  263. }
  264. class AlertRulesListContainer extends Component<Props> {
  265. componentDidMount() {
  266. this.trackView();
  267. }
  268. componentDidUpdate(prevProps: Props) {
  269. const {location} = this.props;
  270. if (prevProps.location.query?.sort !== location.query?.sort) {
  271. this.trackView();
  272. }
  273. }
  274. trackView() {
  275. const {organization, location} = this.props;
  276. trackAdvancedAnalyticsEvent('alert_rules.viewed', {
  277. organization,
  278. sort: Array.isArray(location.query.sort)
  279. ? location.query.sort.join(',')
  280. : location.query.sort,
  281. });
  282. }
  283. render() {
  284. return <AlertRulesList {...this.props} />;
  285. }
  286. }
  287. export default withPageFilters(AlertRulesListContainer);
  288. const StyledLayoutBody = styled(Layout.Body)`
  289. margin-bottom: -20px;
  290. `;
  291. const StyledSortLink = styled(Link)`
  292. color: inherit;
  293. :hover {
  294. color: inherit;
  295. }
  296. `;
  297. const StyledPanelTable = styled(PanelTable)`
  298. position: static;
  299. overflow: auto;
  300. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  301. overflow: initial;
  302. }
  303. grid-template-columns: 4fr auto 140px 60px 110px auto;
  304. white-space: nowrap;
  305. font-size: ${p => p.theme.fontSizeMedium};
  306. `;
  307. const EmptyStateAction = styled('p')`
  308. font-size: ${p => p.theme.fontSizeLarge};
  309. `;