utils.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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, decodeScalar} 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 widgetType = decodeScalar(query.widgetType);
  183. const queries: WidgetQuery[] = [];
  184. if (
  185. queryConditions &&
  186. queryNames &&
  187. queryFields &&
  188. typeof query.queryOrderby === 'string'
  189. ) {
  190. const {columns, aggregates} = getColumnsAndAggregates(queryFields);
  191. queryConditions.forEach((condition, index) => {
  192. queries.push({
  193. name: queryNames[index],
  194. conditions: condition,
  195. fields: queryFields,
  196. columns,
  197. aggregates,
  198. orderby: query.queryOrderby as string,
  199. });
  200. });
  201. }
  202. if (query.title && query.displayType && query.interval && queries.length > 0) {
  203. const newWidget: Widget = {
  204. ...(pick(query, ['title', 'displayType', 'interval']) as {
  205. displayType: DisplayType;
  206. interval: string;
  207. title: string;
  208. }),
  209. widgetType: widgetType ? (widgetType as WidgetType) : WidgetType.DISCOVER,
  210. queries,
  211. };
  212. return newWidget;
  213. }
  214. }
  215. return undefined;
  216. }
  217. export function miniWidget(displayType: DisplayType): string {
  218. switch (displayType) {
  219. case DisplayType.BAR:
  220. return WidgetBar;
  221. case DisplayType.AREA:
  222. case DisplayType.TOP_N:
  223. return WidgetArea;
  224. case DisplayType.BIG_NUMBER:
  225. return WidgetBigNumber;
  226. case DisplayType.TABLE:
  227. return WidgetTable;
  228. case DisplayType.LINE:
  229. default:
  230. return WidgetLine;
  231. }
  232. }
  233. export function getWidgetInterval(
  234. displayType: DisplayType,
  235. datetimeObj: Partial<PageFilters['datetime']>,
  236. widgetInterval?: string,
  237. fidelity?: Fidelity
  238. ): string {
  239. // Don't fetch more than 66 bins as we're plotting on a small area.
  240. const MAX_BIN_COUNT = 66;
  241. // Bars charts are daily totals to aligned with discover. It also makes them
  242. // usefully different from line/area charts until we expose the interval control, or remove it.
  243. let interval = displayType === 'bar' ? '1d' : widgetInterval;
  244. if (!interval) {
  245. // Default to 5 minutes
  246. interval = '5m';
  247. }
  248. const desiredPeriod = parsePeriodToHours(interval);
  249. const selectedRange = getDiffInMinutes(datetimeObj);
  250. if (fidelity) {
  251. // Primarily to support lower fidelity for Release Health widgets
  252. // the sort on releases and hit the metrics API endpoint.
  253. interval = getInterval(datetimeObj, fidelity);
  254. if (selectedRange > SIX_HOURS && selectedRange <= TWENTY_FOUR_HOURS) {
  255. interval = '1h';
  256. }
  257. return displayType === 'bar' ? '1d' : interval;
  258. }
  259. // selectedRange is in minutes, desiredPeriod is in hours
  260. // convert desiredPeriod to minutes
  261. if (selectedRange / (desiredPeriod * 60) > MAX_BIN_COUNT) {
  262. const highInterval = getInterval(datetimeObj, 'high');
  263. // Only return high fidelity interval if desired interval is higher fidelity
  264. if (desiredPeriod < parsePeriodToHours(highInterval)) {
  265. return highInterval;
  266. }
  267. }
  268. return interval;
  269. }
  270. export function getFieldsFromEquations(fields: string[]): string[] {
  271. // Gather all fields and functions used in equations and prepend them to the provided fields
  272. const termsSet: Set<string> = new Set();
  273. fields.filter(isEquation).forEach(field => {
  274. const parsed = parseArithmetic(stripEquationPrefix(field)).tc;
  275. parsed.fields.forEach(({term}) => termsSet.add(term as string));
  276. parsed.functions.forEach(({term}) => termsSet.add(term as string));
  277. });
  278. return Array.from(termsSet);
  279. }
  280. export function getWidgetDiscoverUrl(
  281. widget: Widget,
  282. selection: PageFilters,
  283. organization: Organization,
  284. index: number = 0,
  285. isMetricsData: boolean = false
  286. ) {
  287. const eventView = eventViewFromWidget(widget.title, widget.queries[index], selection);
  288. const discoverLocation = eventView.getResultsViewUrlTarget(
  289. organization.slug,
  290. false,
  291. hasDatasetSelector(organization) && widget.widgetType
  292. ? WIDGET_TYPE_TO_SAVED_QUERY_DATASET[widget.widgetType]
  293. : undefined
  294. );
  295. // Pull a max of 3 valid Y-Axis from the widget
  296. const yAxisOptions = eventView.getYAxisOptions().map(({value}) => value);
  297. discoverLocation.query.yAxis = [
  298. ...new Set(
  299. widget.queries[0].aggregates.filter(aggregate => yAxisOptions.includes(aggregate))
  300. ),
  301. ].slice(0, 3);
  302. // Visualization specific transforms
  303. switch (widget.displayType) {
  304. case DisplayType.BAR:
  305. discoverLocation.query.display = DisplayModes.BAR;
  306. break;
  307. case DisplayType.TOP_N:
  308. discoverLocation.query.display = DisplayModes.TOP5;
  309. // Last field is used as the yAxis
  310. const aggregates = widget.queries[0].aggregates;
  311. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  312. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  313. discoverLocation.query.field = aggregates.slice(0, -1);
  314. }
  315. break;
  316. default:
  317. break;
  318. }
  319. // Equation fields need to have their terms explicitly selected as columns in the discover table
  320. const fields =
  321. Array.isArray(discoverLocation.query.field) || !discoverLocation.query.field
  322. ? discoverLocation.query.field
  323. : [discoverLocation.query.field];
  324. const query = widget.queries[0];
  325. const queryFields = defined(query.fields)
  326. ? query.fields
  327. : [...query.columns, ...query.aggregates];
  328. // Updates fields by adding any individual terms from equation fields as a column
  329. getFieldsFromEquations(queryFields).forEach(term => {
  330. if (Array.isArray(fields) && !fields.includes(term)) {
  331. fields.unshift(term);
  332. }
  333. });
  334. discoverLocation.query.field = fields;
  335. if (isMetricsData) {
  336. discoverLocation.query.fromMetric = 'true';
  337. }
  338. // Construct and return the discover url
  339. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  340. ...discoverLocation.query,
  341. })}`;
  342. return discoverPath;
  343. }
  344. export function getWidgetIssueUrl(
  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 issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  355. query: widget.queries?.[0]?.conditions,
  356. sort: widget.queries?.[0]?.orderby,
  357. ...datetime,
  358. project: selection.projects,
  359. environment: selection.environments,
  360. })}`;
  361. return issuesLocation;
  362. }
  363. export function getWidgetReleasesUrl(
  364. _widget: Widget,
  365. selection: PageFilters,
  366. organization: Organization
  367. ) {
  368. const {start, end, utc, period} = selection.datetime;
  369. const datetime =
  370. start && end
  371. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  372. : {statsPeriod: period};
  373. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  374. ...datetime,
  375. project: selection.projects,
  376. environment: selection.environments,
  377. })}`;
  378. return releasesLocation;
  379. }
  380. export function getWidgetMetricsUrl(
  381. _widget: Widget,
  382. selection: PageFilters,
  383. organization: Organization
  384. ) {
  385. const {start, end, utc, period} = selection.datetime;
  386. const datetime =
  387. start && end
  388. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  389. : {statsPeriod: period};
  390. // ensures that My Projects selection is properly handled
  391. const project = selection.projects.length ? selection.projects : [0];
  392. const metricsLocation = getMetricsUrl(organization.slug, {
  393. ...datetime,
  394. project,
  395. environment: selection.environments,
  396. widgets: _widget.queries.map(query => {
  397. const parsed = parseField(query.aggregates[0]);
  398. return {
  399. mri: parsed?.mri,
  400. aggregation: parsed?.aggregation,
  401. groupBy: query.columns,
  402. query: query.conditions ?? '',
  403. displayType: getMetricDisplayType(_widget.displayType),
  404. } satisfies Partial<MetricsWidget>;
  405. }),
  406. });
  407. return metricsLocation;
  408. }
  409. export function flattenErrors(
  410. data: ValidationError | string,
  411. update: FlatValidationError
  412. ): FlatValidationError {
  413. if (typeof data === 'string') {
  414. update.error = data;
  415. } else {
  416. Object.keys(data).forEach((key: string) => {
  417. const value = data[key];
  418. if (typeof value === 'string') {
  419. update[key] = value;
  420. return;
  421. }
  422. // Recurse into nested objects.
  423. if (Array.isArray(value) && typeof value[0] === 'string') {
  424. update[key] = value[0];
  425. return;
  426. }
  427. if (Array.isArray(value) && typeof value[0] === 'object') {
  428. (value as ValidationError[]).map(item => flattenErrors(item, update));
  429. } else {
  430. flattenErrors(value as ValidationError, update);
  431. }
  432. });
  433. }
  434. return update;
  435. }
  436. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  437. return isMEPEnabled
  438. ? {
  439. dataset: DiscoverDatasets.METRICS_ENHANCED,
  440. }
  441. : {};
  442. }
  443. export function getNumEquations(possibleEquations: string[]) {
  444. return possibleEquations.filter(isEquation).length;
  445. }
  446. const DEFINED_MEASUREMENTS = new Set(Object.keys(getMeasurements()));
  447. export function isCustomMeasurement(field: string) {
  448. return !DEFINED_MEASUREMENTS.has(field) && isMeasurement(field);
  449. }
  450. export function isCustomMeasurementWidget(widget: Widget) {
  451. return (
  452. widget.widgetType === WidgetType.DISCOVER &&
  453. widget.queries.some(({aggregates, columns, fields}) => {
  454. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  455. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  456. // but there aren't any custom measurement aggregates that use custom measurements
  457. // outside of the first arg.
  458. const aggregateArg = getAggregateArg(aggregate);
  459. if (aggregateArg) {
  460. acc.push(aggregateArg);
  461. }
  462. return acc;
  463. }, []);
  464. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  465. isCustomMeasurement(field)
  466. );
  467. })
  468. );
  469. }
  470. export function getCustomMeasurementQueryParams() {
  471. return {
  472. dataset: 'metrics',
  473. };
  474. }
  475. export function isWidgetUsingTransactionName(widget: Widget) {
  476. return (
  477. widget.widgetType === WidgetType.DISCOVER &&
  478. widget.queries.some(({aggregates, columns, fields, conditions}) => {
  479. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  480. const aggregateArg = getAggregateArg(aggregate);
  481. if (aggregateArg) {
  482. acc.push(aggregateArg);
  483. }
  484. return acc;
  485. }, []);
  486. const transactionSelected = [...aggregateArgs, ...columns, ...(fields ?? [])].some(
  487. field => field === 'transaction'
  488. );
  489. const transactionUsedInFilter = parseSearch(conditions)?.some(
  490. parsedCondition =>
  491. parsedCondition.type === Token.FILTER &&
  492. parsedCondition.key?.text === 'transaction'
  493. );
  494. return transactionSelected || transactionUsedInFilter;
  495. })
  496. );
  497. }
  498. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  499. return !(
  500. dashboard.projects &&
  501. dashboard.projects.length === 0 &&
  502. dashboard.environment === undefined &&
  503. dashboard.start === undefined &&
  504. dashboard.end === undefined &&
  505. dashboard.period === undefined
  506. );
  507. }
  508. export function hasUnsavedFilterChanges(
  509. initialDashboard: DashboardDetails,
  510. location: Location
  511. ) {
  512. // Use Sets to compare the filter fields that are arrays
  513. type Filters = {
  514. end?: string;
  515. environment?: Set<string>;
  516. period?: string;
  517. projects?: Set<number>;
  518. release?: Set<string>;
  519. start?: string;
  520. utc?: boolean;
  521. };
  522. const savedFilters: Filters = {
  523. projects: new Set(initialDashboard.projects),
  524. environment: new Set(initialDashboard.environment),
  525. period: initialDashboard.period,
  526. start: normalizeDateTimeString(initialDashboard.start),
  527. end: normalizeDateTimeString(initialDashboard.end),
  528. utc: initialDashboard.utc,
  529. };
  530. let currentFilters = {
  531. ...getCurrentPageFilters(location),
  532. } as unknown as Filters;
  533. currentFilters = {
  534. ...currentFilters,
  535. projects: new Set(currentFilters.projects),
  536. environment: new Set(currentFilters.environment),
  537. };
  538. if (defined(location.query?.release)) {
  539. // Release is only included in the comparison if it exists in the query
  540. // params, otherwise the dashboard should be using its saved state
  541. savedFilters.release = new Set(initialDashboard.filters?.release);
  542. currentFilters.release = new Set(location.query?.release);
  543. }
  544. return !isEqual(savedFilters, currentFilters);
  545. }
  546. export function getSavedFiltersAsPageFilters(dashboard: DashboardDetails): PageFilters {
  547. return {
  548. datetime: {
  549. end: dashboard.end || null,
  550. period: dashboard.period || null,
  551. start: dashboard.start || null,
  552. utc: null,
  553. },
  554. environments: dashboard.environment || [],
  555. projects: dashboard.projects || [],
  556. };
  557. }
  558. export function getSavedPageFilters(dashboard: DashboardDetails) {
  559. return {
  560. project: dashboard.projects,
  561. environment: dashboard.environment,
  562. statsPeriod: dashboard.period,
  563. start: normalizeDateTimeString(dashboard.start),
  564. end: normalizeDateTimeString(dashboard.end),
  565. utc: dashboard.utc,
  566. };
  567. }
  568. export function resetPageFilters(dashboard: DashboardDetails, location: Location) {
  569. browserHistory.replace({
  570. ...location,
  571. query: getSavedPageFilters(dashboard),
  572. });
  573. }
  574. export function getCurrentPageFilters(
  575. location: Location
  576. ): Pick<
  577. DashboardDetails,
  578. 'projects' | 'environment' | 'period' | 'start' | 'end' | 'utc'
  579. > {
  580. const {project, environment, statsPeriod, start, end, utc} = location.query ?? {};
  581. return {
  582. // Ensure projects and environment are sent as arrays, or undefined in the request
  583. // location.query will return a string if there's only one value
  584. projects:
  585. project === undefined || project === null
  586. ? []
  587. : typeof project === 'string'
  588. ? [Number(project)]
  589. : project.map(Number),
  590. environment:
  591. typeof environment === 'string' ? [environment] : environment ?? undefined,
  592. period: statsPeriod as string | undefined,
  593. start: defined(start) ? normalizeDateTimeString(start as string) : undefined,
  594. end: defined(end) ? normalizeDateTimeString(end as string) : undefined,
  595. utc: defined(utc) ? utc === 'true' : undefined,
  596. };
  597. }
  598. export function getDashboardFiltersFromURL(location: Location): DashboardFilters | null {
  599. const dashboardFilters: DashboardFilters = {};
  600. Object.values(DashboardFilterKeys).forEach(key => {
  601. if (defined(location.query?.[key])) {
  602. dashboardFilters[key] = decodeList(location.query?.[key]);
  603. }
  604. });
  605. return Object.keys(dashboardFilters).length > 0 ? dashboardFilters : null;
  606. }
  607. export function dashboardFiltersToString(
  608. dashboardFilters: DashboardFilters | null | undefined
  609. ): string {
  610. let dashboardFilterConditions = '';
  611. if (dashboardFilters) {
  612. for (const [key, activeFilters] of Object.entries(dashboardFilters)) {
  613. if (activeFilters.length === 1) {
  614. dashboardFilterConditions += `${key}:"${activeFilters[0]}" `;
  615. } else if (activeFilters.length > 1) {
  616. dashboardFilterConditions += `${key}:[${activeFilters
  617. .map(f => `"${f}"`)
  618. .join(',')}] `;
  619. }
  620. }
  621. }
  622. return dashboardFilterConditions;
  623. }
  624. export function connectDashboardCharts(groupName: string) {
  625. connect?.(groupName);
  626. }
  627. export function hasDatasetSelector(organization: Organization): boolean {
  628. return organization.features.includes('performance-discover-dataset-selector');
  629. }
  630. export function appendQueryDatasetParam(
  631. organization: Organization,
  632. queryDataset?: SavedQueryDatasets
  633. ) {
  634. if (hasDatasetSelector(organization) && queryDataset) {
  635. return {queryDataset: queryDataset};
  636. }
  637. return {};
  638. }