createAlertButton.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import React from 'react';
  2. import {withRouter, WithRouterProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {
  5. addErrorMessage,
  6. addLoadingMessage,
  7. addSuccessMessage,
  8. } from 'app/actionCreators/indicator';
  9. import {navigateTo} from 'app/actionCreators/navigation';
  10. import {Client} from 'app/api';
  11. import Access from 'app/components/acl/access';
  12. import Alert from 'app/components/alert';
  13. import GuideAnchor from 'app/components/assistant/guideAnchor';
  14. import Button from 'app/components/button';
  15. import Link from 'app/components/links/link';
  16. import {IconClose, IconInfo, IconSiren} from 'app/icons';
  17. import {t, tct} from 'app/locale';
  18. import {Organization, Project} from 'app/types';
  19. import EventView from 'app/utils/discover/eventView';
  20. import {Aggregation, AGGREGATIONS, explodeFieldString} from 'app/utils/discover/fields';
  21. import withApi from 'app/utils/withApi';
  22. import {getQueryDatasource} from 'app/views/alerts/utils';
  23. import {
  24. errorFieldConfig,
  25. transactionFieldConfig,
  26. } from 'app/views/settings/incidentRules/constants';
  27. /**
  28. * Discover query supports more features than alert rules
  29. * To create an alert rule from a discover query, some parameters need to be adjusted
  30. */
  31. type IncompatibleQueryProperties = {
  32. /**
  33. * Must have exactly one project selected and not -1 (all projects)
  34. */
  35. hasProjectError: boolean;
  36. /**
  37. * Must have zero or one environments
  38. */
  39. hasEnvironmentError: boolean;
  40. /**
  41. * event.type must be error or transaction
  42. */
  43. hasEventTypeError: boolean;
  44. hasYAxisError: boolean;
  45. };
  46. type AlertProps = {
  47. incompatibleQuery: IncompatibleQueryProperties;
  48. eventView: EventView;
  49. orgId: string;
  50. /**
  51. * Dismiss alert
  52. */
  53. onClose: () => void;
  54. };
  55. /**
  56. * Displays messages to the user on what needs to change in their query
  57. */
  58. function IncompatibleQueryAlert({
  59. incompatibleQuery,
  60. eventView,
  61. orgId,
  62. onClose,
  63. }: AlertProps) {
  64. const {
  65. hasProjectError,
  66. hasEnvironmentError,
  67. hasEventTypeError,
  68. hasYAxisError,
  69. } = incompatibleQuery;
  70. const totalErrors = Object.values(incompatibleQuery).filter(val => val === true).length;
  71. const eventTypeError = eventView.clone();
  72. eventTypeError.query += ' event.type:error';
  73. const eventTypeTransaction = eventView.clone();
  74. eventTypeTransaction.query += ' event.type:transaction';
  75. const eventTypeDefault = eventView.clone();
  76. eventTypeDefault.query += ' event.type:default';
  77. const eventTypeErrorDefault = eventView.clone();
  78. eventTypeErrorDefault.query += ' event.type:error or event.type:default';
  79. const pathname = `/organizations/${orgId}/discover/results/`;
  80. const eventTypeLinks = {
  81. error: (
  82. <Link
  83. to={{
  84. pathname,
  85. query: eventTypeError.generateQueryStringObject(),
  86. }}
  87. />
  88. ),
  89. default: (
  90. <Link
  91. to={{
  92. pathname,
  93. query: eventTypeDefault.generateQueryStringObject(),
  94. }}
  95. />
  96. ),
  97. transaction: (
  98. <Link
  99. to={{
  100. pathname,
  101. query: eventTypeTransaction.generateQueryStringObject(),
  102. }}
  103. />
  104. ),
  105. errorDefault: (
  106. <Link
  107. to={{
  108. pathname,
  109. query: eventTypeErrorDefault.generateQueryStringObject(),
  110. }}
  111. />
  112. ),
  113. };
  114. return (
  115. <StyledAlert type="warning" icon={<IconInfo color="yellow300" size="sm" />}>
  116. {totalErrors === 1 && (
  117. <React.Fragment>
  118. {hasProjectError &&
  119. t('An alert can use data from only one Project. Select one and try again.')}
  120. {hasEnvironmentError &&
  121. t(
  122. 'An alert supports data from a single Environment or All Environments. Pick one try again.'
  123. )}
  124. {hasEventTypeError &&
  125. tct(
  126. 'An alert needs a filter of [error:event.type:error], [default:event.type:default], [transaction:event.type:transaction], [errorDefault:(event.type:error OR event.type:default)]. Use one of these and try again.',
  127. eventTypeLinks
  128. )}
  129. {hasYAxisError &&
  130. tct(
  131. 'An alert can’t use the metric [yAxis] just yet. Select another metric and try again.',
  132. {
  133. yAxis: <StyledCode>{eventView.getYAxis()}</StyledCode>,
  134. }
  135. )}
  136. </React.Fragment>
  137. )}
  138. {totalErrors > 1 && (
  139. <React.Fragment>
  140. {t('Yikes! That button didn’t work. Please fix the following problems:')}
  141. <StyledUnorderedList>
  142. {hasProjectError && <li>{t('Select one Project.')}</li>}
  143. {hasEnvironmentError && (
  144. <li>{t('Select a single Environment or All Environments.')}</li>
  145. )}
  146. {hasEventTypeError && (
  147. <li>
  148. {tct(
  149. 'Use the filter [error:event.type:error], [default:event.type:default], [transaction:event.type:transaction], [errorDefault:(event.type:error OR event.type:default)].',
  150. eventTypeLinks
  151. )}
  152. </li>
  153. )}
  154. {hasYAxisError && (
  155. <li>
  156. {tct(
  157. 'An alert can’t use the metric [yAxis] just yet. Select another metric and try again.',
  158. {
  159. yAxis: <StyledCode>{eventView.getYAxis()}</StyledCode>,
  160. }
  161. )}
  162. </li>
  163. )}
  164. </StyledUnorderedList>
  165. </React.Fragment>
  166. )}
  167. <StyledCloseButton
  168. icon={<IconClose color="yellow300" size="sm" isCircled />}
  169. aria-label={t('Close')}
  170. size="zero"
  171. onClick={onClose}
  172. borderless
  173. />
  174. </StyledAlert>
  175. );
  176. }
  177. type CreateAlertFromViewButtonProps = React.ComponentProps<typeof Button> & {
  178. className?: string;
  179. projects: Project[];
  180. /**
  181. * Discover query used to create the alert
  182. */
  183. eventView: EventView;
  184. organization: Organization;
  185. referrer?: string;
  186. /**
  187. * Called when the current eventView does not meet the requirements of alert rules
  188. * @returns a function that takes an alert close function argument
  189. */
  190. onIncompatibleQuery: (
  191. incompatibleAlertNoticeFn: (onAlertClose: () => void) => React.ReactNode,
  192. errors: IncompatibleQueryProperties
  193. ) => void;
  194. /**
  195. * Called when the user is redirected to the alert builder
  196. */
  197. onSuccess: () => void;
  198. };
  199. function incompatibleYAxis(eventView: EventView): boolean {
  200. const column = explodeFieldString(eventView.getYAxis());
  201. if (column.kind === 'field') {
  202. return true;
  203. }
  204. const eventTypeMatch = eventView.query.match(/event\.type:(transaction|error)/);
  205. if (!eventTypeMatch) {
  206. return false;
  207. }
  208. const dataset = eventTypeMatch[1];
  209. const yAxisConfig = dataset === 'error' ? errorFieldConfig : transactionFieldConfig;
  210. const invalidFunction = !yAxisConfig.aggregations.includes(column.function[0]);
  211. // Allow empty parameters, allow all numeric parameters - eg. apdex(300)
  212. const aggregation: Aggregation | undefined = AGGREGATIONS[column.function[0]];
  213. if (!aggregation) {
  214. return false;
  215. }
  216. const isNumericParameter = aggregation.parameters.some(
  217. param => param.kind === 'value' && param.dataType === 'number'
  218. );
  219. // There are other measurements possible, but for the time being, only allow alerting
  220. // on the predefined set of measurements for alerts.
  221. const allowedParameters = [
  222. '',
  223. ...yAxisConfig.fields,
  224. ...(yAxisConfig.measurementKeys ?? []),
  225. ];
  226. const invalidParameter =
  227. !isNumericParameter && !allowedParameters.includes(column.function[1]);
  228. return invalidFunction || invalidParameter;
  229. }
  230. /**
  231. * Provide a button that can create an alert from an event view.
  232. * Emits incompatible query issues on click
  233. */
  234. function CreateAlertFromViewButton({
  235. projects,
  236. eventView,
  237. organization,
  238. referrer,
  239. onIncompatibleQuery,
  240. onSuccess,
  241. ...buttonProps
  242. }: CreateAlertFromViewButtonProps) {
  243. // Must have exactly one project selected and not -1 (all projects)
  244. const hasProjectError = eventView.project.length !== 1 || eventView.project[0] === -1;
  245. // Must have one or zero environments
  246. const hasEnvironmentError = eventView.environment.length > 1;
  247. // Must have event.type of error or transaction
  248. const hasEventTypeError = getQueryDatasource(eventView.query) === null;
  249. // yAxis must be a function and enabled on alerts
  250. const hasYAxisError = incompatibleYAxis(eventView);
  251. const errors: IncompatibleQueryProperties = {
  252. hasProjectError,
  253. hasEnvironmentError,
  254. hasEventTypeError,
  255. hasYAxisError,
  256. };
  257. const project = projects.find(p => p.id === `${eventView.project[0]}`);
  258. const hasErrors = Object.values(errors).some(x => x);
  259. const to = hasErrors
  260. ? undefined
  261. : {
  262. pathname: `/organizations/${organization.slug}/alerts/${project?.slug}/new/`,
  263. query: {
  264. ...eventView.generateQueryStringObject(),
  265. createFromDiscover: true,
  266. referrer,
  267. },
  268. };
  269. const handleClick = (event: React.MouseEvent) => {
  270. if (hasErrors) {
  271. event.preventDefault();
  272. onIncompatibleQuery(
  273. (onAlertClose: () => void) => (
  274. <IncompatibleQueryAlert
  275. incompatibleQuery={errors}
  276. eventView={eventView}
  277. orgId={organization.slug}
  278. onClose={onAlertClose}
  279. />
  280. ),
  281. errors
  282. );
  283. return;
  284. }
  285. onSuccess();
  286. };
  287. return (
  288. <CreateAlertButton
  289. organization={organization}
  290. onClick={handleClick}
  291. to={to}
  292. {...buttonProps}
  293. />
  294. );
  295. }
  296. type Props = {
  297. organization: Organization;
  298. projectSlug?: string;
  299. iconProps?: React.ComponentProps<typeof IconSiren>;
  300. referrer?: string;
  301. hideIcon?: boolean;
  302. api: Client;
  303. showPermissionGuide?: boolean;
  304. } & WithRouterProps &
  305. React.ComponentProps<typeof Button>;
  306. const CreateAlertButton = withApi(
  307. withRouter(
  308. ({
  309. organization,
  310. projectSlug,
  311. iconProps,
  312. referrer,
  313. router,
  314. hideIcon,
  315. api,
  316. showPermissionGuide,
  317. ...buttonProps
  318. }: Props) => {
  319. const hasWizard = organization.features.includes('alert-wizard');
  320. const createAlertUrl = (providedProj: string) => {
  321. const alertsBaseUrl = `/organizations/${organization.slug}/alerts/${providedProj}`;
  322. const subUrl = hasWizard ? 'wizard' : 'new';
  323. return `${alertsBaseUrl}/${subUrl}/${referrer ? `?referrer=${referrer}` : ''}`;
  324. };
  325. function handleClickWithoutProject(event: React.MouseEvent) {
  326. event.preventDefault();
  327. navigateTo(createAlertUrl(':projectId'), router);
  328. }
  329. async function enableAlertsMemberWrite() {
  330. const settingsEndpoint = `/organizations/${organization.slug}/`;
  331. addLoadingMessage();
  332. try {
  333. await api.requestPromise(settingsEndpoint, {
  334. method: 'PUT',
  335. data: {
  336. alertsMemberWrite: true,
  337. },
  338. });
  339. addSuccessMessage(t('Successfully updated organization settings'));
  340. } catch (err) {
  341. addErrorMessage(t('Unable to update organization settings'));
  342. }
  343. }
  344. const permissionTooltipText = tct(
  345. 'Ask your organization owner or manager to [settingsLink:enable alerts access] for you.',
  346. {settingsLink: <Link to={`/settings/${organization.slug}`} />}
  347. );
  348. const renderButton = (hasAccess: boolean) => (
  349. <Button
  350. disabled={!hasAccess}
  351. title={!hasAccess ? permissionTooltipText : undefined}
  352. icon={!hideIcon && <IconSiren {...iconProps} />}
  353. to={projectSlug ? createAlertUrl(projectSlug) : undefined}
  354. tooltipProps={{
  355. isHoverable: true,
  356. position: 'top',
  357. popperStyle: {
  358. maxWidth: '270px',
  359. },
  360. }}
  361. onClick={projectSlug ? undefined : handleClickWithoutProject}
  362. {...buttonProps}
  363. >
  364. {buttonProps.children ?? t('Create Alert')}
  365. </Button>
  366. );
  367. const showGuide = !organization.alertsMemberWrite && !!showPermissionGuide;
  368. return (
  369. <Access organization={organization} access={['alerts:write']}>
  370. {({hasAccess}) =>
  371. showGuide ? (
  372. <Access organization={organization} access={['org:write']}>
  373. {({hasAccess: isOrgAdmin}) => (
  374. <GuideAnchor
  375. target={isOrgAdmin ? 'alerts_write_owner' : 'alerts_write_member'}
  376. onFinish={isOrgAdmin ? enableAlertsMemberWrite : undefined}
  377. >
  378. {renderButton(hasAccess)}
  379. </GuideAnchor>
  380. )}
  381. </Access>
  382. ) : (
  383. renderButton(hasAccess)
  384. )
  385. }
  386. </Access>
  387. );
  388. }
  389. )
  390. );
  391. export {CreateAlertFromViewButton};
  392. export default CreateAlertButton;
  393. const StyledAlert = styled(Alert)`
  394. color: ${p => p.theme.textColor};
  395. margin-bottom: 0;
  396. `;
  397. const StyledUnorderedList = styled('ul')`
  398. margin-bottom: 0;
  399. `;
  400. const StyledCode = styled('code')`
  401. background-color: transparent;
  402. padding: 0;
  403. `;
  404. const StyledCloseButton = styled(Button)`
  405. transition: opacity 0.1s linear;
  406. position: absolute;
  407. top: 3px;
  408. right: 0;
  409. &:hover,
  410. &:focus {
  411. background-color: transparent;
  412. opacity: 1;
  413. }
  414. `;