teamReleases.tsx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import {ComponentType, Fragment} from 'react';
  2. import {withTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import chunk from 'lodash/chunk';
  5. import isEqual from 'lodash/isEqual';
  6. import round from 'lodash/round';
  7. import moment from 'moment';
  8. import AsyncComponent from 'app/components/asyncComponent';
  9. import BarChart from 'app/components/charts/barChart';
  10. import MarkLine from 'app/components/charts/components/markLine';
  11. import {DateTimeObject} from 'app/components/charts/utils';
  12. import IdBadge from 'app/components/idBadge';
  13. import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
  14. import PanelTable from 'app/components/panels/panelTable';
  15. import Placeholder from 'app/components/placeholder';
  16. import {IconArrow} from 'app/icons';
  17. import {t, tct} from 'app/locale';
  18. import space from 'app/styles/space';
  19. import {Organization, Project} from 'app/types';
  20. import {Color, Theme} from 'app/utils/theme';
  21. type Props = AsyncComponent['props'] & {
  22. theme: Theme;
  23. organization: Organization;
  24. teamSlug: string;
  25. projects: Project[];
  26. } & DateTimeObject;
  27. type ProjectReleaseCount = {
  28. project_avgs: Record<string, number>;
  29. release_counts: Record<string, number>;
  30. last_week_totals: Record<string, number>;
  31. };
  32. type State = AsyncComponent['state'] & {
  33. /** weekly selected date range */
  34. periodReleases: ProjectReleaseCount | null;
  35. /** Locked to last 7 days */
  36. weekReleases: ProjectReleaseCount | null;
  37. };
  38. class TeamReleases extends AsyncComponent<Props, State> {
  39. shouldRenderBadRequests = true;
  40. getDefaultState(): State {
  41. return {
  42. ...super.getDefaultState(),
  43. weekReleases: null,
  44. periodReleases: null,
  45. };
  46. }
  47. getEndpoints() {
  48. const {organization, start, end, period, utc, teamSlug} = this.props;
  49. const datetime = {start, end, period, utc};
  50. const endpoints: ReturnType<AsyncComponent['getEndpoints']> = [
  51. [
  52. 'periodReleases',
  53. `/teams/${organization.slug}/${teamSlug}/release-count/`,
  54. {
  55. query: {
  56. ...getParams(datetime),
  57. },
  58. },
  59. ],
  60. [
  61. 'weekReleases',
  62. `/teams/${organization.slug}/${teamSlug}/release-count/`,
  63. {
  64. query: {
  65. statsPeriod: '7d',
  66. },
  67. },
  68. ],
  69. ];
  70. return endpoints;
  71. }
  72. componentDidUpdate(prevProps: Props) {
  73. const {teamSlug, start, end, period, utc} = this.props;
  74. if (
  75. prevProps.start !== start ||
  76. prevProps.end !== end ||
  77. prevProps.period !== period ||
  78. prevProps.utc !== utc ||
  79. !isEqual(prevProps.teamSlug, teamSlug)
  80. ) {
  81. this.remountComponent();
  82. }
  83. }
  84. getReleaseCount(projectId: number, dataset: 'week' | 'period'): number | null {
  85. const {periodReleases, weekReleases} = this.state;
  86. const releasesPeriod =
  87. dataset === 'week' ? weekReleases?.last_week_totals : periodReleases?.project_avgs;
  88. const count = releasesPeriod?.[projectId]
  89. ? Math.ceil(releasesPeriod?.[projectId])
  90. : 0;
  91. return count;
  92. }
  93. getTrend(projectId: number): number | null {
  94. const periodCount = this.getReleaseCount(projectId, 'period');
  95. const weekCount = this.getReleaseCount(projectId, 'week');
  96. if (periodCount === null || weekCount === null) {
  97. return null;
  98. }
  99. return weekCount - periodCount;
  100. }
  101. renderLoading() {
  102. return this.renderBody();
  103. }
  104. renderReleaseCount(projectId: string, dataset: 'week' | 'period') {
  105. const {loading} = this.state;
  106. if (loading) {
  107. return (
  108. <div>
  109. <Placeholder width="80px" height="25px" />
  110. </div>
  111. );
  112. }
  113. const count = this.getReleaseCount(Number(projectId), dataset);
  114. if (count === null) {
  115. return '\u2014';
  116. }
  117. return count;
  118. }
  119. renderTrend(projectId: string) {
  120. const {loading} = this.state;
  121. if (loading) {
  122. return (
  123. <div>
  124. <Placeholder width="80px" height="25px" />
  125. </div>
  126. );
  127. }
  128. const trend = this.getTrend(Number(projectId));
  129. if (trend === null) {
  130. return '\u2014';
  131. }
  132. return (
  133. <SubText color={trend >= 0 ? 'green300' : 'red300'}>
  134. {`${round(Math.abs(trend), 3)}`}
  135. <PaddedIconArrow direction={trend >= 0 ? 'up' : 'down'} size="xs" />
  136. </SubText>
  137. );
  138. }
  139. renderBody() {
  140. const {projects, period, theme} = this.props;
  141. const {periodReleases} = this.state;
  142. const data = Object.entries(periodReleases?.release_counts ?? {})
  143. .map(([bucket, count]) => ({
  144. value: Math.ceil(count),
  145. name: new Date(bucket).getTime(),
  146. }))
  147. .sort((a, b) => a.name - b.name);
  148. // Convert from days to 7 day groups
  149. const seriesData = chunk(data, 7).map(week => {
  150. return {
  151. name: week[0].name,
  152. value: week.reduce((total, currentData) => total + currentData.value, 0),
  153. };
  154. });
  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={{
  172. type: 'time',
  173. }}
  174. series={[
  175. {
  176. seriesName: t('This Period'),
  177. silent: true,
  178. data: seriesData,
  179. markLine: MarkLine({
  180. silent: true,
  181. lineStyle: {color: theme.gray200, type: 'dashed', width: 1},
  182. data: [{yAxis: totalPeriodAverage} as any],
  183. }),
  184. } as any,
  185. ]}
  186. tooltip={{
  187. formatter: seriesParams => {
  188. // `seriesParams` can be an array or an object :/
  189. const [series] = Array.isArray(seriesParams)
  190. ? seriesParams
  191. : [seriesParams];
  192. const dateFormat = 'MMM D';
  193. const startDate = moment(series.axisValue).format(dateFormat);
  194. const endDate = moment(series.axisValue)
  195. .add(7, 'days')
  196. .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. headers={[
  212. t('Project'),
  213. <RightAligned key="last">
  214. {tct('Last [period] Average', {period})}
  215. </RightAligned>,
  216. <RightAligned key="curr">{t('Last 7 Days')}</RightAligned>,
  217. <RightAligned key="diff">{t('Difference')}</RightAligned>,
  218. ]}
  219. >
  220. {projects.map(project => (
  221. <Fragment key={project.id}>
  222. <ProjectBadgeContainer>
  223. <ProjectBadge avatarSize={18} project={project} />
  224. </ProjectBadgeContainer>
  225. <ScoreWrapper>{this.renderReleaseCount(project.id, 'period')}</ScoreWrapper>
  226. <ScoreWrapper>{this.renderReleaseCount(project.id, 'week')}</ScoreWrapper>
  227. <ScoreWrapper>{this.renderTrend(project.id)}</ScoreWrapper>
  228. </Fragment>
  229. ))}
  230. </StyledPanelTable>
  231. </div>
  232. );
  233. }
  234. }
  235. export default withTheme(TeamReleases as ComponentType<Props>);
  236. const ChartWrapper = styled('div')`
  237. padding: ${space(2)} ${space(2)} 0 ${space(2)};
  238. border-bottom: 1px solid ${p => p.theme.border};
  239. `;
  240. const StyledPanelTable = styled(PanelTable)`
  241. grid-template-columns: 1fr 0.2fr 0.2fr 0.2fr;
  242. white-space: nowrap;
  243. margin-bottom: 0;
  244. border: 0;
  245. font-size: ${p => p.theme.fontSizeMedium};
  246. box-shadow: unset;
  247. & > div {
  248. padding: ${space(1)} ${space(2)};
  249. }
  250. `;
  251. const RightAligned = styled('span')`
  252. text-align: right;
  253. `;
  254. const ScoreWrapper = styled('div')`
  255. display: flex;
  256. align-items: center;
  257. justify-content: flex-end;
  258. text-align: right;
  259. `;
  260. const PaddedIconArrow = styled(IconArrow)`
  261. margin: 0 ${space(0.5)};
  262. `;
  263. const SubText = styled('div')<{color: Color}>`
  264. color: ${p => p.theme[p.color]};
  265. `;
  266. const ProjectBadgeContainer = styled('div')`
  267. display: flex;
  268. `;
  269. const ProjectBadge = styled(IdBadge)`
  270. flex-shrink: 0;
  271. `;