configureIntegration.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import {Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  5. import {Client} from 'sentry/api';
  6. import Access from 'sentry/components/acl/access';
  7. import {Alert} from 'sentry/components/alert';
  8. import {Button, LinkButton} from 'sentry/components/button';
  9. import Confirm from 'sentry/components/confirm';
  10. import Form from 'sentry/components/forms/form';
  11. import JsonForm from 'sentry/components/forms/jsonForm';
  12. import List from 'sentry/components/list';
  13. import ListItem from 'sentry/components/list/listItem';
  14. import NavTabs from 'sentry/components/navTabs';
  15. import {IconAdd, IconArrow} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {
  19. IntegrationProvider,
  20. IntegrationWithConfig,
  21. Organization,
  22. PluginWithProjectList,
  23. } from 'sentry/types';
  24. import {trackIntegrationAnalytics} from 'sentry/utils/integrationUtil';
  25. import {singleLineRenderer} from 'sentry/utils/marked';
  26. import withApi from 'sentry/utils/withApi';
  27. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  28. import withOrganization from 'sentry/utils/withOrganization';
  29. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  30. import BreadcrumbTitle from 'sentry/views/settings/components/settingsBreadcrumb/breadcrumbTitle';
  31. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  32. import AddIntegration from './addIntegration';
  33. import IntegrationAlertRules from './integrationAlertRules';
  34. import IntegrationCodeMappings from './integrationCodeMappings';
  35. import IntegrationExternalTeamMappings from './integrationExternalTeamMappings';
  36. import IntegrationExternalUserMappings from './integrationExternalUserMappings';
  37. import IntegrationItem from './integrationItem';
  38. import IntegrationMainSettings from './integrationMainSettings';
  39. import IntegrationRepos from './integrationRepos';
  40. import IntegrationServerlessFunctions from './integrationServerlessFunctions';
  41. type RouteParams = {
  42. integrationId: string;
  43. providerKey: string;
  44. };
  45. type Props = RouteComponentProps<RouteParams, {}> & {
  46. api: Client;
  47. organization: Organization;
  48. };
  49. type Tab = 'repos' | 'codeMappings' | 'userMappings' | 'teamMappings' | 'settings';
  50. type State = DeprecatedAsyncView['state'] & {
  51. config: {providers: IntegrationProvider[]};
  52. integration: IntegrationWithConfig;
  53. plugins: PluginWithProjectList[] | null;
  54. tab?: Tab;
  55. };
  56. class ConfigureIntegration extends DeprecatedAsyncView<Props, State> {
  57. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  58. const {organization} = this.props;
  59. const {integrationId} = this.props.params;
  60. return [
  61. ['config', `/organizations/${organization.slug}/config/integrations/`],
  62. [
  63. 'integration',
  64. `/organizations/${organization.slug}/integrations/${integrationId}/`,
  65. ],
  66. ['plugins', `/organizations/${organization.slug}/plugins/configs/`],
  67. ];
  68. }
  69. componentDidMount() {
  70. super.componentDidMount();
  71. const {
  72. location,
  73. router,
  74. organization,
  75. params: {providerKey},
  76. } = this.props;
  77. // This page should not be accessible by members (unless its github or gitlab)
  78. const allowMemberConfiguration = ['github', 'gitlab'].includes(providerKey);
  79. if (!allowMemberConfiguration && !organization.access.includes('org:integrations')) {
  80. router.push(
  81. normalizeUrl({
  82. pathname: `/settings/${organization.slug}/integrations/${providerKey}/`,
  83. })
  84. );
  85. }
  86. const value =
  87. (['codeMappings', 'userMappings', 'teamMappings'] as const).find(
  88. tab => tab === location.query.tab
  89. ) || 'repos';
  90. // eslint-disable-next-line react/no-did-mount-set-state
  91. this.setState({tab: value});
  92. }
  93. onRequestSuccess({stateKey, data}) {
  94. if (stateKey !== 'integration') {
  95. return;
  96. }
  97. trackIntegrationAnalytics('integrations.details_viewed', {
  98. integration: data.provider.key,
  99. integration_type: 'first_party',
  100. organization: this.props.organization,
  101. });
  102. }
  103. getTitle() {
  104. return this.state.integration
  105. ? this.state.integration.provider.name
  106. : 'Configure Integration';
  107. }
  108. hasStacktraceLinking(provider: IntegrationProvider) {
  109. // CodeOwners will only work if the provider has StackTrace Linking
  110. return (
  111. provider.features.includes('stacktrace-link') &&
  112. this.props.organization.features.includes('integrations-stacktrace-link')
  113. );
  114. }
  115. hasCodeOwners() {
  116. return this.props.organization.features.includes('integrations-codeowners');
  117. }
  118. onTabChange = (value: Tab) => {
  119. this.setState({tab: value});
  120. };
  121. get tab() {
  122. return this.state.tab || 'repos';
  123. }
  124. onUpdateIntegration = () => {
  125. this.setState(this.getDefaultState(), this.fetchData);
  126. };
  127. handleJiraMigration = async () => {
  128. try {
  129. const {
  130. organization,
  131. params: {integrationId},
  132. } = this.props;
  133. await this.api.requestPromise(
  134. `/organizations/${organization.slug}/integrations/${integrationId}/issues/`,
  135. {
  136. method: 'PUT',
  137. data: {},
  138. }
  139. );
  140. this.setState(
  141. {
  142. plugins: (this.state.plugins || []).filter(({id}) => id === 'jira'),
  143. },
  144. () => addSuccessMessage(t('Migration in progress.'))
  145. );
  146. } catch (error) {
  147. addErrorMessage(t('Something went wrong! Please try again.'));
  148. }
  149. };
  150. handleOpsgenieMigration = () => {
  151. this.setState(
  152. {
  153. plugins: (this.state.plugins || []).filter(({id}) => id === 'opsgenie'),
  154. },
  155. () => addSuccessMessage(t("This doesn't do anything yet!"))
  156. );
  157. };
  158. isInstalledOpsgeniePlugin = (plugin: PluginWithProjectList) => {
  159. return (
  160. plugin.id === 'opsgenie' &&
  161. plugin.projectList.length >= 1 &&
  162. plugin.projectList.find(({enabled}) => enabled === true)
  163. );
  164. };
  165. getAction = (provider: IntegrationProvider | undefined) => {
  166. const {integration, plugins} = this.state;
  167. const shouldMigrateJiraPlugin =
  168. provider &&
  169. ['jira', 'jira_server'].includes(provider.key) &&
  170. (plugins || []).find(({id}) => id === 'jira');
  171. const shouldMigrateOpsgeniePlugin =
  172. this.props.organization.features.includes('integrations-opsgenie-migration') &&
  173. provider &&
  174. provider.key === 'opsgenie' &&
  175. (plugins || []).find(this.isInstalledOpsgeniePlugin);
  176. const action =
  177. provider && provider.key === 'pagerduty' ? (
  178. <AddIntegration
  179. provider={provider}
  180. onInstall={this.onUpdateIntegration}
  181. account={integration.domainName}
  182. organization={this.props.organization}
  183. >
  184. {onClick => (
  185. <Button
  186. priority="primary"
  187. size="sm"
  188. icon={<IconAdd size="xs" isCircled />}
  189. onClick={() => onClick()}
  190. >
  191. {t('Add Services')}
  192. </Button>
  193. )}
  194. </AddIntegration>
  195. ) : shouldMigrateJiraPlugin ? (
  196. <Access access={['org:integrations']}>
  197. {({hasAccess}) => (
  198. <Confirm
  199. disabled={!hasAccess}
  200. header="Migrate Linked Issues from Jira Plugins"
  201. renderMessage={() => (
  202. <Fragment>
  203. <p>
  204. {t(
  205. 'This will automatically associate all the Linked Issues of your Jira Plugins to this integration.'
  206. )}
  207. </p>
  208. <p>
  209. {t(
  210. 'If the Jira Plugins had the option checked to automatically create a Jira ticket for every new Sentry issue checked, you will need to create alert rules to recreate this behavior. Jira Server does not have this feature.'
  211. )}
  212. </p>
  213. <p>
  214. {t(
  215. 'Once the migration is complete, your Jira Plugins will be disabled.'
  216. )}
  217. </p>
  218. </Fragment>
  219. )}
  220. onConfirm={() => {
  221. this.handleJiraMigration();
  222. }}
  223. >
  224. <Button priority="primary" size="md" disabled={!hasAccess}>
  225. {t('Migrate Plugin')}
  226. </Button>
  227. </Confirm>
  228. )}
  229. </Access>
  230. ) : provider && provider.key === 'discord' ? (
  231. <LinkButton
  232. aria-label="Open this server in the Discord app"
  233. size="sm"
  234. // @ts-ignore - the type of integration here is weird.
  235. href={`discord://discord.com/channels/${integration.externalId}`}
  236. >
  237. Open in Discord
  238. </LinkButton>
  239. ) : shouldMigrateOpsgeniePlugin ? (
  240. <Access access={['org:integrations']}>
  241. {({hasAccess}) => (
  242. <Confirm
  243. disabled={!hasAccess}
  244. header="Migrate API Keys and Alert Rules from Opsgenie"
  245. renderMessage={() => (
  246. <Fragment>
  247. <p>
  248. {t(
  249. 'This will automatically associate all the API keys and Alert Rules of your Opsgenie Plugins to this integration.'
  250. )}
  251. </p>
  252. <p>
  253. {t(
  254. 'API keys will be automatically named after one of the projects with which they were associated.'
  255. )}
  256. </p>
  257. <p>
  258. {t(
  259. 'Once the migration is complete, your Opsgenie Plugins will be disabled.'
  260. )}
  261. </p>
  262. </Fragment>
  263. )}
  264. onConfirm={() => {
  265. this.handleOpsgenieMigration();
  266. }}
  267. >
  268. <Button priority="primary" size="md" disabled={!hasAccess}>
  269. {t('Migrate Plugin')}
  270. </Button>
  271. </Confirm>
  272. )}
  273. </Access>
  274. ) : null;
  275. return action;
  276. };
  277. // TODO(Steve): Refactor components into separate tabs and use more generic tab logic
  278. renderMainTab(provider: IntegrationProvider) {
  279. const {organization} = this.props;
  280. const {integration} = this.state;
  281. const instructions =
  282. integration.dynamicDisplayInformation?.configure_integration?.instructions;
  283. return (
  284. <Fragment>
  285. {integration.configOrganization.length > 0 && (
  286. <Form
  287. hideFooter
  288. saveOnBlur
  289. allowUndo
  290. apiMethod="POST"
  291. initialData={integration.configData || {}}
  292. apiEndpoint={`/organizations/${organization.slug}/integrations/${integration.id}/`}
  293. >
  294. <JsonForm
  295. fields={integration.configOrganization}
  296. title={
  297. integration.provider.aspects.configure_integration?.title ||
  298. t('Organization Integration Settings')
  299. }
  300. />
  301. </Form>
  302. )}
  303. {instructions && instructions.length > 0 && (
  304. <Alert type="info">
  305. {instructions?.length === 1 ? (
  306. <span
  307. dangerouslySetInnerHTML={{__html: singleLineRenderer(instructions[0])}}
  308. />
  309. ) : (
  310. <List symbol={<IconArrow size="xs" direction="right" />}>
  311. {instructions?.map((instruction, i) => (
  312. <ListItem key={i}>
  313. <span
  314. dangerouslySetInnerHTML={{__html: singleLineRenderer(instruction)}}
  315. />
  316. </ListItem>
  317. )) ?? []}
  318. </List>
  319. )}
  320. </Alert>
  321. )}
  322. {provider.features.includes('alert-rule') && <IntegrationAlertRules />}
  323. {provider.features.includes('commits') && (
  324. <IntegrationRepos {...this.props} integration={integration} />
  325. )}
  326. {provider.features.includes('serverless') && (
  327. <IntegrationServerlessFunctions integration={integration} />
  328. )}
  329. </Fragment>
  330. );
  331. }
  332. renderBody() {
  333. const {integration} = this.state;
  334. const {organization, router} = this.props;
  335. const provider = this.state.config.providers.find(
  336. p => p.key === integration.provider.key
  337. );
  338. if (!provider) {
  339. return null;
  340. }
  341. const title = <IntegrationItem integration={integration} />;
  342. const header = (
  343. <SettingsPageHeader noTitleStyles title={title} action={this.getAction(provider)} />
  344. );
  345. const backButton = (
  346. <BackButtonWrapper>
  347. <Button
  348. icon={<IconArrow direction="left" size="sm" />}
  349. size="sm"
  350. onClick={() => {
  351. router.push(
  352. normalizeUrl({
  353. pathname: `/settings/${organization.slug}/integrations/${provider.key}/`,
  354. })
  355. );
  356. }}
  357. >
  358. Back
  359. </Button>
  360. </BackButtonWrapper>
  361. );
  362. return (
  363. <Fragment>
  364. {backButton}
  365. {header}
  366. {this.renderMainContent(provider)}
  367. <BreadcrumbTitle
  368. routes={this.props.routes}
  369. title={t('Configure %s', integration.provider.name)}
  370. />
  371. </Fragment>
  372. );
  373. }
  374. // renders everything below header
  375. renderMainContent(provider: IntegrationProvider) {
  376. // if no code mappings, render the single tab
  377. if (!this.hasStacktraceLinking(provider)) {
  378. return this.renderMainTab(provider);
  379. }
  380. // otherwise render the tab view
  381. const tabs = [
  382. ['repos', t('Repositories')],
  383. ['codeMappings', t('Code Mappings')],
  384. ...(this.hasCodeOwners() ? [['userMappings', t('User Mappings')]] : []),
  385. ...(this.hasCodeOwners() ? [['teamMappings', t('Team Mappings')]] : []),
  386. ] as [id: Tab, label: string][];
  387. return (
  388. <Fragment>
  389. <NavTabs underlined>
  390. {tabs.map(tabTuple => (
  391. <li
  392. key={tabTuple[0]}
  393. className={this.tab === tabTuple[0] ? 'active' : ''}
  394. onClick={() => this.onTabChange(tabTuple[0])}
  395. >
  396. <CapitalizedLink>{tabTuple[1]}</CapitalizedLink>
  397. </li>
  398. ))}
  399. </NavTabs>
  400. {this.renderTabContent(this.tab, provider)}
  401. </Fragment>
  402. );
  403. }
  404. renderTabContent(tab: Tab, provider: IntegrationProvider) {
  405. const {integration} = this.state;
  406. const {organization} = this.props;
  407. switch (tab) {
  408. case 'codeMappings':
  409. return <IntegrationCodeMappings integration={integration} />;
  410. case 'repos':
  411. return this.renderMainTab(provider);
  412. case 'userMappings':
  413. return <IntegrationExternalUserMappings integration={integration} />;
  414. case 'teamMappings':
  415. return <IntegrationExternalTeamMappings integration={integration} />;
  416. case 'settings':
  417. return (
  418. <IntegrationMainSettings
  419. onUpdate={this.onUpdateIntegration}
  420. organization={organization}
  421. integration={integration}
  422. />
  423. );
  424. default:
  425. return this.renderMainTab(provider);
  426. }
  427. }
  428. }
  429. export default withOrganization(withApi(ConfigureIntegration));
  430. const BackButtonWrapper = styled('div')`
  431. margin-bottom: ${space(2)};
  432. width: 100%;
  433. `;
  434. const CapitalizedLink = styled('a')`
  435. text-transform: capitalize;
  436. `;