createProject.tsx 15 KB

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