index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import {Component, Fragment} 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, PanelTableHeader} from 'app/components/panels';
  13. import SearchBar from 'app/components/searchBar';
  14. import SentryDocumentTitle from 'app/components/sentryDocumentTitle';
  15. import {IconArrow, IconCheckmark} 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, organization} = this.props;
  41. const {query} = location;
  42. if (organization.features.includes('alert-details-redesign')) {
  43. query.expand = ['latestIncident'];
  44. }
  45. if (organization.features.includes('team-alerts-ownership')) {
  46. query.team = getTeamParams(query.team);
  47. }
  48. if (organization.features.includes('alert-details-redesign') && !query.sort) {
  49. query.sort = ['incident_status', 'date_triggered'];
  50. }
  51. return [
  52. [
  53. 'ruleList',
  54. `/organizations/${params && params.orgId}/combined-rules/`,
  55. {
  56. query,
  57. },
  58. ],
  59. ];
  60. }
  61. tryRenderEmpty() {
  62. const {ruleList} = this.state;
  63. if (ruleList && ruleList.length > 0) {
  64. return null;
  65. }
  66. return (
  67. <Fragment>
  68. <IconWrapper>
  69. <IconCheckmark isCircled size="48" />
  70. </IconWrapper>
  71. <Title>{t('No alert rules exist for these projects.')}</Title>
  72. <Description>
  73. {tct('Learn more about [link:Alerts]', {
  74. link: <ExternalLink href={DOCS_URL} />,
  75. })}
  76. </Description>
  77. </Fragment>
  78. );
  79. }
  80. handleChangeFilter = (_sectionId: string, activeFilters: Set<string>) => {
  81. const {router, location} = this.props;
  82. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  83. const teams = [...activeFilters];
  84. router.push({
  85. pathname: location.pathname,
  86. query: {
  87. ...currentQuery,
  88. team: teams.length ? teams : '',
  89. },
  90. });
  91. };
  92. handleChangeSearch = (name: string) => {
  93. const {router, location} = this.props;
  94. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  95. router.push({
  96. pathname: location.pathname,
  97. query: {
  98. ...currentQuery,
  99. name,
  100. },
  101. });
  102. };
  103. handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
  104. const {params} = this.props;
  105. const {orgId} = params;
  106. const alertPath = isIssueAlert(rule) ? 'rules' : 'alert-rules';
  107. try {
  108. await this.api.requestPromise(
  109. `/projects/${orgId}/${projectId}/${alertPath}/${rule.id}/`,
  110. {
  111. method: 'DELETE',
  112. }
  113. );
  114. this.reloadData();
  115. } catch (_err) {
  116. addErrorMessage(t('Error deleting rule'));
  117. }
  118. };
  119. renderLoading() {
  120. return this.renderBody();
  121. }
  122. renderFilterBar() {
  123. const {teams, location} = this.props;
  124. const selectedTeams = new Set(getTeamParams(location.query.team));
  125. return (
  126. <FilterWrapper>
  127. <TeamFilter
  128. teams={teams}
  129. selectedTeams={selectedTeams}
  130. handleChangeFilter={this.handleChangeFilter}
  131. />
  132. <StyledSearchBar
  133. placeholder={t('Search by name')}
  134. query={location.query?.name}
  135. onSearch={this.handleChangeSearch}
  136. />
  137. </FilterWrapper>
  138. );
  139. }
  140. renderList() {
  141. const {
  142. params: {orgId},
  143. location: {query},
  144. organization,
  145. teams,
  146. } = this.props;
  147. const {loading, ruleList = [], ruleListPageLinks} = this.state;
  148. const allProjectsFromIncidents = new Set(
  149. flatten(ruleList?.map(({projects}) => projects))
  150. );
  151. const sort: {
  152. asc: boolean;
  153. field: 'date_added' | 'name' | ['incident_status', 'date_triggered'];
  154. } = {
  155. asc: query.asc === '1',
  156. field: query.sort || 'date_added',
  157. };
  158. const {cursor: _cursor, page: _page, ...currentQuery} = query;
  159. const hasAlertOwnership = organization.features.includes('team-alerts-ownership');
  160. const hasAlertList = organization.features.includes('alert-details-redesign');
  161. const isAlertRuleSort =
  162. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  163. const sortArrow = (
  164. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  165. );
  166. const userTeams = new Set(teams.filter(({isMember}) => isMember).map(({id}) => id));
  167. return (
  168. <StyledLayoutBody>
  169. <Layout.Main fullWidth>
  170. {hasAlertOwnership && this.renderFilterBar()}
  171. <StyledPanelTable
  172. headers={[
  173. ...(hasAlertList
  174. ? [
  175. // eslint-disable-next-line react/jsx-key
  176. <StyledSortLink
  177. to={{
  178. pathname: location.pathname,
  179. query: {
  180. ...currentQuery,
  181. asc: sort.field === 'name' && !sort.asc ? '1' : undefined,
  182. sort: 'name',
  183. },
  184. }}
  185. >
  186. {t('Alert Rule')} {sort.field === 'name' && sortArrow}
  187. </StyledSortLink>,
  188. // eslint-disable-next-line react/jsx-key
  189. <StyledSortLink
  190. to={{
  191. pathname: location.pathname,
  192. query: {
  193. ...currentQuery,
  194. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  195. sort: ['incident_status', 'date_triggered'],
  196. },
  197. }}
  198. >
  199. {t('Status')} {isAlertRuleSort && sortArrow}
  200. </StyledSortLink>,
  201. ]
  202. : [
  203. t('Type'),
  204. // eslint-disable-next-line react/jsx-key
  205. <StyledSortLink
  206. to={{
  207. pathname: location.pathname,
  208. query: {
  209. ...currentQuery,
  210. asc: sort.field === 'name' && !sort.asc ? '1' : undefined,
  211. sort: 'name',
  212. },
  213. }}
  214. >
  215. {t('Alert Name')} {sort.field === 'name' && sortArrow}
  216. </StyledSortLink>,
  217. ]),
  218. t('Project'),
  219. ...(hasAlertOwnership ? [t('Team')] : []),
  220. ...(hasAlertList ? [] : [t('Created By')]),
  221. // eslint-disable-next-line react/jsx-key
  222. <StyledSortLink
  223. to={{
  224. pathname: location.pathname,
  225. query: {
  226. ...currentQuery,
  227. asc: sort.field === 'date_added' && !sort.asc ? '1' : undefined,
  228. sort: 'date_added',
  229. },
  230. }}
  231. >
  232. {t('Created')} {sort.field === 'date_added' && sortArrow}
  233. </StyledSortLink>,
  234. t('Actions'),
  235. ]}
  236. isLoading={loading}
  237. isEmpty={ruleList?.length === 0}
  238. emptyMessage={this.tryRenderEmpty()}
  239. showTeamCol={hasAlertOwnership}
  240. hasAlertList={hasAlertList}
  241. >
  242. <Projects orgId={orgId} slugs={Array.from(allProjectsFromIncidents)}>
  243. {({initiallyLoaded, projects}) =>
  244. ruleList.map(rule => (
  245. <RuleListRow
  246. // Metric and issue alerts can have the same id
  247. key={`${isIssueAlert(rule) ? 'metric' : 'issue'}-${rule.id}`}
  248. projectsLoaded={initiallyLoaded}
  249. projects={projects as Project[]}
  250. rule={rule}
  251. orgId={orgId}
  252. onDelete={this.handleDeleteRule}
  253. organization={organization}
  254. userTeams={userTeams}
  255. />
  256. ))
  257. }
  258. </Projects>
  259. </StyledPanelTable>
  260. <Pagination pageLinks={ruleListPageLinks} />
  261. </Layout.Main>
  262. </StyledLayoutBody>
  263. );
  264. }
  265. renderBody() {
  266. const {params, organization, router} = this.props;
  267. const {orgId} = params;
  268. return (
  269. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  270. <GlobalSelectionHeader
  271. organization={organization}
  272. showDateSelector={false}
  273. showEnvironmentSelector={false}
  274. >
  275. <AlertHeader organization={organization} router={router} activeTab="rules" />
  276. {this.renderList()}
  277. </GlobalSelectionHeader>
  278. </SentryDocumentTitle>
  279. );
  280. }
  281. }
  282. class AlertRulesListContainer extends Component<Props> {
  283. componentDidMount() {
  284. this.trackView();
  285. }
  286. componentDidUpdate(prevProps: Props) {
  287. const {location} = this.props;
  288. if (prevProps.location.query?.sort !== location.query?.sort) {
  289. this.trackView();
  290. }
  291. }
  292. trackView() {
  293. const {organization, location} = this.props;
  294. trackAnalyticsEvent({
  295. eventKey: 'alert_rules.viewed',
  296. eventName: 'Alert Rules: Viewed',
  297. organization_id: organization.id,
  298. sort: Array.isArray(location.query.sort)
  299. ? location.query.sort.join(',')
  300. : location.query.sort,
  301. });
  302. }
  303. render() {
  304. return <AlertRulesList {...this.props} />;
  305. }
  306. }
  307. export default withGlobalSelection(withTeams(AlertRulesListContainer));
  308. const StyledLayoutBody = styled(Layout.Body)`
  309. margin-bottom: -20px;
  310. `;
  311. const StyledSortLink = styled(Link)`
  312. color: inherit;
  313. :hover {
  314. color: inherit;
  315. }
  316. `;
  317. const FilterWrapper = styled('div')`
  318. display: flex;
  319. margin-bottom: ${space(1.5)};
  320. `;
  321. const StyledSearchBar = styled(SearchBar)`
  322. flex-grow: 1;
  323. margin-left: ${space(1.5)};
  324. `;
  325. const StyledPanelTable = styled(PanelTable)<{
  326. showTeamCol: boolean;
  327. hasAlertList: boolean;
  328. }>`
  329. overflow: auto;
  330. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  331. overflow: initial;
  332. }
  333. ${PanelTableHeader} {
  334. padding: ${space(2)};
  335. line-height: normal;
  336. }
  337. font-size: ${p => p.theme.fontSizeMedium};
  338. grid-template-columns: auto 1.5fr 1fr 1fr ${p => (!p.hasAlertList ? '1fr' : '')} ${p =>
  339. p.showTeamCol ? '1fr' : ''} auto;
  340. margin-bottom: 0;
  341. white-space: nowrap;
  342. ${p =>
  343. p.emptyMessage &&
  344. `svg:not([data-test-id='icon-check-mark']) {
  345. display: none;`}
  346. & > * {
  347. padding: ${p => (p.hasAlertList ? `${space(2)} ${space(2)}` : space(2))};
  348. }
  349. `;
  350. const IconWrapper = styled('span')`
  351. color: ${p => p.theme.gray200};
  352. display: block;
  353. `;
  354. const Title = styled('strong')`
  355. font-size: ${p => p.theme.fontSizeExtraLarge};
  356. margin-bottom: ${space(1)};
  357. `;
  358. const Description = styled('span')`
  359. font-size: ${p => p.theme.fontSizeLarge};
  360. display: block;
  361. margin: 0;
  362. `;