index.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. to={{
  151. pathname: location.pathname,
  152. query: {
  153. ...currentQuery,
  154. // sort by name should start by ascending on first click
  155. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  156. sort: 'name',
  157. },
  158. }}
  159. >
  160. {t('Alert Rule')} {sort.field === 'name' && sortArrow}
  161. </StyledSortLink>,
  162. <StyledSortLink
  163. key="status"
  164. to={{
  165. pathname: location.pathname,
  166. query: {
  167. ...currentQuery,
  168. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  169. sort: ['incident_status', 'date_triggered'],
  170. },
  171. }}
  172. >
  173. {t('Status')} {isAlertRuleSort && sortArrow}
  174. </StyledSortLink>,
  175. t('Project'),
  176. t('Team'),
  177. <StyledSortLink
  178. key="dateAdded"
  179. to={{
  180. pathname: location.pathname,
  181. query: {
  182. ...currentQuery,
  183. asc: sort.field === 'date_added' && !sort.asc ? '1' : undefined,
  184. sort: 'date_added',
  185. },
  186. }}
  187. >
  188. {t('Created')} {sort.field === 'date_added' && sortArrow}
  189. </StyledSortLink>,
  190. t('Actions'),
  191. ]}
  192. isLoading={loading}
  193. isEmpty={ruleList?.length === 0}
  194. emptyMessage={t('No alert rules found for the current query.')}
  195. emptyAction={
  196. <EmptyStateAction>
  197. {tct('Learn more about [link:Alerts]', {
  198. link: <ExternalLink href={DOCS_URL} />,
  199. })}
  200. </EmptyStateAction>
  201. }
  202. >
  203. <Projects orgId={orgId} slugs={Array.from(allProjectsFromIncidents)}>
  204. {({initiallyLoaded, projects}) =>
  205. ruleList.map(rule => (
  206. <RuleListRow
  207. // Metric and issue alerts can have the same id
  208. key={`${isIssueAlert(rule) ? 'metric' : 'issue'}-${rule.id}`}
  209. projectsLoaded={initiallyLoaded}
  210. projects={projects as Project[]}
  211. rule={rule}
  212. orgId={orgId}
  213. onDelete={this.handleDeleteRule}
  214. organization={organization}
  215. userTeams={userTeams}
  216. />
  217. ))
  218. }
  219. </Projects>
  220. </StyledPanelTable>
  221. <Pagination pageLinks={ruleListPageLinks} />
  222. </Layout.Main>
  223. </StyledLayoutBody>
  224. );
  225. }
  226. renderBody() {
  227. const {params, organization, router} = this.props;
  228. const {orgId} = params;
  229. return (
  230. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  231. <GlobalSelectionHeader
  232. organization={organization}
  233. showDateSelector={false}
  234. showEnvironmentSelector={false}
  235. >
  236. <AlertHeader organization={organization} router={router} activeTab="rules" />
  237. {this.renderList()}
  238. </GlobalSelectionHeader>
  239. </SentryDocumentTitle>
  240. );
  241. }
  242. }
  243. class AlertRulesListContainer extends Component<Props> {
  244. componentDidMount() {
  245. this.trackView();
  246. }
  247. componentDidUpdate(prevProps: Props) {
  248. const {location} = this.props;
  249. if (prevProps.location.query?.sort !== location.query?.sort) {
  250. this.trackView();
  251. }
  252. }
  253. trackView() {
  254. const {organization, location} = this.props;
  255. trackAnalyticsEvent({
  256. eventKey: 'alert_rules.viewed',
  257. eventName: 'Alert Rules: Viewed',
  258. organization_id: organization.id,
  259. sort: Array.isArray(location.query.sort)
  260. ? location.query.sort.join(',')
  261. : location.query.sort,
  262. });
  263. }
  264. render() {
  265. return <AlertRulesList {...this.props} />;
  266. }
  267. }
  268. export default withGlobalSelection(withTeams(AlertRulesListContainer));
  269. const StyledLayoutBody = styled(Layout.Body)`
  270. margin-bottom: -20px;
  271. `;
  272. const StyledSortLink = styled(Link)`
  273. color: inherit;
  274. :hover {
  275. color: inherit;
  276. }
  277. `;
  278. const FilterWrapper = styled('div')`
  279. display: flex;
  280. margin-bottom: ${space(1.5)};
  281. `;
  282. const StyledSearchBar = styled(SearchBar)`
  283. flex-grow: 1;
  284. margin-left: ${space(1.5)};
  285. `;
  286. const StyledPanelTable = styled(PanelTable)`
  287. overflow: auto;
  288. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  289. overflow: initial;
  290. }
  291. grid-template-columns: auto 1.5fr 1fr 1fr 1fr auto;
  292. white-space: nowrap;
  293. font-size: ${p => p.theme.fontSizeMedium};
  294. `;
  295. const EmptyStateAction = styled('p')`
  296. font-size: ${p => p.theme.fontSizeLarge};
  297. `;