teamReleases.tsx 9.5 KB

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