metricsExtractionRuleCreateModal.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import {Fragment, useCallback, useMemo, useState} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  5. import {
  6. type ModalOptions,
  7. type ModalRenderProps,
  8. openModal,
  9. } from 'sentry/actionCreators/modal';
  10. import SelectControl from 'sentry/components/forms/controls/selectControl';
  11. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  12. import {t} from 'sentry/locale';
  13. import {space} from 'sentry/styles/space';
  14. import type {MetricsExtractionRule} from 'sentry/types/metrics';
  15. import type {Organization} from 'sentry/types/organization';
  16. import type {Project} from 'sentry/types/project';
  17. import {trackAnalytics} from 'sentry/utils/analytics';
  18. import {useCardinalityLimitedMetricVolume} from 'sentry/utils/metrics/useCardinalityLimitedMetricVolume';
  19. import useOrganization from 'sentry/utils/useOrganization';
  20. import usePageFilters from 'sentry/utils/usePageFilters';
  21. import useProjects from 'sentry/utils/useProjects';
  22. import {
  23. createCondition,
  24. explodeAggregateGroup,
  25. type FormData,
  26. MetricsExtractionRuleForm,
  27. } from 'sentry/views/settings/projectMetrics/metricsExtractionRuleForm';
  28. import {useCreateMetricsExtractionRules} from 'sentry/views/settings/projectMetrics/utils/useMetricsExtractionRules';
  29. interface Props {
  30. organization: Organization;
  31. /**
  32. * Source parameter for analytics
  33. */
  34. source: string;
  35. /**
  36. * Initial data to populate the form with
  37. */
  38. initialData?: Partial<FormData>;
  39. /**
  40. * Callback when the form is submitted successfully
  41. */
  42. onSubmitSuccess?: (data: FormData) => void;
  43. /**
  44. * The project to create the metric for
  45. * If not provided, the user will be prompted to select a project
  46. */
  47. projectId?: string | number;
  48. }
  49. export const INITIAL_DATA: FormData = {
  50. spanAttribute: null,
  51. unit: 'none',
  52. aggregates: ['count'],
  53. tags: ['release', 'environment'],
  54. conditions: [createCondition()],
  55. };
  56. export function MetricsExtractionRuleCreateModal({
  57. Header,
  58. Body,
  59. closeModal,
  60. CloseButton,
  61. initialData: initalDataProp = {},
  62. projectId: projectIdProp,
  63. onSubmitSuccess,
  64. }: Props & ModalRenderProps) {
  65. const {projects} = useProjects();
  66. const {selection} = usePageFilters();
  67. const initialData = useMemo(() => {
  68. return {
  69. ...INITIAL_DATA,
  70. ...initalDataProp,
  71. };
  72. }, [initalDataProp]);
  73. const initialProjectId = useMemo(() => {
  74. if (projectIdProp) {
  75. return projectIdProp;
  76. }
  77. if (selection.projects.length === 1 && selection.projects[0] !== -1) {
  78. return projects.find(p => p.id === String(selection.projects[0]))?.id;
  79. }
  80. return undefined;
  81. // eslint-disable-next-line react-hooks/exhaustive-deps
  82. }, []);
  83. const [projectId, setProjectId] = useState<string | number | undefined>(
  84. initialProjectId
  85. );
  86. const projectOptions = useMemo(() => {
  87. const nonMemberProjects: Project[] = [];
  88. const memberProjects: Project[] = [];
  89. projects
  90. .filter(
  91. project =>
  92. selection.projects.length === 0 ||
  93. selection.projects.includes(parseInt(project.id, 10))
  94. )
  95. .forEach(project =>
  96. project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
  97. );
  98. return [
  99. {
  100. label: t('My Projects'),
  101. options: memberProjects.map(p => ({
  102. value: p.id,
  103. label: p.slug,
  104. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  105. })),
  106. },
  107. {
  108. label: t('All Projects'),
  109. options: nonMemberProjects.map(p => ({
  110. value: p.id,
  111. label: p.slug,
  112. leadingItems: <ProjectBadge project={p} avatarSize={16} hideName disableLink />,
  113. })),
  114. },
  115. ];
  116. }, [selection.projects, projects]);
  117. return (
  118. <Fragment>
  119. <Header>
  120. <h4>{t('Create Metric')}</h4>
  121. </Header>
  122. <CloseButton />
  123. <Body>
  124. <p>
  125. {t(
  126. "Set up the metric you'd like to track and we'll collect it for you from future data."
  127. )}
  128. </p>
  129. {initialProjectId === undefined ? (
  130. <ProjectSelectionWrapper>
  131. <label htmlFor="project-select">{t('Project')}</label>
  132. <SelectControl
  133. id="project-select"
  134. placeholder={t('Select a project')}
  135. options={projectOptions}
  136. value={projectId}
  137. onChange={({value}) => setProjectId(value)}
  138. stacked={false}
  139. />
  140. </ProjectSelectionWrapper>
  141. ) : null}
  142. {projectId ? (
  143. <FormWrapper
  144. initialData={initialData}
  145. projectId={projectId}
  146. closeModal={closeModal}
  147. onSubmitSuccess={onSubmitSuccess}
  148. />
  149. ) : null}
  150. </Body>
  151. </Fragment>
  152. );
  153. }
  154. function FormWrapper({
  155. closeModal,
  156. projectId,
  157. initialData,
  158. onSubmitSuccess: onSubmitSuccessProp,
  159. }: {
  160. closeModal: () => void;
  161. initialData: FormData;
  162. projectId: string | number;
  163. onSubmitSuccess?: (data: FormData) => void;
  164. }) {
  165. const organization = useOrganization();
  166. const createExtractionRuleMutation = useCreateMetricsExtractionRules(
  167. organization.slug,
  168. projectId
  169. );
  170. const {data: cardinality} = useCardinalityLimitedMetricVolume({
  171. projects: [projectId],
  172. });
  173. const handleSubmit = useCallback(
  174. (
  175. data: FormData,
  176. onSubmitSuccess: (data: FormData) => void,
  177. onSubmitError: (error: any) => void
  178. ) => {
  179. const extractionRule: MetricsExtractionRule = {
  180. spanAttribute: data.spanAttribute!,
  181. tags: data.tags,
  182. aggregates: data.aggregates.flatMap(explodeAggregateGroup),
  183. unit: data.unit,
  184. conditions: data.conditions,
  185. projectId: Number(projectId),
  186. // Will be set by the backend
  187. createdById: null,
  188. dateAdded: '',
  189. dateUpdated: '',
  190. };
  191. createExtractionRuleMutation.mutate(
  192. {
  193. metricsExtractionRules: [extractionRule],
  194. },
  195. {
  196. onSuccess: () => {
  197. onSubmitSuccessProp?.(data);
  198. onSubmitSuccess(data);
  199. addSuccessMessage(t('Metric extraction rule created'));
  200. closeModal();
  201. },
  202. onError: error => {
  203. const message = error?.responseJSON?.detail
  204. ? (error.responseJSON.detail as string)
  205. : t('Unable to save your changes.');
  206. onSubmitError(message);
  207. addErrorMessage(message);
  208. },
  209. }
  210. );
  211. onSubmitSuccess(data);
  212. },
  213. [projectId, createExtractionRuleMutation, onSubmitSuccessProp, closeModal]
  214. );
  215. return (
  216. <MetricsExtractionRuleForm
  217. initialData={initialData}
  218. projectId={projectId}
  219. submitLabel={t('Add Metric')}
  220. cancelLabel={t('Cancel')}
  221. onCancel={closeModal}
  222. onSubmit={handleSubmit}
  223. cardinality={cardinality}
  224. submitDisabled={createExtractionRuleMutation.isLoading}
  225. />
  226. );
  227. }
  228. const ProjectSelectionWrapper = styled('div')`
  229. padding-bottom: ${space(2)};
  230. & > label {
  231. color: ${p => p.theme.gray300};
  232. }
  233. `;
  234. export const modalCss = css`
  235. width: 100%;
  236. max-width: 900px;
  237. `;
  238. export function openExtractionRuleCreateModal(props: Props, options?: ModalOptions) {
  239. const {organization, source, onSubmitSuccess} = props;
  240. trackAnalytics('ddm.span-metric.create.open', {
  241. organization,
  242. source,
  243. });
  244. const handleClose: ModalOptions['onClose'] = reason => {
  245. if (reason && ['close-button', 'backdrop-click', 'escape-key'].includes(reason)) {
  246. trackAnalytics('ddm.span-metric.create.cancel', {organization});
  247. }
  248. options?.onClose?.(reason);
  249. };
  250. const handleSubmitSuccess: Props['onSubmitSuccess'] = data => {
  251. trackAnalytics('ddm.span-metric.create.success', {
  252. organization,
  253. hasFilters: data.conditions.some(condition => condition.value),
  254. });
  255. onSubmitSuccess?.(data);
  256. };
  257. openModal(
  258. modalProps => (
  259. <MetricsExtractionRuleCreateModal
  260. {...props}
  261. onSubmitSuccess={handleSubmitSuccess}
  262. {...modalProps}
  263. />
  264. ),
  265. {
  266. modalCss,
  267. ...options,
  268. onClose: handleClose,
  269. }
  270. );
  271. }