utils.tsx 22 KB

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