projectsEditTable.tsx 9.7 KB

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