utils.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. import {connect} from 'echarts';
  2. import type {Location, Query} from 'history';
  3. import cloneDeep from 'lodash/cloneDeep';
  4. import isEqual from 'lodash/isEqual';
  5. import pick from 'lodash/pick';
  6. import trimStart from 'lodash/trimStart';
  7. import * as qs from 'query-string';
  8. import WidgetArea from 'sentry-images/dashboard/widget-area.svg';
  9. import WidgetBar from 'sentry-images/dashboard/widget-bar.svg';
  10. import WidgetBigNumber from 'sentry-images/dashboard/widget-big-number.svg';
  11. import WidgetLine from 'sentry-images/dashboard/widget-line-1.svg';
  12. import WidgetTable from 'sentry-images/dashboard/widget-table.svg';
  13. import {parseArithmetic} from 'sentry/components/arithmeticInput/parser';
  14. import type {Fidelity} from 'sentry/components/charts/utils';
  15. import {
  16. getDiffInMinutes,
  17. getInterval,
  18. SIX_HOURS,
  19. TWENTY_FOUR_HOURS,
  20. } from 'sentry/components/charts/utils';
  21. import CircleIndicator from 'sentry/components/circleIndicator';
  22. import {normalizeDateTimeString} from 'sentry/components/organizations/pageFilters/parse';
  23. import {parseSearch, Token} from 'sentry/components/searchSyntax/parser';
  24. import {t} from 'sentry/locale';
  25. import type {PageFilters} from 'sentry/types/core';
  26. import type {Organization} from 'sentry/types/organization';
  27. import {defined} from 'sentry/utils';
  28. import {browserHistory} from 'sentry/utils/browserHistory';
  29. import {getUtcDateString} from 'sentry/utils/dates';
  30. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  31. import EventView from 'sentry/utils/discover/eventView';
  32. import {DURATION_UNITS} from 'sentry/utils/discover/fieldRenderers';
  33. import {
  34. getAggregateAlias,
  35. getAggregateArg,
  36. getColumnsAndAggregates,
  37. isEquation,
  38. isMeasurement,
  39. RATE_UNIT_MULTIPLIERS,
  40. RateUnit,
  41. stripEquationPrefix,
  42. } from 'sentry/utils/discover/fields';
  43. import {
  44. DiscoverDatasets,
  45. DisplayModes,
  46. type SavedQueryDatasets,
  47. } from 'sentry/utils/discover/types';
  48. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  49. import {getMeasurements} from 'sentry/utils/measurements/measurements';
  50. import {getMetricDisplayType, getMetricsUrl} from 'sentry/utils/metrics';
  51. import {parseField} from 'sentry/utils/metrics/mri';
  52. import type {MetricsWidget} from 'sentry/utils/metrics/types';
  53. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  54. import theme from 'sentry/utils/theme';
  55. import type {
  56. DashboardDetails,
  57. DashboardFilters,
  58. Widget,
  59. WidgetQuery,
  60. } from 'sentry/views/dashboards/types';
  61. import {
  62. DashboardFilterKeys,
  63. DisplayType,
  64. WIDGET_TYPE_TO_SAVED_QUERY_DATASET,
  65. WidgetType,
  66. } from 'sentry/views/dashboards/types';
  67. import {ThresholdsHoverWrapper} from './widgetBuilder/buildSteps/thresholdsStep/thresholdsHoverWrapper';
  68. import type {ThresholdsConfig} from './widgetBuilder/buildSteps/thresholdsStep/thresholdsStep';
  69. import {ThresholdMaxKeys} from './widgetBuilder/buildSteps/thresholdsStep/thresholdsStep';
  70. export type ValidationError = {
  71. [key: string]: string | string[] | ValidationError[] | ValidationError;
  72. };
  73. export type FlatValidationError = {
  74. [key: string]: string | FlatValidationError[] | FlatValidationError;
  75. };
  76. export function cloneDashboard(dashboard: DashboardDetails): DashboardDetails {
  77. return cloneDeep(dashboard);
  78. }
  79. export function eventViewFromWidget(
  80. title: string,
  81. query: WidgetQuery,
  82. selection: PageFilters
  83. ): EventView {
  84. const {start, end, period: statsPeriod} = selection.datetime;
  85. const {projects, environments} = selection;
  86. // World Map requires an additional column (geo.country_code) to display in discover when navigating from the widget
  87. const fields = [...query.columns, ...query.aggregates];
  88. const conditions = query.conditions;
  89. const {orderby} = query;
  90. // Need to convert orderby to aggregate alias because eventView still uses aggregate alias format
  91. const aggregateAliasOrderBy = orderby
  92. ? `${orderby.startsWith('-') ? '-' : ''}${getAggregateAlias(trimStart(orderby, '-'))}`
  93. : orderby;
  94. return EventView.fromSavedQuery({
  95. id: undefined,
  96. name: title,
  97. version: 2,
  98. fields,
  99. query: conditions,
  100. orderby: aggregateAliasOrderBy,
  101. projects,
  102. range: statsPeriod ?? undefined,
  103. start: start ? getUtcDateString(start) : undefined,
  104. end: end ? getUtcDateString(end) : undefined,
  105. environment: environments,
  106. });
  107. }
  108. export function getThresholdUnitSelectOptions(
  109. dataType: string
  110. ): {label: string; value: string}[] {
  111. if (dataType === 'duration') {
  112. return Object.keys(DURATION_UNITS)
  113. .map(unit => ({label: unit, value: unit}))
  114. .slice(2);
  115. }
  116. if (dataType === 'rate') {
  117. return Object.values(RateUnit).map(unit => ({
  118. label: `/${unit.split('/')[1]}`,
  119. value: unit,
  120. }));
  121. }
  122. return [];
  123. }
  124. export function hasThresholdMaxValue(thresholdsConfig: ThresholdsConfig): boolean {
  125. return Object.keys(thresholdsConfig.max_values).length > 0;
  126. }
  127. export function normalizeUnit(value: number, unit: string, dataType: string): number {
  128. const multiplier =
  129. dataType === 'rate'
  130. ? RATE_UNIT_MULTIPLIERS[unit]
  131. : dataType === 'duration'
  132. ? DURATION_UNITS[unit]
  133. : 1;
  134. return value * multiplier;
  135. }
  136. export function getColoredWidgetIndicator(
  137. thresholds: ThresholdsConfig,
  138. tableData: TableDataWithTitle[]
  139. ): React.ReactNode {
  140. const tableMeta = {...tableData[0].meta};
  141. const fields = Object.keys(tableMeta);
  142. const field = fields[0];
  143. const dataType = tableMeta[field];
  144. const dataUnit = tableMeta.units?.[field];
  145. const dataRow = tableData[0].data[0];
  146. if (!dataRow) {
  147. return null;
  148. }
  149. const data = Number(dataRow[field]);
  150. const normalizedData = dataUnit ? normalizeUnit(data, dataUnit, dataType) : data;
  151. const {max_values} = thresholds;
  152. let color = theme.red300;
  153. const yellowMax = max_values[ThresholdMaxKeys.MAX_2];
  154. const normalizedYellowMax =
  155. thresholds.unit && yellowMax
  156. ? normalizeUnit(yellowMax, thresholds.unit, dataType)
  157. : yellowMax;
  158. if (normalizedYellowMax && normalizedData <= normalizedYellowMax) {
  159. color = theme.yellow300;
  160. }
  161. const greenMax = max_values[ThresholdMaxKeys.MAX_1];
  162. const normalizedGreenMax =
  163. thresholds.unit && greenMax
  164. ? normalizeUnit(greenMax, thresholds.unit, dataType)
  165. : greenMax;
  166. if (normalizedGreenMax && normalizedData <= normalizedGreenMax) {
  167. color = theme.green300;
  168. }
  169. return (
  170. <ThresholdsHoverWrapper thresholds={thresholds} type={dataType}>
  171. <CircleIndicator color={color} size={12} />
  172. </ThresholdsHoverWrapper>
  173. );
  174. }
  175. function coerceStringToArray(value?: string | string[] | null) {
  176. return typeof value === 'string' ? [value] : value;
  177. }
  178. export function constructWidgetFromQuery(query?: Query): Widget | undefined {
  179. if (query) {
  180. const queryNames = coerceStringToArray(query.queryNames);
  181. const queryConditions = coerceStringToArray(query.queryConditions);
  182. const queryFields = coerceStringToArray(query.queryFields);
  183. const widgetType = decodeScalar(query.widgetType);
  184. const queries: WidgetQuery[] = [];
  185. if (
  186. queryConditions &&
  187. queryNames &&
  188. queryFields &&
  189. typeof query.queryOrderby === 'string'
  190. ) {
  191. const {columns, aggregates} = getColumnsAndAggregates(queryFields);
  192. queryConditions.forEach((condition, index) => {
  193. queries.push({
  194. name: queryNames[index],
  195. conditions: condition,
  196. fields: queryFields,
  197. columns,
  198. aggregates,
  199. orderby: query.queryOrderby as string,
  200. });
  201. });
  202. }
  203. if (query.title && query.displayType && query.interval && queries.length > 0) {
  204. const newWidget: Widget = {
  205. ...(pick(query, ['title', 'displayType', 'interval']) as {
  206. displayType: DisplayType;
  207. interval: string;
  208. title: string;
  209. }),
  210. widgetType: widgetType ? (widgetType as WidgetType) : WidgetType.DISCOVER,
  211. queries,
  212. };
  213. return newWidget;
  214. }
  215. }
  216. return undefined;
  217. }
  218. export function miniWidget(displayType: DisplayType): string {
  219. switch (displayType) {
  220. case DisplayType.BAR:
  221. return WidgetBar;
  222. case DisplayType.AREA:
  223. case DisplayType.TOP_N:
  224. return WidgetArea;
  225. case DisplayType.BIG_NUMBER:
  226. return WidgetBigNumber;
  227. case DisplayType.TABLE:
  228. return WidgetTable;
  229. case DisplayType.LINE:
  230. default:
  231. return WidgetLine;
  232. }
  233. }
  234. export function getWidgetInterval(
  235. displayType: DisplayType,
  236. datetimeObj: Partial<PageFilters['datetime']>,
  237. widgetInterval?: string,
  238. fidelity?: Fidelity
  239. ): string {
  240. // Don't fetch more than 66 bins as we're plotting on a small area.
  241. const MAX_BIN_COUNT = 66;
  242. // Bars charts are daily totals to aligned with discover. It also makes them
  243. // usefully different from line/area charts until we expose the interval control, or remove it.
  244. let interval = displayType === 'bar' ? '1d' : widgetInterval;
  245. if (!interval) {
  246. // Default to 5 minutes
  247. interval = '5m';
  248. }
  249. const desiredPeriod = parsePeriodToHours(interval);
  250. const selectedRange = getDiffInMinutes(datetimeObj);
  251. if (fidelity) {
  252. // Primarily to support lower fidelity for Release Health widgets
  253. // the sort on releases and hit the metrics API endpoint.
  254. interval = getInterval(datetimeObj, fidelity);
  255. if (selectedRange > SIX_HOURS && selectedRange <= TWENTY_FOUR_HOURS) {
  256. interval = '1h';
  257. }
  258. return displayType === 'bar' ? '1d' : interval;
  259. }
  260. // selectedRange is in minutes, desiredPeriod is in hours
  261. // convert desiredPeriod to minutes
  262. if (selectedRange / (desiredPeriod * 60) > MAX_BIN_COUNT) {
  263. const highInterval = getInterval(datetimeObj, 'high');
  264. // Only return high fidelity interval if desired interval is higher fidelity
  265. if (desiredPeriod < parsePeriodToHours(highInterval)) {
  266. return highInterval;
  267. }
  268. }
  269. return interval;
  270. }
  271. export function getFieldsFromEquations(fields: string[]): string[] {
  272. // Gather all fields and functions used in equations and prepend them to the provided fields
  273. const termsSet: Set<string> = new Set();
  274. fields.filter(isEquation).forEach(field => {
  275. const parsed = parseArithmetic(stripEquationPrefix(field)).tc;
  276. parsed.fields.forEach(({term}) => termsSet.add(term as string));
  277. parsed.functions.forEach(({term}) => termsSet.add(term as string));
  278. });
  279. return Array.from(termsSet);
  280. }
  281. export function getWidgetDiscoverUrl(
  282. widget: Widget,
  283. selection: PageFilters,
  284. organization: Organization,
  285. index: number = 0,
  286. isMetricsData: boolean = false
  287. ) {
  288. const eventView = eventViewFromWidget(widget.title, widget.queries[index], selection);
  289. const discoverLocation = eventView.getResultsViewUrlTarget(
  290. organization.slug,
  291. false,
  292. hasDatasetSelector(organization) && widget.widgetType
  293. ? WIDGET_TYPE_TO_SAVED_QUERY_DATASET[widget.widgetType]
  294. : undefined
  295. );
  296. // Pull a max of 3 valid Y-Axis from the widget
  297. const yAxisOptions = eventView.getYAxisOptions().map(({value}) => value);
  298. discoverLocation.query.yAxis = [
  299. ...new Set(
  300. widget.queries[0].aggregates.filter(aggregate => yAxisOptions.includes(aggregate))
  301. ),
  302. ].slice(0, 3);
  303. // Visualization specific transforms
  304. switch (widget.displayType) {
  305. case DisplayType.BAR:
  306. discoverLocation.query.display = DisplayModes.BAR;
  307. break;
  308. case DisplayType.TOP_N:
  309. discoverLocation.query.display = DisplayModes.TOP5;
  310. // Last field is used as the yAxis
  311. const aggregates = widget.queries[0].aggregates;
  312. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  313. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  314. discoverLocation.query.field = aggregates.slice(0, -1);
  315. }
  316. break;
  317. default:
  318. break;
  319. }
  320. // Equation fields need to have their terms explicitly selected as columns in the discover table
  321. const fields =
  322. Array.isArray(discoverLocation.query.field) || !discoverLocation.query.field
  323. ? discoverLocation.query.field
  324. : [discoverLocation.query.field];
  325. const query = widget.queries[0];
  326. const queryFields = defined(query.fields)
  327. ? query.fields
  328. : [...query.columns, ...query.aggregates];
  329. // Updates fields by adding any individual terms from equation fields as a column
  330. getFieldsFromEquations(queryFields).forEach(term => {
  331. if (Array.isArray(fields) && !fields.includes(term)) {
  332. fields.unshift(term);
  333. }
  334. });
  335. discoverLocation.query.field = fields;
  336. if (isMetricsData) {
  337. discoverLocation.query.fromMetric = 'true';
  338. }
  339. // Construct and return the discover url
  340. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  341. ...discoverLocation.query,
  342. })}`;
  343. return discoverPath;
  344. }
  345. export function getWidgetIssueUrl(
  346. widget: Widget,
  347. selection: PageFilters,
  348. organization: Organization
  349. ) {
  350. const {start, end, utc, period} = selection.datetime;
  351. const datetime =
  352. start && end
  353. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  354. : {statsPeriod: period};
  355. const issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  356. query: widget.queries?.[0]?.conditions,
  357. sort: widget.queries?.[0]?.orderby,
  358. ...datetime,
  359. project: selection.projects,
  360. environment: selection.environments,
  361. })}`;
  362. return issuesLocation;
  363. }
  364. export function getWidgetReleasesUrl(
  365. _widget: Widget,
  366. selection: PageFilters,
  367. organization: Organization
  368. ) {
  369. const {start, end, utc, period} = selection.datetime;
  370. const datetime =
  371. start && end
  372. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  373. : {statsPeriod: period};
  374. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  375. ...datetime,
  376. project: selection.projects,
  377. environment: selection.environments,
  378. })}`;
  379. return releasesLocation;
  380. }
  381. export function getWidgetMetricsUrl(
  382. _widget: Widget,
  383. selection: PageFilters,
  384. organization: Organization
  385. ) {
  386. const {start, end, utc, period} = selection.datetime;
  387. const datetime =
  388. start && end
  389. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  390. : {statsPeriod: period};
  391. // ensures that My Projects selection is properly handled
  392. const project = selection.projects.length ? selection.projects : [0];
  393. const metricsLocation = getMetricsUrl(organization.slug, {
  394. ...datetime,
  395. project,
  396. environment: selection.environments,
  397. widgets: _widget.queries.map(query => {
  398. const parsed = parseField(query.aggregates[0]);
  399. return {
  400. mri: parsed?.mri,
  401. aggregation: parsed?.aggregation,
  402. groupBy: query.columns,
  403. query: query.conditions ?? '',
  404. displayType: getMetricDisplayType(_widget.displayType),
  405. } satisfies Partial<MetricsWidget>;
  406. }),
  407. });
  408. return metricsLocation;
  409. }
  410. export function flattenErrors(
  411. data: ValidationError | string,
  412. update: FlatValidationError
  413. ): FlatValidationError {
  414. if (typeof data === 'string') {
  415. update.error = data;
  416. } else {
  417. Object.keys(data).forEach((key: string) => {
  418. const value = data[key];
  419. if (typeof value === 'string') {
  420. update[key] = value;
  421. return;
  422. }
  423. // Recurse into nested objects.
  424. if (Array.isArray(value) && typeof value[0] === 'string') {
  425. update[key] = value[0];
  426. return;
  427. }
  428. if (Array.isArray(value) && typeof value[0] === 'object') {
  429. (value as ValidationError[]).map(item => flattenErrors(item, update));
  430. } else {
  431. flattenErrors(value as ValidationError, update);
  432. }
  433. });
  434. }
  435. return update;
  436. }
  437. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  438. return isMEPEnabled
  439. ? {
  440. dataset: DiscoverDatasets.METRICS_ENHANCED,
  441. }
  442. : {};
  443. }
  444. export function getNumEquations(possibleEquations: string[]) {
  445. return possibleEquations.filter(isEquation).length;
  446. }
  447. const DEFINED_MEASUREMENTS = new Set(Object.keys(getMeasurements()));
  448. export function isCustomMeasurement(field: string) {
  449. return !DEFINED_MEASUREMENTS.has(field) && isMeasurement(field);
  450. }
  451. export function isCustomMeasurementWidget(widget: Widget) {
  452. return (
  453. widget.widgetType === WidgetType.DISCOVER &&
  454. widget.queries.some(({aggregates, columns, fields}) => {
  455. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  456. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  457. // but there aren't any custom measurement aggregates that use custom measurements
  458. // outside of the first arg.
  459. const aggregateArg = getAggregateArg(aggregate);
  460. if (aggregateArg) {
  461. acc.push(aggregateArg);
  462. }
  463. return acc;
  464. }, []);
  465. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  466. isCustomMeasurement(field)
  467. );
  468. })
  469. );
  470. }
  471. export function getCustomMeasurementQueryParams() {
  472. return {
  473. dataset: 'metrics',
  474. };
  475. }
  476. export function isWidgetUsingTransactionName(widget: Widget) {
  477. return (
  478. widget.widgetType === WidgetType.DISCOVER &&
  479. widget.queries.some(({aggregates, columns, fields, conditions}) => {
  480. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  481. const aggregateArg = getAggregateArg(aggregate);
  482. if (aggregateArg) {
  483. acc.push(aggregateArg);
  484. }
  485. return acc;
  486. }, []);
  487. const transactionSelected = [...aggregateArgs, ...columns, ...(fields ?? [])].some(
  488. field => field === 'transaction'
  489. );
  490. const transactionUsedInFilter = parseSearch(conditions)?.some(
  491. parsedCondition =>
  492. parsedCondition.type === Token.FILTER &&
  493. parsedCondition.key?.text === 'transaction'
  494. );
  495. return transactionSelected || transactionUsedInFilter;
  496. })
  497. );
  498. }
  499. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  500. return !(
  501. dashboard.projects &&
  502. dashboard.projects.length === 0 &&
  503. dashboard.environment === undefined &&
  504. dashboard.start === undefined &&
  505. dashboard.end === undefined &&
  506. dashboard.period === undefined
  507. );
  508. }
  509. export function hasUnsavedFilterChanges(
  510. initialDashboard: DashboardDetails,
  511. location: Location
  512. ) {
  513. // Use Sets to compare the filter fields that are arrays
  514. type Filters = {
  515. end?: string;
  516. environment?: Set<string>;
  517. period?: string;
  518. projects?: Set<number>;
  519. release?: Set<string>;
  520. start?: string;
  521. utc?: boolean;
  522. };
  523. const savedFilters: Filters = {
  524. projects: new Set(initialDashboard.projects),
  525. environment: new Set(initialDashboard.environment),
  526. period: initialDashboard.period,
  527. start: normalizeDateTimeString(initialDashboard.start),
  528. end: normalizeDateTimeString(initialDashboard.end),
  529. utc: initialDashboard.utc,
  530. };
  531. let currentFilters = {
  532. ...getCurrentPageFilters(location),
  533. } as unknown as Filters;
  534. currentFilters = {
  535. ...currentFilters,
  536. projects: new Set(currentFilters.projects),
  537. environment: new Set(currentFilters.environment),
  538. };
  539. if (defined(location.query?.release)) {
  540. // Release is only included in the comparison if it exists in the query
  541. // params, otherwise the dashboard should be using its saved state
  542. savedFilters.release = new Set(initialDashboard.filters?.release);
  543. currentFilters.release = new Set(location.query?.release);
  544. }
  545. return !isEqual(savedFilters, currentFilters);
  546. }
  547. export function getSavedFiltersAsPageFilters(dashboard: DashboardDetails): PageFilters {
  548. return {
  549. datetime: {
  550. end: dashboard.end || null,
  551. period: dashboard.period || null,
  552. start: dashboard.start || null,
  553. utc: null,
  554. },
  555. environments: dashboard.environment || [],
  556. projects: dashboard.projects || [],
  557. };
  558. }
  559. export function getSavedPageFilters(dashboard: DashboardDetails) {
  560. return {
  561. project: dashboard.projects,
  562. environment: dashboard.environment,
  563. statsPeriod: dashboard.period,
  564. start: normalizeDateTimeString(dashboard.start),
  565. end: normalizeDateTimeString(dashboard.end),
  566. utc: dashboard.utc,
  567. };
  568. }
  569. export function resetPageFilters(dashboard: DashboardDetails, location: Location) {
  570. browserHistory.replace({
  571. ...location,
  572. query: getSavedPageFilters(dashboard),
  573. });
  574. }
  575. export function getCurrentPageFilters(
  576. location: Location
  577. ): Pick<
  578. DashboardDetails,
  579. 'projects' | 'environment' | 'period' | 'start' | 'end' | 'utc'
  580. > {
  581. const {project, environment, statsPeriod, start, end, utc} = location.query ?? {};
  582. return {
  583. // Ensure projects and environment are sent as arrays, or undefined in the request
  584. // location.query will return a string if there's only one value
  585. projects:
  586. project === undefined || project === null
  587. ? []
  588. : typeof project === 'string'
  589. ? [Number(project)]
  590. : project.map(Number),
  591. environment:
  592. typeof environment === 'string' ? [environment] : environment ?? undefined,
  593. period: statsPeriod as string | undefined,
  594. start: defined(start) ? normalizeDateTimeString(start as string) : undefined,
  595. end: defined(end) ? normalizeDateTimeString(end as string) : undefined,
  596. utc: defined(utc) ? utc === 'true' : undefined,
  597. };
  598. }
  599. export function getDashboardFiltersFromURL(location: Location): DashboardFilters | null {
  600. const dashboardFilters: DashboardFilters = {};
  601. Object.values(DashboardFilterKeys).forEach(key => {
  602. if (defined(location.query?.[key])) {
  603. dashboardFilters[key] = decodeList(location.query?.[key]);
  604. }
  605. });
  606. return Object.keys(dashboardFilters).length > 0 ? dashboardFilters : null;
  607. }
  608. export function dashboardFiltersToString(
  609. dashboardFilters: DashboardFilters | null | undefined
  610. ): string {
  611. let dashboardFilterConditions = '';
  612. if (dashboardFilters) {
  613. for (const [key, activeFilters] of Object.entries(dashboardFilters)) {
  614. if (activeFilters.length === 1) {
  615. dashboardFilterConditions += `${key}:"${activeFilters[0]}" `;
  616. } else if (activeFilters.length > 1) {
  617. dashboardFilterConditions += `${key}:[${activeFilters
  618. .map(f => `"${f}"`)
  619. .join(',')}] `;
  620. }
  621. }
  622. }
  623. return dashboardFilterConditions;
  624. }
  625. export function connectDashboardCharts(groupName: string) {
  626. connect?.(groupName);
  627. }
  628. export function hasDatasetSelector(organization: Organization): boolean {
  629. return organization.features.includes('performance-discover-dataset-selector');
  630. }
  631. export function appendQueryDatasetParam(
  632. organization: Organization,
  633. queryDataset?: SavedQueryDatasets
  634. ) {
  635. if (hasDatasetSelector(organization) && queryDataset) {
  636. return {queryDataset: queryDataset};
  637. }
  638. return {};
  639. }
  640. /**
  641. * Checks if the widget is using the performance_score aggregate
  642. */
  643. export function isUsingPerformanceScore(widget: Widget) {
  644. if (widget.queries.length === 0) {
  645. return false;
  646. }
  647. return widget.queries.some(_doesWidgetUsePerformanceScore);
  648. }
  649. function _doesWidgetUsePerformanceScore(query: WidgetQuery) {
  650. if (query.conditions?.includes('performance_score')) {
  651. return true;
  652. }
  653. if (query.aggregates.some(aggregate => aggregate.includes('performance_score'))) {
  654. return true;
  655. }
  656. return false;
  657. }
  658. export const performanceScoreTooltip = t('peformance_score is not supported in Discover');