utils.tsx 21 KB

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