integrationOrganizationLink.tsx 11 KB

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