utils.tsx 22 KB

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