ticketRuleModal.tsx 8.5 KB

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