teamReleases.tsx 9.3 KB

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