integrationListDirectory.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import {Fragment} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import debounce from 'lodash/debounce';
  5. import groupBy from 'lodash/groupBy';
  6. import startCase from 'lodash/startCase';
  7. import * as qs from 'query-string';
  8. import DocIntegrationAvatar from 'sentry/components/avatar/docIntegrationAvatar';
  9. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  10. import SelectControl from 'sentry/components/forms/controls/selectControl';
  11. import HookOrDefault from 'sentry/components/hookOrDefault';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelBody from 'sentry/components/panels/panelBody';
  15. import SearchBar from 'sentry/components/searchBar';
  16. import SentryAppIcon from 'sentry/components/sentryAppIcon';
  17. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  18. import {t, tct} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import {
  21. AppOrProviderOrPlugin,
  22. DocIntegration,
  23. Integration,
  24. IntegrationProvider,
  25. Organization,
  26. PluginWithProjectList,
  27. SentryApp,
  28. SentryAppInstallation,
  29. } from 'sentry/types';
  30. import {uniq} from 'sentry/utils/array/uniq';
  31. import {createFuzzySearch, Fuse} from 'sentry/utils/fuzzySearch';
  32. import {
  33. getAlertText,
  34. getCategoriesForIntegration,
  35. getIntegrationStatus,
  36. getSentryAppInstallStatus,
  37. isDocIntegration,
  38. isPlugin,
  39. isSentryApp,
  40. trackIntegrationAnalytics,
  41. } from 'sentry/utils/integrationUtil';
  42. import withOrganization from 'sentry/utils/withOrganization';
  43. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  44. import PermissionAlert from 'sentry/views/settings/organization/permissionAlert';
  45. import CreateIntegrationButton from 'sentry/views/settings/organizationIntegrations/createIntegrationButton';
  46. import ReinstallAlert from 'sentry/views/settings/organizationIntegrations/reinstallAlert';
  47. import {POPULARITY_WEIGHT} from './constants';
  48. import IntegrationRow from './integrationRow';
  49. const FirstPartyIntegrationAlert = HookOrDefault({
  50. hookName: 'component:first-party-integration-alert',
  51. defaultComponent: () => null,
  52. });
  53. const fuseOptions = {
  54. threshold: 0.3,
  55. location: 0,
  56. distance: 100,
  57. includeScore: true as const,
  58. keys: ['slug', 'key', 'name', 'id'],
  59. };
  60. type Props = RouteComponentProps<{}, {}> & {
  61. hideHeader: boolean;
  62. organization: Organization;
  63. };
  64. type State = {
  65. appInstalls: SentryAppInstallation[] | null;
  66. config: {providers: IntegrationProvider[]} | null;
  67. displayedList: AppOrProviderOrPlugin[];
  68. docIntegrations: DocIntegration[] | null;
  69. integrations: Integration[] | null;
  70. list: AppOrProviderOrPlugin[];
  71. orgOwnedApps: SentryApp[] | null;
  72. plugins: PluginWithProjectList[] | null;
  73. publishedApps: SentryApp[] | null;
  74. searchInput: string;
  75. selectedCategory: string;
  76. extraApp?: SentryApp;
  77. fuzzy?: Fuse<AppOrProviderOrPlugin>;
  78. };
  79. const TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS = 1000;
  80. export class IntegrationListDirectory extends DeprecatedAsyncComponent<
  81. Props & DeprecatedAsyncComponent['props'],
  82. State & DeprecatedAsyncComponent['state']
  83. > {
  84. // Some integrations require visiting a different website to add them. When
  85. // we come back to the tab we want to show our integrations as soon as we can.
  86. shouldReload = true;
  87. reloadOnVisible = true;
  88. shouldReloadOnVisible = true;
  89. getDefaultState() {
  90. return {
  91. ...super.getDefaultState(),
  92. list: [],
  93. displayedList: [],
  94. selectedCategory: '',
  95. };
  96. }
  97. onLoadAllEndpointsSuccess() {
  98. const {publishedApps, orgOwnedApps, extraApp, plugins, docIntegrations} = this.state;
  99. const published = publishedApps || [];
  100. // If we have an extra app in state from query parameter, add it as org owned app
  101. if (orgOwnedApps !== null && extraApp) {
  102. orgOwnedApps.push(extraApp);
  103. }
  104. // we don't want the app to render twice if its the org that created
  105. // the published app.
  106. const orgOwned = orgOwnedApps?.filter(
  107. app => !published.find(p => p.slug === app.slug)
  108. );
  109. /**
  110. * We should have three sections:
  111. * 1. Public apps and integrations available to everyone
  112. * 2. Unpublished apps available to that org
  113. * 3. Internal apps available to that org
  114. */
  115. const combined = ([] as AppOrProviderOrPlugin[])
  116. .concat(published)
  117. .concat(orgOwned ?? [])
  118. .concat(this.providers)
  119. .concat(plugins ?? [])
  120. .concat(docIntegrations ?? []);
  121. const list = this.sortIntegrations(combined);
  122. const {searchInput, selectedCategory} = this.getFilterParameters();
  123. this.setState({list, searchInput, selectedCategory}, () => {
  124. this.updateDisplayedList();
  125. this.trackPageViewed();
  126. });
  127. }
  128. trackPageViewed() {
  129. // count the number of installed apps
  130. const {integrations, publishedApps, plugins} = this.state;
  131. const integrationsInstalled = new Set();
  132. // add installed integrations
  133. integrations?.forEach((integration: Integration) => {
  134. integrationsInstalled.add(integration.provider.key);
  135. });
  136. // add sentry apps
  137. publishedApps?.filter(this.getAppInstall).forEach((sentryApp: SentryApp) => {
  138. integrationsInstalled.add(sentryApp.slug);
  139. });
  140. // add plugins
  141. plugins?.forEach((plugin: PluginWithProjectList) => {
  142. if (plugin.projectList.length) {
  143. integrationsInstalled.add(plugin.slug);
  144. }
  145. });
  146. trackIntegrationAnalytics(
  147. 'integrations.index_viewed',
  148. {
  149. integrations_installed: integrationsInstalled.size,
  150. view: 'integrations_directory',
  151. organization: this.props.organization,
  152. },
  153. {startSession: true}
  154. );
  155. }
  156. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  157. const {organization} = this.props;
  158. const baseEndpoints: ([string, string, any] | [string, string])[] = [
  159. ['config', `/organizations/${organization.slug}/config/integrations/`],
  160. [
  161. 'integrations',
  162. `/organizations/${organization.slug}/integrations/`,
  163. {query: {includeConfig: 0}},
  164. ],
  165. ['orgOwnedApps', `/organizations/${organization.slug}/sentry-apps/`],
  166. ['publishedApps', '/sentry-apps/', {query: {status: 'published'}}],
  167. ['appInstalls', `/organizations/${organization.slug}/sentry-app-installations/`],
  168. ['plugins', `/organizations/${organization.slug}/plugins/configs/`],
  169. ['docIntegrations', '/doc-integrations/'],
  170. ];
  171. /**
  172. * optional app to load for super users
  173. * should only be done for unpublished integrations from another org
  174. * but no checks are in place to ensure the above condition
  175. */
  176. const extraAppSlug = new URLSearchParams(this.props.location.search).get('extra_app');
  177. if (extraAppSlug) {
  178. baseEndpoints.push(['extraApp', `/sentry-apps/${extraAppSlug}/`]);
  179. }
  180. return baseEndpoints;
  181. }
  182. // State
  183. get unmigratableReposByOrg() {
  184. // Group by [GitHub|BitBucket|VSTS] Org name
  185. return groupBy(this.state.unmigratableRepos, repo => repo.name.split('/')[0]);
  186. }
  187. get providers(): IntegrationProvider[] {
  188. return this.state.config?.providers ?? [];
  189. }
  190. getAppInstall = (app: SentryApp) =>
  191. this.state.appInstalls?.find(i => i.app.slug === app.slug);
  192. // Returns 0 if uninstalled, 1 if pending, and 2 if installed
  193. getInstallValue(integration: AppOrProviderOrPlugin) {
  194. const {integrations} = this.state;
  195. if (isPlugin(integration)) {
  196. return integration.projectList.length > 0 ? 2 : 0;
  197. }
  198. if (isSentryApp(integration)) {
  199. const install = this.getAppInstall(integration);
  200. if (install) {
  201. return install.status === 'pending' ? 1 : 2;
  202. }
  203. return 0;
  204. }
  205. if (isDocIntegration(integration)) {
  206. return 0;
  207. }
  208. return integrations?.find(i => i.provider.key === integration.key) ? 2 : 0;
  209. }
  210. getInstallStatuses(integrations: Integration[]) {
  211. const statusList = integrations?.map(getIntegrationStatus);
  212. // if we have conflicting statuses, we have a priority order
  213. if (statusList.includes('active')) {
  214. return 'Installed';
  215. }
  216. if (statusList.includes('disabled')) {
  217. return 'Disabled';
  218. }
  219. if (statusList.includes('pending_deletion')) {
  220. return 'Pending Deletion';
  221. }
  222. return 'Not Installed';
  223. }
  224. getPopularityWeight = (integration: AppOrProviderOrPlugin) => {
  225. if (isSentryApp(integration) || isDocIntegration(integration)) {
  226. return integration?.popularity ?? 1;
  227. }
  228. return POPULARITY_WEIGHT[integration.slug] ?? 1;
  229. };
  230. sortByName = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  231. a.slug.localeCompare(b.slug);
  232. sortByPopularity = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  233. const weightA = this.getPopularityWeight(a);
  234. const weightB = this.getPopularityWeight(b);
  235. return weightB - weightA;
  236. };
  237. sortByInstalled = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  238. this.getInstallValue(b) - this.getInstallValue(a);
  239. sortIntegrations(integrations: AppOrProviderOrPlugin[]) {
  240. return integrations.sort((a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  241. // sort by whether installed first
  242. const diffWeight = this.sortByInstalled(a, b);
  243. if (diffWeight !== 0) {
  244. return diffWeight;
  245. }
  246. // then sort by popularity
  247. const diffPop = this.sortByPopularity(a, b);
  248. if (diffPop !== 0) {
  249. return diffPop;
  250. }
  251. // then sort by name
  252. return this.sortByName(a, b);
  253. });
  254. }
  255. async componentDidUpdate(_: Props, prevState: State) {
  256. if (this.state.list.length !== prevState.list.length) {
  257. await this.createSearch();
  258. }
  259. }
  260. async createSearch() {
  261. const {list} = this.state;
  262. this.setState({
  263. fuzzy: await createFuzzySearch(list || [], fuseOptions),
  264. });
  265. }
  266. debouncedTrackIntegrationSearch = debounce((search: string, numResults: number) => {
  267. trackIntegrationAnalytics('integrations.directory_item_searched', {
  268. view: 'integrations_directory',
  269. search_term: search,
  270. num_results: numResults,
  271. organization: this.props.organization,
  272. });
  273. }, TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS);
  274. /**
  275. * Get filter parameters and guard against `qs.parse` returning arrays.
  276. */
  277. getFilterParameters = (): {searchInput: string; selectedCategory: string} => {
  278. const {category, search} = qs.parse(this.props.location.search);
  279. const selectedCategory = Array.isArray(category) ? category[0] : category || '';
  280. const searchInput = Array.isArray(search) ? search[0] : search || '';
  281. return {searchInput, selectedCategory};
  282. };
  283. /**
  284. * Update the query string with the current filter parameter values.
  285. */
  286. updateQueryString = () => {
  287. const {searchInput, selectedCategory} = this.state;
  288. const searchString = qs.stringify({
  289. ...qs.parse(this.props.location.search),
  290. search: searchInput ? searchInput : undefined,
  291. category: selectedCategory ? selectedCategory : undefined,
  292. });
  293. browserHistory.replace({
  294. pathname: this.props.location.pathname,
  295. search: searchString ? `?${searchString}` : undefined,
  296. });
  297. };
  298. /**
  299. * Filter the integrations list by ANDing together the search query and the category select.
  300. */
  301. updateDisplayedList = (): AppOrProviderOrPlugin[] => {
  302. const {fuzzy, list, searchInput, selectedCategory} = this.state;
  303. let displayedList = list;
  304. if (searchInput && fuzzy) {
  305. const searchResults = fuzzy.search(searchInput);
  306. displayedList = this.sortIntegrations(searchResults.map(i => i.item));
  307. }
  308. if (selectedCategory) {
  309. displayedList = displayedList.filter(integration =>
  310. getCategoriesForIntegration(integration).includes(selectedCategory)
  311. );
  312. }
  313. this.setState({displayedList});
  314. return displayedList;
  315. };
  316. handleSearchChange = (value: string) => {
  317. this.setState({searchInput: value}, () => {
  318. this.updateQueryString();
  319. const result = this.updateDisplayedList();
  320. if (value) {
  321. this.debouncedTrackIntegrationSearch(value, result.length);
  322. }
  323. });
  324. };
  325. onCategorySelect = ({value: category}: {value: string}) => {
  326. this.setState({selectedCategory: category}, () => {
  327. this.updateQueryString();
  328. this.updateDisplayedList();
  329. if (category) {
  330. trackIntegrationAnalytics('integrations.directory_category_selected', {
  331. view: 'integrations_directory',
  332. category,
  333. organization: this.props.organization,
  334. });
  335. }
  336. });
  337. };
  338. getCategoryLabel = (value: string) => {
  339. if (value === 'api') {
  340. return 'API';
  341. }
  342. return startCase(value);
  343. };
  344. // Rendering
  345. renderProvider = (provider: IntegrationProvider) => {
  346. const {organization} = this.props;
  347. // find the integration installations for that provider
  348. const integrations =
  349. this.state.integrations?.filter(i => i.provider.key === provider.key) ?? [];
  350. return (
  351. <IntegrationRow
  352. key={`row-${provider.key}`}
  353. data-test-id="integration-row"
  354. organization={organization}
  355. type="firstParty"
  356. slug={provider.slug}
  357. displayName={provider.name}
  358. status={this.getInstallStatuses(integrations)}
  359. publishStatus="published"
  360. configurations={integrations.length}
  361. categories={getCategoriesForIntegration(provider)}
  362. alertText={getAlertText(integrations)}
  363. resolveText={t('Update Now')}
  364. customAlert={
  365. <FirstPartyIntegrationAlert integrations={integrations} wrapWithContainer />
  366. }
  367. />
  368. );
  369. };
  370. renderPlugin = (plugin: PluginWithProjectList) => {
  371. const {organization} = this.props;
  372. const isLegacy = plugin.isHidden;
  373. const displayName = `${plugin.name} ${isLegacy ? '(Legacy)' : ''}`;
  374. // hide legacy integrations if we don't have any projects with them
  375. if (isLegacy && !plugin.projectList.length) {
  376. return null;
  377. }
  378. return (
  379. <IntegrationRow
  380. key={`row-plugin-${plugin.id}`}
  381. data-test-id="integration-row"
  382. organization={organization}
  383. type="plugin"
  384. slug={plugin.slug}
  385. displayName={displayName}
  386. status={plugin.projectList.length ? 'Installed' : 'Not Installed'}
  387. publishStatus="published"
  388. configurations={plugin.projectList.length}
  389. categories={getCategoriesForIntegration(plugin)}
  390. plugin={plugin}
  391. />
  392. );
  393. };
  394. // render either an internal or non-internal app
  395. renderSentryApp = (app: SentryApp) => {
  396. const {organization} = this.props;
  397. const status = getSentryAppInstallStatus(this.getAppInstall(app));
  398. const categories = getCategoriesForIntegration(app);
  399. return (
  400. <IntegrationRow
  401. key={`sentry-app-row-${app.slug}`}
  402. data-test-id="integration-row"
  403. organization={organization}
  404. type="sentryApp"
  405. slug={app.slug}
  406. displayName={app.name}
  407. status={status}
  408. publishStatus={app.status}
  409. configurations={0}
  410. categories={categories}
  411. customIcon={<SentryAppIcon sentryApp={app} size={36} />}
  412. />
  413. );
  414. };
  415. renderDocIntegration = (doc: DocIntegration) => {
  416. const {organization} = this.props;
  417. return (
  418. <IntegrationRow
  419. key={`doc-int-${doc.slug}`}
  420. data-test-id="integration-row"
  421. organization={organization}
  422. type="docIntegration"
  423. slug={doc.slug}
  424. displayName={doc.name}
  425. publishStatus="published"
  426. configurations={0}
  427. categories={getCategoriesForIntegration(doc)}
  428. customIcon={<DocIntegrationAvatar docIntegration={doc} size={36} />}
  429. />
  430. );
  431. };
  432. renderIntegration = (integration: AppOrProviderOrPlugin) => {
  433. if (isSentryApp(integration)) {
  434. return this.renderSentryApp(integration);
  435. }
  436. if (isPlugin(integration)) {
  437. return this.renderPlugin(integration);
  438. }
  439. if (isDocIntegration(integration)) {
  440. return this.renderDocIntegration(integration);
  441. }
  442. return this.renderProvider(integration);
  443. };
  444. renderBody() {
  445. const {organization} = this.props;
  446. const {displayedList, list, searchInput, selectedCategory, integrations} = this.state;
  447. const title = t('Integrations');
  448. const categoryList = uniq(list.flatMap(getCategoriesForIntegration)).sort();
  449. return (
  450. <Fragment>
  451. <SentryDocumentTitle title={title} orgSlug={organization.slug} />
  452. {!this.props.hideHeader && (
  453. <SettingsPageHeader
  454. title={title}
  455. body={
  456. <ActionContainer>
  457. <SelectControl
  458. name="select-categories"
  459. onChange={this.onCategorySelect}
  460. value={selectedCategory}
  461. options={[
  462. {value: '', label: t('All Categories')},
  463. ...categoryList.map(category => ({
  464. value: category,
  465. label: this.getCategoryLabel(category),
  466. })),
  467. ]}
  468. />
  469. <SearchBar
  470. query={searchInput || ''}
  471. onChange={this.handleSearchChange}
  472. placeholder={t('Filter Integrations...')}
  473. aria-label={t('Filter')}
  474. width="100%"
  475. data-test-id="search-bar"
  476. />
  477. </ActionContainer>
  478. }
  479. action={<CreateIntegrationButton analyticsView="integrations_directory" />}
  480. />
  481. )}
  482. <PermissionAlert access={['org:integrations']} />
  483. <ReinstallAlert integrations={integrations} />
  484. <Panel>
  485. <PanelBody data-test-id="integration-panel">
  486. {displayedList.length ? (
  487. displayedList.map(this.renderIntegration)
  488. ) : (
  489. <EmptyResultsContainer>
  490. <EmptyResultsBody>
  491. {tct('No Integrations found for "[searchTerm]".', {
  492. searchTerm: searchInput,
  493. })}
  494. </EmptyResultsBody>
  495. <EmptyResultsBodyBold>
  496. {t("Not seeing what you're looking for?")}
  497. </EmptyResultsBodyBold>
  498. <EmptyResultsBody>
  499. {tct('[link:Build it on the Sentry Integration Platform.]', {
  500. link: (
  501. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/" />
  502. ),
  503. })}
  504. </EmptyResultsBody>
  505. </EmptyResultsContainer>
  506. )}
  507. </PanelBody>
  508. </Panel>
  509. </Fragment>
  510. );
  511. }
  512. }
  513. const ActionContainer = styled('div')`
  514. display: grid;
  515. grid-template-columns: 240px auto;
  516. gap: ${space(2)};
  517. `;
  518. const EmptyResultsContainer = styled('div')`
  519. height: 200px;
  520. display: flex;
  521. flex-direction: column;
  522. align-items: center;
  523. justify-content: center;
  524. `;
  525. const EmptyResultsBody = styled('div')`
  526. font-size: 16px;
  527. line-height: 28px;
  528. color: ${p => p.theme.gray300};
  529. padding-bottom: ${space(2)};
  530. `;
  531. const EmptyResultsBodyBold = styled(EmptyResultsBody)`
  532. font-weight: bold;
  533. `;
  534. export default withOrganization(IntegrationListDirectory);