index.tsx 9.9 KB

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