projectsEditTable.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import {Fragment, useCallback, useEffect, useMemo, useRef, useState} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import partition from 'lodash/partition';
  5. import {Button} from 'sentry/components/button';
  6. import FieldGroup from 'sentry/components/forms/fieldGroup';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import Panel from 'sentry/components/panels/panel';
  9. import {Tooltip} from 'sentry/components/tooltip';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import useProjects from 'sentry/utils/useProjects';
  13. import {PercentInput} from 'sentry/views/settings/dynamicSampling/percentInput';
  14. import {ProjectsTable} from 'sentry/views/settings/dynamicSampling/projectsTable';
  15. import {SamplingBreakdown} from 'sentry/views/settings/dynamicSampling/samplingBreakdown';
  16. import {useHasDynamicSamplingWriteAccess} from 'sentry/views/settings/dynamicSampling/utils/access';
  17. import {formatPercent} from 'sentry/views/settings/dynamicSampling/utils/formatPercent';
  18. import {parsePercent} from 'sentry/views/settings/dynamicSampling/utils/parsePercent';
  19. import {projectSamplingForm} from 'sentry/views/settings/dynamicSampling/utils/projectSamplingForm';
  20. import {scaleSampleRates} from 'sentry/views/settings/dynamicSampling/utils/scaleSampleRates';
  21. import type {ProjectSampleCount} from 'sentry/views/settings/dynamicSampling/utils/useProjectSampleCounts';
  22. interface Props {
  23. editMode: 'single' | 'bulk';
  24. isLoading: boolean;
  25. onEditModeChange: (mode: 'single' | 'bulk') => void;
  26. sampleCounts: ProjectSampleCount[];
  27. }
  28. const {useFormField} = projectSamplingForm;
  29. const EMPTY_ARRAY = [];
  30. export function ProjectsEditTable({
  31. isLoading: isLoadingProp,
  32. sampleCounts,
  33. editMode,
  34. onEditModeChange,
  35. }: Props) {
  36. const {projects, fetching} = useProjects();
  37. const hasAccess = useHasDynamicSamplingWriteAccess();
  38. const {value, initialValue, error, onChange} = useFormField('projectRates');
  39. const [isBulkEditEnabled, setIsBulkEditEnabled] = useState(false);
  40. const inputRef = useRef<HTMLInputElement>(null);
  41. const [orgRate, setOrgRate] = useState<string>('');
  42. const projectRateSnapshotRef = useRef<Record<string, string>>({});
  43. const dataByProjectId = useMemo(
  44. () =>
  45. sampleCounts.reduce(
  46. (acc, item) => {
  47. acc[item.project.id] = item;
  48. return acc;
  49. },
  50. {} as Record<string, (typeof sampleCounts)[0]>
  51. ),
  52. [sampleCounts]
  53. );
  54. useEffect(() => {
  55. if (isBulkEditEnabled) {
  56. inputRef.current?.focus();
  57. }
  58. }, [isBulkEditEnabled]);
  59. const handleProjectChange = useCallback(
  60. (projectId: string, newRate: string) => {
  61. onChange(prev => ({
  62. ...prev,
  63. [projectId]: newRate,
  64. }));
  65. onEditModeChange('single');
  66. },
  67. [onChange, onEditModeChange]
  68. );
  69. const handleOrgChange = useCallback(
  70. (event: React.ChangeEvent<HTMLInputElement>) => {
  71. const newRate = event.target.value;
  72. if (editMode === 'single') {
  73. projectRateSnapshotRef.current = value;
  74. }
  75. const cappedOrgRate = parsePercent(newRate, 1);
  76. const scalingItems = Object.entries(projectRateSnapshotRef.current)
  77. .map(([projectId, rate]) => ({
  78. id: projectId,
  79. sampleRate: rate ? parsePercent(rate) : 0,
  80. count: dataByProjectId[projectId]?.count ?? 0,
  81. }))
  82. // We do not wan't to bulk edit inactive projects as they have no effect on the outcome
  83. .filter(item => item.count !== 0);
  84. const {scaledItems} = scaleSampleRates({
  85. items: scalingItems,
  86. sampleRate: cappedOrgRate,
  87. });
  88. const newProjectValues = scaledItems.reduce((acc, item) => {
  89. acc[item.id] = formatPercent(item.sampleRate);
  90. return acc;
  91. }, {});
  92. onChange(prev => {
  93. return {...prev, ...newProjectValues};
  94. });
  95. setOrgRate(newRate);
  96. onEditModeChange('bulk');
  97. },
  98. [dataByProjectId, editMode, onChange, onEditModeChange, value]
  99. );
  100. const handleOrgBlur = useCallback(() => {
  101. setIsBulkEditEnabled(false);
  102. // Parse to ensure valid values
  103. setOrgRate(rate => (parsePercent(rate, 1) * 100).toString());
  104. }, []);
  105. const items = useMemo(
  106. () =>
  107. projects.map(project => {
  108. const item = dataByProjectId[project.id] as
  109. | (typeof dataByProjectId)[string]
  110. | undefined;
  111. return {
  112. id: project.slug,
  113. name: project.slug,
  114. count: item?.count || 0,
  115. ownCount: item?.ownCount || 0,
  116. subProjects: item?.subProjects ?? EMPTY_ARRAY,
  117. project: project,
  118. initialSampleRate: initialValue[project.id],
  119. sampleRate: value[project.id],
  120. error: error?.[project.id],
  121. };
  122. }),
  123. [dataByProjectId, error, initialValue, projects, value]
  124. );
  125. const totalSpanCount = useMemo(
  126. () => items.reduce((acc, item) => acc + item.count, 0),
  127. [items]
  128. );
  129. const projectedOrgRate = useMemo(() => {
  130. if (editMode === 'bulk') {
  131. return orgRate;
  132. }
  133. const totalSampledSpans = items.reduce(
  134. (acc, item) => acc + item.count * parsePercent(value[item.project.id], 1),
  135. 0
  136. );
  137. return formatPercent(totalSampledSpans / totalSpanCount);
  138. }, [editMode, items, orgRate, totalSpanCount, value]);
  139. const initialOrgRate = useMemo(() => {
  140. const totalSampledSpans = items.reduce(
  141. (acc, item) => acc + item.count * parsePercent(initialValue[item.project.id], 1),
  142. 0
  143. );
  144. return formatPercent(totalSampledSpans / totalSpanCount);
  145. }, [initialValue, items, totalSpanCount]);
  146. const breakdownSampleRates = useMemo(
  147. () =>
  148. Object.entries(value).reduce(
  149. (acc, [projectId, rate]) => {
  150. acc[projectId] = parsePercent(rate);
  151. return acc;
  152. },
  153. {} as Record<string, number>
  154. ),
  155. [value]
  156. );
  157. const [activeItems, inactiveItems] = useMemo(
  158. () => partition(items, item => item.count > 0 || item.initialSampleRate !== '100'),
  159. [items]
  160. );
  161. const isLoading = fetching || isLoadingProp;
  162. return (
  163. <Fragment>
  164. <BreakdownPanel>
  165. {isLoading ? (
  166. <LoadingIndicator
  167. css={css`
  168. margin: 60px 0;
  169. `}
  170. />
  171. ) : (
  172. <Fragment>
  173. <BreakdownWrapper>
  174. <SamplingBreakdown
  175. sampleCounts={sampleCounts}
  176. sampleRates={breakdownSampleRates}
  177. />
  178. </BreakdownWrapper>
  179. <FieldGroup
  180. label={t('Estimated Organization Rate')}
  181. help={t('An estimate of the combined sample rate for all projects.')}
  182. flexibleControlStateSize
  183. alignRight
  184. >
  185. <InputWrapper>
  186. <Tooltip
  187. disabled={hasAccess}
  188. title={t('You do not have permission to change the sample rate')}
  189. >
  190. <PercentInput
  191. type="number"
  192. ref={inputRef}
  193. disabled={!hasAccess || !isBulkEditEnabled}
  194. size="sm"
  195. onChange={handleOrgChange}
  196. value={projectedOrgRate}
  197. onKeyDown={event => {
  198. if (event.key === 'Enter') {
  199. event.preventDefault();
  200. inputRef.current?.blur();
  201. }
  202. }}
  203. onBlur={handleOrgBlur}
  204. />
  205. </Tooltip>
  206. <FlexRow>
  207. <PreviousValue>
  208. {initialOrgRate !== projectedOrgRate
  209. ? t('previous: %f%%', initialOrgRate)
  210. : // Placeholder char to prevent the line from collapsing
  211. '\u200b'}
  212. </PreviousValue>
  213. {hasAccess && !isBulkEditEnabled && (
  214. <BulkEditButton
  215. size="zero"
  216. tooltipProps={{
  217. position: 'bottom',
  218. }}
  219. title={t('Proportionally scale project rates')}
  220. priority="link"
  221. onClick={() => {
  222. setIsBulkEditEnabled(true);
  223. }}
  224. >
  225. {t('edit')}
  226. </BulkEditButton>
  227. )}
  228. </FlexRow>
  229. </InputWrapper>
  230. </FieldGroup>
  231. </Fragment>
  232. )}
  233. </BreakdownPanel>
  234. <ProjectsTable
  235. rateHeader={t('Target Rate')}
  236. canEdit={!isBulkEditEnabled}
  237. onChange={handleProjectChange}
  238. emptyMessage={t('No active projects found in the selected period.')}
  239. isLoading={isLoading}
  240. items={activeItems}
  241. inactiveItems={inactiveItems}
  242. />
  243. </Fragment>
  244. );
  245. }
  246. const BreakdownPanel = styled(Panel)`
  247. margin-bottom: ${space(3)};
  248. `;
  249. const BreakdownWrapper = styled('div')`
  250. padding: ${space(2)};
  251. border-bottom: 1px solid ${p => p.theme.innerBorder};
  252. `;
  253. const InputWrapper = styled('div')`
  254. display: flex;
  255. flex-direction: column;
  256. gap: ${space(0.5)};
  257. `;
  258. const FlexRow = styled('div')`
  259. display: flex;
  260. align-items: center;
  261. justify-content: space-between;
  262. gap: ${space(1)};
  263. `;
  264. const PreviousValue = styled('span')`
  265. font-size: ${p => p.theme.fontSizeExtraSmall};
  266. color: ${p => p.theme.subText};
  267. `;
  268. const BulkEditButton = styled(Button)`
  269. font-size: ${p => p.theme.fontSizeExtraSmall};
  270. padding: 0;
  271. border: none;
  272. `;