ruleNode.tsx 17 KB

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