createProject.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import {useCallback, useContext, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import omit from 'lodash/omit';
  5. import startCase from 'lodash/startCase';
  6. import {PlatformIcon} from 'platformicons';
  7. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  8. import {openModal} from 'sentry/actionCreators/modal';
  9. import Access from 'sentry/components/acl/access';
  10. import {Alert} from 'sentry/components/alert';
  11. import {Button} from 'sentry/components/button';
  12. import Input from 'sentry/components/input';
  13. import * as Layout from 'sentry/components/layouts/thirds';
  14. import ExternalLink from 'sentry/components/links/externalLink';
  15. import List from 'sentry/components/list';
  16. import ListItem from 'sentry/components/list/listItem';
  17. import {SupportedLanguages} from 'sentry/components/onboarding/frameworkSuggestionModal';
  18. import type {Platform} from 'sentry/components/platformPicker';
  19. import PlatformPicker from 'sentry/components/platformPicker';
  20. import {canCreateProject} from 'sentry/components/projects/canCreateProject';
  21. import TeamSelector from 'sentry/components/teamSelector';
  22. import {Tooltip} from 'sentry/components/tooltip';
  23. import {t, tct} from 'sentry/locale';
  24. import ProjectsStore from 'sentry/stores/projectsStore';
  25. import {space} from 'sentry/styles/space';
  26. import type {OnboardingSelectedSDK} from 'sentry/types/onboarding';
  27. import type {Team} from 'sentry/types/organization';
  28. import {trackAnalytics} from 'sentry/utils/analytics';
  29. import {browserHistory} from 'sentry/utils/browserHistory';
  30. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  31. import slugify from 'sentry/utils/slugify';
  32. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  33. import useApi from 'sentry/utils/useApi';
  34. import {useLocation} from 'sentry/utils/useLocation';
  35. import useOrganization from 'sentry/utils/useOrganization';
  36. import {useTeams} from 'sentry/utils/useTeams';
  37. import {
  38. MultipleCheckboxOptions,
  39. useCreateNotificationAction,
  40. } from 'sentry/views/projectInstall/issueAlertNotificationOptions';
  41. import IssueAlertOptions, {
  42. MetricValues,
  43. RuleAction,
  44. } from 'sentry/views/projectInstall/issueAlertOptions';
  45. import {GettingStartedWithProjectContext} from 'sentry/views/projects/gettingStartedWithProjectContext';
  46. export type IssueAlertFragment = Parameters<
  47. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  48. >[0];
  49. function CreateProject() {
  50. const api = useApi();
  51. const organization = useOrganization();
  52. const location = useLocation();
  53. const gettingStartedWithProjectContext = useContext(GettingStartedWithProjectContext);
  54. const {teams} = useTeams();
  55. const autoFill =
  56. location.query.referrer === 'getting-started' &&
  57. location.query.project === gettingStartedWithProjectContext.project?.id;
  58. const accessTeams = teams.filter((team: Team) => team.access.includes('team:admin'));
  59. useRouteAnalyticsEventNames(
  60. 'project_creation_page.viewed',
  61. 'Project Create: Creation page viewed'
  62. );
  63. const [projectName, setProjectName] = useState(
  64. autoFill ? gettingStartedWithProjectContext.project?.name : ''
  65. );
  66. const [platform, setPlatform] = useState<OnboardingSelectedSDK | undefined>(
  67. autoFill ? gettingStartedWithProjectContext.project?.platform : undefined
  68. );
  69. const [team, setTeam] = useState(
  70. autoFill
  71. ? gettingStartedWithProjectContext.project?.teamSlug ?? accessTeams?.[0]?.slug
  72. : accessTeams?.[0]?.slug
  73. );
  74. const [errors, setErrors] = useState(false);
  75. const [inFlight, setInFlight] = useState(false);
  76. const [alertRuleConfig, setAlertRuleConfig] = useState<IssueAlertFragment | undefined>(
  77. undefined
  78. );
  79. const {createNotificationAction, notificationProps} = useCreateNotificationAction();
  80. const createProject = useCallback(
  81. async (selectedFramework?: OnboardingSelectedSDK) => {
  82. const {slug} = organization;
  83. const {
  84. shouldCreateRule,
  85. shouldCreateCustomRule,
  86. name,
  87. conditions,
  88. actions,
  89. actionMatch,
  90. frequency,
  91. defaultRules,
  92. } = alertRuleConfig || {};
  93. const selectedPlatform = selectedFramework ?? platform;
  94. if (!selectedPlatform) {
  95. addErrorMessage(t('Please select a platform in Step 1'));
  96. return;
  97. }
  98. setInFlight(true);
  99. try {
  100. const url = team
  101. ? `/teams/${slug}/${team}/projects/`
  102. : `/organizations/${slug}/experimental/projects/`;
  103. const projectData = await api.requestPromise(url, {
  104. method: 'POST',
  105. data: {
  106. name: projectName,
  107. platform: selectedPlatform.key,
  108. default_rules: defaultRules ?? true,
  109. },
  110. });
  111. const ruleIds: string[] = [];
  112. if (shouldCreateCustomRule) {
  113. const ruleData = await api.requestPromise(
  114. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  115. {
  116. method: 'POST',
  117. data: {
  118. name,
  119. conditions,
  120. actions,
  121. actionMatch,
  122. frequency,
  123. },
  124. }
  125. );
  126. ruleIds.push(ruleData.id);
  127. }
  128. const ruleData = await createNotificationAction({
  129. shouldCreateRule,
  130. name,
  131. projectSlug: projectData.slug,
  132. conditions,
  133. actionMatch,
  134. frequency,
  135. });
  136. if (ruleData) {
  137. ruleIds.push(ruleData.id);
  138. }
  139. trackAnalytics('project_creation_page.created', {
  140. organization,
  141. issue_alert: defaultRules
  142. ? 'Default'
  143. : shouldCreateCustomRule
  144. ? 'Custom'
  145. : 'No Rule',
  146. project_id: projectData.id,
  147. platform: selectedPlatform.key,
  148. rule_ids: ruleIds,
  149. has_onboarding_feature_flag: organization.features.includes(
  150. 'messaging-integration-onboarding-project-creation'
  151. ),
  152. created_integration_notification: shouldCreateRule ?? false,
  153. });
  154. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  155. if (team) {
  156. addSuccessMessage(
  157. tct('Created project [project]', {
  158. project: `${projectData.slug}`,
  159. })
  160. );
  161. } else {
  162. addSuccessMessage(
  163. tct('Created [project] under new team [team]', {
  164. project: `${projectData.slug}`,
  165. team: `#${projectData.team_slug}`,
  166. })
  167. );
  168. }
  169. browserHistory.push(
  170. normalizeUrl(
  171. `/organizations/${organization.slug}/projects/${projectData.slug}/getting-started/`
  172. )
  173. );
  174. } catch (err) {
  175. setInFlight(false);
  176. setErrors(err.responseJSON);
  177. addErrorMessage(
  178. tct('Failed to create project [project]', {
  179. project: `${projectName}`,
  180. })
  181. );
  182. // Only log this if the error is something other than:
  183. // * The user not having access to create a project, or,
  184. // * A project with that slug already exists
  185. if (err.status !== 403 && err.status !== 409) {
  186. Sentry.withScope(scope => {
  187. scope.setExtra('err', err);
  188. Sentry.captureMessage('Project creation failed');
  189. });
  190. }
  191. }
  192. },
  193. [
  194. api,
  195. alertRuleConfig,
  196. organization,
  197. platform,
  198. projectName,
  199. team,
  200. createNotificationAction,
  201. ]
  202. );
  203. const handleProjectCreation = useCallback(async () => {
  204. const selectedPlatform = platform;
  205. if (!selectedPlatform) {
  206. addErrorMessage(t('Please select a platform in Step 1'));
  207. return;
  208. }
  209. if (
  210. selectedPlatform.type !== 'language' ||
  211. !Object.values(SupportedLanguages).includes(
  212. selectedPlatform.language as SupportedLanguages
  213. )
  214. ) {
  215. createProject();
  216. return;
  217. }
  218. const {FrameworkSuggestionModal, modalCss} = await import(
  219. 'sentry/components/onboarding/frameworkSuggestionModal'
  220. );
  221. openModal(
  222. deps => (
  223. <FrameworkSuggestionModal
  224. {...deps}
  225. organization={organization}
  226. selectedPlatform={selectedPlatform}
  227. onConfigure={selectedFramework => {
  228. createProject(selectedFramework);
  229. }}
  230. onSkip={createProject}
  231. />
  232. ),
  233. {
  234. modalCss,
  235. onClose: () => {
  236. trackAnalytics('project_creation.select_framework_modal_close_button_clicked', {
  237. platform: selectedPlatform.key,
  238. organization,
  239. });
  240. },
  241. }
  242. );
  243. }, [platform, createProject, organization]);
  244. function handlePlatformChange(selectedPlatform: Platform | null) {
  245. if (!selectedPlatform?.id) {
  246. setPlatform(undefined);
  247. setProjectName('');
  248. return;
  249. }
  250. const userModifiedName = !!projectName && projectName !== platform?.key;
  251. const newName = userModifiedName ? projectName : selectedPlatform.id;
  252. setPlatform({
  253. ...omit(selectedPlatform, 'id'),
  254. key: selectedPlatform.id,
  255. });
  256. setProjectName(newName);
  257. }
  258. const {shouldCreateRule, shouldCreateCustomRule, conditions} = alertRuleConfig || {};
  259. const canUserCreateProject = canCreateProject(organization);
  260. const canCreateTeam = organization.access.includes('project:admin');
  261. const isOrgMemberWithNoAccess = accessTeams.length === 0 && !canCreateTeam;
  262. const isMissingTeam = !isOrgMemberWithNoAccess && !team;
  263. const isMissingProjectName = projectName === '';
  264. const isMissingAlertThreshold =
  265. shouldCreateCustomRule && !conditions?.every?.(condition => condition.value);
  266. const isMissingMessagingIntegrationChannel =
  267. organization.features.includes('messaging-integration-onboarding-project-creation') &&
  268. shouldCreateRule &&
  269. notificationProps.actions?.some(
  270. action => action === MultipleCheckboxOptions.INTEGRATION
  271. ) &&
  272. !notificationProps.channel;
  273. const formErrorCount = [
  274. isMissingTeam,
  275. isMissingProjectName,
  276. isMissingAlertThreshold,
  277. isMissingMessagingIntegrationChannel,
  278. ].filter(value => value).length;
  279. const canSubmitForm = !inFlight && canUserCreateProject && formErrorCount === 0;
  280. let submitTooltipText: string = t('Please select a team');
  281. if (formErrorCount > 1) {
  282. submitTooltipText = t('Please fill out all the required fields');
  283. } else if (isMissingProjectName) {
  284. submitTooltipText = t('Please provide a project name');
  285. } else if (isMissingAlertThreshold) {
  286. submitTooltipText = t('Please provide an alert threshold');
  287. } else if (isMissingMessagingIntegrationChannel) {
  288. submitTooltipText = t(
  289. 'Please provide an integration channel for alert notifications'
  290. );
  291. }
  292. const keyToErrorText = {
  293. actions: t('Notify via integration'),
  294. conditions: t('Alert conditions'),
  295. name: t('Alert name'),
  296. detail: t('Project details'),
  297. };
  298. const alertFrequencyDefaultValues = useMemo(() => {
  299. if (!autoFill) {
  300. return {};
  301. }
  302. const alertRules = gettingStartedWithProjectContext.project?.alertRules;
  303. if (alertRules?.length === 0) {
  304. return {
  305. alertSetting: String(RuleAction.CREATE_ALERT_LATER),
  306. };
  307. }
  308. if (
  309. alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition') ||
  310. alertRules?.[0].conditions?.[0].id?.endsWith('EventUniqueUserFrequencyCondition')
  311. ) {
  312. return {
  313. alertSetting: String(RuleAction.CUSTOMIZED_ALERTS),
  314. interval: String(alertRules?.[0].conditions?.[0].interval),
  315. threshold: String(alertRules?.[0].conditions?.[0].value),
  316. metric: alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition')
  317. ? MetricValues.ERRORS
  318. : MetricValues.USERS,
  319. };
  320. }
  321. return {
  322. alertSetting: String(RuleAction.DEFAULT_ALERT),
  323. };
  324. }, [autoFill, gettingStartedWithProjectContext.project?.alertRules]);
  325. return (
  326. <Access access={canUserCreateProject ? ['project:read'] : ['project:admin']}>
  327. <div data-test-id="onboarding-info">
  328. <List symbol="colored-numeric">
  329. <Layout.Title withMargins>{t('Create a new project in 3 steps')}</Layout.Title>
  330. <HelpText>
  331. {tct(
  332. 'Set up a separate project for each part of your application (for example, your API server and frontend client), to quickly pinpoint which part of your application errors are coming from. [link: Read the docs].',
  333. {
  334. link: (
  335. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/" />
  336. ),
  337. }
  338. )}
  339. </HelpText>
  340. <StyledListItem>{t('Choose your platform')}</StyledListItem>
  341. <PlatformPicker
  342. platform={platform?.key}
  343. defaultCategory={platform?.category}
  344. setPlatform={handlePlatformChange}
  345. organization={organization}
  346. showOther
  347. noAutoFilter
  348. />
  349. <StyledListItem>{t('Set your alert frequency')}</StyledListItem>
  350. <IssueAlertOptions
  351. {...alertFrequencyDefaultValues}
  352. platformLanguage={platform?.language as SupportedLanguages}
  353. onChange={updatedData => setAlertRuleConfig(updatedData)}
  354. notificationProps={notificationProps}
  355. />
  356. <StyledListItem>{t('Name your project and assign it a team')}</StyledListItem>
  357. <CreateProjectForm
  358. onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
  359. // Prevent the page from reloading
  360. event.preventDefault();
  361. handleProjectCreation();
  362. }}
  363. >
  364. <div>
  365. <FormLabel>{t('Project name')}</FormLabel>
  366. <ProjectNameInputWrap>
  367. <StyledPlatformIcon platform={platform?.key ?? 'other'} size={20} />
  368. <ProjectNameInput
  369. type="text"
  370. name="name"
  371. placeholder={t('project-name')}
  372. autoComplete="off"
  373. value={projectName}
  374. onChange={e => setProjectName(slugify(e.target.value))}
  375. />
  376. </ProjectNameInputWrap>
  377. </div>
  378. {!isOrgMemberWithNoAccess && (
  379. <div>
  380. <FormLabel>{t('Team')}</FormLabel>
  381. <TeamSelectInput>
  382. <TeamSelector
  383. allowCreate
  384. name="select-team"
  385. aria-label={t('Select a Team')}
  386. menuPlacement="auto"
  387. clearable={false}
  388. value={team}
  389. placeholder={t('Select a Team')}
  390. onChange={choice => setTeam(choice.value)}
  391. teamFilter={(tm: Team) => tm.access.includes('team:admin')}
  392. />
  393. </TeamSelectInput>
  394. </div>
  395. )}
  396. <div>
  397. <Tooltip title={submitTooltipText} disabled={formErrorCount === 0}>
  398. <Button
  399. type="submit"
  400. data-test-id="create-project"
  401. priority="primary"
  402. disabled={!canSubmitForm}
  403. >
  404. {t('Create Project')}
  405. </Button>
  406. </Tooltip>
  407. </div>
  408. </CreateProjectForm>
  409. {errors && (
  410. <Alert type="error">
  411. {Object.keys(errors).map(key => (
  412. <div key={key}>
  413. <strong>{keyToErrorText[key] ?? startCase(key)}</strong>: {errors[key]}
  414. </div>
  415. ))}
  416. </Alert>
  417. )}
  418. </List>
  419. </div>
  420. </Access>
  421. );
  422. }
  423. export {CreateProject};
  424. const StyledListItem = styled(ListItem)`
  425. margin: ${space(2)} 0 ${space(1)} 0;
  426. font-size: ${p => p.theme.fontSizeExtraLarge};
  427. `;
  428. const CreateProjectForm = styled('form')`
  429. display: grid;
  430. grid-template-columns: 300px minmax(250px, max-content) max-content;
  431. gap: ${space(2)};
  432. align-items: end;
  433. padding: ${space(3)} 0;
  434. background: ${p => p.theme.background};
  435. `;
  436. const FormLabel = styled('div')`
  437. font-size: ${p => p.theme.fontSizeExtraLarge};
  438. margin-bottom: ${space(1)};
  439. `;
  440. const ProjectNameInputWrap = styled('div')`
  441. position: relative;
  442. `;
  443. const ProjectNameInput = styled(Input)`
  444. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  445. `;
  446. const StyledPlatformIcon = styled(PlatformIcon)`
  447. position: absolute;
  448. top: 50%;
  449. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  450. transform: translateY(-50%);
  451. `;
  452. const TeamSelectInput = styled('div')`
  453. display: grid;
  454. gap: ${space(1)};
  455. grid-template-columns: 1fr min-content;
  456. align-items: center;
  457. `;
  458. const HelpText = styled('p')`
  459. color: ${p => p.theme.subText};
  460. max-width: 760px;
  461. `;