projectsEditTable.tsx 9.0 KB

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