teamReleases.tsx 9.9 KB

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