utils.tsx 24 KB

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