utils.tsx 21 KB

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