teamReleases.tsx 9.9 KB

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