teamReleases.tsx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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, Project} from 'sentry/types';
  20. import {useApiQuery} from 'sentry/utils/queryClient';
  21. import type {ColorOrAlias} from 'sentry/utils/theme';
  22. import toArray from 'sentry/utils/toArray';
  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. theme: Theme;
  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. theme,
  41. start,
  42. end,
  43. period,
  44. utc,
  45. }: TeamReleasesProps) {
  46. const datetime = {start, end, period, utc};
  47. const {
  48. data: periodReleases,
  49. isLoading: 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. isLoading: 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 => {
  185. // `seriesParams` can be an array or an object :/
  186. const [series] = toArray(seriesParams);
  187. const dateFormat = 'MMM D';
  188. const startDate = moment(series.data[0]).format(dateFormat);
  189. const endDate = moment(series.data[0]).add(7, 'days').format(dateFormat);
  190. return [
  191. '<div class="tooltip-series">',
  192. `<div><span class="tooltip-label">${series.marker} <strong>${series.seriesName}</strong></span> ${series.data[1]}</div>`,
  193. `<div><span class="tooltip-label"><strong>Last ${period} Average</strong></span> ${totalPeriodAverage}</div>`,
  194. '</div>',
  195. `<div class="tooltip-footer">${startDate} - ${endDate}</div>`,
  196. '<div class="tooltip-arrow"></div>',
  197. ].join('');
  198. },
  199. }}
  200. />
  201. </ChartWrapper>
  202. <StyledPanelTable
  203. isEmpty={projects.length === 0}
  204. emptyMessage={t('No releases were setup for this team’s projects')}
  205. emptyAction={
  206. <Button
  207. size="sm"
  208. external
  209. href="https://docs.sentry.io/product/releases/setup/"
  210. >
  211. {t('Learn More')}
  212. </Button>
  213. }
  214. headers={[
  215. t('Releases Per Project'),
  216. <RightAligned key="last">
  217. {tct('Last [period] Average', {period})}
  218. </RightAligned>,
  219. <RightAligned key="curr">{t('Last 7 Days')}</RightAligned>,
  220. <RightAligned key="diff">{t('Difference')}</RightAligned>,
  221. ]}
  222. >
  223. {groupedProjects.map(({project}) => (
  224. <Fragment key={project.id}>
  225. <ProjectBadgeContainer>
  226. <ProjectBadge
  227. avatarSize={18}
  228. project={project}
  229. to={{
  230. pathname: `/organizations/${organization.slug}/releases/`,
  231. query: {project: project.id},
  232. }}
  233. />
  234. </ProjectBadgeContainer>
  235. <ScoreWrapper>{renderReleaseCount(project.id, 'period')}</ScoreWrapper>
  236. <ScoreWrapper>
  237. <Link
  238. to={{
  239. pathname: `/organizations/${organization.slug}/releases/`,
  240. query: {project: project.id, statsPeriod: '7d'},
  241. }}
  242. >
  243. {renderReleaseCount(project.id, 'week')}
  244. </Link>
  245. </ScoreWrapper>
  246. <ScoreWrapper>{renderTrend(project.id)}</ScoreWrapper>
  247. </Fragment>
  248. ))}
  249. </StyledPanelTable>
  250. </div>
  251. );
  252. }
  253. export default withTheme(TeamReleases);
  254. const ChartWrapper = styled('div')`
  255. padding: ${space(2)} ${space(2)} 0 ${space(2)};
  256. border-bottom: 1px solid ${p => p.theme.border};
  257. `;
  258. const StyledPanelTable = styled(PanelTable)<{isEmpty: boolean}>`
  259. grid-template-columns: 1fr 0.2fr 0.2fr 0.2fr;
  260. white-space: nowrap;
  261. margin-bottom: 0;
  262. border: 0;
  263. font-size: ${p => p.theme.fontSizeMedium};
  264. box-shadow: unset;
  265. & > div {
  266. padding: ${space(1)} ${space(2)};
  267. }
  268. ${p =>
  269. p.isEmpty &&
  270. css`
  271. & > div:last-child {
  272. padding: 48px ${space(2)};
  273. }
  274. `}
  275. `;
  276. const RightAligned = styled('span')`
  277. text-align: right;
  278. `;
  279. const ScoreWrapper = styled('div')`
  280. display: flex;
  281. align-items: center;
  282. justify-content: flex-end;
  283. text-align: right;
  284. `;
  285. const PaddedIconArrow = styled(IconArrow)`
  286. margin: 0 ${space(0.5)};
  287. `;
  288. const SubText = styled('div')<{color: ColorOrAlias}>`
  289. color: ${p => p.theme[p.color]};
  290. `;