ticketRuleModal.tsx 6.8 KB

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