index.tsx 10 KB

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