configureIntegration.tsx 16 KB

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