utils.tsx 25 KB

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