createProject.tsx 16 KB

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