ticketRuleModal.tsx 8.4 KB

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