teamReleases.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import {Fragment} from 'react';
  2. import type {Theme} from '@emotion/react';
  3. import {css, withTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import round from 'lodash/round';
  6. import moment from 'moment';
  7. import {Button} from 'sentry/components/button';
  8. import {BarChart} from 'sentry/components/charts/barChart';
  9. import MarkLine from 'sentry/components/charts/components/markLine';
  10. import type {DateTimeObject} from 'sentry/components/charts/utils';
  11. import Link from 'sentry/components/links/link';
  12. import LoadingError from 'sentry/components/loadingError';
  13. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  14. import {PanelTable} from 'sentry/components/panels/panelTable';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import {IconArrow} from 'sentry/icons';
  17. import {t, tct} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import type {Organization} from 'sentry/types/organization';
  20. import type {Project} from 'sentry/types/project';
  21. import toArray from 'sentry/utils/array/toArray';
  22. import {useApiQuery} from 'sentry/utils/queryClient';
  23. import type {ColorOrAlias} from 'sentry/utils/theme';
  24. import {ProjectBadge, ProjectBadgeContainer} from './styles';
  25. import {barAxisLabel, groupByTrend, sortSeriesByDay} from './utils';
  26. interface TeamReleasesProps extends DateTimeObject {
  27. organization: Organization;
  28. projects: Project[];
  29. teamSlug: string;
  30. theme: Theme;
  31. }
  32. export type ProjectReleaseCount = {
  33. last_week_totals: Record<string, number>;
  34. project_avgs: Record<string, number>;
  35. release_counts: Record<string, number>;
  36. };
  37. function TeamReleases({
  38. organization,
  39. projects,
  40. teamSlug,
  41. theme,
  42. start,
  43. end,
  44. period,
  45. utc,
  46. }: TeamReleasesProps) {
  47. const datetime = {start, end, period, utc};
  48. const {
  49. data: periodReleases,
  50. isLoading: isPeriodReleasesLoading,
  51. isError: isPeriodReleasesError,
  52. refetch: refetchPeriodReleases,
  53. } = useApiQuery<ProjectReleaseCount>(
  54. [
  55. `/teams/${organization.slug}/${teamSlug}/release-count/`,
  56. {
  57. query: {
  58. ...normalizeDateTimeParams(datetime),
  59. },
  60. },
  61. ],
  62. {staleTime: 5000}
  63. );
  64. const {
  65. data: weekReleases,
  66. isLoading: isWeekReleasesLoading,
  67. isError: isWeekReleasesError,
  68. refetch: refetchWeekReleases,
  69. } = useApiQuery<ProjectReleaseCount>(
  70. [
  71. `/teams/${organization.slug}/${teamSlug}/release-count/`,
  72. {
  73. query: {
  74. statsPeriod: '7d',
  75. },
  76. },
  77. ],
  78. {staleTime: 5000}
  79. );
  80. const isLoading = isPeriodReleasesLoading || isWeekReleasesLoading;
  81. if (isPeriodReleasesError || isWeekReleasesError) {
  82. return (
  83. <LoadingError
  84. onRetry={() => {
  85. refetchPeriodReleases();
  86. refetchWeekReleases();
  87. }}
  88. />
  89. );
  90. }
  91. function getReleaseCount(projectId: number, dataset: 'week' | 'period'): number | null {
  92. const releasesPeriod =
  93. dataset === 'week' ? weekReleases?.last_week_totals : periodReleases?.project_avgs;
  94. const count = releasesPeriod?.[projectId]
  95. ? Math.ceil(releasesPeriod?.[projectId])
  96. : 0;
  97. return count;
  98. }
  99. function getTrend(projectId: number): number | null {
  100. const periodCount = getReleaseCount(projectId, 'period');
  101. const weekCount = getReleaseCount(projectId, 'week');
  102. if (periodCount === null || weekCount === null) {
  103. return null;
  104. }
  105. return weekCount - periodCount;
  106. }
  107. function renderReleaseCount(projectId: string, dataset: 'week' | 'period') {
  108. if (isLoading) {
  109. return (
  110. <div>
  111. <Placeholder width="80px" height="25px" />
  112. </div>
  113. );
  114. }
  115. const count = getReleaseCount(Number(projectId), dataset);
  116. if (count === null) {
  117. return '\u2014';
  118. }
  119. return count;
  120. }
  121. function renderTrend(projectId: string) {
  122. if (isLoading) {
  123. return (
  124. <div>
  125. <Placeholder width="80px" height="25px" />
  126. </div>
  127. );
  128. }
  129. const trend = getTrend(Number(projectId));
  130. if (trend === null) {
  131. return '\u2014';
  132. }
  133. return (
  134. <SubText color={trend >= 0 ? 'successText' : 'errorText'}>
  135. {`${round(Math.abs(trend), 3)}`}
  136. <PaddedIconArrow direction={trend >= 0 ? 'up' : 'down'} size="xs" />
  137. </SubText>
  138. );
  139. }
  140. const sortedProjects = projects
  141. .map(project => ({project, trend: getTrend(Number(project.id)) ?? 0}))
  142. .sort((a, b) => Math.abs(b.trend) - Math.abs(a.trend));
  143. const groupedProjects = groupByTrend(sortedProjects);
  144. const data = Object.entries(periodReleases?.release_counts ?? {}).map(
  145. ([bucket, count]) => ({
  146. value: Math.ceil(count),
  147. name: new Date(bucket).getTime(),
  148. })
  149. );
  150. const seriesData = sortSeriesByDay(data);
  151. const averageValues = Object.values(periodReleases?.project_avgs ?? {});
  152. const projectAvgSum = averageValues.reduce(
  153. (total, currentData) => total + currentData,
  154. 0
  155. );
  156. const totalPeriodAverage = Math.ceil(projectAvgSum / averageValues.length);
  157. return (
  158. <div>
  159. <ChartWrapper>
  160. <BarChart
  161. style={{height: 190}}
  162. isGroupedByDate
  163. useShortDate
  164. period="7d"
  165. legend={{right: 3, top: 0}}
  166. yAxis={{minInterval: 1}}
  167. xAxis={barAxisLabel()}
  168. series={[
  169. {
  170. seriesName: t('This Period'),
  171. silent: true,
  172. data: seriesData,
  173. markLine: MarkLine({
  174. silent: true,
  175. lineStyle: {color: theme.gray200, type: 'dashed', width: 1},
  176. data: [{yAxis: totalPeriodAverage}],
  177. label: {
  178. show: false,
  179. },
  180. }),
  181. barCategoryGap: '5%',
  182. },
  183. ]}
  184. tooltip={{
  185. formatter: seriesParams => {
  186. // `seriesParams` can be an array or an object :/
  187. const [series] = toArray(seriesParams);
  188. const dateFormat = 'MMM D';
  189. const startDate = moment(series.data[0]).format(dateFormat);
  190. const endDate = moment(series.data[0]).add(7, 'days').format(dateFormat);
  191. return [
  192. '<div class="tooltip-series">',
  193. `<div><span class="tooltip-label">${series.marker} <strong>${series.seriesName}</strong></span> ${series.data[1]}</div>`,
  194. `<div><span class="tooltip-label"><strong>Last ${period} Average</strong></span> ${totalPeriodAverage}</div>`,
  195. '</div>',
  196. `<div class="tooltip-footer">${startDate} - ${endDate}</div>`,
  197. '<div class="tooltip-arrow"></div>',
  198. ].join('');
  199. },
  200. }}
  201. />
  202. </ChartWrapper>
  203. <StyledPanelTable
  204. isEmpty={projects.length === 0}
  205. emptyMessage={t('No releases were setup for this team’s projects')}
  206. emptyAction={
  207. <Button
  208. size="sm"
  209. external
  210. href="https://docs.sentry.io/product/releases/setup/"
  211. >
  212. {t('Learn More')}
  213. </Button>
  214. }
  215. headers={[
  216. t('Releases Per Project'),
  217. <RightAligned key="last">
  218. {tct('Last [period] Average', {period})}
  219. </RightAligned>,
  220. <RightAligned key="curr">{t('Last 7 Days')}</RightAligned>,
  221. <RightAligned key="diff">{t('Difference')}</RightAligned>,
  222. ]}
  223. >
  224. {groupedProjects.map(({project}) => (
  225. <Fragment key={project.id}>
  226. <ProjectBadgeContainer>
  227. <ProjectBadge
  228. avatarSize={18}
  229. project={project}
  230. to={{
  231. pathname: `/organizations/${organization.slug}/releases/`,
  232. query: {project: project.id},
  233. }}
  234. />
  235. </ProjectBadgeContainer>
  236. <ScoreWrapper>{renderReleaseCount(project.id, 'period')}</ScoreWrapper>
  237. <ScoreWrapper>
  238. <Link
  239. to={{
  240. pathname: `/organizations/${organization.slug}/releases/`,
  241. query: {project: project.id, statsPeriod: '7d'},
  242. }}
  243. >
  244. {renderReleaseCount(project.id, 'week')}
  245. </Link>
  246. </ScoreWrapper>
  247. <ScoreWrapper>{renderTrend(project.id)}</ScoreWrapper>
  248. </Fragment>
  249. ))}
  250. </StyledPanelTable>
  251. </div>
  252. );
  253. }
  254. export default withTheme(TeamReleases);
  255. const ChartWrapper = styled('div')`
  256. padding: ${space(2)} ${space(2)} 0 ${space(2)};
  257. border-bottom: 1px solid ${p => p.theme.border};
  258. `;
  259. const StyledPanelTable = styled(PanelTable)<{isEmpty: boolean}>`
  260. grid-template-columns: 1fr 0.2fr 0.2fr 0.2fr;
  261. white-space: nowrap;
  262. margin-bottom: 0;
  263. border: 0;
  264. font-size: ${p => p.theme.fontSizeMedium};
  265. box-shadow: unset;
  266. & > div {
  267. padding: ${space(1)} ${space(2)};
  268. }
  269. ${p =>
  270. p.isEmpty &&
  271. css`
  272. & > div:last-child {
  273. padding: 48px ${space(2)};
  274. }
  275. `}
  276. `;
  277. const RightAligned = styled('span')`
  278. text-align: right;
  279. `;
  280. const ScoreWrapper = styled('div')`
  281. display: flex;
  282. align-items: center;
  283. justify-content: flex-end;
  284. text-align: right;
  285. `;
  286. const PaddedIconArrow = styled(IconArrow)`
  287. margin: 0 ${space(0.5)};
  288. `;
  289. const SubText = styled('div')<{color: ColorOrAlias}>`
  290. color: ${p => p.theme[p.color]};
  291. `;