projectsEditTable.tsx 9.0 KB

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