utils.tsx 21 KB

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