integrationExternalTeamMappings.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import {Fragment} from 'react';
  2. import {withRouter, WithRouterProps} from 'react-router';
  3. import uniqBy from 'lodash/uniqBy';
  4. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  5. import {openModal} from 'sentry/actionCreators/modal';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import IntegrationExternalMappingForm from 'sentry/components/integrationExternalMappingForm';
  8. import IntegrationExternalMappings from 'sentry/components/integrationExternalMappings';
  9. import {t} from 'sentry/locale';
  10. import {
  11. ExternalActorMapping,
  12. ExternalActorMappingOrSuggestion,
  13. Integration,
  14. Organization,
  15. Team,
  16. } from 'sentry/types';
  17. import {sentryNameToOption} from 'sentry/utils/integrationUtil';
  18. import withOrganization from 'sentry/utils/withOrganization';
  19. type Props = AsyncComponent['props'] &
  20. WithRouterProps & {
  21. integration: Integration;
  22. organization: Organization;
  23. };
  24. type State = AsyncComponent['state'] & {
  25. initialResults: Team[];
  26. queryResults: {
  27. // For inline forms, the mappingKey will be the external name (since multiple will be rendered at one time)
  28. // For the modal form, the mappingKey will be this.modalMappingKey (since only one modal form is rendered at any time)
  29. [mappingKey: string]: Team[];
  30. };
  31. teams: Team[];
  32. };
  33. class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
  34. getDefaultState() {
  35. return {
  36. ...super.getDefaultState(),
  37. teams: [],
  38. initialResults: [],
  39. queryResults: {},
  40. };
  41. }
  42. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  43. const {organization, location} = this.props;
  44. return [
  45. // We paginate on this query, since we're filtering by hasExternalTeams:true
  46. [
  47. 'teams',
  48. `/organizations/${organization.slug}/teams/`,
  49. {query: {...location?.query, query: 'hasExternalTeams:true'}},
  50. ],
  51. // We use this query as defaultOptions to reduce identical API calls
  52. ['initialResults', `/organizations/${organization.slug}/teams/`],
  53. ];
  54. }
  55. handleDelete = async (mapping: ExternalActorMapping) => {
  56. try {
  57. const {organization} = this.props;
  58. const {teams} = this.state;
  59. const team = teams.find(item => item.id === mapping.teamId);
  60. if (!team) {
  61. throw new Error('Cannot find correct team slug.');
  62. }
  63. const endpoint = `/teams/${organization.slug}/${team.slug}/external-teams/${mapping.id}/`;
  64. await this.api.requestPromise(endpoint, {
  65. method: 'DELETE',
  66. });
  67. // remove config and update state
  68. addSuccessMessage(t('Deletion successful'));
  69. this.fetchData();
  70. } catch {
  71. // no 4xx errors should happen on delete
  72. addErrorMessage(t('An error occurred'));
  73. }
  74. };
  75. handleSubmitSuccess = () => {
  76. this.fetchData();
  77. };
  78. get mappings() {
  79. const {integration} = this.props;
  80. const {teams} = this.state;
  81. const externalTeamMappings = teams.reduce((acc, team) => {
  82. const {externalTeams} = team;
  83. acc.push(
  84. ...externalTeams
  85. .filter(externalTeam => externalTeam.provider === integration.provider.key)
  86. .map(externalTeam => ({...externalTeam, sentryName: team.slug}))
  87. );
  88. return acc;
  89. }, [] as ExternalActorMapping[]);
  90. return externalTeamMappings.sort((a, b) => parseInt(a.id, 10) - parseInt(b.id, 10));
  91. }
  92. modalMappingKey = '__MODAL_RESULTS__';
  93. get dataEndpoint() {
  94. const {organization} = this.props;
  95. return `/organizations/${organization.slug}/teams/`;
  96. }
  97. get defaultTeamOptions() {
  98. const {initialResults} = this.state;
  99. return this.sentryNamesMapper(initialResults).map(sentryNameToOption);
  100. }
  101. getBaseFormEndpoint(mapping?: ExternalActorMappingOrSuggestion) {
  102. if (!mapping) {
  103. return '';
  104. }
  105. const {organization} = this.props;
  106. const {queryResults, initialResults} = this.state;
  107. const fieldResults =
  108. queryResults[mapping.externalName] ?? queryResults[this.modalMappingKey];
  109. const team =
  110. // First, search for the team in the query results...
  111. fieldResults?.find(item => item.id === mapping.teamId) ??
  112. // Then in the initial results, if nothing was found.
  113. initialResults?.find(item => item.id === mapping.teamId);
  114. return `/teams/${organization.slug}/${team?.slug ?? ''}/external-teams/`;
  115. }
  116. sentryNamesMapper(teams: Team[]) {
  117. return teams.map(({id, slug}) => ({id, name: slug}));
  118. }
  119. /**
  120. * This method combines the results from searches made on a form dropping repeated entries
  121. * that have identical 'id's. This is because we need the result of the the search query when
  122. * the user submits to get the team slug, but it won't always be the last query they've made.
  123. *
  124. * If they search (but not select) after making a selection, and we didn't keep a running collection of results,
  125. * we wouldn't have the team to generate the endpoint from.
  126. */
  127. combineResultsById = (resultList1, resultList2) => {
  128. return uniqBy([...resultList1, ...resultList2], 'id');
  129. };
  130. handleResults = (results, mappingKey?: string) => {
  131. if (mappingKey) {
  132. const {queryResults} = this.state;
  133. this.setState({
  134. queryResults: {
  135. ...queryResults,
  136. // Ensure we always have a team to pull the slug from
  137. [mappingKey]: this.combineResultsById(results, queryResults[mappingKey] ?? []),
  138. },
  139. });
  140. }
  141. };
  142. openModal = (mapping?: ExternalActorMappingOrSuggestion) => {
  143. const {integration} = this.props;
  144. openModal(({Body, Header, closeModal}) => (
  145. <Fragment>
  146. <Header closeButton>{t('Configure External Team Mapping')}</Header>
  147. <Body>
  148. <IntegrationExternalMappingForm
  149. type="team"
  150. integration={integration}
  151. dataEndpoint={this.dataEndpoint}
  152. getBaseFormEndpoint={map => this.getBaseFormEndpoint(map)}
  153. defaultOptions={this.defaultTeamOptions}
  154. mapping={mapping}
  155. mappingKey={this.modalMappingKey}
  156. sentryNamesMapper={this.sentryNamesMapper}
  157. onCancel={closeModal}
  158. onResults={this.handleResults}
  159. onSubmitSuccess={() => {
  160. this.handleSubmitSuccess();
  161. closeModal();
  162. }}
  163. />
  164. </Body>
  165. </Fragment>
  166. ));
  167. };
  168. renderBody() {
  169. const {integration, organization} = this.props;
  170. const {teamsPageLinks} = this.state;
  171. return (
  172. <IntegrationExternalMappings
  173. type="team"
  174. integration={integration}
  175. organization={organization}
  176. mappings={this.mappings}
  177. dataEndpoint={this.dataEndpoint}
  178. getBaseFormEndpoint={mapping => this.getBaseFormEndpoint(mapping)}
  179. defaultOptions={this.defaultTeamOptions}
  180. sentryNamesMapper={this.sentryNamesMapper}
  181. onCreate={this.openModal}
  182. onDelete={this.handleDelete}
  183. pageLinks={teamsPageLinks}
  184. onResults={this.handleResults}
  185. />
  186. );
  187. }
  188. }
  189. export default withRouter(withOrganization(IntegrationExternalTeamMappings));