teamReleases.tsx 9.1 KB

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