index.tsx 11 KB

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