ticketRuleModal.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. onSubmitAction: (
  21. data: {[key: string]: string},
  22. fetchedFieldOptionsCache: Record<string, Choices>
  23. ) => void;
  24. organization: Organization;
  25. link?: string;
  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: Object.fromEntries(
  38. issueConfigFieldsCache.map(field => [field.name, field.choices as Choices])
  39. ),
  40. issueConfigFieldsCache,
  41. };
  42. }
  43. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  44. const {instance} = this.props;
  45. const query = (instance.dynamic_form_fields || [])
  46. .filter(field => field.updatesForm)
  47. .filter(field => instance.hasOwnProperty(field.name))
  48. .reduce(
  49. (accumulator, {name}) => {
  50. accumulator[name] = instance[name];
  51. return accumulator;
  52. },
  53. {action: 'create'}
  54. );
  55. return [['integrationDetails', this.getEndPointString(), {query}]];
  56. }
  57. handleReceiveIntegrationDetails = (integrationDetails: any) => {
  58. this.setState({
  59. issueConfigFieldsCache: integrationDetails[this.getConfigName()],
  60. });
  61. };
  62. /**
  63. * Get a list of formFields names with valid config data.
  64. */
  65. getValidAndSavableFieldNames = (): string[] => {
  66. const {issueConfigFieldsCache} = this.state;
  67. return (issueConfigFieldsCache || [])
  68. .filter(field => field.hasOwnProperty('name'))
  69. .map(field => field.name);
  70. };
  71. getEndPointString(): string {
  72. const {instance, organization} = this.props;
  73. return `/organizations/${organization.slug}/integrations/${instance.integration}/?ignored=${IGNORED_FIELDS}`;
  74. }
  75. /**
  76. * Clean up the form data before saving it to state.
  77. */
  78. cleanData = (data: {
  79. [key: string]: string;
  80. }): {
  81. [key: string]: any;
  82. integration?: string | number;
  83. } => {
  84. const {instance} = this.props;
  85. const {issueConfigFieldsCache} = this.state;
  86. const names: string[] = this.getValidAndSavableFieldNames();
  87. const formData: {
  88. [key: string]: any;
  89. integration?: string | number;
  90. } = {};
  91. if (instance?.hasOwnProperty('integration')) {
  92. formData.integration = instance.integration;
  93. }
  94. formData.dynamic_form_fields = issueConfigFieldsCache;
  95. for (const [key, value] of Object.entries(data)) {
  96. if (names.includes(key)) {
  97. formData[key] = value;
  98. }
  99. }
  100. return formData;
  101. };
  102. onFormSubmit: FormProps['onSubmit'] = (data, _success, _error, e, model) => {
  103. const {onSubmitAction, closeModal} = this.props;
  104. const {fetchedFieldOptionsCache} = this.state;
  105. // This is a "fake form", so don't actually POST to an endpoint.
  106. e.preventDefault();
  107. e.stopPropagation();
  108. if (model.validateForm()) {
  109. onSubmitAction(this.cleanData(data), fetchedFieldOptionsCache);
  110. addSuccessMessage(t('Changes applied.'));
  111. closeModal();
  112. }
  113. };
  114. getFormProps = (): FormProps => {
  115. const {closeModal} = this.props;
  116. return {
  117. ...this.getDefaultFormProps(),
  118. cancelLabel: t('Close'),
  119. onCancel: closeModal,
  120. onSubmit: this.onFormSubmit,
  121. submitLabel: t('Apply Changes'),
  122. };
  123. };
  124. /**
  125. * Set the initial data from the Rule, replace `title` and `description` with
  126. * disabled inputs, and use the cached dynamic choices.
  127. */
  128. cleanFields = (): IssueConfigField[] => {
  129. const {instance} = this.props;
  130. const fields: IssueConfigField[] = [
  131. {
  132. name: 'title',
  133. label: 'Title',
  134. type: 'string',
  135. default: 'This will be the same as the Sentry Issue.',
  136. disabled: true,
  137. } as IssueConfigField,
  138. {
  139. name: 'description',
  140. label: 'Description',
  141. type: 'string',
  142. default: 'This will be generated from the Sentry Issue details.',
  143. disabled: true,
  144. } as IssueConfigField,
  145. ];
  146. return fields.concat(
  147. this.getCleanedFields()
  148. // Skip fields if they already exist.
  149. .filter(field => !fields.map(f => f.name).includes(field.name))
  150. .map(field => {
  151. // Overwrite defaults from cache.
  152. if (instance.hasOwnProperty(field.name)) {
  153. field.default = instance[field.name] || field.default;
  154. }
  155. return field;
  156. })
  157. );
  158. };
  159. getErrors() {
  160. const errors: ExternalIssueFormErrors = {};
  161. for (const field of this.cleanFields()) {
  162. if (field.type === 'select' && field.default) {
  163. const fieldChoices = (field.choices || []) as Choices;
  164. const found = fieldChoices.find(([value, _]) =>
  165. Array.isArray(field.default)
  166. ? field.default.includes(value)
  167. : value === field.default
  168. );
  169. if (!found) {
  170. errors[field.name] = (
  171. <FieldErrorLabel>{`Could not fetch saved option for ${field.label}. Please reselect.`}</FieldErrorLabel>
  172. );
  173. }
  174. }
  175. }
  176. return errors;
  177. }
  178. renderBodyText = () => {
  179. // `ticketType` already includes indefinite article.
  180. const {ticketType, link} = this.props;
  181. return (
  182. <BodyText>
  183. {tct(
  184. 'When this alert is triggered [ticketType] will be created with the following fields. It will also [linkToDocs] with the new Sentry Issue.',
  185. {
  186. linkToDocs: <ExternalLink href={link}>{t('stay in sync')}</ExternalLink>,
  187. ticketType,
  188. }
  189. )}
  190. </BodyText>
  191. );
  192. };
  193. render() {
  194. return this.renderForm(this.cleanFields(), this.getErrors());
  195. }
  196. }
  197. const BodyText = styled('div')`
  198. margin-bottom: ${space(3)};
  199. `;
  200. const FieldErrorLabel = styled('label')`
  201. padding-bottom: ${space(2)};
  202. color: ${p => p.theme.errorText};
  203. `;
  204. export default TicketRuleModal;