createProject.tsx 14 KB

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