createProject.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 ProjectActions from 'sentry/actions/projectActions';
  9. import Alert from 'sentry/components/alert';
  10. import Button from 'sentry/components/button';
  11. import TeamSelector from 'sentry/components/forms/teamSelector';
  12. import PageHeading from 'sentry/components/pageHeading';
  13. import PlatformPicker from 'sentry/components/platformPicker';
  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, Team} from 'sentry/types';
  20. import {logExperiment} from 'sentry/utils/analytics';
  21. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  22. import getPlatformName from 'sentry/utils/getPlatformName';
  23. import slugify from 'sentry/utils/slugify';
  24. import withApi from 'sentry/utils/withApi';
  25. import withOrganization from 'sentry/utils/withOrganization';
  26. import withTeams from 'sentry/utils/withTeams';
  27. import IssueAlertOptions from 'sentry/views/projectInstall/issueAlertOptions';
  28. import {PRESET_AGGREGATES} from '../alerts/rules/metric/presets';
  29. const getCategoryName = (category?: string) =>
  30. categoryList.find(({id}) => id === category)?.id;
  31. type Props = WithRouterProps & {
  32. api: any;
  33. organization: Organization;
  34. teams: Team[];
  35. };
  36. type PlatformName = React.ComponentProps<typeof PlatformIcon>['platform'];
  37. type IssueAlertFragment = Parameters<
  38. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  39. >[0];
  40. type State = {
  41. dataFragment: IssueAlertFragment | undefined;
  42. error: boolean;
  43. inFlight: boolean;
  44. platform: PlatformName | null;
  45. projectName: string;
  46. team: string;
  47. };
  48. class CreateProject extends Component<Props, State> {
  49. constructor(props: Props, context) {
  50. super(props, context);
  51. const {teams, location} = props;
  52. const {query} = location;
  53. const accessTeams = teams.filter((team: Team) => team.hasAccess);
  54. const team = query.team || (accessTeams.length && accessTeams[0].slug);
  55. const platform = getPlatformName(query.platform) ? query.platform : '';
  56. this.state = {
  57. error: false,
  58. projectName: getPlatformName(platform) || '',
  59. team,
  60. platform,
  61. inFlight: false,
  62. dataFragment: undefined,
  63. };
  64. }
  65. componentDidMount() {
  66. trackAdvancedAnalyticsEvent('project_creation_page.viewed', {
  67. organization: this.props.organization,
  68. });
  69. logExperiment({
  70. key: 'MetricAlertOnProjectCreationExperiment',
  71. organization: this.props.organization,
  72. });
  73. }
  74. get defaultCategory() {
  75. const {query} = this.props.location;
  76. return getCategoryName(query.category);
  77. }
  78. renderProjectForm() {
  79. const {organization} = this.props;
  80. const {projectName, platform, team} = this.state;
  81. const createProjectForm = (
  82. <CreateProjectForm onSubmit={this.createProject}>
  83. <div>
  84. <FormLabel>{t('Project name')}</FormLabel>
  85. <ProjectNameInput>
  86. <StyledPlatformIcon platform={platform ?? ''} />
  87. <input
  88. type="text"
  89. name="name"
  90. placeholder={t('project-name')}
  91. autoComplete="off"
  92. value={projectName}
  93. onChange={e => this.setState({projectName: slugify(e.target.value)})}
  94. />
  95. </ProjectNameInput>
  96. </div>
  97. <div>
  98. <FormLabel>{t('Team')}</FormLabel>
  99. <TeamSelectInput>
  100. <TeamSelector
  101. name="select-team"
  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. metricAlertPresets,
  166. } = dataFragment || {};
  167. this.setState({inFlight: true});
  168. if (!projectName) {
  169. Sentry.withScope(scope => {
  170. scope.setExtra('props', this.props);
  171. scope.setExtra('state', this.state);
  172. Sentry.captureMessage('No project name');
  173. });
  174. }
  175. try {
  176. const projectData = await api.requestPromise(`/teams/${slug}/${team}/projects/`, {
  177. method: 'POST',
  178. data: {
  179. name: projectName,
  180. platform,
  181. default_rules: defaultRules ?? true,
  182. },
  183. });
  184. let ruleId: string | undefined;
  185. if (shouldCreateCustomRule) {
  186. const ruleData = await api.requestPromise(
  187. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  188. {
  189. method: 'POST',
  190. data: {
  191. name,
  192. conditions,
  193. actions,
  194. actionMatch,
  195. frequency,
  196. },
  197. }
  198. );
  199. ruleId = ruleData.id;
  200. }
  201. if (
  202. !!organization.experiments.MetricAlertOnProjectCreationExperiment &&
  203. metricAlertPresets &&
  204. metricAlertPresets.length > 0
  205. ) {
  206. const presets = PRESET_AGGREGATES.filter(aggregate =>
  207. metricAlertPresets.includes(aggregate.id)
  208. );
  209. const teamObj = this.props.teams.find(aTeam => aTeam.slug === team);
  210. await Promise.all([
  211. presets.map(preset => {
  212. const context = preset.makeUnqueriedContext(
  213. {
  214. ...projectData,
  215. teams: teamObj ? [teamObj] : [],
  216. },
  217. organization
  218. );
  219. return api.requestPromise(
  220. `/projects/${organization.slug}/${projectData.slug}/alert-rules/?referrer=create_project`,
  221. {
  222. method: 'POST',
  223. data: {
  224. aggregate: context.aggregate,
  225. comparisonDelta: context.comparisonDelta,
  226. dataset: context.dataset,
  227. eventTypes: context.eventTypes,
  228. name: context.name,
  229. owner: null,
  230. projectId: projectData.id,
  231. projects: [projectData.slug],
  232. query: '',
  233. resolveThreshold: null,
  234. thresholdPeriod: 1,
  235. thresholdType: context.thresholdType,
  236. timeWindow: context.timeWindow,
  237. triggers: context.triggers,
  238. },
  239. }
  240. );
  241. }),
  242. ]);
  243. }
  244. trackAdvancedAnalyticsEvent('project_creation_page.created', {
  245. organization,
  246. metric_alerts: (metricAlertPresets || []).join(','),
  247. issue_alert: defaultRules
  248. ? 'Default'
  249. : shouldCreateCustomRule
  250. ? 'Custom'
  251. : 'No Rule',
  252. project_id: projectData.id,
  253. rule_id: ruleId || '',
  254. });
  255. ProjectActions.createSuccess(projectData);
  256. const platformKey = platform || 'other';
  257. const nextUrl = `/${organization.slug}/${projectData.slug}/getting-started/${platformKey}/`;
  258. browserHistory.push(nextUrl);
  259. } catch (err) {
  260. this.setState({
  261. inFlight: false,
  262. error: err.responseJSON.detail,
  263. });
  264. // Only log this if the error is something other than:
  265. // * The user not having access to create a project, or,
  266. // * A project with that slug already exists
  267. if (err.status !== 403 && err.status !== 409) {
  268. Sentry.withScope(scope => {
  269. scope.setExtra('err', err);
  270. scope.setExtra('props', this.props);
  271. scope.setExtra('state', this.state);
  272. Sentry.captureMessage('Project creation failed');
  273. });
  274. }
  275. }
  276. };
  277. setPlatform = (platformId: PlatformName | null) =>
  278. this.setState(({projectName, platform}: State) => ({
  279. platform: platformId,
  280. projectName:
  281. !projectName || (platform && getPlatformName(platform) === projectName)
  282. ? getPlatformName(platformId) || ''
  283. : projectName,
  284. }));
  285. render() {
  286. const {platform, error} = this.state;
  287. return (
  288. <Fragment>
  289. {error && <Alert type="error">{error}</Alert>}
  290. <div data-test-id="onboarding-info">
  291. <PageHeading withMargins>{t('Create a new Project')}</PageHeading>
  292. <HelpText>
  293. {t(
  294. `Projects allow you to scope error and transaction events to a specific
  295. application in your organization. For example, you might have separate
  296. projects for your API server and frontend client.`
  297. )}
  298. </HelpText>
  299. <PageHeading withMargins>{t('Choose a platform')}</PageHeading>
  300. <PlatformPicker
  301. platform={platform}
  302. defaultCategory={this.defaultCategory}
  303. setPlatform={this.setPlatform}
  304. organization={this.props.organization}
  305. showOther
  306. />
  307. <IssueAlertOptions
  308. onChange={updatedData => {
  309. this.setState({dataFragment: updatedData});
  310. }}
  311. />
  312. {this.renderProjectForm()}
  313. </div>
  314. </Fragment>
  315. );
  316. }
  317. }
  318. // TODO(davidenwang): change to functional component and replace withTeams with useTeams
  319. export default withApi(withRouter(withOrganization(withTeams(CreateProject))));
  320. export {CreateProject};
  321. const CreateProjectForm = styled('form')`
  322. display: grid;
  323. grid-template-columns: 300px minmax(250px, max-content) max-content;
  324. gap: ${space(2)};
  325. align-items: end;
  326. padding: ${space(3)} 0;
  327. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  328. background: ${p => p.theme.background};
  329. `;
  330. const FormLabel = styled('div')`
  331. font-size: ${p => p.theme.fontSizeExtraLarge};
  332. margin-bottom: ${space(1)};
  333. `;
  334. const StyledPlatformIcon = styled(PlatformIcon)`
  335. margin-right: ${space(1)};
  336. `;
  337. const ProjectNameInput = styled('div')`
  338. ${p => inputStyles(p)};
  339. padding: 5px 10px;
  340. display: flex;
  341. align-items: center;
  342. input {
  343. background: ${p => p.theme.background};
  344. border: 0;
  345. outline: 0;
  346. flex: 1;
  347. }
  348. `;
  349. const TeamSelectInput = styled('div')`
  350. display: grid;
  351. gap: ${space(1)};
  352. grid-template-columns: 1fr min-content;
  353. align-items: center;
  354. `;
  355. const HelpText = styled('p')`
  356. color: ${p => p.theme.subText};
  357. max-width: 760px;
  358. `;