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