index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import {Component} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import isEmpty from 'lodash/isEmpty';
  5. import uniq from 'lodash/uniq';
  6. import {addErrorMessage, addMessage} from 'sentry/actionCreators/indicator';
  7. import AsyncComponent from 'sentry/components/asyncComponent';
  8. import * as Layout from 'sentry/components/layouts/thirds';
  9. import Link from 'sentry/components/links/link';
  10. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  11. import Pagination from 'sentry/components/pagination';
  12. import {PanelTable} from 'sentry/components/panels';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {IconArrow} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import {Organization, PageFilters, Project} from 'sentry/types';
  17. import {defined} from 'sentry/utils';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  20. import Projects from 'sentry/utils/projects';
  21. import Teams from 'sentry/utils/teams';
  22. import withPageFilters from 'sentry/utils/withPageFilters';
  23. import FilterBar from '../../filterBar';
  24. import {AlertRuleType, CombinedMetricIssueAlerts} from '../../types';
  25. import {getTeamParams, isIssueAlert} from '../../utils';
  26. import AlertHeader from '../header';
  27. import RuleListRow from './row';
  28. type Props = RouteComponentProps<{}, {}> & {
  29. organization: Organization;
  30. selection: PageFilters;
  31. };
  32. type State = {
  33. ruleList?: Array<CombinedMetricIssueAlerts | null> | null;
  34. teamFilterSearch?: string;
  35. };
  36. class AlertRulesList extends AsyncComponent<Props, State & AsyncComponent['state']> {
  37. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  38. const {organization, 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/${organization.slug}/combined-rules/`,
  49. {
  50. query,
  51. },
  52. ],
  53. ];
  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, ruleListPageLinks} = this.state;
  118. const {query} = location;
  119. const hasEditAccess = organization.access.includes('alerts:write');
  120. const ruleList = (this.state.ruleList ?? []).filter(defined);
  121. const projectsFromResults = uniq(ruleList.flatMap(({projects}) => projects));
  122. const sort: {
  123. asc: boolean;
  124. field: 'date_added' | 'name' | ['incident_status', 'date_triggered'];
  125. } = {
  126. asc: query.asc === '1',
  127. field: query.sort || 'date_added',
  128. };
  129. const {cursor: _cursor, page: _page, ...currentQuery} = query;
  130. const isAlertRuleSort =
  131. sort.field.includes('incident_status') || sort.field.includes('date_triggered');
  132. const sortArrow = (
  133. <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
  134. );
  135. return (
  136. <Layout.Body>
  137. <Layout.Main fullWidth>
  138. <FilterBar
  139. location={location}
  140. onChangeFilter={this.handleChangeFilter}
  141. onChangeSearch={this.handleChangeSearch}
  142. />
  143. <Teams provideUserTeams>
  144. {({initiallyLoaded: loadedTeams, teams}) => (
  145. <StyledPanelTable
  146. headers={[
  147. <StyledSortLink
  148. key="name"
  149. role="columnheader"
  150. aria-sort={
  151. sort.field !== 'name'
  152. ? 'none'
  153. : sort.asc
  154. ? 'ascending'
  155. : 'descending'
  156. }
  157. to={{
  158. pathname: location.pathname,
  159. query: {
  160. ...currentQuery,
  161. // sort by name should start by ascending on first click
  162. asc: sort.field === 'name' && sort.asc ? undefined : '1',
  163. sort: 'name',
  164. },
  165. }}
  166. >
  167. {t('Alert Rule')} {sort.field === 'name' && sortArrow}
  168. </StyledSortLink>,
  169. <StyledSortLink
  170. key="status"
  171. role="columnheader"
  172. aria-sort={
  173. !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
  174. }
  175. to={{
  176. pathname: location.pathname,
  177. query: {
  178. ...currentQuery,
  179. asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
  180. sort: ['incident_status', 'date_triggered'],
  181. },
  182. }}
  183. >
  184. {t('Status')} {isAlertRuleSort && sortArrow}
  185. </StyledSortLink>,
  186. t('Project'),
  187. t('Team'),
  188. t('Actions'),
  189. ]}
  190. isLoading={loading || !loadedTeams}
  191. isEmpty={ruleList.length === 0}
  192. emptyMessage={t('No alert rules found for the current query.')}
  193. >
  194. <VisuallyCompleteWithData
  195. id="AlertRules-Body"
  196. hasData={loadedTeams && !isEmpty(ruleList)}
  197. >
  198. <Projects orgId={organization.slug} slugs={projectsFromResults}>
  199. {({initiallyLoaded, projects}) =>
  200. ruleList.map(rule => (
  201. <RuleListRow
  202. // Metric and issue alerts can have the same id
  203. key={`${
  204. isIssueAlert(rule)
  205. ? AlertRuleType.METRIC
  206. : AlertRuleType.ISSUE
  207. }-${rule.id}`}
  208. projectsLoaded={initiallyLoaded}
  209. projects={projects as Project[]}
  210. rule={rule}
  211. orgId={organization.slug}
  212. onOwnerChange={this.handleOwnerChange}
  213. onDelete={this.handleDeleteRule}
  214. userTeams={new Set(teams.map(team => team.id))}
  215. hasEditAccess={hasEditAccess}
  216. />
  217. ))
  218. }
  219. </Projects>
  220. </VisuallyCompleteWithData>
  221. </StyledPanelTable>
  222. )}
  223. </Teams>
  224. <Pagination
  225. pageLinks={ruleListPageLinks}
  226. onCursor={(cursor, path, _direction) => {
  227. let team = currentQuery.team;
  228. // Keep team parameter, but empty to remove parameters
  229. if (!team || team.length === 0) {
  230. team = '';
  231. }
  232. router.push({
  233. pathname: path,
  234. query: {...currentQuery, team, cursor},
  235. });
  236. }}
  237. />
  238. </Layout.Main>
  239. </Layout.Body>
  240. );
  241. }
  242. renderBody() {
  243. const {organization, router} = this.props;
  244. return (
  245. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug}>
  246. <PageFiltersContainer>
  247. <AlertHeader router={router} activeTab="rules" />
  248. {this.renderList()}
  249. </PageFiltersContainer>
  250. </SentryDocumentTitle>
  251. );
  252. }
  253. }
  254. class AlertRulesListContainer extends Component<Props> {
  255. componentDidMount() {
  256. this.trackView();
  257. }
  258. componentDidUpdate(prevProps: Props) {
  259. const {location} = this.props;
  260. if (prevProps.location.query?.sort !== location.query?.sort) {
  261. this.trackView();
  262. }
  263. }
  264. trackView() {
  265. const {organization, location} = this.props;
  266. trackAnalytics('alert_rules.viewed', {
  267. organization,
  268. sort: Array.isArray(location.query.sort)
  269. ? location.query.sort.join(',')
  270. : location.query.sort,
  271. });
  272. }
  273. render() {
  274. return <AlertRulesList {...this.props} />;
  275. }
  276. }
  277. export default withPageFilters(AlertRulesListContainer);
  278. const StyledSortLink = styled(Link)`
  279. color: inherit;
  280. :hover {
  281. color: inherit;
  282. }
  283. `;
  284. const StyledPanelTable = styled(PanelTable)`
  285. position: static;
  286. overflow: auto;
  287. @media (min-width: ${p => p.theme.breakpoints.small}) {
  288. overflow: initial;
  289. }
  290. grid-template-columns: 4fr auto 140px 60px auto;
  291. white-space: nowrap;
  292. font-size: ${p => p.theme.fontSizeMedium};
  293. `;