ticketRuleModal.tsx 8.3 KB

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