utils.tsx 25 KB

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