ruleNode.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. import {Fragment, useCallback, useEffect} from 'react';
  2. import styled from '@emotion/styled';
  3. import merge from 'lodash/merge';
  4. import {openModal} from 'sentry/actionCreators/modal';
  5. import {Alert} from 'sentry/components/alert';
  6. import {Button} from 'sentry/components/button';
  7. import SelectControl from 'sentry/components/forms/controls/selectControl';
  8. import Input from 'sentry/components/input';
  9. import ExternalLink from 'sentry/components/links/externalLink';
  10. import NumberInput from 'sentry/components/numberInput';
  11. import {releaseHealth} from 'sentry/data/platformCategories';
  12. import {IconDelete, IconSettings} from 'sentry/icons';
  13. import {t, tct} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {Choices, IssueOwnership, Organization, Project} from 'sentry/types';
  16. import {
  17. AssigneeTargetType,
  18. IssueAlertActionType,
  19. IssueAlertConditionType,
  20. IssueAlertConfiguration,
  21. IssueAlertFilterType,
  22. IssueAlertRuleAction,
  23. IssueAlertRuleCondition,
  24. MailActionTargetType,
  25. } from 'sentry/types/alerts';
  26. import MemberTeamFields from 'sentry/views/alerts/rules/issue/memberTeamFields';
  27. import SentryAppRuleModal from 'sentry/views/alerts/rules/issue/sentryAppRuleModal';
  28. import TicketRuleModal from 'sentry/views/alerts/rules/issue/ticketRuleModal';
  29. import {SchemaFormConfig} from 'sentry/views/settings/organizationIntegrations/sentryAppExternalForm';
  30. export function hasStreamlineTargeting(organization: Organization): boolean {
  31. return organization.features.includes('streamline-targeting-context');
  32. }
  33. interface FieldProps {
  34. data: Props['data'];
  35. disabled: boolean;
  36. fieldConfig: FormField;
  37. index: number;
  38. name: string;
  39. onMemberTeamChange: (data: Props['data']) => void;
  40. onPropertyChange: Props['onPropertyChange'];
  41. onReset: Props['onReset'];
  42. organization: Organization;
  43. project: Project;
  44. }
  45. function NumberField({
  46. data,
  47. index,
  48. disabled,
  49. name,
  50. fieldConfig,
  51. onPropertyChange,
  52. }: FieldProps) {
  53. const value = data[name] && typeof data[name] !== 'boolean' ? Number(data[name]) : NaN;
  54. // Set default value of number fields to the placeholder value
  55. useEffect(() => {
  56. if (
  57. data.id === IssueAlertFilterType.ISSUE_OCCURRENCES &&
  58. isNaN(value) &&
  59. !isNaN(Number(fieldConfig.placeholder))
  60. ) {
  61. onPropertyChange(index, name, `${fieldConfig.placeholder}`);
  62. }
  63. // Value omitted on purpose to avoid overwriting user changes
  64. // eslint-disable-next-line react-hooks/exhaustive-deps
  65. }, [onPropertyChange, index, name, fieldConfig.placeholder, data.id]);
  66. return (
  67. <InlineNumberInput
  68. min={0}
  69. name={name}
  70. value={value}
  71. placeholder={`${fieldConfig.placeholder}`}
  72. disabled={disabled}
  73. onChange={newVal => onPropertyChange(index, name, String(newVal))}
  74. aria-label={t('Value')}
  75. />
  76. );
  77. }
  78. function AssigneeFilterFields({
  79. data,
  80. organization,
  81. project,
  82. disabled,
  83. onMemberTeamChange,
  84. }: FieldProps) {
  85. const isInitialized = data.targetType !== undefined && `${data.targetType}`.length > 0;
  86. return (
  87. <MemberTeamFields
  88. disabled={disabled}
  89. project={project}
  90. organization={organization}
  91. loading={!isInitialized}
  92. ruleData={data}
  93. onChange={onMemberTeamChange}
  94. options={[
  95. {value: AssigneeTargetType.UNASSIGNED, label: t('No One')},
  96. {value: AssigneeTargetType.TEAM, label: t('Team')},
  97. {value: AssigneeTargetType.MEMBER, label: t('Member')},
  98. ]}
  99. memberValue={AssigneeTargetType.MEMBER}
  100. teamValue={AssigneeTargetType.TEAM}
  101. />
  102. );
  103. }
  104. function MailActionFields({
  105. data,
  106. organization,
  107. project,
  108. disabled,
  109. onMemberTeamChange,
  110. }: FieldProps) {
  111. const isInitialized = data.targetType !== undefined && `${data.targetType}`.length > 0;
  112. let issueOwnersLabel = t('Issue Owners');
  113. if (hasStreamlineTargeting(organization)) {
  114. issueOwnersLabel = t('Suggested Assignees');
  115. }
  116. return (
  117. <MemberTeamFields
  118. disabled={disabled}
  119. project={project}
  120. organization={organization}
  121. loading={!isInitialized}
  122. ruleData={data as IssueAlertRuleAction}
  123. onChange={onMemberTeamChange}
  124. options={[
  125. {value: MailActionTargetType.ISSUE_OWNERS, label: issueOwnersLabel},
  126. {value: MailActionTargetType.TEAM, label: t('Team')},
  127. {value: MailActionTargetType.MEMBER, label: t('Member')},
  128. ]}
  129. memberValue={MailActionTargetType.MEMBER}
  130. teamValue={MailActionTargetType.TEAM}
  131. />
  132. );
  133. }
  134. function ChoiceField({
  135. data,
  136. disabled,
  137. index,
  138. onPropertyChange,
  139. onReset,
  140. name,
  141. fieldConfig,
  142. }: FieldProps) {
  143. // Select the first item on this list
  144. // If it's not yet defined, call onPropertyChange to make sure the value is set on state
  145. let initialVal: string | undefined;
  146. if (data[name] === undefined && !!fieldConfig.choices.length) {
  147. initialVal = fieldConfig.initial
  148. ? `${fieldConfig.initial}`
  149. : `${fieldConfig.choices[0][0]}`;
  150. } else {
  151. initialVal = `${data[name]}`;
  152. }
  153. // All `value`s are cast to string
  154. // There are integrations that give the form field choices with the value as number, but
  155. // when the integration configuration gets saved, it gets saved and returned as a string
  156. const options = fieldConfig.choices.map(([value, label]) => ({
  157. value: `${value}`,
  158. label,
  159. }));
  160. return (
  161. <InlineSelectControl
  162. isClearable={false}
  163. name={name}
  164. value={initialVal}
  165. styles={{
  166. control: (provided: any) => ({
  167. ...provided,
  168. minHeight: '28px',
  169. height: '28px',
  170. }),
  171. }}
  172. disabled={disabled}
  173. options={options}
  174. onChange={({value}: {value: string}) => {
  175. if (fieldConfig.resetsForm) {
  176. onReset(index, name, value);
  177. } else {
  178. onPropertyChange(index, name, value);
  179. }
  180. }}
  181. />
  182. );
  183. }
  184. function TextField({
  185. data,
  186. index,
  187. onPropertyChange,
  188. disabled,
  189. name,
  190. fieldConfig,
  191. }: FieldProps) {
  192. const value =
  193. data[name] && typeof data[name] !== 'boolean' ? (data[name] as string | number) : '';
  194. return (
  195. <InlineInput
  196. type="text"
  197. name={name}
  198. value={value}
  199. placeholder={`${fieldConfig.placeholder}`}
  200. disabled={disabled}
  201. onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
  202. onPropertyChange(index, name, e.target.value)
  203. }
  204. />
  205. );
  206. }
  207. export type FormField = {
  208. // The rest is configuration for the form field
  209. [key: string]: any;
  210. // Type of form fields
  211. type: string;
  212. };
  213. interface Props {
  214. data: IssueAlertRuleAction | IssueAlertRuleCondition;
  215. disabled: boolean;
  216. index: number;
  217. onDelete: (rowIndex: number) => void;
  218. onPropertyChange: (rowIndex: number, name: string, value: string) => void;
  219. onReset: (rowIndex: number, name: string, value: string) => void;
  220. organization: Organization;
  221. project: Project;
  222. incompatibleBanner?: boolean;
  223. incompatibleRule?: boolean;
  224. node?: IssueAlertConfiguration[keyof IssueAlertConfiguration][number] | null;
  225. ownership?: null | IssueOwnership;
  226. }
  227. function RuleNode({
  228. index,
  229. data,
  230. node,
  231. organization,
  232. project,
  233. disabled,
  234. onDelete,
  235. onPropertyChange,
  236. onReset,
  237. ownership,
  238. incompatibleRule,
  239. incompatibleBanner,
  240. }: Props) {
  241. const handleDelete = useCallback(() => {
  242. onDelete(index);
  243. }, [index, onDelete]);
  244. const handleMemberTeamChange = useCallback(
  245. ({targetType, targetIdentifier}: IssueAlertRuleAction | IssueAlertRuleCondition) => {
  246. onPropertyChange(index, 'targetType', `${targetType}`);
  247. onPropertyChange(index, 'targetIdentifier', `${targetIdentifier}`);
  248. },
  249. [index, onPropertyChange]
  250. );
  251. function getField(name: string, fieldConfig: FormField) {
  252. const fieldProps: FieldProps = {
  253. index,
  254. name,
  255. fieldConfig,
  256. data,
  257. organization,
  258. project,
  259. disabled,
  260. onMemberTeamChange: handleMemberTeamChange,
  261. onPropertyChange,
  262. onReset,
  263. };
  264. if (name === 'environment') {
  265. return (
  266. <ChoiceField
  267. {...merge(fieldProps, {
  268. fieldConfig: {choices: project.environments.map(env => [env, env])},
  269. })}
  270. />
  271. );
  272. }
  273. switch (fieldConfig.type) {
  274. case 'choice':
  275. return <ChoiceField {...fieldProps} />;
  276. case 'number':
  277. return <NumberField {...fieldProps} />;
  278. case 'string':
  279. return <TextField {...fieldProps} />;
  280. case 'mailAction':
  281. return <MailActionFields {...fieldProps} />;
  282. case 'assignee':
  283. return <AssigneeFilterFields {...fieldProps} />;
  284. default:
  285. return null;
  286. }
  287. }
  288. function renderRow() {
  289. if (!node) {
  290. return (
  291. <Separator>
  292. This node failed to render. It may have migrated to another section of the alert
  293. conditions
  294. </Separator>
  295. );
  296. }
  297. let {label} = node;
  298. if (
  299. data.id === IssueAlertActionType.NOTIFY_EMAIL &&
  300. data.targetType !== MailActionTargetType.ISSUE_OWNERS &&
  301. organization.features.includes('issue-alert-fallback-targeting')
  302. ) {
  303. // Hide the fallback options when targeting team or member
  304. label = 'Send a notification to {targetType}';
  305. }
  306. if (data.id === IssueAlertConditionType.REAPPEARED_EVENT) {
  307. label = t('The issue changes state from archived to escalating');
  308. }
  309. const parts = label.split(/({\w+})/).map((part, i) => {
  310. if (!/^{\w+}$/.test(part)) {
  311. return <Separator key={i}>{part}</Separator>;
  312. }
  313. const key = part.slice(1, -1);
  314. // If matcher is "is set" or "is not set", then we do not want to show the value input
  315. // because it is not required
  316. if (key === 'value' && (data.match === 'is' || data.match === 'ns')) {
  317. return null;
  318. }
  319. return (
  320. <Separator key={key}>
  321. {node.formFields && node.formFields.hasOwnProperty(key)
  322. ? getField(key, node.formFields[key])
  323. : part}
  324. </Separator>
  325. );
  326. });
  327. const [title, ...inputs] = parts;
  328. // We return this so that it can be a grid
  329. return (
  330. <Fragment>
  331. {title}
  332. {inputs}
  333. </Fragment>
  334. );
  335. }
  336. /**
  337. * Displays a button to open a custom modal for sentry apps or ticket integrations
  338. */
  339. function renderIntegrationButton() {
  340. if (!node || !('actionType' in node)) {
  341. return null;
  342. }
  343. if (node.actionType === 'ticket') {
  344. return (
  345. <Button
  346. size="sm"
  347. icon={<IconSettings />}
  348. onClick={() =>
  349. openModal(deps => (
  350. <TicketRuleModal
  351. {...deps}
  352. formFields={node.formFields || {}}
  353. link={node.link!}
  354. ticketType={node.ticketType!}
  355. instance={data}
  356. index={index}
  357. onSubmitAction={updateParentFromTicketRule}
  358. organization={organization}
  359. />
  360. ))
  361. }
  362. >
  363. {t('Issue Link Settings')}
  364. </Button>
  365. );
  366. }
  367. if (node.actionType === 'sentryapp' && node.sentryAppInstallationUuid) {
  368. return (
  369. <Button
  370. size="sm"
  371. icon={<IconSettings />}
  372. disabled={Boolean(data.disabled) || disabled}
  373. onClick={() => {
  374. openModal(
  375. deps => (
  376. <SentryAppRuleModal
  377. {...deps}
  378. sentryAppInstallationUuid={node.sentryAppInstallationUuid!}
  379. config={node.formFields as SchemaFormConfig}
  380. appName={node.prompt ?? node.label}
  381. onSubmitSuccess={updateParentFromSentryAppRule}
  382. resetValues={data}
  383. />
  384. ),
  385. {closeEvents: 'escape-key'}
  386. );
  387. }}
  388. >
  389. {t('Settings')}
  390. </Button>
  391. );
  392. }
  393. return null;
  394. }
  395. function conditionallyRenderHelpfulBanner() {
  396. if (data.id === IssueAlertConditionType.EVENT_FREQUENCY_PERCENT) {
  397. if (!project.platform || !releaseHealth.includes(project.platform)) {
  398. return (
  399. <MarginlessAlert type="error">
  400. {tct(
  401. "This project doesn't support sessions. [link:View supported platforms]",
  402. {
  403. link: (
  404. <ExternalLink href="https://docs.sentry.io/product/releases/setup/#release-health" />
  405. ),
  406. }
  407. )}
  408. </MarginlessAlert>
  409. );
  410. }
  411. return (
  412. <MarginlessAlert type="warning">
  413. {tct(
  414. 'Percent of sessions affected is approximated by the ratio of the issue frequency to the number of sessions in the project. [link:Learn more.]',
  415. {
  416. link: (
  417. <ExternalLink href="https://docs.sentry.io/product/alerts/create-alerts/issue-alert-config/" />
  418. ),
  419. }
  420. )}
  421. </MarginlessAlert>
  422. );
  423. }
  424. if (data.id === IssueAlertActionType.SLACK) {
  425. return (
  426. <MarginlessAlert
  427. type="info"
  428. showIcon
  429. trailingItems={
  430. <Button
  431. href="https://docs.sentry.io/product/integrations/notification-incidents/slack/#rate-limiting-error"
  432. external
  433. size="xs"
  434. >
  435. {t('Learn More')}
  436. </Button>
  437. }
  438. >
  439. {t('Having rate limiting problems? Enter a channel or user ID.')}
  440. </MarginlessAlert>
  441. );
  442. }
  443. if (data.id === IssueAlertActionType.DISCORD) {
  444. return (
  445. <MarginlessAlert
  446. type="info"
  447. showIcon
  448. trailingItems={
  449. <Button
  450. href="https://docs.sentry.io/product/accounts/early-adopter-features/discord/#issue-alerts"
  451. external
  452. size="xs"
  453. >
  454. {t('Learn More')}
  455. </Button>
  456. }
  457. >
  458. {t('Note that you must enter a Discord channel ID, not a channel name.')}
  459. </MarginlessAlert>
  460. );
  461. }
  462. if (
  463. data.id === IssueAlertActionType.NOTIFY_EMAIL &&
  464. data.targetType === MailActionTargetType.ISSUE_OWNERS &&
  465. !organization.features.includes('issue-alert-fallback-targeting')
  466. ) {
  467. return (
  468. <MarginlessAlert type="warning">
  469. {!ownership
  470. ? tct(
  471. 'If there are no matching [issueOwners], ownership is determined by the [ownershipSettings].',
  472. {
  473. issueOwners: (
  474. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  475. {t('issue owners')}
  476. </ExternalLink>
  477. ),
  478. ownershipSettings: (
  479. <ExternalLink
  480. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  481. >
  482. {t('ownership settings')}
  483. </ExternalLink>
  484. ),
  485. }
  486. )
  487. : ownership.fallthrough
  488. ? tct(
  489. 'If there are no matching [issueOwners], all project members will receive this alert. To change this behavior, see [ownershipSettings].',
  490. {
  491. issueOwners: (
  492. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  493. {t('issue owners')}
  494. </ExternalLink>
  495. ),
  496. ownershipSettings: (
  497. <ExternalLink
  498. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  499. >
  500. {t('ownership settings')}
  501. </ExternalLink>
  502. ),
  503. }
  504. )
  505. : tct(
  506. 'If there are no matching [issueOwners], this action will have no effect. To change this behavior, see [ownershipSettings].',
  507. {
  508. issueOwners: (
  509. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  510. {t('issue owners')}
  511. </ExternalLink>
  512. ),
  513. ownershipSettings: (
  514. <ExternalLink
  515. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  516. >
  517. {t('ownership settings')}
  518. </ExternalLink>
  519. ),
  520. }
  521. )}
  522. </MarginlessAlert>
  523. );
  524. }
  525. return null;
  526. }
  527. function renderIncompatibleRuleBanner() {
  528. if (!incompatibleBanner) {
  529. return null;
  530. }
  531. return (
  532. <MarginlessAlert type="error" showIcon>
  533. {t(
  534. 'The conditions highlighted in red are in conflict. They may prevent the alert from ever being triggered.'
  535. )}
  536. </MarginlessAlert>
  537. );
  538. }
  539. /**
  540. * Update all the AlertRuleAction's fields from the TicketRuleModal together
  541. * only after the user clicks "Apply Changes".
  542. * @param formData Form data
  543. * @param fetchedFieldOptionsCache Object
  544. */
  545. const updateParentFromTicketRule = useCallback(
  546. (
  547. formData: Record<string, string>,
  548. fetchedFieldOptionsCache: Record<string, Choices>
  549. ): void => {
  550. // We only know the choices after the form loads.
  551. formData.dynamic_form_fields = ((formData.dynamic_form_fields as any) || []).map(
  552. (field: any) => {
  553. // Overwrite the choices because the user's pick is in this list.
  554. if (
  555. field.name in formData &&
  556. fetchedFieldOptionsCache?.hasOwnProperty(field.name)
  557. ) {
  558. field.choices = fetchedFieldOptionsCache[field.name];
  559. }
  560. return field;
  561. }
  562. );
  563. for (const [name, value] of Object.entries(formData)) {
  564. onPropertyChange(index, name, value);
  565. }
  566. },
  567. [index, onPropertyChange]
  568. );
  569. /**
  570. * Update all the AlertRuleAction's fields from the SentryAppRuleModal together
  571. * only after the user clicks "Save Changes".
  572. * @param formData Form data
  573. */
  574. const updateParentFromSentryAppRule = useCallback(
  575. (formData: Record<string, string>): void => {
  576. for (const [name, value] of Object.entries(formData)) {
  577. onPropertyChange(index, name, value);
  578. }
  579. },
  580. [index, onPropertyChange]
  581. );
  582. return (
  583. <RuleRowContainer incompatible={incompatibleRule}>
  584. <RuleRow>
  585. <Rule>
  586. <input type="hidden" name="id" value={data.id} />
  587. {renderRow()}
  588. {renderIntegrationButton()}
  589. </Rule>
  590. <DeleteButton
  591. disabled={disabled}
  592. aria-label={t('Delete Node')}
  593. onClick={handleDelete}
  594. size="sm"
  595. icon={<IconDelete />}
  596. />
  597. </RuleRow>
  598. {renderIncompatibleRuleBanner()}
  599. {conditionallyRenderHelpfulBanner()}
  600. </RuleRowContainer>
  601. );
  602. }
  603. export default RuleNode;
  604. const InlineInput = styled(Input)`
  605. width: auto;
  606. height: 28px;
  607. min-height: 28px;
  608. `;
  609. const InlineNumberInput = styled(NumberInput)`
  610. width: 90px;
  611. height: 28px;
  612. min-height: 28px;
  613. `;
  614. const InlineSelectControl = styled(SelectControl)`
  615. width: 180px;
  616. `;
  617. const Separator = styled('span')`
  618. margin-right: ${space(1)};
  619. padding-top: ${space(0.5)};
  620. padding-bottom: ${space(0.5)};
  621. `;
  622. const RuleRow = styled('div')`
  623. display: flex;
  624. align-items: center;
  625. padding: ${space(1)};
  626. `;
  627. const RuleRowContainer = styled('div')<{incompatible?: boolean}>`
  628. background-color: ${p => p.theme.backgroundSecondary};
  629. border-radius: ${p => p.theme.borderRadius};
  630. border: 1px ${p => p.theme.innerBorder} solid;
  631. border-color: ${p => (p.incompatible ? p.theme.red200 : 'none')};
  632. `;
  633. const Rule = styled('div')`
  634. display: flex;
  635. align-items: center;
  636. flex: 1;
  637. flex-wrap: wrap;
  638. `;
  639. const DeleteButton = styled(Button)`
  640. flex-shrink: 0;
  641. `;
  642. const MarginlessAlert = styled(Alert)`
  643. border-top-left-radius: 0;
  644. border-top-right-radius: 0;
  645. border-width: 0;
  646. border-top: 1px ${p => p.theme.innerBorder} solid;
  647. margin: 0;
  648. padding: ${space(1)} ${space(1)};
  649. `;