configureIntegration.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import {Fragment, useEffect} from 'react';
  2. import type {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 type {
  21. IntegrationProvider,
  22. IntegrationWithConfig,
  23. Organization,
  24. PluginWithProjectList,
  25. } from 'sentry/types';
  26. import {singleLineRenderer} from 'sentry/utils/marked';
  27. import type {ApiQueryKey} from 'sentry/utils/queryClient';
  28. import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
  29. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  30. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  31. import useApi from 'sentry/utils/useApi';
  32. import useOrganization from 'sentry/utils/useOrganization';
  33. import useProjects from 'sentry/utils/useProjects';
  34. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  35. import BreadcrumbTitle from 'sentry/views/settings/components/settingsBreadcrumb/breadcrumbTitle';
  36. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  37. import AddIntegration from './addIntegration';
  38. import IntegrationAlertRules from './integrationAlertRules';
  39. import IntegrationCodeMappings from './integrationCodeMappings';
  40. import IntegrationExternalTeamMappings from './integrationExternalTeamMappings';
  41. import IntegrationExternalUserMappings from './integrationExternalUserMappings';
  42. import IntegrationItem from './integrationItem';
  43. import IntegrationMainSettings from './integrationMainSettings';
  44. import IntegrationRepos from './integrationRepos';
  45. import IntegrationServerlessFunctions from './integrationServerlessFunctions';
  46. type Props = RouteComponentProps<
  47. {
  48. integrationId: string;
  49. providerKey: string;
  50. },
  51. {}
  52. >;
  53. const TABS = [
  54. 'repos',
  55. 'codeMappings',
  56. 'userMappings',
  57. 'teamMappings',
  58. 'settings',
  59. ] as const;
  60. type Tab = (typeof TABS)[number];
  61. const makeIntegrationQuery = (
  62. organization: Organization,
  63. integrationId: string
  64. ): ApiQueryKey => {
  65. return [`/organizations/${organization.slug}/integrations/${integrationId}/`];
  66. };
  67. const makePluginQuery = (organization: Organization): ApiQueryKey => {
  68. return [`/organizations/${organization.slug}/plugins/configs/`];
  69. };
  70. function ConfigureIntegration({params, router, routes, location}: Props) {
  71. const api = useApi();
  72. const queryClient = useQueryClient();
  73. const organization = useOrganization();
  74. const tab: Tab = TABS.includes(location.query.tab) ? location.query.tab : 'repos';
  75. const {integrationId, providerKey} = params;
  76. const {
  77. data: config = {providers: []},
  78. isLoading: isLoadingConfig,
  79. isError: isErrorConfig,
  80. refetch: refetchConfig,
  81. remove: removeConfig,
  82. } = useApiQuery<{
  83. providers: IntegrationProvider[];
  84. }>([`/organizations/${organization.slug}/config/integrations/`], {staleTime: 0});
  85. const {
  86. data: integration,
  87. isLoading: isLoadingIntegration,
  88. isError: isErrorIntegration,
  89. refetch: refetchIntegration,
  90. remove: removeIntegration,
  91. } = useApiQuery<IntegrationWithConfig>(
  92. makeIntegrationQuery(organization, integrationId),
  93. {staleTime: 0}
  94. );
  95. const {
  96. data: plugins,
  97. isLoading: isLoadingPlugins,
  98. isError: isErrorPlugins,
  99. refetch: refetchPlugins,
  100. remove: removePlugins,
  101. } = useApiQuery<PluginWithProjectList[] | null>(makePluginQuery(organization), {
  102. staleTime: 0,
  103. });
  104. const provider = config.providers.find(p => p.key === integration?.provider.key);
  105. const {projects} = useProjects();
  106. useRouteAnalyticsEventNames(
  107. 'integrations.details_viewed',
  108. 'Integrations: Details Viewed'
  109. );
  110. useRouteAnalyticsParams(
  111. provider
  112. ? {
  113. integration: provider.key,
  114. integration_type: 'first_party',
  115. }
  116. : {}
  117. );
  118. useEffect(() => {
  119. refetchIntegration();
  120. }, [projects, refetchIntegration]);
  121. useEffect(() => {
  122. // This page should not be accessible by members (unless its github or gitlab)
  123. const allowMemberConfiguration = ['github', 'gitlab'].includes(providerKey);
  124. if (!allowMemberConfiguration && !organization.access.includes('org:integrations')) {
  125. router.push(
  126. normalizeUrl({
  127. pathname: `/settings/${organization.slug}/integrations/${providerKey}/`,
  128. })
  129. );
  130. }
  131. }, [router, organization, providerKey]);
  132. if (isLoadingConfig || isLoadingIntegration || isLoadingPlugins) {
  133. return <LoadingIndicator />;
  134. }
  135. if (isErrorConfig || isErrorIntegration || isErrorPlugins) {
  136. return <LoadingError />;
  137. }
  138. if (!provider || !integration) {
  139. return null;
  140. }
  141. const onTabChange = (value: Tab) => {
  142. router.push({
  143. pathname: location.pathname,
  144. query: {...location.query, tab: value},
  145. });
  146. };
  147. /**
  148. * Refetch everything, this could be improved to reload only the right thing
  149. */
  150. const onUpdateIntegration = () => {
  151. removePlugins();
  152. refetchPlugins();
  153. removeConfig();
  154. refetchConfig();
  155. removeIntegration();
  156. refetchIntegration();
  157. };
  158. const handleOpsgenieMigration = async () => {
  159. try {
  160. await api.requestPromise(
  161. `/organizations/${organization.slug}/integrations/${integrationId}/migrate-opsgenie/`,
  162. {
  163. method: 'PUT',
  164. }
  165. );
  166. setApiQueryData<PluginWithProjectList[] | null>(
  167. queryClient,
  168. makePluginQuery(organization),
  169. oldData => {
  170. return oldData?.filter(({id}) => id === 'opsgenie') ?? [];
  171. }
  172. );
  173. addSuccessMessage(t('Migration in progress.'));
  174. } catch (error) {
  175. addErrorMessage(t('Something went wrong! Please try again.'));
  176. }
  177. };
  178. const handleJiraMigration = async () => {
  179. try {
  180. await api.requestPromise(
  181. `/organizations/${organization.slug}/integrations/${integrationId}/issues/`,
  182. {
  183. method: 'PUT',
  184. data: {},
  185. }
  186. );
  187. setApiQueryData<PluginWithProjectList[] | null>(
  188. queryClient,
  189. makePluginQuery(organization),
  190. oldData => {
  191. return oldData?.filter(({id}) => id === 'jira') ?? [];
  192. }
  193. );
  194. addSuccessMessage(t('Migration in progress.'));
  195. } catch (error) {
  196. addErrorMessage(t('Something went wrong! Please try again.'));
  197. }
  198. };
  199. const isOpsgeniePluginInstalled = () => {
  200. return (plugins || []).some(
  201. p =>
  202. p.id === 'opsgenie' &&
  203. p.projectList.length >= 1 &&
  204. p.projectList.some(({enabled}) => enabled === true)
  205. );
  206. };
  207. const getAction = () => {
  208. if (provider.key === 'pagerduty') {
  209. return (
  210. <AddIntegration
  211. provider={provider}
  212. onInstall={onUpdateIntegration}
  213. account={integration.domainName}
  214. organization={organization}
  215. >
  216. {onClick => (
  217. <Button
  218. priority="primary"
  219. size="sm"
  220. icon={<IconAdd isCircled />}
  221. onClick={() => onClick()}
  222. >
  223. {t('Add Services')}
  224. </Button>
  225. )}
  226. </AddIntegration>
  227. );
  228. }
  229. if (provider.key === 'discord') {
  230. return (
  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. {t('Open in Discord')}
  238. </LinkButton>
  239. );
  240. }
  241. const canMigrateJiraPlugin =
  242. ['jira', 'jira_server'].includes(provider.key) &&
  243. (plugins || []).find(({id}) => id === 'jira');
  244. if (canMigrateJiraPlugin) {
  245. return (
  246. <Access access={['org:integrations']}>
  247. {({hasAccess}) => (
  248. <Confirm
  249. disabled={!hasAccess}
  250. header="Migrate Linked Issues from Jira Plugins"
  251. renderMessage={() => (
  252. <Fragment>
  253. <p>
  254. {t(
  255. 'This will automatically associate all the Linked Issues of your Jira Plugins to this integration.'
  256. )}
  257. </p>
  258. <p>
  259. {t(
  260. '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.'
  261. )}
  262. </p>
  263. <p>
  264. {t(
  265. 'Once the migration is complete, your Jira Plugins will be disabled.'
  266. )}
  267. </p>
  268. </Fragment>
  269. )}
  270. onConfirm={() => {
  271. handleJiraMigration();
  272. }}
  273. >
  274. <Button priority="primary" disabled={!hasAccess}>
  275. {t('Migrate Plugin')}
  276. </Button>
  277. </Confirm>
  278. )}
  279. </Access>
  280. );
  281. }
  282. const canMigrateOpsgeniePlugin =
  283. provider.key === 'opsgenie' && isOpsgeniePluginInstalled();
  284. if (canMigrateOpsgeniePlugin) {
  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. `;