createProject.tsx 16 KB

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