index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 alertPath = rule.type === 'alert_rule' ? 'alert-rules' : 'rules';
  87. const endpoint = `/projects/${organization.slug}/${projectId}/${alertPath}/${rule.id}/`;
  88. const updatedRule = {...rule, owner: ownerValue};
  89. this.api.request(endpoint, {
  90. method: 'PUT',
  91. data: updatedRule,
  92. success: () => {
  93. addMessage(t('Updated alert rule'), 'success');
  94. },
  95. error: () => {
  96. addMessage(t('Unable to save change'), 'error');
  97. },
  98. });
  99. };
  100. handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
  101. const {organization} = this.props;
  102. const alertPath = isIssueAlert(rule) ? 'rules' : 'alert-rules';
  103. try {
  104. await this.api.requestPromise(
  105. `/projects/${organization.slug}/${projectId}/${alertPath}/${rule.id}/`,
  106. {
  107. method: 'DELETE',
  108. }
  109. );
  110. this.reloadData();
  111. } catch (_err) {
  112. addErrorMessage(t('Error deleting rule'));
  113. }
  114. };
  115. renderLoading() {
  116. return this.renderBody();
  117. }
  118. renderList() {
  119. const {location, organization, router} = this.props;
  120. const {loading, ruleListPageLinks} = this.state;
  121. const {query} = location;
  122. const hasEditAccess = organization.access.includes('alerts:write');
  123. const ruleList = (this.state.ruleList ?? []).filter(defined);
  124. const projectsFromResults = uniq(ruleList.flatMap(({projects}) => projects));
  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. <VisuallyCompleteWithData
  198. id="AlertRules-Body"
  199. hasData={loadedTeams && !isEmpty(ruleList)}
  200. >
  201. <Projects orgId={organization.slug} slugs={projectsFromResults}>
  202. {({initiallyLoaded, projects}) =>
  203. ruleList.map(rule => (
  204. <RuleListRow
  205. // Metric and issue alerts can have the same id
  206. key={`${
  207. isIssueAlert(rule)
  208. ? AlertRuleType.METRIC
  209. : AlertRuleType.ISSUE
  210. }-${rule.id}`}
  211. projectsLoaded={initiallyLoaded}
  212. projects={projects as Project[]}
  213. rule={rule}
  214. orgId={organization.slug}
  215. onOwnerChange={this.handleOwnerChange}
  216. onDelete={this.handleDeleteRule}
  217. userTeams={new Set(teams.map(team => team.id))}
  218. hasEditAccess={hasEditAccess}
  219. />
  220. ))
  221. }
  222. </Projects>
  223. </VisuallyCompleteWithData>
  224. </StyledPanelTable>
  225. )}
  226. </Teams>
  227. <Pagination
  228. pageLinks={ruleListPageLinks}
  229. onCursor={(cursor, path, _direction) => {
  230. let team = currentQuery.team;
  231. // Keep team parameter, but empty to remove parameters
  232. if (!team || team.length === 0) {
  233. team = '';
  234. }
  235. router.push({
  236. pathname: path,
  237. query: {...currentQuery, team, cursor},
  238. });
  239. }}
  240. />
  241. </Layout.Main>
  242. </Layout.Body>
  243. );
  244. }
  245. renderBody() {
  246. const {organization, router} = this.props;
  247. return (
  248. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug}>
  249. <PageFiltersContainer>
  250. <AlertHeader router={router} activeTab="rules" />
  251. {this.renderList()}
  252. </PageFiltersContainer>
  253. </SentryDocumentTitle>
  254. );
  255. }
  256. }
  257. class AlertRulesListContainer extends Component<Props> {
  258. componentDidMount() {
  259. this.trackView();
  260. }
  261. componentDidUpdate(prevProps: Props) {
  262. const {location} = this.props;
  263. if (prevProps.location.query?.sort !== location.query?.sort) {
  264. this.trackView();
  265. }
  266. }
  267. trackView() {
  268. const {organization, location} = this.props;
  269. trackAnalytics('alert_rules.viewed', {
  270. organization,
  271. sort: Array.isArray(location.query.sort)
  272. ? location.query.sort.join(',')
  273. : location.query.sort,
  274. });
  275. }
  276. render() {
  277. return <AlertRulesList {...this.props} />;
  278. }
  279. }
  280. export default withPageFilters(AlertRulesListContainer);
  281. const StyledSortLink = styled(Link)`
  282. color: inherit;
  283. :hover {
  284. color: inherit;
  285. }
  286. `;
  287. const StyledPanelTable = styled(PanelTable)`
  288. position: static;
  289. overflow: auto;
  290. @media (min-width: ${p => p.theme.breakpoints.small}) {
  291. overflow: initial;
  292. }
  293. grid-template-columns: 4fr auto 140px 60px auto;
  294. white-space: nowrap;
  295. font-size: ${p => p.theme.fontSizeMedium};
  296. `;