index.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import {Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {urlEncode} from '@sentry/utils';
  5. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  6. import {Alert} from 'sentry/components/alert';
  7. import {Button} from 'sentry/components/button';
  8. import SelectControl from 'sentry/components/forms/controls/selectControl';
  9. import FieldGroup from 'sentry/components/forms/fieldGroup';
  10. import IdBadge from 'sentry/components/idBadge';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import NarrowLayout from 'sentry/components/narrowLayout';
  13. import {t, tct} from 'sentry/locale';
  14. import {Integration, IntegrationProvider, Organization} from 'sentry/types';
  15. import {IntegrationAnalyticsKey} from 'sentry/utils/analytics/integrations';
  16. import {
  17. getIntegrationFeatureGate,
  18. trackIntegrationAnalytics,
  19. } from 'sentry/utils/integrationUtil';
  20. import {singleLineRenderer} from 'sentry/utils/marked';
  21. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  22. import AsyncView from 'sentry/views/asyncView';
  23. import AddIntegration from 'sentry/views/settings/organizationIntegrations/addIntegration';
  24. // installationId present for Github flow
  25. type Props = RouteComponentProps<{integrationSlug: string; installationId?: string}, {}>;
  26. type State = AsyncView['state'] & {
  27. organization?: Organization;
  28. provider?: IntegrationProvider;
  29. selectedOrgSlug?: string;
  30. };
  31. export default class IntegrationOrganizationLink extends AsyncView<Props, State> {
  32. disableErrorReport = false;
  33. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  34. return [['organizations', '/organizations/']];
  35. }
  36. getTitle() {
  37. return t('Choose Installation Organization');
  38. }
  39. trackIntegrationAnalytics = (
  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. trackIntegrationAnalytics(
  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. organization,
  57. },
  58. {startSession: !!startSession}
  59. );
  60. };
  61. trackOpened() {
  62. this.trackIntegrationAnalytics('integrations.integration_viewed', true);
  63. }
  64. trackInstallationStart() {
  65. this.trackIntegrationAnalytics('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. normalizeUrl(`/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 {IntegrationFeatures} = 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. <IntegrationFeatures organization={organization} features={featuresComponents}>
  154. {({disabled}) => (
  155. <AddIntegration
  156. provider={provider}
  157. onInstall={this.onInstallWithInstallationId}
  158. organization={organization}
  159. >
  160. {addIntegrationWithInstallationId => (
  161. <ButtonWrapper>
  162. <Button
  163. priority="primary"
  164. disabled={!this.hasAccess() || disabled}
  165. onClick={() =>
  166. installationId
  167. ? addIntegrationWithInstallationId({
  168. installation_id: installationId,
  169. })
  170. : this.finishInstallation()
  171. }
  172. >
  173. {t('Install %s', provider.name)}
  174. </Button>
  175. </ButtonWrapper>
  176. )}
  177. </AddIntegration>
  178. )}
  179. </IntegrationFeatures>
  180. );
  181. }
  182. renderBottom() {
  183. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  184. const {FeatureList} = getIntegrationFeatureGate();
  185. if (reloading) {
  186. return <LoadingIndicator />;
  187. }
  188. return (
  189. <Fragment>
  190. {selectedOrgSlug && organization && !this.hasAccess() && (
  191. <Alert type="error" showIcon>
  192. <p>
  193. {tct(
  194. `You do not have permission to install integrations in
  195. [organization]. Ask an organization owner or manager to
  196. visit this page to finish installing this integration.`,
  197. {organization: <strong>{organization.slug}</strong>}
  198. )}
  199. </p>
  200. <InstallLink>{window.location.href}</InstallLink>
  201. </Alert>
  202. )}
  203. {provider && organization && this.hasAccess() && FeatureList && (
  204. <Fragment>
  205. <p>
  206. {tct(
  207. 'The following features will be available for [organization] when installed.',
  208. {organization: <strong>{organization.slug}</strong>}
  209. )}
  210. </p>
  211. <FeatureList
  212. organization={organization}
  213. features={provider.metadata.features}
  214. provider={provider}
  215. />
  216. </Fragment>
  217. )}
  218. <div className="form-actions">{this.renderAddButton()}</div>
  219. </Fragment>
  220. );
  221. }
  222. renderBody() {
  223. const {selectedOrgSlug} = this.state;
  224. const options = this.state.organizations.map((org: Organization) => ({
  225. value: org.slug,
  226. label: (
  227. <IdBadge
  228. organization={org}
  229. avatarSize={20}
  230. displayName={org.name}
  231. avatarProps={{consistentWidth: true}}
  232. />
  233. ),
  234. }));
  235. return (
  236. <NarrowLayout>
  237. <h3>{t('Finish integration installation')}</h3>
  238. <p>
  239. {tct(
  240. `Please pick a specific [organization:organization] to link with
  241. your integration installation of [integation].`,
  242. {
  243. organization: <strong />,
  244. integation: <strong>{this.integrationSlug}</strong>,
  245. }
  246. )}
  247. </p>
  248. <FieldGroup label={t('Organization')} inline={false} stacked required>
  249. <SelectControl
  250. onChange={this.onSelectOrg}
  251. value={selectedOrgSlug}
  252. placeholder={t('Select an organization')}
  253. options={options}
  254. />
  255. </FieldGroup>
  256. {this.renderBottom()}
  257. </NarrowLayout>
  258. );
  259. }
  260. }
  261. const InstallLink = styled('pre')`
  262. margin-bottom: 0;
  263. background: #fbe3e1;
  264. `;
  265. const FeatureListItem = styled('span')`
  266. line-height: 24px;
  267. `;
  268. const ButtonWrapper = styled('div')`
  269. margin-left: auto;
  270. align-self: center;
  271. display: flex;
  272. flex-direction: column;
  273. align-items: center;
  274. `;