integrationOrganizationLink.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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/selectControl';
  10. import IdBadge from 'sentry/components/idBadge';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import NarrowLayout from 'sentry/components/narrowLayout';
  13. import {IconFlag} from 'sentry/icons';
  14. import {t, tct} from 'sentry/locale';
  15. import {Integration, IntegrationProvider, Organization} from 'sentry/types';
  16. import {IntegrationAnalyticsKey} from 'sentry/utils/analytics/integrationAnalyticsEvents';
  17. import {
  18. getIntegrationFeatureGate,
  19. trackIntegrationAnalytics,
  20. } from 'sentry/utils/integrationUtil';
  21. import {singleLineRenderer} from 'sentry/utils/marked';
  22. import AsyncView from 'sentry/views/asyncView';
  23. import AddIntegration from 'sentry/views/organizationIntegrations/addIntegration';
  24. import Field from 'sentry/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. 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. `/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 {IntegrationDirectoryFeatures} = 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. <IntegrationDirectoryFeatures
  155. organization={organization}
  156. features={featuresComponents}
  157. >
  158. {({disabled}) => (
  159. <AddIntegration
  160. provider={provider}
  161. onInstall={this.onInstallWithInstallationId}
  162. organization={organization}
  163. >
  164. {addIntegrationWithInstallationId => (
  165. <ButtonWrapper>
  166. <Button
  167. priority="primary"
  168. disabled={!this.hasAccess() || disabled}
  169. onClick={() =>
  170. installationId
  171. ? addIntegrationWithInstallationId({
  172. installation_id: installationId,
  173. })
  174. : this.finishInstallation()
  175. }
  176. >
  177. {t('Install %s', provider.name)}
  178. </Button>
  179. </ButtonWrapper>
  180. )}
  181. </AddIntegration>
  182. )}
  183. </IntegrationDirectoryFeatures>
  184. );
  185. }
  186. customOption = orgProps => {
  187. const organization = this.getOrgBySlug(orgProps.value);
  188. if (!organization) {
  189. return null;
  190. }
  191. return (
  192. <components.Option {...orgProps}>
  193. <IdBadge
  194. organization={organization}
  195. avatarSize={20}
  196. displayName={organization.name}
  197. avatarProps={{consistentWidth: true}}
  198. />
  199. </components.Option>
  200. );
  201. };
  202. customValueContainer = containerProps => {
  203. const valueList = containerProps.getValue();
  204. // if no value set, we want to return the default component that is rendered
  205. if (valueList.length === 0) {
  206. return <components.ValueContainer {...containerProps} />;
  207. }
  208. const orgSlug = valueList[0].value;
  209. const organization = this.getOrgBySlug(orgSlug);
  210. if (!organization) {
  211. return <components.ValueContainer {...containerProps} />;
  212. }
  213. return (
  214. <components.ValueContainer {...containerProps}>
  215. <IdBadge
  216. organization={organization}
  217. avatarSize={20}
  218. displayName={organization.name}
  219. avatarProps={{consistentWidth: true}}
  220. />
  221. </components.ValueContainer>
  222. );
  223. };
  224. renderBottom() {
  225. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  226. const {FeatureList} = getIntegrationFeatureGate();
  227. if (reloading) {
  228. return <LoadingIndicator />;
  229. }
  230. return (
  231. <Fragment>
  232. {selectedOrgSlug && organization && !this.hasAccess() && (
  233. <Alert type="error" icon={<IconFlag size="md" />}>
  234. <p>
  235. {tct(
  236. `You do not have permission to install integrations in
  237. [organization]. Ask an organization owner or manager to
  238. visit this page to finish installing this integration.`,
  239. {organization: <strong>{organization.slug}</strong>}
  240. )}
  241. </p>
  242. <InstallLink>{window.location.href}</InstallLink>
  243. </Alert>
  244. )}
  245. {provider && organization && this.hasAccess() && FeatureList && (
  246. <Fragment>
  247. <p>
  248. {tct(
  249. 'The following features will be available for [organization] when installed.',
  250. {organization: <strong>{organization.slug}</strong>}
  251. )}
  252. </p>
  253. <FeatureList
  254. organization={organization}
  255. features={provider.metadata.features}
  256. provider={provider}
  257. />
  258. </Fragment>
  259. )}
  260. <div className="form-actions">{this.renderAddButton()}</div>
  261. </Fragment>
  262. );
  263. }
  264. renderBody() {
  265. const {selectedOrgSlug} = this.state;
  266. const options = this.state.organizations.map((org: Organization) => ({
  267. value: org.slug,
  268. label: org.name,
  269. }));
  270. return (
  271. <NarrowLayout>
  272. <h3>{t('Finish integration installation')}</h3>
  273. <p>
  274. {tct(
  275. `Please pick a specific [organization:organization] to link with
  276. your integration installation of [integation].`,
  277. {
  278. organization: <strong />,
  279. integation: <strong>{this.integrationSlug}</strong>,
  280. }
  281. )}
  282. </p>
  283. <Field label={t('Organization')} inline={false} stacked required>
  284. <SelectControl
  285. onChange={this.onSelectOrg}
  286. value={selectedOrgSlug}
  287. placeholder={t('Select an organization')}
  288. options={options}
  289. components={{
  290. Option: this.customOption,
  291. ValueContainer: this.customValueContainer,
  292. }}
  293. />
  294. </Field>
  295. {this.renderBottom()}
  296. </NarrowLayout>
  297. );
  298. }
  299. }
  300. const InstallLink = styled('pre')`
  301. margin-bottom: 0;
  302. background: #fbe3e1;
  303. `;
  304. const FeatureListItem = styled('span')`
  305. line-height: 24px;
  306. `;
  307. const ButtonWrapper = styled('div')`
  308. margin-left: auto;
  309. align-self: center;
  310. display: flex;
  311. flex-direction: column;
  312. align-items: center;
  313. `;