createProject.tsx 11 KB

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