createProject.tsx 15 KB

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