ticketRuleModal.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import styled from '@emotion/styled';
  2. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  3. import type DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  4. import type {ExternalIssueFormErrors} from 'sentry/components/externalIssues/abstractExternalIssueForm';
  5. import AbstractExternalIssueForm from 'sentry/components/externalIssues/abstractExternalIssueForm';
  6. import type {FormProps} from 'sentry/components/forms/form';
  7. import ExternalLink from 'sentry/components/links/externalLink';
  8. import {t, tct} from 'sentry/locale';
  9. import {space} from 'sentry/styles/space';
  10. import type {IssueAlertRuleAction} from 'sentry/types/alerts';
  11. import type {Choices} from 'sentry/types/core';
  12. import type {IssueConfigField} from 'sentry/types/integrations';
  13. import type {Organization} from 'sentry/types/organization';
  14. const IGNORED_FIELDS = ['Sprint'];
  15. type Props = {
  16. // Comes from the in-code definition of a `TicketEventAction`.
  17. formFields: {[key: string]: any};
  18. index: number;
  19. // The AlertRuleAction from DB.
  20. instance: IssueAlertRuleAction;
  21. link: string | null;
  22. onSubmitAction: (
  23. data: {[key: string]: string},
  24. fetchedFieldOptionsCache: Record<string, Choices>
  25. ) => void;
  26. organization: Organization;
  27. ticketType: string;
  28. } & AbstractExternalIssueForm['props'];
  29. type State = {
  30. issueConfigFieldsCache: IssueConfigField[];
  31. } & AbstractExternalIssueForm['state'];
  32. class TicketRuleModal extends AbstractExternalIssueForm<Props, State> {
  33. getDefaultState(): State {
  34. const {instance} = this.props;
  35. const issueConfigFieldsCache = Object.values(instance?.dynamic_form_fields || {});
  36. return {
  37. ...super.getDefaultState(),
  38. // fetchedFieldOptionsCache should contain async fields so we
  39. // need to filter beforehand. Only async fields have a `url` property.
  40. fetchedFieldOptionsCache: Object.fromEntries(
  41. issueConfigFieldsCache
  42. .filter(field => field.url)
  43. .map(field => [field.name, field.choices as Choices])
  44. ),
  45. issueConfigFieldsCache,
  46. };
  47. }
  48. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  49. const {instance} = this.props;
  50. const query = (instance.dynamic_form_fields || [])
  51. .filter(field => field.updatesForm)
  52. .filter(field => instance.hasOwnProperty(field.name))
  53. .reduce(
  54. (accumulator, {name}) => {
  55. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  56. accumulator[name] = instance[name];
  57. return accumulator;
  58. },
  59. {action: 'create'}
  60. );
  61. return [['integrationDetails', this.getEndPointString(), {query}]];
  62. }
  63. handleReceiveIntegrationDetails = (integrationDetails: any) => {
  64. this.setState({
  65. issueConfigFieldsCache: integrationDetails[this.getConfigName()],
  66. });
  67. };
  68. /**
  69. * Get a list of formFields names with valid config data.
  70. */
  71. getValidAndSavableFieldNames = (): string[] => {
  72. const {issueConfigFieldsCache} = this.state;
  73. return (issueConfigFieldsCache || [])
  74. .filter(field => field.hasOwnProperty('name'))
  75. .map(field => field.name);
  76. };
  77. getEndPointString(): string {
  78. const {instance, organization} = this.props;
  79. return `/organizations/${organization.slug}/integrations/${instance.integration}/?ignored=${IGNORED_FIELDS}`;
  80. }
  81. /**
  82. * Clean up the form data before saving it to state.
  83. */
  84. cleanData = (data: {
  85. [key: string]: string;
  86. }): {
  87. [key: string]: any;
  88. integration?: string | number;
  89. } => {
  90. const {instance} = this.props;
  91. const {issueConfigFieldsCache} = this.state;
  92. const names: string[] = this.getValidAndSavableFieldNames();
  93. const formData: {
  94. [key: string]: any;
  95. integration?: string | number;
  96. } = {};
  97. if (instance?.hasOwnProperty('integration')) {
  98. formData.integration = instance.integration;
  99. }
  100. formData.dynamic_form_fields = issueConfigFieldsCache;
  101. for (const [key, value] of Object.entries(data)) {
  102. if (names.includes(key)) {
  103. formData[key] = value;
  104. }
  105. }
  106. return formData;
  107. };
  108. onFormSubmit: FormProps['onSubmit'] = (data, _success, _error, e, model) => {
  109. const {onSubmitAction, closeModal} = this.props;
  110. const {fetchedFieldOptionsCache} = this.state;
  111. // This is a "fake form", so don't actually POST to an endpoint.
  112. e.preventDefault();
  113. e.stopPropagation();
  114. if (model.validateForm()) {
  115. onSubmitAction(this.cleanData(data), fetchedFieldOptionsCache);
  116. addSuccessMessage(t('Changes applied.'));
  117. closeModal();
  118. }
  119. };
  120. getFormProps = (): FormProps => {
  121. const {closeModal} = this.props;
  122. return {
  123. ...this.getDefaultFormProps(),
  124. cancelLabel: t('Close'),
  125. onCancel: closeModal,
  126. onSubmit: this.onFormSubmit,
  127. submitLabel: t('Apply Changes'),
  128. };
  129. };
  130. /**
  131. * Set the initial data from the Rule, replace `title` and `description` with
  132. * disabled inputs, and use the cached dynamic choices.
  133. */
  134. cleanFields = (): IssueConfigField[] => {
  135. const {instance} = this.props;
  136. const fields: IssueConfigField[] = [
  137. {
  138. name: 'title',
  139. label: 'Title',
  140. type: 'string',
  141. default: 'This will be the same as the Sentry Issue.',
  142. disabled: true,
  143. } as IssueConfigField,
  144. {
  145. name: 'description',
  146. label: 'Description',
  147. type: 'string',
  148. default: 'This will be generated from the Sentry Issue details.',
  149. disabled: true,
  150. } as IssueConfigField,
  151. ];
  152. const cleanedFields = this.loadAsyncThenFetchAllFields()
  153. // Don't overwrite the default values for title and description.
  154. .filter(field => !fields.map(f => f.name).includes(field.name))
  155. .map(field => {
  156. // Overwrite defaults with previously selected values if they exist.
  157. // Certain fields such as priority (for Jira) have their options change
  158. // because they depend on another field such as Project, so we need to
  159. // check if the last selected value is in the list of available field choices.
  160. const prevChoice = instance?.[field.name];
  161. // Note that field.choices is an array of tuples, where each tuple
  162. // contains a numeric id and string label, eg. ("10000", "EX") or ("1", "Bug")
  163. if (!prevChoice) {
  164. return field;
  165. }
  166. let shouldDefaultChoice = true;
  167. if (field.choices) {
  168. shouldDefaultChoice = !!(Array.isArray(prevChoice)
  169. ? prevChoice.every(value => field.choices?.some(tuple => tuple[0] === value))
  170. : // Single-select fields have a single value, eg: 'a'
  171. field.choices?.some(item => item[0] === prevChoice));
  172. }
  173. if (shouldDefaultChoice) {
  174. field.default = prevChoice;
  175. }
  176. return field;
  177. });
  178. return [...fields, ...cleanedFields];
  179. };
  180. getErrors() {
  181. const errors: ExternalIssueFormErrors = {};
  182. for (const field of this.cleanFields()) {
  183. // If the field is a select and has a default value, make sure that the
  184. // default value exists in the choices. Skip check if the default is not
  185. // set, an empty string, or an empty array.
  186. if (
  187. field.type === 'select' &&
  188. field.default &&
  189. !(Array.isArray(field.default) && !field.default.length)
  190. ) {
  191. const fieldChoices = (field.choices || []) as Choices;
  192. const found = fieldChoices.find(([value, _]) =>
  193. Array.isArray(field.default)
  194. ? field.default.includes(value)
  195. : value === field.default
  196. );
  197. if (!found) {
  198. errors[field.name] = (
  199. <FieldErrorLabel>{`Could not fetch saved option for ${field.label}. Please reselect.`}</FieldErrorLabel>
  200. );
  201. }
  202. }
  203. }
  204. return errors;
  205. }
  206. renderBodyText = () => {
  207. // `ticketType` already includes indefinite article.
  208. const {ticketType, link} = this.props;
  209. let body: React.ReactNode;
  210. if (link) {
  211. body = tct(
  212. 'When this alert is triggered [ticketType] will be created with the following fields. It will also [linkToDocs:stay in sync] with the new Sentry Issue.',
  213. {
  214. linkToDocs: <ExternalLink href={link} />,
  215. ticketType,
  216. }
  217. );
  218. } else {
  219. body = tct(
  220. 'When this alert is triggered [ticketType] will be created with the following fields.',
  221. {
  222. ticketType,
  223. }
  224. );
  225. }
  226. return <BodyText>{body}</BodyText>;
  227. };
  228. render() {
  229. return this.renderForm(this.cleanFields(), this.getErrors());
  230. }
  231. }
  232. const BodyText = styled('div')`
  233. margin-bottom: ${space(3)};
  234. `;
  235. const FieldErrorLabel = styled('label')`
  236. padding-bottom: ${space(2)};
  237. color: ${p => p.theme.errorText};
  238. `;
  239. export default TicketRuleModal;