createProject.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import {Component, Fragment} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {browserHistory, withRouter, WithRouterProps} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import * as Sentry from '@sentry/react';
  6. import {PlatformIcon} from 'platformicons';
  7. import {openCreateTeamModal} from 'sentry/actionCreators/modal';
  8. import Alert from 'sentry/components/alert';
  9. import Button from 'sentry/components/button';
  10. import Input from 'sentry/components/input';
  11. import PageHeading from 'sentry/components/pageHeading';
  12. import PlatformPicker from 'sentry/components/platformPicker';
  13. import TeamSelector from 'sentry/components/teamSelector';
  14. import categoryList from 'sentry/data/platformCategories';
  15. import {IconAdd} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import ProjectsStore from 'sentry/stores/projectsStore';
  18. import space from 'sentry/styles/space';
  19. import {Organization, Team} from 'sentry/types';
  20. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  21. import getPlatformName from 'sentry/utils/getPlatformName';
  22. import withRouteAnalytics, {
  23. WithRouteAnalyticsProps,
  24. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  25. import slugify from 'sentry/utils/slugify';
  26. import withApi from 'sentry/utils/withApi';
  27. import withOrganization from 'sentry/utils/withOrganization';
  28. import withTeams from 'sentry/utils/withTeams';
  29. import IssueAlertOptions from 'sentry/views/projectInstall/issueAlertOptions';
  30. const getCategoryName = (category?: string) =>
  31. categoryList.find(({id}) => id === category)?.id;
  32. type Props = WithRouterProps &
  33. WithRouteAnalyticsProps & {
  34. api: any;
  35. organization: Organization;
  36. teams: Team[];
  37. };
  38. type PlatformName = React.ComponentProps<typeof PlatformIcon>['platform'];
  39. type IssueAlertFragment = Parameters<
  40. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  41. >[0];
  42. type State = {
  43. dataFragment: IssueAlertFragment | undefined;
  44. error: boolean;
  45. inFlight: boolean;
  46. platform: PlatformName | null;
  47. projectName: string;
  48. team: string;
  49. };
  50. class CreateProject extends Component<Props, State> {
  51. constructor(props: Props, context) {
  52. super(props, context);
  53. const {teams, location} = props;
  54. const {query} = location;
  55. const accessTeams = teams.filter((team: Team) => team.hasAccess);
  56. const team = query.team || (accessTeams.length && accessTeams[0].slug);
  57. const platform = getPlatformName(query.platform) ? query.platform : '';
  58. this.state = {
  59. error: false,
  60. projectName: getPlatformName(platform) || '',
  61. team,
  62. platform,
  63. inFlight: false,
  64. dataFragment: undefined,
  65. };
  66. }
  67. componentDidMount() {
  68. this.props.setEventNames(
  69. 'project_creation_page.viewed',
  70. 'Project Create: Creation page viewed'
  71. );
  72. }
  73. get defaultCategory() {
  74. const {query} = this.props.location;
  75. return getCategoryName(query.category);
  76. }
  77. renderProjectForm() {
  78. const {organization} = this.props;
  79. const {projectName, platform, team} = this.state;
  80. const createProjectForm = (
  81. <CreateProjectForm onSubmit={this.createProject}>
  82. <div>
  83. <FormLabel>{t('Project name')}</FormLabel>
  84. <ProjectNameInputWrap>
  85. <StyledPlatformIcon platform={platform ?? ''} size={20} />
  86. <ProjectNameInput
  87. type="text"
  88. name="name"
  89. placeholder={t('project-name')}
  90. autoComplete="off"
  91. value={projectName}
  92. onChange={e => this.setState({projectName: slugify(e.target.value)})}
  93. />
  94. </ProjectNameInputWrap>
  95. </div>
  96. <div>
  97. <FormLabel>{t('Team')}</FormLabel>
  98. <TeamSelectInput>
  99. <TeamSelector
  100. name="select-team"
  101. menuPlacement="auto"
  102. clearable={false}
  103. value={team}
  104. placeholder={t('Select a Team')}
  105. onChange={choice => this.setState({team: choice.value})}
  106. teamFilter={(filterTeam: Team) => filterTeam.hasAccess}
  107. />
  108. <Button
  109. borderless
  110. data-test-id="create-team"
  111. type="button"
  112. icon={<IconAdd isCircled />}
  113. onClick={() =>
  114. openCreateTeamModal({
  115. organization,
  116. onClose: ({slug}) => this.setState({team: slug}),
  117. })
  118. }
  119. title={t('Create a team')}
  120. aria-label={t('Create a team')}
  121. />
  122. </TeamSelectInput>
  123. </div>
  124. <div>
  125. <Button
  126. data-test-id="create-project"
  127. priority="primary"
  128. disabled={!this.canSubmitForm}
  129. >
  130. {t('Create Project')}
  131. </Button>
  132. </div>
  133. </CreateProjectForm>
  134. );
  135. return (
  136. <Fragment>
  137. <PageHeading withMargins>{t('Give your project a name')}</PageHeading>
  138. {createProjectForm}
  139. </Fragment>
  140. );
  141. }
  142. get canSubmitForm() {
  143. const {projectName, team, inFlight} = this.state;
  144. const {shouldCreateCustomRule, conditions} = this.state.dataFragment || {};
  145. return (
  146. !inFlight &&
  147. team &&
  148. projectName !== '' &&
  149. (!shouldCreateCustomRule || conditions?.every?.(condition => condition.value))
  150. );
  151. }
  152. createProject = async e => {
  153. e.preventDefault();
  154. const {organization, api} = this.props;
  155. const {projectName, platform, team, dataFragment} = this.state;
  156. const {slug} = organization;
  157. const {
  158. shouldCreateCustomRule,
  159. name,
  160. conditions,
  161. actions,
  162. actionMatch,
  163. frequency,
  164. defaultRules,
  165. } = dataFragment || {};
  166. this.setState({inFlight: true});
  167. if (!projectName) {
  168. Sentry.withScope(scope => {
  169. scope.setExtra('props', this.props);
  170. scope.setExtra('state', this.state);
  171. Sentry.captureMessage('No project name');
  172. });
  173. }
  174. try {
  175. const projectData = await api.requestPromise(`/teams/${slug}/${team}/projects/`, {
  176. method: 'POST',
  177. data: {
  178. name: projectName,
  179. platform,
  180. default_rules: defaultRules ?? true,
  181. },
  182. });
  183. let ruleId: string | undefined;
  184. if (shouldCreateCustomRule) {
  185. const ruleData = await api.requestPromise(
  186. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  187. {
  188. method: 'POST',
  189. data: {
  190. name,
  191. conditions,
  192. actions,
  193. actionMatch,
  194. frequency,
  195. },
  196. }
  197. );
  198. ruleId = ruleData.id;
  199. }
  200. trackAdvancedAnalyticsEvent('project_creation_page.created', {
  201. organization,
  202. issue_alert: defaultRules
  203. ? 'Default'
  204. : shouldCreateCustomRule
  205. ? 'Custom'
  206. : 'No Rule',
  207. project_id: projectData.id,
  208. rule_id: ruleId || '',
  209. });
  210. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  211. const platformKey = platform || 'other';
  212. const nextUrl = `/${organization.slug}/${projectData.slug}/getting-started/${platformKey}/`;
  213. browserHistory.push(nextUrl);
  214. } catch (err) {
  215. this.setState({
  216. inFlight: false,
  217. error: err.responseJSON.detail,
  218. });
  219. // Only log this if the error is something other than:
  220. // * The user not having access to create a project, or,
  221. // * A project with that slug already exists
  222. if (err.status !== 403 && err.status !== 409) {
  223. Sentry.withScope(scope => {
  224. scope.setExtra('err', err);
  225. scope.setExtra('props', this.props);
  226. scope.setExtra('state', this.state);
  227. Sentry.captureMessage('Project creation failed');
  228. });
  229. }
  230. }
  231. };
  232. setPlatform = (platformKey: PlatformName | null) => {
  233. if (!platformKey) {
  234. this.setState({platform: null, projectName: ''});
  235. return;
  236. }
  237. this.setState(({projectName, platform}) => {
  238. // Avoid replacing project name when the user already modified it
  239. const userModifiedName = projectName && projectName !== platform;
  240. const newName = userModifiedName ? projectName : platformKey;
  241. return {
  242. platform: platformKey,
  243. projectName: slugify(newName),
  244. };
  245. });
  246. };
  247. render() {
  248. const {platform, error} = this.state;
  249. return (
  250. <Fragment>
  251. {error && <Alert type="error">{error}</Alert>}
  252. <div data-test-id="onboarding-info">
  253. <PageHeading withMargins>{t('Create a new Project')}</PageHeading>
  254. <HelpText>
  255. {t(
  256. `Projects allow you to scope error and transaction events to a specific
  257. application in your organization. For example, you might have separate
  258. projects for your API server and frontend client.`
  259. )}
  260. </HelpText>
  261. <PageHeading withMargins>{t('Choose a platform')}</PageHeading>
  262. <PlatformPicker
  263. platform={platform}
  264. defaultCategory={this.defaultCategory}
  265. setPlatform={this.setPlatform}
  266. organization={this.props.organization}
  267. showOther
  268. />
  269. <IssueAlertOptions
  270. onChange={updatedData => {
  271. this.setState({dataFragment: updatedData});
  272. }}
  273. />
  274. {this.renderProjectForm()}
  275. </div>
  276. </Fragment>
  277. );
  278. }
  279. }
  280. // TODO(davidenwang): change to functional component and replace withTeams with useTeams
  281. export default withRouteAnalytics(
  282. withApi(withRouter(withOrganization(withTeams(CreateProject))))
  283. );
  284. export {CreateProject};
  285. const CreateProjectForm = styled('form')`
  286. display: grid;
  287. grid-template-columns: 300px minmax(250px, max-content) max-content;
  288. gap: ${space(2)};
  289. align-items: end;
  290. padding: ${space(3)} 0;
  291. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  292. background: ${p => p.theme.background};
  293. `;
  294. const FormLabel = styled('div')`
  295. font-size: ${p => p.theme.fontSizeExtraLarge};
  296. margin-bottom: ${space(1)};
  297. `;
  298. const ProjectNameInputWrap = styled('div')`
  299. position: relative;
  300. `;
  301. const ProjectNameInput = styled(Input)`
  302. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  303. `;
  304. const StyledPlatformIcon = styled(PlatformIcon)`
  305. position: absolute;
  306. top: 50%;
  307. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  308. transform: translateY(-50%);
  309. `;
  310. const TeamSelectInput = styled('div')`
  311. display: grid;
  312. gap: ${space(1)};
  313. grid-template-columns: 1fr min-content;
  314. align-items: center;
  315. `;
  316. const HelpText = styled('p')`
  317. color: ${p => p.theme.subText};
  318. max-width: 760px;
  319. `;