utils.tsx 23 KB

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