createProject.tsx 11 KB

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