utils.tsx 21 KB

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