index.tsx 10 KB

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