index.tsx 10 KB

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