createProject.tsx 15 KB

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