utils.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. import type {InjectedRouter} from 'react-router';
  2. import {urlEncode} from '@sentry/utils';
  3. import type {Location, Query} from 'history';
  4. import * as Papa from 'papaparse';
  5. import {openAddToDashboardModal} from 'sentry/actionCreators/modal';
  6. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  7. import {URL_PARAM} from 'sentry/constants/pageFilters';
  8. import {t} from 'sentry/locale';
  9. import type {SelectValue} from 'sentry/types/core';
  10. import type {Event} from 'sentry/types/event';
  11. import type {
  12. NewQuery,
  13. Organization,
  14. OrganizationSummary,
  15. } from 'sentry/types/organization';
  16. import type {Project} from 'sentry/types/project';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import {getUtcDateString} from 'sentry/utils/dates';
  19. import type {TableDataRow} from 'sentry/utils/discover/discoverQuery';
  20. import type {EventData} from 'sentry/utils/discover/eventView';
  21. import type EventView from 'sentry/utils/discover/eventView';
  22. import type {
  23. Aggregation,
  24. Column,
  25. ColumnType,
  26. ColumnValueType,
  27. Field,
  28. } from 'sentry/utils/discover/fields';
  29. import {
  30. aggregateFunctionOutputType,
  31. AGGREGATIONS,
  32. explodeFieldString,
  33. getAggregateAlias,
  34. getAggregateArg,
  35. getColumnsAndAggregates,
  36. getEquation,
  37. isAggregateEquation,
  38. isEquation,
  39. isMeasurement,
  40. isSpanOperationBreakdownField,
  41. measurementType,
  42. PROFILING_FIELDS,
  43. TRACING_FIELDS,
  44. } from 'sentry/utils/discover/fields';
  45. import {type DisplayModes, SavedQueryDatasets, TOP_N} from 'sentry/utils/discover/types';
  46. import {getTitle} from 'sentry/utils/events';
  47. import {DISCOVER_FIELDS, FieldValueType, getFieldDefinition} from 'sentry/utils/fields';
  48. import localStorage from 'sentry/utils/localStorage';
  49. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  50. import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
  51. import {
  52. DashboardWidgetSource,
  53. DisplayType,
  54. type WidgetQuery,
  55. WidgetType,
  56. } from '../dashboards/types';
  57. import {transactionSummaryRouteWithQuery} from '../performance/transactionSummary/utils';
  58. import {displayModeToDisplayType, getSavedQueryDataset} from './savedQuery/utils';
  59. import type {FieldValue, TableColumn} from './table/types';
  60. import {FieldValueKind} from './table/types';
  61. import {getAllViews, getTransactionViews, getWebVitalsViews} from './data';
  62. export type QueryWithColumnState =
  63. | Query
  64. | {
  65. field: string | string[] | null | undefined;
  66. sort: string | string[] | null | undefined;
  67. };
  68. const TEMPLATE_TABLE_COLUMN: TableColumn<string> = {
  69. key: '',
  70. name: '',
  71. type: 'never',
  72. isSortable: false,
  73. column: Object.freeze({kind: 'field', field: ''}),
  74. width: COL_WIDTH_UNDEFINED,
  75. };
  76. // TODO(mark) these types are coupled to the gridEditable component types and
  77. // I'd prefer the types to be more general purpose but that will require a second pass.
  78. export function decodeColumnOrder(fields: Readonly<Field[]>): TableColumn<string>[] {
  79. return fields.map((f: Field) => {
  80. const column: TableColumn<string> = {...TEMPLATE_TABLE_COLUMN};
  81. const col = explodeFieldString(f.field, f.alias);
  82. const columnName = f.field;
  83. if (isEquation(f.field)) {
  84. column.key = f.field;
  85. column.name = getEquation(columnName);
  86. column.type = 'number';
  87. } else {
  88. column.key = columnName;
  89. column.name = columnName;
  90. }
  91. column.width = f.width || COL_WIDTH_UNDEFINED;
  92. if (col.kind === 'function') {
  93. // Aggregations can have a strict outputType or they can inherit from their field.
  94. // Otherwise use the FIELDS data to infer types.
  95. const outputType = aggregateFunctionOutputType(col.function[0], col.function[1]);
  96. if (outputType !== null) {
  97. column.type = outputType;
  98. }
  99. const aggregate = AGGREGATIONS[col.function[0]];
  100. column.isSortable = aggregate?.isSortable;
  101. } else if (col.kind === 'field') {
  102. if (getFieldDefinition(col.field) !== null) {
  103. column.type = getFieldDefinition(col.field)?.valueType as ColumnValueType;
  104. } else if (isMeasurement(col.field)) {
  105. column.type = measurementType(col.field);
  106. } else if (isSpanOperationBreakdownField(col.field)) {
  107. column.type = 'duration';
  108. }
  109. }
  110. column.column = col;
  111. return column;
  112. });
  113. }
  114. export function pushEventViewToLocation(props: {
  115. location: Location;
  116. nextEventView: EventView;
  117. extraQuery?: Query;
  118. }) {
  119. const {location, nextEventView} = props;
  120. const extraQuery = props.extraQuery || {};
  121. const queryStringObject = nextEventView.generateQueryStringObject();
  122. browserHistory.push({
  123. ...location,
  124. query: {
  125. ...extraQuery,
  126. ...queryStringObject,
  127. },
  128. });
  129. }
  130. export function generateTitle({eventView, event}: {eventView: EventView; event?: Event}) {
  131. const titles = [t('Discover')];
  132. const eventViewName = eventView.name;
  133. if (typeof eventViewName === 'string' && String(eventViewName).trim().length > 0) {
  134. titles.push(String(eventViewName).trim());
  135. }
  136. const eventTitle = event ? getTitle(event).title : undefined;
  137. if (eventTitle) {
  138. titles.push(eventTitle);
  139. }
  140. titles.reverse();
  141. return titles.join(' — ');
  142. }
  143. export function getPrebuiltQueries(organization: Organization) {
  144. const views = [...getAllViews(organization)];
  145. if (organization.features.includes('performance-view')) {
  146. // insert transactions queries at index 2
  147. views.splice(2, 0, ...getTransactionViews(organization));
  148. views.push(...getWebVitalsViews(organization));
  149. }
  150. return views;
  151. }
  152. function disableMacros(value: string | null | boolean | number) {
  153. const unsafeCharacterRegex = /^[\=\+\-\@]/;
  154. if (typeof value === 'string' && `${value}`.match(unsafeCharacterRegex)) {
  155. return `'${value}`;
  156. }
  157. return value;
  158. }
  159. export function downloadAsCsv(tableData, columnOrder, filename) {
  160. const {data} = tableData;
  161. const headings = columnOrder.map(column => column.name);
  162. const keys = columnOrder.map(column => column.key);
  163. const csvContent = Papa.unparse({
  164. fields: headings,
  165. data: data.map(row =>
  166. keys.map(key => {
  167. return disableMacros(row[key]);
  168. })
  169. ),
  170. });
  171. // Need to also manually replace # since encodeURI skips them
  172. const encodedDataUrl = `data:text/csv;charset=utf8,${encodeURIComponent(csvContent)}`;
  173. // Create a download link then click it, this is so we can get a filename
  174. const link = document.createElement('a');
  175. const now = new Date();
  176. link.setAttribute('href', encodedDataUrl);
  177. link.setAttribute('download', `${filename} ${getUtcDateString(now)}.csv`);
  178. link.click();
  179. link.remove();
  180. // Make testing easier
  181. return encodedDataUrl;
  182. }
  183. const ALIASED_AGGREGATES_COLUMN = {
  184. last_seen: 'timestamp',
  185. failure_count: 'transaction.status',
  186. };
  187. /**
  188. * Convert an aggregate into the resulting column from a drilldown action.
  189. * The result is null if the drilldown results in the aggregate being removed.
  190. */
  191. function drilldownAggregate(
  192. func: Extract<Column, {kind: 'function'}>
  193. ): Extract<Column, {kind: 'field'}> | null {
  194. const key = func.function[0];
  195. const aggregation = AGGREGATIONS[key];
  196. let column = func.function[1];
  197. if (ALIASED_AGGREGATES_COLUMN.hasOwnProperty(key)) {
  198. // Some aggregates are just shortcuts to other aggregates with
  199. // predefined arguments so we can directly map them to the result.
  200. column = ALIASED_AGGREGATES_COLUMN[key];
  201. } else if (aggregation?.parameters?.[0]) {
  202. const parameter = aggregation.parameters[0];
  203. if (parameter.kind !== 'column') {
  204. // The aggregation does not accept a column as a parameter,
  205. // so we clear the column.
  206. column = '';
  207. } else if (!column && parameter.required === false) {
  208. // The parameter was not given for a non-required parameter,
  209. // so we fall back to the default.
  210. column = parameter.defaultValue;
  211. }
  212. } else {
  213. // The aggregation does not exist or does not have any parameters,
  214. // so we clear the column.
  215. column = '';
  216. }
  217. return column ? {kind: 'field', field: column} : null;
  218. }
  219. /**
  220. * Convert an aggregated query into one that does not have aggregates.
  221. * Will also apply additions conditions defined in `additionalConditions`
  222. * and generate conditions based on the `dataRow` parameter and the current fields
  223. * in the `eventView`.
  224. */
  225. export function getExpandedResults(
  226. eventView: EventView,
  227. additionalConditions: Record<string, string>,
  228. dataRow?: TableDataRow | Event
  229. ): EventView {
  230. const fieldSet = new Set();
  231. // Expand any functions in the resulting column, and dedupe the result.
  232. // Mark any column as null to remove it.
  233. const expandedColumns: (Column | null)[] = eventView.fields.map((field: Field) => {
  234. const exploded = explodeFieldString(field.field, field.alias);
  235. const column = exploded.kind === 'function' ? drilldownAggregate(exploded) : exploded;
  236. if (
  237. // if expanding the function failed
  238. column === null ||
  239. // the new column is already present
  240. fieldSet.has(column.field) ||
  241. // Skip aggregate equations, their functions will already be added so we just want to remove it
  242. isAggregateEquation(field.field)
  243. ) {
  244. return null;
  245. }
  246. fieldSet.add(column.field);
  247. return column;
  248. });
  249. // id should be default column when expanded results in no columns; but only if
  250. // the Discover query's columns is non-empty.
  251. // This typically occurs in Discover drilldowns.
  252. if (fieldSet.size === 0 && expandedColumns.length) {
  253. expandedColumns[0] = {kind: 'field', field: 'id'};
  254. }
  255. // update the columns according the expansion above
  256. const nextView = expandedColumns.reduceRight(
  257. (newView, column, index) =>
  258. column === null
  259. ? newView.withDeletedColumn(index, undefined)
  260. : newView.withUpdatedColumn(index, column, undefined),
  261. eventView.clone()
  262. );
  263. nextView.query = generateExpandedConditions(nextView, additionalConditions, dataRow);
  264. return nextView;
  265. }
  266. /**
  267. * Create additional conditions based on the fields in an EventView
  268. * and a datarow/event
  269. */
  270. function generateAdditionalConditions(
  271. eventView: EventView,
  272. dataRow?: TableDataRow | Event
  273. ): Record<string, string | string[]> {
  274. const specialKeys = Object.values(URL_PARAM);
  275. const conditions: Record<string, string | string[]> = {};
  276. if (!dataRow) {
  277. return conditions;
  278. }
  279. eventView.fields.forEach((field: Field) => {
  280. const column = explodeFieldString(field.field, field.alias);
  281. // Skip aggregate fields
  282. if (column.kind === 'function') {
  283. return;
  284. }
  285. const dataKey = getAggregateAlias(field.field);
  286. // Append the current field as a condition if it exists in the dataRow
  287. // Or is a simple key in the event. More complex deeply nested fields are
  288. // more challenging to get at as their location in the structure does not
  289. // match their name.
  290. if (dataRow.hasOwnProperty(dataKey)) {
  291. let value = dataRow[dataKey];
  292. if (Array.isArray(value)) {
  293. if (value.length > 1) {
  294. conditions[column.field] = value;
  295. return;
  296. }
  297. // An array with only one value is equivalent to the value itself.
  298. value = value[0];
  299. }
  300. // if the value will be quoted, then do not trim it as the whitespaces
  301. // may be important to the query and should not be trimmed
  302. const shouldQuote =
  303. value === null || value === undefined
  304. ? false
  305. : /[\s\(\)\\"]/g.test(String(value).trim());
  306. const nextValue =
  307. value === null || value === undefined
  308. ? ''
  309. : shouldQuote
  310. ? String(value)
  311. : String(value).trim();
  312. if (isMeasurement(column.field) && !nextValue) {
  313. // Do not add measurement conditions if nextValue is falsey.
  314. // It's expected that nextValue is a numeric value.
  315. return;
  316. }
  317. switch (column.field) {
  318. case 'timestamp':
  319. // normalize the "timestamp" field to ensure the payload works
  320. conditions[column.field] = getUtcDateString(nextValue);
  321. break;
  322. default:
  323. conditions[column.field] = nextValue;
  324. }
  325. }
  326. // If we have an event, check tags as well.
  327. if (dataRow.tags && Array.isArray(dataRow.tags)) {
  328. const tagIndex = dataRow.tags.findIndex(item => item.key === dataKey);
  329. if (tagIndex > -1) {
  330. const key = specialKeys.includes(column.field)
  331. ? `tags[${column.field}]`
  332. : column.field;
  333. const tagValue = dataRow.tags[tagIndex].value;
  334. conditions[key] = tagValue;
  335. }
  336. }
  337. });
  338. return conditions;
  339. }
  340. /**
  341. * Discover queries can query either Errors, Transactions or a combination
  342. * of the two datasets. This is a util to determine if the query will excusively
  343. * hit the Transactions dataset.
  344. */
  345. export function usesTransactionsDataset(eventView: EventView, yAxisValue: string[]) {
  346. let usesTransactions: boolean = false;
  347. const parsedQuery = new MutableSearch(eventView.query);
  348. for (let index = 0; index < yAxisValue.length; index++) {
  349. const yAxis = yAxisValue[index];
  350. const aggregateArg = getAggregateArg(yAxis) ?? '';
  351. if (isMeasurement(aggregateArg) || aggregateArg === 'transaction.duration') {
  352. usesTransactions = true;
  353. break;
  354. }
  355. const eventTypeFilter = parsedQuery.getFilterValues('event.type');
  356. if (
  357. eventTypeFilter.length > 0 &&
  358. eventTypeFilter.every(filter => filter === 'transaction')
  359. ) {
  360. usesTransactions = true;
  361. break;
  362. }
  363. }
  364. return usesTransactions;
  365. }
  366. function generateExpandedConditions(
  367. eventView: EventView,
  368. additionalConditions: Record<string, string>,
  369. dataRow?: TableDataRow | Event
  370. ): string {
  371. const parsedQuery = new MutableSearch(eventView.query);
  372. // Remove any aggregates from the search conditions.
  373. // otherwise, it'll lead to an invalid query result.
  374. for (const key in parsedQuery.filters) {
  375. const column = explodeFieldString(key);
  376. if (column.kind === 'function') {
  377. parsedQuery.removeFilter(key);
  378. }
  379. }
  380. const conditions: Record<string, string | string[]> = Object.assign(
  381. {},
  382. additionalConditions,
  383. generateAdditionalConditions(eventView, dataRow)
  384. );
  385. // Add additional conditions provided and generated.
  386. for (const key in conditions) {
  387. const value = conditions[key];
  388. if (Array.isArray(value)) {
  389. parsedQuery.setFilterValues(key, value);
  390. continue;
  391. }
  392. if (key === 'project.id') {
  393. eventView.project = [...eventView.project, parseInt(value, 10)];
  394. continue;
  395. }
  396. if (key === 'environment') {
  397. if (!eventView.environment.includes(value)) {
  398. eventView.environment = [...eventView.environment, value];
  399. }
  400. continue;
  401. }
  402. const column = explodeFieldString(key);
  403. // Skip aggregates as they will be invalid.
  404. if (column.kind === 'function') {
  405. continue;
  406. }
  407. parsedQuery.setFilterValues(key, [value]);
  408. }
  409. return parsedQuery.formatString();
  410. }
  411. type FieldGeneratorOpts = {
  412. organization: OrganizationSummary;
  413. aggregations?: Record<string, Aggregation>;
  414. customMeasurements?: {functions: string[]; key: string}[] | null;
  415. fieldKeys?: string[];
  416. measurementKeys?: string[] | null;
  417. spanOperationBreakdownKeys?: string[];
  418. tagKeys?: string[] | null;
  419. };
  420. export function generateFieldOptions({
  421. organization,
  422. tagKeys,
  423. measurementKeys,
  424. spanOperationBreakdownKeys,
  425. customMeasurements,
  426. aggregations = AGGREGATIONS,
  427. fieldKeys = DISCOVER_FIELDS,
  428. }: FieldGeneratorOpts) {
  429. let functions = Object.keys(aggregations);
  430. // Strip tracing features if the org doesn't have access.
  431. if (!organization.features.includes('performance-view')) {
  432. fieldKeys = fieldKeys.filter(item => !TRACING_FIELDS.includes(item));
  433. functions = functions.filter(item => !TRACING_FIELDS.includes(item));
  434. }
  435. // Strip profiling features if the org doesn't have access.
  436. if (!organization.features.includes('profiling')) {
  437. fieldKeys = fieldKeys.filter(item => !PROFILING_FIELDS.includes(item));
  438. }
  439. const fieldOptions: Record<string, SelectValue<FieldValue>> = {};
  440. // Index items by prefixed keys as custom tags can overlap both fields and
  441. // function names. Having a mapping makes finding the value objects easier
  442. // later as well.
  443. functions.forEach(func => {
  444. const ellipsis = aggregations[func].parameters.length ? '\u2026' : '';
  445. const parameters = aggregations[func].parameters.map(param => {
  446. const overrides = AGGREGATIONS[func].getFieldOverrides;
  447. if (typeof overrides === 'undefined') {
  448. return param;
  449. }
  450. return {
  451. ...param,
  452. ...overrides({parameter: param}),
  453. };
  454. });
  455. fieldOptions[`function:${func}`] = {
  456. label: `${func}(${ellipsis})`,
  457. value: {
  458. kind: FieldValueKind.FUNCTION,
  459. meta: {
  460. name: func,
  461. parameters,
  462. },
  463. },
  464. };
  465. });
  466. fieldKeys.forEach(field => {
  467. fieldOptions[`field:${field}`] = {
  468. label: field,
  469. value: {
  470. kind: FieldValueKind.FIELD,
  471. meta: {
  472. name: field,
  473. dataType: (getFieldDefinition(field)?.valueType ??
  474. FieldValueType.STRING) as ColumnType,
  475. },
  476. },
  477. };
  478. });
  479. if (measurementKeys !== undefined && measurementKeys !== null) {
  480. measurementKeys.sort();
  481. measurementKeys.forEach(measurement => {
  482. fieldOptions[`measurement:${measurement}`] = {
  483. label: measurement,
  484. value: {
  485. kind: FieldValueKind.MEASUREMENT,
  486. meta: {name: measurement, dataType: measurementType(measurement)},
  487. },
  488. };
  489. });
  490. }
  491. if (customMeasurements !== undefined && customMeasurements !== null) {
  492. customMeasurements.sort(({key: currentKey}, {key: nextKey}) =>
  493. currentKey > nextKey ? 1 : currentKey === nextKey ? 0 : -1
  494. );
  495. customMeasurements.forEach(({key, functions: supportedFunctions}) => {
  496. fieldOptions[`measurement:${key}`] = {
  497. label: key,
  498. value: {
  499. kind: FieldValueKind.CUSTOM_MEASUREMENT,
  500. meta: {
  501. name: key,
  502. dataType: measurementType(key),
  503. functions: supportedFunctions,
  504. },
  505. },
  506. };
  507. });
  508. }
  509. if (Array.isArray(spanOperationBreakdownKeys)) {
  510. spanOperationBreakdownKeys.sort();
  511. spanOperationBreakdownKeys.forEach(breakdownField => {
  512. fieldOptions[`span_op_breakdown:${breakdownField}`] = {
  513. label: breakdownField,
  514. value: {
  515. kind: FieldValueKind.BREAKDOWN,
  516. meta: {name: breakdownField, dataType: 'duration'},
  517. },
  518. };
  519. });
  520. }
  521. if (tagKeys !== undefined && tagKeys !== null) {
  522. tagKeys.sort();
  523. tagKeys.forEach(tag => {
  524. const tagValue =
  525. fieldKeys.includes(tag) || AGGREGATIONS.hasOwnProperty(tag)
  526. ? `tags[${tag}]`
  527. : tag;
  528. fieldOptions[`tag:${tag}`] = {
  529. label: tag,
  530. value: {
  531. kind: FieldValueKind.TAG,
  532. meta: {name: tagValue, dataType: 'string'},
  533. },
  534. };
  535. });
  536. }
  537. return fieldOptions;
  538. }
  539. const RENDER_PREBUILT_KEY = 'discover-render-prebuilt';
  540. export function shouldRenderPrebuilt(): boolean {
  541. const shouldRender = localStorage.getItem(RENDER_PREBUILT_KEY);
  542. return shouldRender === 'true' || shouldRender === null;
  543. }
  544. export function setRenderPrebuilt(value: boolean) {
  545. localStorage.setItem(RENDER_PREBUILT_KEY, value ? 'true' : 'false');
  546. }
  547. export function eventViewToWidgetQuery({
  548. eventView,
  549. yAxis,
  550. displayType,
  551. }: {
  552. displayType: DisplayType;
  553. eventView: EventView;
  554. yAxis?: string | string[];
  555. }) {
  556. const fields = eventView.fields.map(({field}) => field);
  557. const {columns, aggregates} = getColumnsAndAggregates(fields);
  558. const sort = eventView.sorts[0];
  559. const queryYAxis = typeof yAxis === 'string' ? [yAxis] : yAxis ?? ['count()'];
  560. let orderby = '';
  561. // The orderby should only be set to sort.field if it is a Top N query
  562. // since the query uses all of the fields, or if the ordering is used in the y-axis
  563. if (sort) {
  564. let orderbyFunction = '';
  565. const aggregateFields = [...queryYAxis, ...aggregates];
  566. for (let i = 0; i < aggregateFields.length; i++) {
  567. if (sort.field === getAggregateAlias(aggregateFields[i])) {
  568. orderbyFunction = aggregateFields[i];
  569. break;
  570. }
  571. }
  572. const bareOrderby = orderbyFunction === '' ? sort.field : orderbyFunction;
  573. if (displayType === DisplayType.TOP_N || bareOrderby) {
  574. orderby = `${sort.kind === 'desc' ? '-' : ''}${bareOrderby}`;
  575. }
  576. }
  577. let newAggregates = aggregates;
  578. if (displayType !== DisplayType.TABLE) {
  579. newAggregates = queryYAxis;
  580. }
  581. const widgetQuery: WidgetQuery = {
  582. name: '',
  583. aggregates: newAggregates,
  584. columns: [...(displayType === DisplayType.TOP_N ? columns : [])],
  585. fields: [...(displayType === DisplayType.TOP_N ? fields : []), ...queryYAxis],
  586. conditions: eventView.query,
  587. orderby,
  588. };
  589. return widgetQuery;
  590. }
  591. export function handleAddQueryToDashboard({
  592. eventView,
  593. location,
  594. query,
  595. organization,
  596. router,
  597. yAxis,
  598. }: {
  599. eventView: EventView;
  600. location: Location;
  601. organization: Organization;
  602. router: InjectedRouter;
  603. query?: NewQuery;
  604. yAxis?: string | string[];
  605. }) {
  606. const displayType = displayModeToDisplayType(eventView.display as DisplayModes);
  607. const defaultWidgetQuery = eventViewToWidgetQuery({
  608. eventView,
  609. displayType,
  610. yAxis,
  611. });
  612. const dataset = getSavedQueryDataset(organization, location, query);
  613. const {query: widgetAsQueryParams} = constructAddQueryToDashboardLink({
  614. eventView,
  615. query,
  616. organization,
  617. yAxis,
  618. location,
  619. });
  620. openAddToDashboardModal({
  621. organization,
  622. selection: {
  623. projects: eventView.project,
  624. environments: eventView.environment,
  625. datetime: {
  626. start: eventView.start,
  627. end: eventView.end,
  628. period: eventView.statsPeriod,
  629. utc: eventView.utc,
  630. },
  631. },
  632. widget: {
  633. title: query?.name ?? eventView.name,
  634. displayType: displayType === DisplayType.TOP_N ? DisplayType.AREA : displayType,
  635. queries: [
  636. {
  637. ...defaultWidgetQuery,
  638. aggregates: [...(typeof yAxis === 'string' ? [yAxis] : yAxis ?? ['count()'])],
  639. },
  640. ],
  641. interval: eventView.interval,
  642. limit:
  643. displayType === DisplayType.TOP_N
  644. ? Number(eventView.topEvents) || TOP_N
  645. : undefined,
  646. widgetType: hasDatasetSelector(organization)
  647. ? SAVED_QUERY_DATASET_TO_WIDGET_TYPE[dataset]
  648. : undefined,
  649. },
  650. router,
  651. widgetAsQueryParams,
  652. location,
  653. });
  654. return;
  655. }
  656. export function getTargetForTransactionSummaryLink(
  657. dataRow: EventData,
  658. organization: Organization,
  659. projects?: Project[],
  660. nextView?: EventView,
  661. location?: Location
  662. ) {
  663. let projectID: string | string[] | undefined;
  664. const filterProjects = location?.query.project;
  665. if (typeof filterProjects === 'string' && filterProjects !== '-1') {
  666. // Project selector in discover has just one selected project
  667. projectID = filterProjects;
  668. } else {
  669. const projectMatch = projects?.find(
  670. project =>
  671. project.slug && [dataRow['project.name'], dataRow.project].includes(project.slug)
  672. );
  673. projectID = projectMatch ? [projectMatch.id] : undefined;
  674. }
  675. const target = transactionSummaryRouteWithQuery({
  676. orgSlug: organization.slug,
  677. transaction: String(dataRow.transaction),
  678. projectID,
  679. query: nextView?.getPageFiltersQuery() || {},
  680. });
  681. // Pass on discover filter params when there are multiple
  682. // projects associated with the transaction
  683. if (!projectID && filterProjects) {
  684. target.query.project = filterProjects;
  685. }
  686. return target;
  687. }
  688. export function constructAddQueryToDashboardLink({
  689. eventView,
  690. query,
  691. organization,
  692. yAxis,
  693. location,
  694. }: {
  695. eventView: EventView;
  696. organization: Organization;
  697. location?: Location;
  698. query?: NewQuery;
  699. yAxis?: string | string[];
  700. }) {
  701. const displayType = displayModeToDisplayType(eventView.display as DisplayModes);
  702. const defaultTableFields = eventView.fields.map(({field}) => field);
  703. const defaultWidgetQuery = eventViewToWidgetQuery({
  704. eventView,
  705. displayType,
  706. yAxis,
  707. });
  708. const dataset = getSavedQueryDataset(organization, location, query);
  709. const defaultTitle =
  710. query?.name ?? (eventView.name !== 'All Events' ? eventView.name : undefined);
  711. return {
  712. pathname: `/organizations/${organization.slug}/dashboards/new/widget/new/`,
  713. query: {
  714. ...location?.query,
  715. source: DashboardWidgetSource.DISCOVERV2,
  716. start: eventView.start,
  717. end: eventView.end,
  718. statsPeriod: eventView.statsPeriod,
  719. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  720. defaultTableColumns: defaultTableFields,
  721. defaultTitle,
  722. displayType: displayType === DisplayType.TOP_N ? DisplayType.AREA : displayType,
  723. dataset: hasDatasetSelector(organization)
  724. ? SAVED_QUERY_DATASET_TO_WIDGET_TYPE[dataset]
  725. : undefined,
  726. limit:
  727. displayType === DisplayType.TOP_N
  728. ? Number(eventView.topEvents) || TOP_N
  729. : undefined,
  730. },
  731. };
  732. }
  733. export const SAVED_QUERY_DATASET_TO_WIDGET_TYPE = {
  734. [SavedQueryDatasets.ERRORS]: WidgetType.ERRORS,
  735. [SavedQueryDatasets.TRANSACTIONS]: WidgetType.TRANSACTIONS,
  736. };