utils.tsx 21 KB

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