index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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[];
  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 projectsFromIncidents() {
  52. const {ruleList = []} = this.state;
  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. <StyledSortLink
  192. key="dateAdded"
  193. role="columnheader"
  194. aria-sort={
  195. sort.field !== 'date_added'
  196. ? 'none'
  197. : sort.asc
  198. ? 'ascending'
  199. : 'descending'
  200. }
  201. to={{
  202. pathname: location.pathname,
  203. query: {
  204. ...currentQuery,
  205. asc: sort.field === 'date_added' && !sort.asc ? '1' : undefined,
  206. sort: 'date_added',
  207. },
  208. }}
  209. >
  210. {t('Created')} {sort.field === 'date_added' && sortArrow}
  211. </StyledSortLink>,
  212. t('Actions'),
  213. ]}
  214. isLoading={loading || !loadedTeams}
  215. isEmpty={ruleList?.length === 0}
  216. emptyMessage={t('No alert rules found for the current query.')}
  217. >
  218. <Projects orgId={orgId} slugs={this.projectsFromIncidents}>
  219. {({initiallyLoaded, projects}) =>
  220. ruleList.map(rule => (
  221. <RuleListRow
  222. // Metric and issue alerts can have the same id
  223. key={`${
  224. isIssueAlert(rule) ? AlertRuleType.METRIC : AlertRuleType.ISSUE
  225. }-${rule.id}`}
  226. projectsLoaded={initiallyLoaded}
  227. projects={projects as Project[]}
  228. rule={rule}
  229. orgId={orgId}
  230. onOwnerChange={this.handleOwnerChange}
  231. onDelete={this.handleDeleteRule}
  232. userTeams={new Set(teams.map(team => team.id))}
  233. hasDuplicateAlertRules={organization.features.includes(
  234. 'duplicate-alert-rule'
  235. )}
  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, organization, router} = this.props;
  264. const {orgId} = params;
  265. return (
  266. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  267. <PageFiltersContainer
  268. organization={organization}
  269. showDateSelector={false}
  270. showEnvironmentSelector={false}
  271. hideGlobalHeader
  272. >
  273. <AlertHeader
  274. organization={organization}
  275. router={router}
  276. activeTab="rules"
  277. projectSlugs={this.projectsFromIncidents}
  278. />
  279. {this.renderList()}
  280. </PageFiltersContainer>
  281. </SentryDocumentTitle>
  282. );
  283. }
  284. }
  285. class AlertRulesListContainer extends Component<Props> {
  286. componentDidMount() {
  287. this.trackView();
  288. }
  289. componentDidUpdate(prevProps: Props) {
  290. const {location} = this.props;
  291. if (prevProps.location.query?.sort !== location.query?.sort) {
  292. this.trackView();
  293. }
  294. }
  295. trackView() {
  296. const {organization, location} = this.props;
  297. trackAdvancedAnalyticsEvent('alert_rules.viewed', {
  298. organization,
  299. sort: Array.isArray(location.query.sort)
  300. ? location.query.sort.join(',')
  301. : location.query.sort,
  302. });
  303. }
  304. render() {
  305. return <AlertRulesList {...this.props} />;
  306. }
  307. }
  308. export default withPageFilters(AlertRulesListContainer);
  309. const StyledSortLink = styled(Link)`
  310. color: inherit;
  311. :hover {
  312. color: inherit;
  313. }
  314. `;
  315. const StyledPanelTable = styled(PanelTable)`
  316. position: static;
  317. overflow: auto;
  318. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  319. overflow: initial;
  320. }
  321. grid-template-columns: 4fr auto 140px 60px 110px auto;
  322. white-space: nowrap;
  323. font-size: ${p => p.theme.fontSizeMedium};
  324. `;