integrationOrganizationLink.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import {Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import {components} from 'react-select';
  4. import styled from '@emotion/styled';
  5. import {urlEncode} from '@sentry/utils';
  6. import {addErrorMessage} from 'app/actionCreators/indicator';
  7. import Alert from 'app/components/alert';
  8. import Button from 'app/components/button';
  9. import SelectControl from 'app/components/forms/selectControl';
  10. import IdBadge from 'app/components/idBadge';
  11. import LoadingIndicator from 'app/components/loadingIndicator';
  12. import NarrowLayout from 'app/components/narrowLayout';
  13. import {IconFlag} from 'app/icons';
  14. import {t, tct} from 'app/locale';
  15. import {Integration, IntegrationProvider, Organization} from 'app/types';
  16. import {IntegrationAnalyticsKey} from 'app/utils/integrationEvents';
  17. import {
  18. getIntegrationFeatureGate,
  19. trackIntegrationEvent,
  20. } from 'app/utils/integrationUtil';
  21. import {singleLineRenderer} from 'app/utils/marked';
  22. import AsyncView from 'app/views/asyncView';
  23. import AddIntegration from 'app/views/organizationIntegrations/addIntegration';
  24. import Field from 'app/views/settings/components/forms/field';
  25. // installationId present for Github flow
  26. type Props = RouteComponentProps<{integrationSlug: string; installationId?: string}, {}>;
  27. type State = AsyncView['state'] & {
  28. selectedOrgSlug?: string;
  29. organization?: Organization;
  30. provider?: IntegrationProvider;
  31. };
  32. export default class IntegrationOrganizationLink extends AsyncView<Props, State> {
  33. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  34. return [['organizations', '/organizations/']];
  35. }
  36. getTitle() {
  37. return t('Choose Installation Organization');
  38. }
  39. trackIntegrationEvent = (
  40. eventName: IntegrationAnalyticsKey,
  41. startSession?: boolean
  42. ) => {
  43. const {organization, provider} = this.state;
  44. // should have these set but need to make TS happy
  45. if (!organization || !provider) {
  46. return;
  47. }
  48. trackIntegrationEvent(
  49. eventName,
  50. {
  51. integration_type: 'first_party',
  52. integration: provider.key,
  53. // We actually don't know if it's installed but neither does the user in the view and multiple installs is possible
  54. already_installed: false,
  55. view: 'external_install',
  56. },
  57. organization,
  58. {startSession: !!startSession}
  59. );
  60. };
  61. trackOpened() {
  62. this.trackIntegrationEvent('integrations.integration_viewed', true);
  63. }
  64. trackInstallationStart() {
  65. this.trackIntegrationEvent('integrations.installation_start');
  66. }
  67. get integrationSlug() {
  68. return this.props.params.integrationSlug;
  69. }
  70. get queryParams() {
  71. return this.props.location.query;
  72. }
  73. getOrgBySlug = (orgSlug: string): Organization | undefined => {
  74. return this.state.organizations.find((org: Organization) => org.slug === orgSlug);
  75. };
  76. onLoadAllEndpointsSuccess() {
  77. // auto select the org if there is only one
  78. const {organizations} = this.state;
  79. if (organizations.length === 1) {
  80. this.onSelectOrg({value: organizations[0].slug});
  81. }
  82. }
  83. onSelectOrg = async ({value: orgSlug}: {value: string}) => {
  84. this.setState({selectedOrgSlug: orgSlug, reloading: true, organization: undefined});
  85. try {
  86. const [organization, {providers}]: [
  87. Organization,
  88. {providers: IntegrationProvider[]}
  89. ] = await Promise.all([
  90. this.api.requestPromise(`/organizations/${orgSlug}/`),
  91. this.api.requestPromise(
  92. `/organizations/${orgSlug}/config/integrations/?provider_key=${this.integrationSlug}`
  93. ),
  94. ]);
  95. // should never happen with a valid provider
  96. if (providers.length === 0) {
  97. throw new Error('Invalid provider');
  98. }
  99. this.setState(
  100. {organization, reloading: false, provider: providers[0]},
  101. this.trackOpened
  102. );
  103. } catch (_err) {
  104. addErrorMessage(t('Failed to retrieve organization or integration details'));
  105. this.setState({reloading: false});
  106. }
  107. };
  108. hasAccess = () => {
  109. const {organization} = this.state;
  110. return organization?.access.includes('org:integrations');
  111. };
  112. // used with Github to redirect to the the integration detail
  113. onInstallWithInstallationId = (data: Integration) => {
  114. const {organization} = this.state;
  115. const orgId = organization && organization.slug;
  116. this.props.router.push(
  117. `/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`
  118. );
  119. };
  120. // non-Github redirects to the extension view where the backend will finish the installation
  121. finishInstallation = () => {
  122. // add the selected org to the query parameters and then redirect back to configure
  123. const {selectedOrgSlug} = this.state;
  124. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  125. this.trackInstallationStart();
  126. window.location.assign(
  127. `/extensions/${this.integrationSlug}/configure/?${urlEncode(query)}`
  128. );
  129. };
  130. renderAddButton() {
  131. const {installationId} = this.props.params;
  132. const {organization, provider} = this.state;
  133. // should never happen but we need this check for TS
  134. if (!provider || !organization) {
  135. return null;
  136. }
  137. const {features} = provider.metadata;
  138. // Prepare the features list
  139. const featuresComponents = features.map(f => ({
  140. featureGate: f.featureGate,
  141. description: (
  142. <FeatureListItem
  143. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  144. />
  145. ),
  146. }));
  147. const {IntegrationDirectoryFeatures} = getIntegrationFeatureGate();
  148. // Github uses a different installation flow with the installationId as a parameter
  149. // We have to wrap our installation button with AddIntegration so we can get the
  150. // addIntegrationWithInstallationId callback.
  151. // if we don't hve an installationId, we need to use the finishInstallation callback.
  152. return (
  153. <IntegrationDirectoryFeatures
  154. organization={organization}
  155. features={featuresComponents}
  156. >
  157. {({disabled}) => (
  158. <AddIntegration
  159. provider={provider}
  160. onInstall={this.onInstallWithInstallationId}
  161. organization={organization}
  162. >
  163. {addIntegrationWithInstallationId => (
  164. <ButtonWrapper>
  165. <Button
  166. priority="primary"
  167. disabled={!this.hasAccess() || disabled}
  168. onClick={() =>
  169. installationId
  170. ? addIntegrationWithInstallationId({
  171. installation_id: installationId,
  172. })
  173. : this.finishInstallation()
  174. }
  175. >
  176. {t('Install %s', provider.name)}
  177. </Button>
  178. </ButtonWrapper>
  179. )}
  180. </AddIntegration>
  181. )}
  182. </IntegrationDirectoryFeatures>
  183. );
  184. }
  185. customOption = orgProps => {
  186. const organization = this.getOrgBySlug(orgProps.value);
  187. if (!organization) {
  188. return null;
  189. }
  190. return (
  191. <components.Option {...orgProps}>
  192. <IdBadge
  193. organization={organization}
  194. avatarSize={20}
  195. displayName={organization.name}
  196. avatarProps={{consistentWidth: true}}
  197. />
  198. </components.Option>
  199. );
  200. };
  201. customValueContainer = containerProps => {
  202. const valueList = containerProps.getValue();
  203. // if no value set, we want to return the default component that is rendered
  204. if (valueList.length === 0) {
  205. return <components.ValueContainer {...containerProps} />;
  206. }
  207. const orgSlug = valueList[0].value;
  208. const organization = this.getOrgBySlug(orgSlug);
  209. if (!organization) {
  210. return <components.ValueContainer {...containerProps} />;
  211. }
  212. return (
  213. <components.ValueContainer {...containerProps}>
  214. <IdBadge
  215. organization={organization}
  216. avatarSize={20}
  217. displayName={organization.name}
  218. avatarProps={{consistentWidth: true}}
  219. />
  220. </components.ValueContainer>
  221. );
  222. };
  223. renderBottom() {
  224. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  225. const {FeatureList} = getIntegrationFeatureGate();
  226. if (reloading) {
  227. return <LoadingIndicator />;
  228. }
  229. return (
  230. <Fragment>
  231. {selectedOrgSlug && organization && !this.hasAccess() && (
  232. <Alert type="error" icon={<IconFlag size="md" />}>
  233. <p>
  234. {tct(
  235. `You do not have permission to install integrations in
  236. [organization]. Ask an organization owner or manager to
  237. visit this page to finish installing this integration.`,
  238. {organization: <strong>{organization.slug}</strong>}
  239. )}
  240. </p>
  241. <InstallLink>{window.location.href}</InstallLink>
  242. </Alert>
  243. )}
  244. {provider && organization && this.hasAccess() && FeatureList && (
  245. <Fragment>
  246. <p>
  247. {tct(
  248. 'The following features will be available for [organization] when installed.',
  249. {organization: <strong>{organization.slug}</strong>}
  250. )}
  251. </p>
  252. <FeatureList
  253. organization={organization}
  254. features={provider.metadata.features}
  255. provider={provider}
  256. />
  257. </Fragment>
  258. )}
  259. <div className="form-actions">{this.renderAddButton()}</div>
  260. </Fragment>
  261. );
  262. }
  263. renderBody() {
  264. const {selectedOrgSlug} = this.state;
  265. const options = this.state.organizations.map((org: Organization) => ({
  266. value: org.slug,
  267. label: org.name,
  268. }));
  269. return (
  270. <NarrowLayout>
  271. <h3>{t('Finish integration installation')}</h3>
  272. <p>
  273. {tct(
  274. `Please pick a specific [organization:organization] to link with
  275. your integration installation of [integation].`,
  276. {
  277. organization: <strong />,
  278. integation: <strong>{this.integrationSlug}</strong>,
  279. }
  280. )}
  281. </p>
  282. <Field label={t('Organization')} inline={false} stacked required>
  283. <SelectControl
  284. onChange={this.onSelectOrg}
  285. value={selectedOrgSlug}
  286. placeholder={t('Select an organization')}
  287. options={options}
  288. components={{
  289. Option: this.customOption,
  290. ValueContainer: this.customValueContainer,
  291. }}
  292. />
  293. </Field>
  294. {this.renderBottom()}
  295. </NarrowLayout>
  296. );
  297. }
  298. }
  299. const InstallLink = styled('pre')`
  300. margin-bottom: 0;
  301. background: #fbe3e1;
  302. `;
  303. const FeatureListItem = styled('span')`
  304. line-height: 24px;
  305. `;
  306. const ButtonWrapper = styled('div')`
  307. margin-left: auto;
  308. align-self: center;
  309. display: flex;
  310. flex-direction: column;
  311. align-items: center;
  312. `;