utils.tsx 22 KB

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