index.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 * as Layout from 'sentry/components/layouts/thirds';
  7. import Link from 'sentry/components/links/link';
  8. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  9. import Pagination from 'sentry/components/pagination';
  10. import {PanelTable} from 'sentry/components/panels';
  11. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  12. import {IconArrow} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import {Organization, PageFilters, Project} from 'sentry/types';
  15. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  16. import Projects from 'sentry/utils/projects';
  17. import Teams from 'sentry/utils/teams';
  18. import withPageFilters from 'sentry/utils/withPageFilters';
  19. import FilterBar from '../../filterBar';
  20. import {AlertRuleType, CombinedMetricIssueAlerts} from '../../types';
  21. import {getTeamParams, isIssueAlert} from '../../utils';
  22. import AlertHeader from '../header';
  23. import RuleListRow from './row';
  24. type Props = RouteComponentProps<{}, {}> & {
  25. organization: Organization;
  26. selection: PageFilters;
  27. };
  28. type State = {
  29. ruleList?: CombinedMetricIssueAlerts[] | null;
  30. teamFilterSearch?: string;
  31. };
  32. class AlertRulesList extends AsyncComponent<Props, State & AsyncComponent['state']> {
  33. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  34. const {organization, location} = this.props;
  35. const {query} = location;
  36. query.expand = ['latestIncident', 'lastTriggered'];
  37. query.team = getTeamParams(query.team);
  38. if (!query.sort) {
  39. query.sort = ['incident_status', 'date_triggered'];
  40. }
  41. return [
  42. [
  43. 'ruleList',
  44. `/organizations/${organization.slug}/combined-rules/`,
  45. {
  46. query,
  47. },
  48. ],
  49. ];
  50. }
  51. get projectsFromResults() {
  52. const ruleList = this.state.ruleList ?? [];
  53. return [...new Set(ruleList.map(({projects}) => projects).flat())];
  54. }
  55. handleChangeFilter = (activeFilters: string[]) => {
  56. const {router, location} = this.props;
  57. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  58. router.push({
  59. pathname: location.pathname,
  60. query: {
  61. ...currentQuery,
  62. team: activeFilters.length > 0 ? activeFilters : '',
  63. },
  64. });
  65. };
  66. handleChangeSearch = (name: string) => {
  67. const {router, location} = this.props;
  68. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  69. router.push({
  70. pathname: location.pathname,
  71. query: {
  72. ...currentQuery,
  73. name,
  74. },
  75. });
  76. };
  77. handleOwnerChange = (
  78. projectId: string,
  79. rule: CombinedMetricIssueAlerts,
  80. ownerValue: string
  81. ) => {
  82. const {organization} = this.props;
  83. const alertPath = rule.type === 'alert_rule' ? 'alert-rules' : 'rules';
  84. const endpoint = `/projects/${organization.slug}/${projectId}/${alertPath}/${rule.id}/`;
  85. const updatedRule = {...rule, owner: ownerValue};
  86. this.api.request(endpoint, {
  87. method: 'PUT',
  88. data: updatedRule,
  89. success: () => {
  90. addMessage(t('Updated alert rule'), 'success');
  91. },
  92. error: () => {
  93. addMessage(t('Unable to save change'), 'error');
  94. },
  95. });
  96. };
  97. handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
  98. const {organization} = this.props;
  99. const alertPath = isIssueAlert(rule) ? 'rules' : 'alert-rules';
  100. try {
  101. await this.api.requestPromise(
  102. `/projects/${organization.slug}/${projectId}/${alertPath}/${rule.id}/`,
  103. {
  104. method: 'DELETE',
  105. }
  106. );
  107. this.reloadData();
  108. } catch (_err) {
  109. addErrorMessage(t('Error deleting rule'));
  110. }
  111. };
  112. renderLoading() {
  113. return this.renderBody();
  114. }
  115. renderList() {
  116. const {location, organization, router} = this.props;
  117. const {loading, ruleList = [], ruleListPageLinks} = this.state;
  118. const {query} = location;
  119. const hasEditAccess = organization.access.includes('alerts:write');
  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={this.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. `;