ruleNode.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import {Fragment, useCallback, useEffect} from 'react';
  2. import styled from '@emotion/styled';
  3. import {openModal} from 'sentry/actionCreators/modal';
  4. import {Alert} from 'sentry/components/alert';
  5. import {Button} from 'sentry/components/button';
  6. import SelectControl from 'sentry/components/forms/controls/selectControl';
  7. import Input from 'sentry/components/input';
  8. import ExternalLink from 'sentry/components/links/externalLink';
  9. import NumberInput from 'sentry/components/numberInput';
  10. import {releaseHealth} from 'sentry/data/platformCategories';
  11. import {IconDelete, IconSettings} from 'sentry/icons';
  12. import {t, tct} from 'sentry/locale';
  13. import {space} from 'sentry/styles/space';
  14. import {Choices, IssueOwnership, Organization, Project} from 'sentry/types';
  15. import {
  16. AssigneeTargetType,
  17. IssueAlertActionType,
  18. IssueAlertConditionType,
  19. IssueAlertFilterType,
  20. IssueAlertRuleAction,
  21. IssueAlertRuleActionTemplate,
  22. IssueAlertRuleCondition,
  23. IssueAlertRuleConditionTemplate,
  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?: IssueAlertRuleActionTemplate | IssueAlertRuleConditionTemplate | 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. switch (fieldConfig.type) {
  265. case 'choice':
  266. return <ChoiceField {...fieldProps} />;
  267. case 'number':
  268. return <NumberField {...fieldProps} />;
  269. case 'string':
  270. return <TextField {...fieldProps} />;
  271. case 'mailAction':
  272. return <MailActionFields {...fieldProps} />;
  273. case 'assignee':
  274. return <AssigneeFilterFields {...fieldProps} />;
  275. default:
  276. return null;
  277. }
  278. }
  279. function renderRow() {
  280. if (!node) {
  281. return (
  282. <Separator>
  283. This node failed to render. It may have migrated to another section of the alert
  284. conditions
  285. </Separator>
  286. );
  287. }
  288. let {label} = node;
  289. if (
  290. data.id === IssueAlertActionType.NOTIFY_EMAIL &&
  291. data.targetType !== MailActionTargetType.ISSUE_OWNERS &&
  292. organization.features.includes('issue-alert-fallback-targeting')
  293. ) {
  294. // Hide the fallback options when targeting team or member
  295. label = 'Send a notification to {targetType}';
  296. }
  297. if (
  298. data.id === IssueAlertConditionType.REAPPEARED_EVENT &&
  299. organization.features.includes('escalating-issues')
  300. ) {
  301. label = t('The issue changes state from archived to escalating');
  302. }
  303. const parts = label.split(/({\w+})/).map((part, i) => {
  304. if (!/^{\w+}$/.test(part)) {
  305. return <Separator key={i}>{part}</Separator>;
  306. }
  307. const key = part.slice(1, -1);
  308. // If matcher is "is set" or "is not set", then we do not want to show the value input
  309. // because it is not required
  310. if (key === 'value' && (data.match === 'is' || data.match === 'ns')) {
  311. return null;
  312. }
  313. return (
  314. <Separator key={key}>
  315. {node.formFields && node.formFields.hasOwnProperty(key)
  316. ? getField(key, node.formFields[key])
  317. : part}
  318. </Separator>
  319. );
  320. });
  321. const [title, ...inputs] = parts;
  322. // We return this so that it can be a grid
  323. return (
  324. <Fragment>
  325. {title}
  326. {inputs}
  327. </Fragment>
  328. );
  329. }
  330. /**
  331. * Displays a button to open a custom modal for sentry apps or ticket integrations
  332. */
  333. function renderIntegrationButton() {
  334. if (!node || !('actionType' in node)) {
  335. return null;
  336. }
  337. if (node.actionType === 'ticket') {
  338. return (
  339. <Button
  340. size="sm"
  341. icon={<IconSettings size="xs" />}
  342. onClick={() =>
  343. openModal(deps => (
  344. <TicketRuleModal
  345. {...deps}
  346. formFields={node.formFields || {}}
  347. link={node.link!}
  348. ticketType={node.ticketType!}
  349. instance={data}
  350. index={index}
  351. onSubmitAction={updateParentFromTicketRule}
  352. organization={organization}
  353. />
  354. ))
  355. }
  356. >
  357. {t('Issue Link Settings')}
  358. </Button>
  359. );
  360. }
  361. if (node.actionType === 'sentryapp' && node.sentryAppInstallationUuid) {
  362. return (
  363. <Button
  364. size="sm"
  365. icon={<IconSettings size="xs" />}
  366. disabled={Boolean(data.disabled) || disabled}
  367. onClick={() => {
  368. openModal(
  369. deps => (
  370. <SentryAppRuleModal
  371. {...deps}
  372. sentryAppInstallationUuid={node.sentryAppInstallationUuid!}
  373. config={node.formFields as SchemaFormConfig}
  374. appName={node.prompt ?? node.label}
  375. onSubmitSuccess={updateParentFromSentryAppRule}
  376. resetValues={data}
  377. />
  378. ),
  379. {closeEvents: 'escape-key'}
  380. );
  381. }}
  382. >
  383. {t('Settings')}
  384. </Button>
  385. );
  386. }
  387. return null;
  388. }
  389. function conditionallyRenderHelpfulBanner() {
  390. if (data.id === IssueAlertConditionType.EVENT_FREQUENCY_PERCENT) {
  391. if (!project.platform || !releaseHealth.includes(project.platform)) {
  392. return (
  393. <MarginlessAlert type="error">
  394. {tct(
  395. "This project doesn't support sessions. [link:View supported platforms]",
  396. {
  397. link: (
  398. <ExternalLink href="https://docs.sentry.io/product/releases/setup/#release-health" />
  399. ),
  400. }
  401. )}
  402. </MarginlessAlert>
  403. );
  404. }
  405. return (
  406. <MarginlessAlert type="warning">
  407. {tct(
  408. 'Percent of sessions affected is approximated by the ratio of the issue frequency to the number of sessions in the project. [link:Learn more.]',
  409. {
  410. link: (
  411. <ExternalLink href="https://docs.sentry.io/product/alerts/create-alerts/issue-alert-config/" />
  412. ),
  413. }
  414. )}
  415. </MarginlessAlert>
  416. );
  417. }
  418. if (data.id === IssueAlertActionType.SLACK) {
  419. return (
  420. <MarginlessAlert
  421. type="info"
  422. showIcon
  423. trailingItems={
  424. <Button
  425. href="https://docs.sentry.io/product/integrations/notification-incidents/slack/#rate-limiting-error"
  426. external
  427. size="xs"
  428. >
  429. {t('Learn More')}
  430. </Button>
  431. }
  432. >
  433. {t('Having rate limiting problems? Enter a channel or user ID.')}
  434. </MarginlessAlert>
  435. );
  436. }
  437. if (data.id === IssueAlertActionType.DISCORD) {
  438. return (
  439. <MarginlessAlert
  440. type="info"
  441. showIcon
  442. trailingItems={
  443. <Button
  444. href="https://docs.sentry.io/product/accounts/early-adopter-features/discord/#issue-alerts"
  445. external
  446. size="xs"
  447. >
  448. {t('Learn More')}
  449. </Button>
  450. }
  451. >
  452. {t('Note that you must enter a Discord channel ID, not a channel name.')}
  453. </MarginlessAlert>
  454. );
  455. }
  456. if (
  457. data.id === IssueAlertActionType.NOTIFY_EMAIL &&
  458. data.targetType === MailActionTargetType.ISSUE_OWNERS &&
  459. !organization.features.includes('issue-alert-fallback-targeting')
  460. ) {
  461. return (
  462. <MarginlessAlert type="warning">
  463. {!ownership
  464. ? tct(
  465. 'If there are no matching [issueOwners], ownership is determined by the [ownershipSettings].',
  466. {
  467. issueOwners: (
  468. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  469. {t('issue owners')}
  470. </ExternalLink>
  471. ),
  472. ownershipSettings: (
  473. <ExternalLink
  474. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  475. >
  476. {t('ownership settings')}
  477. </ExternalLink>
  478. ),
  479. }
  480. )
  481. : ownership.fallthrough
  482. ? tct(
  483. 'If there are no matching [issueOwners], all project members will receive this alert. To change this behavior, see [ownershipSettings].',
  484. {
  485. issueOwners: (
  486. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  487. {t('issue owners')}
  488. </ExternalLink>
  489. ),
  490. ownershipSettings: (
  491. <ExternalLink
  492. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  493. >
  494. {t('ownership settings')}
  495. </ExternalLink>
  496. ),
  497. }
  498. )
  499. : tct(
  500. 'If there are no matching [issueOwners], this action will have no effect. To change this behavior, see [ownershipSettings].',
  501. {
  502. issueOwners: (
  503. <ExternalLink href="https://docs.sentry.io/product/error-monitoring/issue-owners/">
  504. {t('issue owners')}
  505. </ExternalLink>
  506. ),
  507. ownershipSettings: (
  508. <ExternalLink
  509. href={`/settings/${organization.slug}/projects/${project.slug}/ownership/`}
  510. >
  511. {t('ownership settings')}
  512. </ExternalLink>
  513. ),
  514. }
  515. )}
  516. </MarginlessAlert>
  517. );
  518. }
  519. return null;
  520. }
  521. function renderIncompatibleRuleBanner() {
  522. if (!incompatibleBanner) {
  523. return null;
  524. }
  525. return (
  526. <MarginlessAlert type="error" showIcon>
  527. {t(
  528. 'The conditions highlighted in red are in conflict. They may prevent the alert from ever being triggered.'
  529. )}
  530. </MarginlessAlert>
  531. );
  532. }
  533. /**
  534. * Update all the AlertRuleAction's fields from the TicketRuleModal together
  535. * only after the user clicks "Apply Changes".
  536. * @param formData Form data
  537. * @param fetchedFieldOptionsCache Object
  538. */
  539. const updateParentFromTicketRule = useCallback(
  540. (
  541. formData: Record<string, string>,
  542. fetchedFieldOptionsCache: Record<string, Choices>
  543. ): void => {
  544. // We only know the choices after the form loads.
  545. formData.dynamic_form_fields = ((formData.dynamic_form_fields as any) || []).map(
  546. (field: any) => {
  547. // Overwrite the choices because the user's pick is in this list.
  548. if (
  549. field.name in formData &&
  550. fetchedFieldOptionsCache?.hasOwnProperty(field.name)
  551. ) {
  552. field.choices = fetchedFieldOptionsCache[field.name];
  553. }
  554. return field;
  555. }
  556. );
  557. for (const [name, value] of Object.entries(formData)) {
  558. onPropertyChange(index, name, value);
  559. }
  560. },
  561. [index, onPropertyChange]
  562. );
  563. /**
  564. * Update all the AlertRuleAction's fields from the SentryAppRuleModal together
  565. * only after the user clicks "Save Changes".
  566. * @param formData Form data
  567. */
  568. const updateParentFromSentryAppRule = useCallback(
  569. (formData: Record<string, string>): void => {
  570. for (const [name, value] of Object.entries(formData)) {
  571. onPropertyChange(index, name, value);
  572. }
  573. },
  574. [index, onPropertyChange]
  575. );
  576. return (
  577. <RuleRowContainer incompatible={incompatibleRule}>
  578. <RuleRow>
  579. <Rule>
  580. <input type="hidden" name="id" value={data.id} />
  581. {renderRow()}
  582. {renderIntegrationButton()}
  583. </Rule>
  584. <DeleteButton
  585. disabled={disabled}
  586. aria-label={t('Delete Node')}
  587. onClick={handleDelete}
  588. size="sm"
  589. icon={<IconDelete />}
  590. />
  591. </RuleRow>
  592. {renderIncompatibleRuleBanner()}
  593. {conditionallyRenderHelpfulBanner()}
  594. </RuleRowContainer>
  595. );
  596. }
  597. export default RuleNode;
  598. const InlineInput = styled(Input)`
  599. width: auto;
  600. height: 28px;
  601. min-height: 28px;
  602. `;
  603. const InlineNumberInput = styled(NumberInput)`
  604. width: 90px;
  605. height: 28px;
  606. min-height: 28px;
  607. `;
  608. const InlineSelectControl = styled(SelectControl)`
  609. width: 180px;
  610. `;
  611. const Separator = styled('span')`
  612. margin-right: ${space(1)};
  613. padding-top: ${space(0.5)};
  614. padding-bottom: ${space(0.5)};
  615. `;
  616. const RuleRow = styled('div')`
  617. display: flex;
  618. align-items: center;
  619. padding: ${space(1)};
  620. `;
  621. const RuleRowContainer = styled('div')<{incompatible?: boolean}>`
  622. background-color: ${p => p.theme.backgroundSecondary};
  623. border-radius: ${p => p.theme.borderRadius};
  624. border: 1px ${p => p.theme.innerBorder} solid;
  625. border-color: ${p => (p.incompatible ? p.theme.red200 : 'none')};
  626. `;
  627. const Rule = styled('div')`
  628. display: flex;
  629. align-items: center;
  630. flex: 1;
  631. flex-wrap: wrap;
  632. `;
  633. const DeleteButton = styled(Button)`
  634. flex-shrink: 0;
  635. `;
  636. const MarginlessAlert = styled(Alert)`
  637. border-top-left-radius: 0;
  638. border-top-right-radius: 0;
  639. border-width: 0;
  640. border-top: 1px ${p => p.theme.innerBorder} solid;
  641. margin: 0;
  642. padding: ${space(1)} ${space(1)};
  643. `;