index.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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<{orgId: string}, {}> & {
  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 {params, 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/${params && params.orgId}/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 {orgId} = this.props.params;
  83. const alertPath = rule.type === 'alert_rule' ? 'alert-rules' : 'rules';
  84. const endpoint = `/projects/${orgId}/${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 {orgId} = this.props.params;
  99. const alertPath = isIssueAlert(rule) ? 'rules' : 'alert-rules';
  100. try {
  101. await this.api.requestPromise(
  102. `/projects/${orgId}/${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 {
  117. params: {orgId},
  118. location,
  119. organization,
  120. router,
  121. } = this.props;
  122. const {loading, ruleList = [], ruleListPageLinks} = this.state;
  123. const {query} = location;
  124. const hasEditAccess = organization.access.includes('alerts:write');
  125. const sort: {
  126. asc: boolean;
  127. field: 'date_added' | 'name' | ['incident_status', 'date_triggered'];
  128. } = {
  129. asc: query.asc === '1',
  130. field: query.sort || 'date_added',
  131. };
  132. const {cursor: _cursor, page: _page, ...currentQuery} = query;
  133. const isAlertRuleSort =
  134. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  135. const sortArrow = (
  136. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  137. );
  138. return (
  139. <Layout.Body>
  140. <Layout.Main fullWidth>
  141. <FilterBar
  142. location={location}
  143. onChangeFilter={this.handleChangeFilter}
  144. onChangeSearch={this.handleChangeSearch}
  145. />
  146. <Teams provideUserTeams>
  147. {({initiallyLoaded: loadedTeams, teams}) => (
  148. <StyledPanelTable
  149. headers={[
  150. <StyledSortLink
  151. key="name"
  152. role="columnheader"
  153. aria-sort={
  154. sort.field !== 'name'
  155. ? 'none'
  156. : sort.asc
  157. ? 'ascending'
  158. : 'descending'
  159. }
  160. to={{
  161. pathname: location.pathname,
  162. query: {
  163. ...currentQuery,
  164. // sort by name should start by ascending on first click
  165. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  166. sort: 'name',
  167. },
  168. }}
  169. >
  170. {t('Alert Rule')} {sort.field === 'name' && sortArrow}
  171. </StyledSortLink>,
  172. <StyledSortLink
  173. key="status"
  174. role="columnheader"
  175. aria-sort={
  176. !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
  177. }
  178. to={{
  179. pathname: location.pathname,
  180. query: {
  181. ...currentQuery,
  182. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  183. sort: ['incident_status', 'date_triggered'],
  184. },
  185. }}
  186. >
  187. {t('Status')} {isAlertRuleSort && sortArrow}
  188. </StyledSortLink>,
  189. t('Project'),
  190. t('Team'),
  191. t('Actions'),
  192. ]}
  193. isLoading={loading || !loadedTeams}
  194. isEmpty={ruleList?.length === 0}
  195. emptyMessage={t('No alert rules found for the current query.')}
  196. >
  197. <Projects orgId={orgId} slugs={this.projectsFromResults}>
  198. {({initiallyLoaded, projects}) =>
  199. ruleList?.map(rule => (
  200. <RuleListRow
  201. // Metric and issue alerts can have the same id
  202. key={`${
  203. isIssueAlert(rule) ? AlertRuleType.METRIC : AlertRuleType.ISSUE
  204. }-${rule.id}`}
  205. projectsLoaded={initiallyLoaded}
  206. projects={projects as Project[]}
  207. rule={rule}
  208. orgId={orgId}
  209. onOwnerChange={this.handleOwnerChange}
  210. onDelete={this.handleDeleteRule}
  211. userTeams={new Set(teams.map(team => team.id))}
  212. hasEditAccess={hasEditAccess}
  213. />
  214. ))
  215. }
  216. </Projects>
  217. </StyledPanelTable>
  218. )}
  219. </Teams>
  220. <Pagination
  221. pageLinks={ruleListPageLinks}
  222. onCursor={(cursor, path, _direction) => {
  223. let team = currentQuery.team;
  224. // Keep team parameter, but empty to remove parameters
  225. if (!team || team.length === 0) {
  226. team = '';
  227. }
  228. router.push({
  229. pathname: path,
  230. query: {...currentQuery, team, cursor},
  231. });
  232. }}
  233. />
  234. </Layout.Main>
  235. </Layout.Body>
  236. );
  237. }
  238. renderBody() {
  239. const {params, router} = this.props;
  240. const {orgId} = params;
  241. return (
  242. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  243. <PageFiltersContainer>
  244. <AlertHeader router={router} activeTab="rules" />
  245. {this.renderList()}
  246. </PageFiltersContainer>
  247. </SentryDocumentTitle>
  248. );
  249. }
  250. }
  251. class AlertRulesListContainer extends Component<Props> {
  252. componentDidMount() {
  253. this.trackView();
  254. }
  255. componentDidUpdate(prevProps: Props) {
  256. const {location} = this.props;
  257. if (prevProps.location.query?.sort !== location.query?.sort) {
  258. this.trackView();
  259. }
  260. }
  261. trackView() {
  262. const {organization, location} = this.props;
  263. trackAdvancedAnalyticsEvent('alert_rules.viewed', {
  264. organization,
  265. sort: Array.isArray(location.query.sort)
  266. ? location.query.sort.join(',')
  267. : location.query.sort,
  268. });
  269. }
  270. render() {
  271. return <AlertRulesList {...this.props} />;
  272. }
  273. }
  274. export default withPageFilters(AlertRulesListContainer);
  275. const StyledSortLink = styled(Link)`
  276. color: inherit;
  277. :hover {
  278. color: inherit;
  279. }
  280. `;
  281. const StyledPanelTable = styled(PanelTable)`
  282. position: static;
  283. overflow: auto;
  284. @media (min-width: ${p => p.theme.breakpoints.small}) {
  285. overflow: initial;
  286. }
  287. grid-template-columns: 4fr auto 140px 60px auto;
  288. white-space: nowrap;
  289. font-size: ${p => p.theme.fontSizeMedium};
  290. `;