eventView.tsx 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. import type {Location, Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isEqual from 'lodash/isEqual';
  4. import omit from 'lodash/omit';
  5. import pick from 'lodash/pick';
  6. import uniqBy from 'lodash/uniqBy';
  7. import moment from 'moment';
  8. import type {EventQuery} from 'sentry/actionCreators/events';
  9. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  10. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  11. import {DEFAULT_PER_PAGE} from 'sentry/constants';
  12. import {ALL_ACCESS_PROJECTS, URL_PARAM} from 'sentry/constants/pageFilters';
  13. import {t} from 'sentry/locale';
  14. import type {
  15. NewQuery,
  16. PageFilters,
  17. Project,
  18. SavedQuery,
  19. SelectValue,
  20. User,
  21. } from 'sentry/types';
  22. import type {Column, ColumnType, Field, Sort} from 'sentry/utils/discover/fields';
  23. import {
  24. aggregateOutputType,
  25. generateFieldAsString,
  26. getAggregateAlias,
  27. getEquation,
  28. isAggregateEquation,
  29. isAggregateField,
  30. isEquation,
  31. isLegalYAxisType,
  32. } from 'sentry/utils/discover/fields';
  33. import {
  34. CHART_AXIS_OPTIONS,
  35. DiscoverDatasets,
  36. DISPLAY_MODE_FALLBACK_OPTIONS,
  37. DISPLAY_MODE_OPTIONS,
  38. DisplayModes,
  39. TOP_N,
  40. } from 'sentry/utils/discover/types';
  41. import {decodeList, decodeScalar, decodeSorts} from 'sentry/utils/queryString';
  42. import toArray from 'sentry/utils/toArray';
  43. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  44. import type {TableColumn, TableColumnSort} from 'sentry/views/discover/table/types';
  45. import {FieldValueKind} from 'sentry/views/discover/table/types';
  46. import {decodeColumnOrder} from 'sentry/views/discover/utils';
  47. import type {SpanOperationBreakdownFilter} from 'sentry/views/performance/transactionSummary/filter';
  48. import type {EventsDisplayFilterName} from 'sentry/views/performance/transactionSummary/transactionEvents/utils';
  49. import {statsPeriodToDays} from '../dates';
  50. import type {WebVital} from '../fields';
  51. import {MutableSearch} from '../tokenizeSearch';
  52. import {getSortField} from './fieldRenderers';
  53. // Metadata mapping for discover results.
  54. export type MetaType = Record<string, any> & {
  55. isMetricsData?: boolean;
  56. isMetricsExtractedData?: boolean;
  57. tips?: {columns: string; query: string};
  58. units?: Record<string, string>;
  59. };
  60. export type EventsMetaType = {fields: Record<string, ColumnType>} & {
  61. units: Record<string, string>;
  62. } & {
  63. isMetricsData?: boolean;
  64. isMetricsExtractedData?: boolean;
  65. };
  66. // Data in discover results.
  67. export type EventData = Record<string, any>;
  68. export type LocationQuery = {
  69. cursor?: string | string[] | null;
  70. end?: string | string[] | null;
  71. start?: string | string[] | null;
  72. statsPeriod?: string | string[] | null;
  73. utc?: string | string[] | null;
  74. };
  75. const DATETIME_QUERY_STRING_KEYS = ['start', 'end', 'utc', 'statsPeriod'] as const;
  76. const EXTERNAL_QUERY_STRING_KEYS: Readonly<Array<keyof LocationQuery>> = [
  77. ...DATETIME_QUERY_STRING_KEYS,
  78. 'cursor',
  79. ];
  80. const setSortOrder = (sort: Sort, kind: 'desc' | 'asc'): Sort => ({
  81. kind,
  82. field: sort.field,
  83. });
  84. const reverseSort = (sort: Sort): Sort => ({
  85. kind: sort.kind === 'desc' ? 'asc' : 'desc',
  86. field: sort.field,
  87. });
  88. const isSortEqualToField = (
  89. sort: Sort,
  90. field: Field,
  91. tableMeta: MetaType | undefined
  92. ): boolean => {
  93. const sortKey = getSortKeyFromField(field, tableMeta);
  94. return sort.field === sortKey;
  95. };
  96. const fieldToSort = (
  97. field: Field,
  98. tableMeta: MetaType | undefined,
  99. kind?: 'desc' | 'asc',
  100. useFunctionFormat?: boolean
  101. ): Sort | undefined => {
  102. const sortKey = getSortKeyFromField(field, tableMeta, useFunctionFormat);
  103. if (!sortKey) {
  104. return void 0;
  105. }
  106. return {
  107. kind: kind || 'desc',
  108. field: sortKey,
  109. };
  110. };
  111. function getSortKeyFromField(
  112. field: Field,
  113. tableMeta?: MetaType,
  114. useFunctionFormat?: boolean
  115. ): string | null {
  116. const fieldString = useFunctionFormat ? field.field : getAggregateAlias(field.field);
  117. return getSortField(fieldString, tableMeta);
  118. }
  119. export function isFieldSortable(
  120. field: Field,
  121. tableMeta?: MetaType,
  122. useFunctionFormat?: boolean
  123. ): boolean {
  124. return !!getSortKeyFromField(field, tableMeta, useFunctionFormat);
  125. }
  126. const decodeFields = (location: Location): Array<Field> => {
  127. const {query} = location;
  128. if (!query || !query.field) {
  129. return [];
  130. }
  131. const fields = decodeList(query.field);
  132. const widths = decodeList(query.widths);
  133. const parsed: Field[] = [];
  134. fields.forEach((field, i) => {
  135. const w = Number(widths[i]);
  136. const width = !isNaN(w) ? w : COL_WIDTH_UNDEFINED;
  137. parsed.push({field, width});
  138. });
  139. return parsed;
  140. };
  141. export const encodeSort = (sort: Sort): string => {
  142. switch (sort.kind) {
  143. case 'desc': {
  144. return `-${sort.field}`;
  145. }
  146. case 'asc': {
  147. return String(sort.field);
  148. }
  149. default: {
  150. throw new Error('Unexpected sort type');
  151. }
  152. }
  153. };
  154. const encodeSorts = (sorts: Readonly<Array<Sort>>): Array<string> =>
  155. sorts.map(encodeSort);
  156. const collectQueryStringByKey = (query: Query, key: string): Array<string> => {
  157. const needle = query[key];
  158. const collection = decodeList(needle);
  159. return collection.reduce((acc: Array<string>, item: string) => {
  160. item = item.trim();
  161. if (item.length > 0) {
  162. acc.push(item);
  163. }
  164. return acc;
  165. }, []);
  166. };
  167. const decodeQuery = (location: Location): string => {
  168. if (!location.query || !location.query.query) {
  169. return '';
  170. }
  171. const queryParameter = location.query.query;
  172. return decodeScalar(queryParameter, '').trim();
  173. };
  174. const decodeTeam = (value: string): 'myteams' | number => {
  175. if (value === 'myteams') {
  176. return value;
  177. }
  178. return parseInt(value, 10);
  179. };
  180. const decodeTeams = (location: Location): ('myteams' | number)[] => {
  181. if (!location.query || !location.query.team) {
  182. return [];
  183. }
  184. const value = location.query.team;
  185. return toArray(value)
  186. .map(decodeTeam)
  187. .filter(team => team === 'myteams' || !isNaN(team));
  188. };
  189. const decodeProjects = (location: Location): number[] => {
  190. if (!location.query || !location.query.project) {
  191. return [];
  192. }
  193. const value = location.query.project;
  194. return toArray(value).map(i => parseInt(i, 10));
  195. };
  196. const queryStringFromSavedQuery = (saved: NewQuery | SavedQuery): string => {
  197. if (saved.query) {
  198. return saved.query || '';
  199. }
  200. return '';
  201. };
  202. function validateTableMeta(tableMeta: MetaType | undefined): MetaType | undefined {
  203. return tableMeta && Object.keys(tableMeta).length > 0 ? tableMeta : undefined;
  204. }
  205. export type EventViewOptions = {
  206. createdBy: User | undefined;
  207. display: string | undefined;
  208. end: string | undefined;
  209. environment: Readonly<string[]>;
  210. fields: Readonly<Field[]>;
  211. id: string | undefined;
  212. name: string | undefined;
  213. project: Readonly<number[]>;
  214. query: string;
  215. sorts: Readonly<Sort[]>;
  216. start: string | undefined;
  217. statsPeriod: string | undefined;
  218. team: Readonly<('myteams' | number)[]>;
  219. topEvents: string | undefined;
  220. additionalConditions?: MutableSearch;
  221. dataset?: DiscoverDatasets;
  222. expired?: boolean;
  223. interval?: string;
  224. utc?: string | boolean | undefined;
  225. yAxis?: string | string[] | undefined;
  226. };
  227. class EventView {
  228. id: string | undefined;
  229. name: string | undefined;
  230. fields: Readonly<Field[]>;
  231. sorts: Readonly<Sort[]>;
  232. query: string;
  233. team: Readonly<('myteams' | number)[]>;
  234. project: Readonly<number[]>;
  235. start: string | undefined;
  236. end: string | undefined;
  237. statsPeriod: string | undefined;
  238. utc?: string | boolean | undefined;
  239. environment: Readonly<string[]>;
  240. yAxis: string | string[] | undefined;
  241. display: string | undefined;
  242. topEvents: string | undefined;
  243. interval: string | undefined;
  244. expired?: boolean;
  245. createdBy: User | undefined;
  246. additionalConditions: MutableSearch; // This allows views to always add additional conditions to the query to get specific data. It should not show up in the UI unless explicitly called.
  247. dataset?: DiscoverDatasets;
  248. constructor(props: EventViewOptions) {
  249. const fields: Field[] = Array.isArray(props.fields) ? props.fields : [];
  250. let sorts: Sort[] = Array.isArray(props.sorts) ? props.sorts : [];
  251. const team = Array.isArray(props.team) ? props.team : [];
  252. const project = Array.isArray(props.project) ? props.project : [];
  253. const environment = Array.isArray(props.environment) ? props.environment : [];
  254. // only include sort keys that are included in the fields
  255. let equations = 0;
  256. const sortKeys: string[] = [];
  257. fields.forEach(field => {
  258. if (field.field && isEquation(field.field)) {
  259. const sortKey = getSortKeyFromField({field: `equation[${equations}]`}, undefined);
  260. equations += 1;
  261. if (sortKey) {
  262. sortKeys.push(sortKey);
  263. }
  264. }
  265. const sortKey = getSortKeyFromField(field, undefined);
  266. if (sortKey) {
  267. sortKeys.push(sortKey);
  268. }
  269. });
  270. const sort = sorts.find(currentSort => sortKeys.includes(currentSort.field));
  271. sorts = sort ? [sort] : [];
  272. const id = props.id !== null && props.id !== void 0 ? String(props.id) : void 0;
  273. this.id = id;
  274. this.name = props.name;
  275. this.fields = fields;
  276. this.sorts = sorts;
  277. this.query = typeof props.query === 'string' ? props.query : '';
  278. this.team = team;
  279. this.project = project;
  280. this.start = props.start;
  281. this.end = props.end;
  282. this.statsPeriod = props.statsPeriod;
  283. this.utc = props.utc;
  284. this.environment = environment;
  285. this.yAxis = props.yAxis;
  286. this.dataset = props.dataset;
  287. this.display = props.display;
  288. this.topEvents = props.topEvents;
  289. this.interval = props.interval;
  290. this.createdBy = props.createdBy;
  291. this.expired = props.expired;
  292. this.additionalConditions = props.additionalConditions
  293. ? props.additionalConditions.copy()
  294. : new MutableSearch([]);
  295. }
  296. static fromLocation(location: Location): EventView {
  297. const {start, end, statsPeriod} = normalizeDateTimeParams(location.query);
  298. return new EventView({
  299. id: decodeScalar(location.query.id),
  300. name: decodeScalar(location.query.name),
  301. fields: decodeFields(location),
  302. sorts: decodeSorts(location.query.sort),
  303. query: decodeQuery(location),
  304. team: decodeTeams(location),
  305. project: decodeProjects(location),
  306. start: decodeScalar(start),
  307. end: decodeScalar(end),
  308. statsPeriod: decodeScalar(statsPeriod),
  309. environment: collectQueryStringByKey(location.query, 'environment'),
  310. yAxis: decodeScalar(location.query.yAxis),
  311. display: decodeScalar(location.query.display),
  312. topEvents: decodeScalar(location.query.topEvents),
  313. interval: decodeScalar(location.query.interval),
  314. createdBy: undefined,
  315. additionalConditions: new MutableSearch([]),
  316. dataset: decodeScalar(location.query.dataset) as DiscoverDatasets,
  317. });
  318. }
  319. static fromNewQueryWithLocation(newQuery: NewQuery, location: Location): EventView {
  320. const query = location.query;
  321. // apply global selection header values from location whenever possible
  322. const environment: string[] =
  323. Array.isArray(newQuery.environment) && newQuery.environment.length > 0
  324. ? newQuery.environment
  325. : collectQueryStringByKey(query, 'environment');
  326. const project: number[] =
  327. Array.isArray(newQuery.projects) && newQuery.projects.length > 0
  328. ? newQuery.projects
  329. : decodeProjects(location);
  330. const saved: NewQuery = {
  331. ...newQuery,
  332. environment,
  333. projects: project,
  334. // datetime selection
  335. start: newQuery.start || decodeScalar(query.start),
  336. end: newQuery.end || decodeScalar(query.end),
  337. range: newQuery.range || decodeScalar(query.statsPeriod),
  338. };
  339. return EventView.fromSavedQuery(saved);
  340. }
  341. static fromNewQueryWithPageFilters(newQuery: NewQuery, pageFilters: PageFilters) {
  342. return EventView.fromSavedQuery({
  343. ...newQuery,
  344. environment: newQuery.environment ?? pageFilters.environments,
  345. projects: newQuery.projects ?? pageFilters.projects,
  346. start: newQuery.start ?? pageFilters.datetime.start ?? undefined,
  347. end: newQuery.end ?? pageFilters.datetime.end ?? undefined,
  348. range: newQuery.range ?? pageFilters.datetime.period ?? undefined,
  349. utc: newQuery.utc ?? pageFilters.datetime.utc ?? undefined,
  350. });
  351. }
  352. static getFields(saved: NewQuery | SavedQuery) {
  353. return saved.fields.map((field, i) => {
  354. const width = saved.widths?.[i] ? Number(saved.widths[i]) : COL_WIDTH_UNDEFINED;
  355. return {field, width};
  356. });
  357. }
  358. static fromSavedQuery(saved: NewQuery | SavedQuery): EventView {
  359. const fields = EventView.getFields(saved);
  360. // normalize datetime selection
  361. const {start, end, statsPeriod, utc} = normalizeDateTimeParams({
  362. start: saved.start,
  363. end: saved.end,
  364. statsPeriod: saved.range,
  365. utc: saved.utc,
  366. });
  367. return new EventView({
  368. id: saved.id,
  369. name: saved.name,
  370. fields,
  371. query: queryStringFromSavedQuery(saved),
  372. team: saved.teams ?? [],
  373. project: saved.projects ?? [],
  374. start: decodeScalar(start),
  375. end: decodeScalar(end),
  376. statsPeriod: decodeScalar(statsPeriod),
  377. utc,
  378. sorts: decodeSorts(saved.orderby),
  379. environment: collectQueryStringByKey(
  380. {
  381. environment: saved.environment as string[],
  382. },
  383. 'environment'
  384. ),
  385. yAxis:
  386. Array.isArray(saved.yAxis) && saved.yAxis.length === 1
  387. ? saved.yAxis[0]
  388. : saved.yAxis,
  389. display: saved.display,
  390. topEvents: saved.topEvents ? saved.topEvents.toString() : undefined,
  391. interval: saved.interval,
  392. createdBy: saved.createdBy,
  393. expired: saved.expired,
  394. additionalConditions: new MutableSearch([]),
  395. dataset: saved.dataset,
  396. });
  397. }
  398. static fromSavedQueryOrLocation(
  399. saved: SavedQuery | undefined,
  400. location: Location
  401. ): EventView {
  402. let fields = decodeFields(location);
  403. const id = decodeScalar(location.query.id);
  404. const teams = decodeTeams(location);
  405. const projects = decodeProjects(location);
  406. const sorts = decodeSorts(location.query.sort);
  407. const environments = collectQueryStringByKey(location.query, 'environment');
  408. if (saved) {
  409. if (fields.length === 0) {
  410. fields = EventView.getFields(saved);
  411. }
  412. const {start, end, statsPeriod, utc} = normalizeDateTimeParams(
  413. location.query.start ||
  414. location.query.end ||
  415. location.query.statsPeriod ||
  416. location.query.utc
  417. ? location.query
  418. : {
  419. start: saved.start,
  420. end: saved.end,
  421. statsPeriod: saved.range,
  422. utc: saved.utc,
  423. }
  424. );
  425. return new EventView({
  426. id: id || saved.id,
  427. name: decodeScalar(location.query.name) || saved.name,
  428. fields,
  429. query:
  430. 'query' in location.query
  431. ? decodeQuery(location)
  432. : queryStringFromSavedQuery(saved),
  433. sorts: sorts.length === 0 ? decodeSorts(saved.orderby) : sorts,
  434. yAxis:
  435. decodeScalar(location.query.yAxis) ||
  436. // Workaround to only use the first yAxis since eventView yAxis doesn't accept string[]
  437. (Array.isArray(saved.yAxis) ? saved.yAxis[0] : saved.yAxis),
  438. display: decodeScalar(location.query.display) || saved.display,
  439. topEvents: (
  440. decodeScalar(location.query.topEvents) ||
  441. saved.topEvents ||
  442. TOP_N
  443. ).toString(),
  444. interval: decodeScalar(location.query.interval) || saved.interval,
  445. createdBy: saved.createdBy,
  446. expired: saved.expired,
  447. additionalConditions: new MutableSearch([]),
  448. // Always read team from location since they can be set by other parts
  449. // of the UI
  450. team: teams,
  451. // Always read project and environment from location since they can
  452. // be set by the GlobalSelectionHeaders.
  453. project: projects,
  454. environment: environments,
  455. start: decodeScalar(start),
  456. end: decodeScalar(end),
  457. statsPeriod: decodeScalar(statsPeriod),
  458. utc,
  459. dataset:
  460. (decodeScalar(location.query.dataset) as DiscoverDatasets) ?? saved.dataset,
  461. });
  462. }
  463. return EventView.fromLocation(location);
  464. }
  465. isEqualTo(other: EventView, omitList: string[] = []): boolean {
  466. const defaults = {
  467. id: undefined,
  468. name: undefined,
  469. query: undefined,
  470. statsPeriod: undefined,
  471. fields: undefined,
  472. sorts: undefined,
  473. project: undefined,
  474. environment: undefined,
  475. interval: undefined,
  476. yAxis: 'count()',
  477. display: DisplayModes.DEFAULT,
  478. topEvents: '5',
  479. dataset: DiscoverDatasets.DISCOVER,
  480. };
  481. const keys = Object.keys(defaults).filter(key => !omitList.includes(key));
  482. for (const key of keys) {
  483. const currentValue = this[key] ?? defaults[key];
  484. const otherValue = other[key] ?? defaults[key];
  485. if (!isEqual(currentValue, otherValue)) {
  486. return false;
  487. }
  488. }
  489. // compare datetime selections using moment
  490. const dateTimeKeys = ['start', 'end'];
  491. for (const key of dateTimeKeys) {
  492. const currentValue = this[key];
  493. const otherValue = other[key];
  494. if (currentValue && otherValue) {
  495. const currentDateTime = moment.utc(currentValue);
  496. const otherDateTime = moment.utc(otherValue);
  497. if (!currentDateTime.isSame(otherDateTime)) {
  498. return false;
  499. }
  500. }
  501. }
  502. return true;
  503. }
  504. toNewQuery(): NewQuery {
  505. const orderby = this.sorts.length > 0 ? encodeSorts(this.sorts)[0] : undefined;
  506. const newQuery: NewQuery = {
  507. version: 2,
  508. id: this.id,
  509. name: this.name || '',
  510. fields: this.getFields(),
  511. widths: this.getWidths().map(w => String(w)),
  512. orderby,
  513. query: this.query || '',
  514. projects: this.project,
  515. start: this.start,
  516. end: this.end,
  517. range: this.statsPeriod,
  518. environment: this.environment,
  519. yAxis: typeof this.yAxis === 'string' ? [this.yAxis] : this.yAxis,
  520. dataset: this.dataset,
  521. display: this.display,
  522. topEvents: this.topEvents,
  523. interval: this.interval,
  524. };
  525. if (!newQuery.query) {
  526. // if query is an empty string, then it cannot be saved, so we omit it
  527. // from the payload
  528. delete newQuery.query;
  529. }
  530. return newQuery;
  531. }
  532. getPageFilters(): PageFilters {
  533. return {
  534. projects: this.project as number[],
  535. environments: this.environment as string[],
  536. datetime: {
  537. start: this.start ?? null,
  538. end: this.end ?? null,
  539. period: this.statsPeriod ?? null,
  540. // TODO(tony) Add support for the Use UTC option from the global
  541. // headers, currently, that option is not supported and all times are
  542. // assumed to be UTC
  543. utc: true,
  544. },
  545. };
  546. }
  547. getPageFiltersQuery(): Query {
  548. const {
  549. environments: environment,
  550. projects,
  551. datetime: {start, end, period, utc},
  552. } = this.getPageFilters();
  553. return {
  554. project: projects.map(proj => proj.toString()),
  555. environment,
  556. utc: utc ? 'true' : 'false',
  557. // since these values are from `getGlobalSelection`
  558. // we know they have type `string | null`
  559. start: (start ?? undefined) as string | undefined,
  560. end: (end ?? undefined) as string | undefined,
  561. // we can't use the ?? operator here as we want to
  562. // convert the empty string to undefined
  563. statsPeriod: period ? period : undefined,
  564. };
  565. }
  566. generateBlankQueryStringObject(): Query {
  567. const output = {
  568. id: undefined,
  569. name: undefined,
  570. field: undefined,
  571. widths: undefined,
  572. sort: undefined,
  573. tag: undefined,
  574. query: undefined,
  575. yAxis: undefined,
  576. display: undefined,
  577. topEvents: undefined,
  578. interval: undefined,
  579. };
  580. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  581. output[field] = undefined;
  582. }
  583. return output;
  584. }
  585. generateQueryStringObject(): Query {
  586. const output = {
  587. id: this.id,
  588. name: this.name,
  589. field: this.getFields(),
  590. widths: this.getWidths(),
  591. sort: encodeSorts(this.sorts),
  592. environment: this.environment,
  593. project: this.project,
  594. query: this.query,
  595. yAxis: this.yAxis || this.getYAxis(),
  596. dataset: this.dataset,
  597. display: this.display,
  598. topEvents: this.topEvents,
  599. interval: this.interval,
  600. };
  601. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  602. if (this[field]?.length) {
  603. output[field] = this[field];
  604. }
  605. }
  606. return cloneDeep(output as any);
  607. }
  608. isValid(): boolean {
  609. return this.fields.length > 0;
  610. }
  611. getWidths(): number[] {
  612. const result = this.fields.map(field =>
  613. field.width ? field.width : COL_WIDTH_UNDEFINED
  614. );
  615. while (result.length > 0) {
  616. const width = result[result.length - 1];
  617. if (width === COL_WIDTH_UNDEFINED) {
  618. result.pop();
  619. continue;
  620. }
  621. break;
  622. }
  623. return result;
  624. }
  625. getFields(): string[] {
  626. return this.fields.map(field => field.field);
  627. }
  628. getEquations(): string[] {
  629. return this.fields
  630. .filter(field => isEquation(field.field))
  631. .map(field => getEquation(field.field));
  632. }
  633. getAggregateFields(): Field[] {
  634. return this.fields.filter(
  635. field => isAggregateField(field.field) || isAggregateEquation(field.field)
  636. );
  637. }
  638. hasAggregateField() {
  639. return this.fields.some(field => isAggregateField(field.field));
  640. }
  641. hasIdField() {
  642. return this.fields.some(field => field.field === 'id');
  643. }
  644. numOfColumns(): number {
  645. return this.fields.length;
  646. }
  647. getColumns(): TableColumn<React.ReactText>[] {
  648. return decodeColumnOrder(this.fields);
  649. }
  650. getDays(): number {
  651. const statsPeriod = decodeScalar(this.statsPeriod);
  652. return statsPeriodToDays(statsPeriod, this.start, this.end);
  653. }
  654. clone(): EventView {
  655. // NOTE: We rely on usage of Readonly from TypeScript to ensure we do not mutate
  656. // the attributes of EventView directly. This enables us to quickly
  657. // clone new instances of EventView.
  658. return new EventView({
  659. id: this.id,
  660. name: this.name,
  661. fields: this.fields,
  662. sorts: this.sorts,
  663. query: this.query,
  664. team: this.team,
  665. project: this.project,
  666. start: this.start,
  667. end: this.end,
  668. statsPeriod: this.statsPeriod,
  669. environment: this.environment,
  670. yAxis: this.yAxis,
  671. dataset: this.dataset,
  672. display: this.display,
  673. topEvents: this.topEvents,
  674. interval: this.interval,
  675. expired: this.expired,
  676. createdBy: this.createdBy,
  677. additionalConditions: this.additionalConditions.copy(),
  678. });
  679. }
  680. withSorts(sorts: Sort[]): EventView {
  681. const newEventView = this.clone();
  682. const fields = newEventView.fields.map(field => getAggregateAlias(field.field));
  683. newEventView.sorts = sorts.filter(sort => fields.includes(sort.field));
  684. return newEventView;
  685. }
  686. withColumns(columns: Column[]): EventView {
  687. const newEventView = this.clone();
  688. const fields: Field[] = columns
  689. .filter(
  690. col =>
  691. ((col.kind === 'field' || col.kind === FieldValueKind.EQUATION) && col.field) ||
  692. (col.kind === 'function' && col.function[0])
  693. )
  694. .map(col => generateFieldAsString(col))
  695. .map((field, i) => {
  696. // newly added field
  697. if (!newEventView.fields[i]) {
  698. return {field, width: COL_WIDTH_UNDEFINED};
  699. }
  700. // Existing columns that were not re ordered should retain
  701. // their old widths.
  702. const existing = newEventView.fields[i];
  703. const width =
  704. existing.field === field && existing.width !== undefined
  705. ? existing.width
  706. : COL_WIDTH_UNDEFINED;
  707. return {field, width};
  708. });
  709. newEventView.fields = fields;
  710. // Update sorts as sorted fields may have been removed.
  711. if (newEventView.sorts) {
  712. // Filter the sort fields down to those that are still selected.
  713. const sortKeys = fields.map(field => fieldToSort(field, undefined)?.field);
  714. const newSort = newEventView.sorts.filter(
  715. sort => sort && sortKeys.includes(sort.field)
  716. );
  717. // If the sort field was removed, try and find a new sortable column.
  718. if (newSort.length === 0) {
  719. const sortField = fields.find(field => isFieldSortable(field, undefined));
  720. if (sortField) {
  721. newSort.push({field: sortField.field, kind: 'desc'});
  722. }
  723. }
  724. newEventView.sorts = newSort;
  725. }
  726. newEventView.yAxis = newEventView.getYAxis();
  727. return newEventView;
  728. }
  729. withNewColumn(newColumn: Column): EventView {
  730. const fieldAsString = generateFieldAsString(newColumn);
  731. const newField: Field = {
  732. field: fieldAsString,
  733. width: COL_WIDTH_UNDEFINED,
  734. };
  735. const newEventView = this.clone();
  736. newEventView.fields = [...newEventView.fields, newField];
  737. return newEventView;
  738. }
  739. withResizedColumn(columnIndex: number, newWidth: number) {
  740. const field = this.fields[columnIndex];
  741. const newEventView = this.clone();
  742. if (!field) {
  743. return newEventView;
  744. }
  745. const updateWidth = field.width !== newWidth;
  746. if (updateWidth) {
  747. const fields = [...newEventView.fields];
  748. fields[columnIndex] = {
  749. ...field,
  750. width: newWidth,
  751. };
  752. newEventView.fields = fields;
  753. }
  754. return newEventView;
  755. }
  756. withUpdatedColumn(
  757. columnIndex: number,
  758. updatedColumn: Column,
  759. tableMeta: MetaType | undefined
  760. ): EventView {
  761. const columnToBeUpdated = this.fields[columnIndex];
  762. const fieldAsString = generateFieldAsString(updatedColumn);
  763. const updateField = columnToBeUpdated.field !== fieldAsString;
  764. if (!updateField) {
  765. return this;
  766. }
  767. // ensure tableMeta is non-empty
  768. tableMeta = validateTableMeta(tableMeta);
  769. const newEventView = this.clone();
  770. const updatedField: Field = {
  771. field: fieldAsString,
  772. width: COL_WIDTH_UNDEFINED,
  773. };
  774. const fields = [...newEventView.fields];
  775. fields[columnIndex] = updatedField;
  776. newEventView.fields = fields;
  777. // if the updated column is one of the sorted columns, we may need to remove
  778. // it from the list of sorts
  779. const needleSortIndex = this.sorts.findIndex(sort =>
  780. isSortEqualToField(sort, columnToBeUpdated, tableMeta)
  781. );
  782. if (needleSortIndex >= 0) {
  783. const needleSort = this.sorts[needleSortIndex];
  784. const numOfColumns = this.fields.reduce((sum, currentField) => {
  785. if (isSortEqualToField(needleSort, currentField, tableMeta)) {
  786. return sum + 1;
  787. }
  788. return sum;
  789. }, 0);
  790. // do not bother deleting the sort key if there are more than one columns
  791. // of it in the table.
  792. if (numOfColumns <= 1) {
  793. if (isFieldSortable(updatedField, tableMeta)) {
  794. // use the current updated field as the sort key
  795. const sort = fieldToSort(updatedField, tableMeta)!;
  796. // preserve the sort kind
  797. sort.kind = needleSort.kind;
  798. const sorts = [...newEventView.sorts];
  799. sorts[needleSortIndex] = sort;
  800. newEventView.sorts = sorts;
  801. } else {
  802. const sorts = [...newEventView.sorts];
  803. sorts.splice(needleSortIndex, 1);
  804. newEventView.sorts = [...new Set(sorts)];
  805. }
  806. }
  807. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  808. // establish a default sort by finding the first sortable field
  809. if (isFieldSortable(updatedField, tableMeta)) {
  810. // use the current updated field as the sort key
  811. const sort = fieldToSort(updatedField, tableMeta)!;
  812. // preserve the sort kind
  813. sort.kind = needleSort.kind;
  814. newEventView.sorts = [sort];
  815. } else {
  816. const sortableFieldIndex = newEventView.fields.findIndex(currentField =>
  817. isFieldSortable(currentField, tableMeta)
  818. );
  819. if (sortableFieldIndex >= 0) {
  820. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  821. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  822. newEventView.sorts = [sort];
  823. }
  824. }
  825. }
  826. }
  827. newEventView.yAxis = newEventView.getYAxis();
  828. return newEventView;
  829. }
  830. withDeletedColumn(columnIndex: number, tableMeta: MetaType | undefined): EventView {
  831. // Disallow removal of the orphan column, and check for out-of-bounds
  832. if (this.fields.length <= 1 || this.fields.length <= columnIndex || columnIndex < 0) {
  833. return this;
  834. }
  835. // ensure tableMeta is non-empty
  836. tableMeta = validateTableMeta(tableMeta);
  837. // delete the column
  838. const newEventView = this.clone();
  839. const fields = [...newEventView.fields];
  840. fields.splice(columnIndex, 1);
  841. newEventView.fields = fields;
  842. // Ensure there is at least one auto width column
  843. // To ensure a well formed table results.
  844. const hasAutoIndex = fields.find(field => field.width === COL_WIDTH_UNDEFINED);
  845. if (!hasAutoIndex) {
  846. newEventView.fields[0].width = COL_WIDTH_UNDEFINED;
  847. }
  848. // if the deleted column is one of the sorted columns, we need to remove
  849. // it from the list of sorts
  850. const columnToBeDeleted = this.fields[columnIndex];
  851. const needleSortIndex = this.sorts.findIndex(sort =>
  852. isSortEqualToField(sort, columnToBeDeleted, tableMeta)
  853. );
  854. if (needleSortIndex >= 0) {
  855. const needleSort = this.sorts[needleSortIndex];
  856. const numOfColumns = this.fields.reduce((sum, field) => {
  857. if (isSortEqualToField(needleSort, field, tableMeta)) {
  858. return sum + 1;
  859. }
  860. return sum;
  861. }, 0);
  862. // do not bother deleting the sort key if there are more than one columns
  863. // of it in the table.
  864. if (numOfColumns <= 1) {
  865. const sorts = [...newEventView.sorts];
  866. sorts.splice(needleSortIndex, 1);
  867. newEventView.sorts = [...new Set(sorts)];
  868. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  869. // establish a default sort by finding the first sortable field
  870. const sortableFieldIndex = newEventView.fields.findIndex(field =>
  871. isFieldSortable(field, tableMeta)
  872. );
  873. if (sortableFieldIndex >= 0) {
  874. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  875. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  876. newEventView.sorts = [sort];
  877. }
  878. }
  879. }
  880. }
  881. newEventView.yAxis = newEventView.getYAxis();
  882. return newEventView;
  883. }
  884. withTeams(teams: ('myteams' | number)[]): EventView {
  885. const newEventView = this.clone();
  886. newEventView.team = teams;
  887. return newEventView;
  888. }
  889. getSorts(): TableColumnSort<React.ReactText>[] {
  890. return this.sorts.map(
  891. sort =>
  892. ({
  893. key: sort.field,
  894. order: sort.kind,
  895. }) as TableColumnSort<string>
  896. );
  897. }
  898. // returns query input for the search
  899. getQuery(inputQuery: string | string[] | null | undefined = undefined): string {
  900. const queryParts: string[] = [];
  901. if (this.query) {
  902. if (this.additionalConditions) {
  903. queryParts.push(this.getQueryWithAdditionalConditions());
  904. } else {
  905. queryParts.push(this.query);
  906. }
  907. }
  908. if (inputQuery) {
  909. // there may be duplicate query in the query string
  910. // e.g. query=hello&query=world
  911. if (Array.isArray(inputQuery)) {
  912. inputQuery.forEach(query => {
  913. if (typeof query === 'string' && !queryParts.includes(query)) {
  914. queryParts.push(query);
  915. }
  916. });
  917. }
  918. if (typeof inputQuery === 'string' && !queryParts.includes(inputQuery)) {
  919. queryParts.push(inputQuery);
  920. }
  921. }
  922. return queryParts.join(' ');
  923. }
  924. getFacetsAPIPayload(
  925. location: Location
  926. ): Exclude<EventQuery & LocationQuery, 'sort' | 'cursor'> {
  927. const payload = this.getEventsAPIPayload(location);
  928. const remove = [
  929. 'id',
  930. 'name',
  931. 'per_page',
  932. 'sort',
  933. 'cursor',
  934. 'field',
  935. 'equation',
  936. 'interval',
  937. ];
  938. for (const key of remove) {
  939. delete payload[key];
  940. }
  941. return payload;
  942. }
  943. normalizeDateSelection(location: Location) {
  944. const query = location?.query || {};
  945. // pick only the query strings that we care about
  946. const picked = pickRelevantLocationQueryStrings(location);
  947. const hasDateSelection = this.statsPeriod || (this.start && this.end);
  948. // an eventview's date selection has higher precedence than the date selection in the query string
  949. const dateSelection = hasDateSelection
  950. ? {
  951. start: this.start,
  952. end: this.end,
  953. statsPeriod: this.statsPeriod,
  954. }
  955. : {
  956. start: picked.start,
  957. end: picked.end,
  958. period: decodeScalar(query.period),
  959. statsPeriod: picked.statsPeriod,
  960. };
  961. // normalize datetime selection
  962. return normalizeDateTimeParams({
  963. ...dateSelection,
  964. utc: decodeScalar(query.utc),
  965. });
  966. }
  967. // Takes an EventView instance and converts it into the format required for the events API
  968. getEventsAPIPayload(
  969. location: Location,
  970. forceAppendRawQueryString?: string
  971. ): EventQuery & LocationQuery {
  972. // pick only the query strings that we care about
  973. const picked = pickRelevantLocationQueryStrings(location);
  974. // normalize datetime selection
  975. const normalizedTimeWindowParams = this.normalizeDateSelection(location);
  976. const sort =
  977. this.sorts.length <= 0
  978. ? undefined
  979. : this.sorts.length > 1
  980. ? encodeSorts(this.sorts)
  981. : encodeSort(this.sorts[0]);
  982. const fields = this.getFields();
  983. const team = this.team.map(proj => String(proj));
  984. const project = this.project.map(proj => String(proj));
  985. const environment = this.environment as string[];
  986. let queryString = this.getQueryWithAdditionalConditions();
  987. if (forceAppendRawQueryString) {
  988. queryString += ' ' + forceAppendRawQueryString;
  989. }
  990. // generate event query
  991. const eventQuery = Object.assign(
  992. omit(picked, DATETIME_QUERY_STRING_KEYS),
  993. normalizedTimeWindowParams,
  994. {
  995. team,
  996. project,
  997. environment,
  998. field: [...new Set(fields)],
  999. sort,
  1000. per_page: DEFAULT_PER_PAGE,
  1001. query: queryString,
  1002. dataset: this.dataset,
  1003. }
  1004. ) as EventQuery & LocationQuery;
  1005. if (eventQuery.team && !eventQuery.team.length) {
  1006. delete eventQuery.team;
  1007. }
  1008. if (!eventQuery.sort) {
  1009. delete eventQuery.sort;
  1010. }
  1011. return eventQuery;
  1012. }
  1013. getResultsViewUrlTarget(
  1014. slug: string,
  1015. isHomepage: boolean = false
  1016. ): {pathname: string; query: Query} {
  1017. const target = isHomepage ? 'homepage' : 'results';
  1018. return {
  1019. pathname: normalizeUrl(`/organizations/${slug}/discover/${target}/`),
  1020. query: this.generateQueryStringObject(),
  1021. };
  1022. }
  1023. getResultsViewShortUrlTarget(slug: string): {pathname: string; query: Query} {
  1024. const output = {id: this.id};
  1025. for (const field of [...Object.values(URL_PARAM), 'cursor']) {
  1026. if (this[field]?.length) {
  1027. output[field] = this[field];
  1028. }
  1029. }
  1030. return {
  1031. pathname: normalizeUrl(`/organizations/${slug}/discover/results/`),
  1032. query: cloneDeep(output as any),
  1033. };
  1034. }
  1035. getPerformanceTransactionEventsViewUrlTarget(
  1036. slug: string,
  1037. options: {
  1038. breakdown?: SpanOperationBreakdownFilter;
  1039. showTransactions?: EventsDisplayFilterName;
  1040. webVital?: WebVital;
  1041. }
  1042. ): {pathname: string; query: Query} {
  1043. const {showTransactions, breakdown, webVital} = options;
  1044. const output = {
  1045. sort: encodeSorts(this.sorts),
  1046. project: this.project,
  1047. query: this.query,
  1048. transaction: this.name,
  1049. showTransactions,
  1050. breakdown,
  1051. webVital,
  1052. };
  1053. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  1054. if (this[field]?.length) {
  1055. output[field] = this[field];
  1056. }
  1057. }
  1058. const query = cloneDeep(output as any);
  1059. return {
  1060. pathname: normalizeUrl(`/organizations/${slug}/performance/summary/events/`),
  1061. query,
  1062. };
  1063. }
  1064. sortForField(field: Field, tableMeta: MetaType | undefined): Sort | undefined {
  1065. if (!tableMeta) {
  1066. return undefined;
  1067. }
  1068. return this.sorts.find(sort => isSortEqualToField(sort, field, tableMeta));
  1069. }
  1070. sortOnField(
  1071. field: Field,
  1072. tableMeta: MetaType,
  1073. kind?: 'desc' | 'asc',
  1074. useFunctionFormat?: boolean
  1075. ): EventView {
  1076. // check if field can be sorted
  1077. if (!isFieldSortable(field, tableMeta)) {
  1078. return this;
  1079. }
  1080. const needleIndex = this.sorts.findIndex(sort =>
  1081. isSortEqualToField(sort, field, tableMeta)
  1082. );
  1083. if (needleIndex >= 0) {
  1084. const newEventView = this.clone();
  1085. const currentSort = this.sorts[needleIndex];
  1086. const sorts = [...newEventView.sorts];
  1087. sorts[needleIndex] = kind
  1088. ? setSortOrder(
  1089. {...currentSort, ...(useFunctionFormat ? {field: field.field} : {})},
  1090. kind
  1091. )
  1092. : reverseSort({
  1093. ...currentSort,
  1094. ...(useFunctionFormat ? {field: field.field} : {}),
  1095. });
  1096. newEventView.sorts = sorts;
  1097. return newEventView;
  1098. }
  1099. // field is currently not sorted; so, we sort on it
  1100. const newEventView = this.clone();
  1101. // invariant: this is not falsey, since sortKey exists
  1102. const sort = fieldToSort(field, tableMeta, kind, useFunctionFormat)!;
  1103. newEventView.sorts = [sort];
  1104. return newEventView;
  1105. }
  1106. getYAxisOptions(): SelectValue<string>[] {
  1107. // Make option set and add the default options in.
  1108. return uniqBy(
  1109. this.getAggregateFields()
  1110. // Only include aggregates that make sense to be graphable (eg. not string or date)
  1111. .filter(
  1112. (field: Field) =>
  1113. isLegalYAxisType(aggregateOutputType(field.field)) ||
  1114. isAggregateEquation(field.field)
  1115. )
  1116. .map((field: Field) => ({
  1117. label: isEquation(field.field) ? getEquation(field.field) : field.field,
  1118. value: field.field,
  1119. }))
  1120. .concat(CHART_AXIS_OPTIONS),
  1121. 'value'
  1122. );
  1123. }
  1124. getYAxis(): string {
  1125. const yAxisOptions = this.getYAxisOptions();
  1126. const yAxis = this.yAxis;
  1127. const defaultOption = yAxisOptions[0].value;
  1128. if (!yAxis) {
  1129. return defaultOption;
  1130. }
  1131. // ensure current selected yAxis is one of the items in yAxisOptions
  1132. const result = yAxisOptions.findIndex(
  1133. (option: SelectValue<string>) => option.value === yAxis
  1134. );
  1135. if (result >= 0) {
  1136. return typeof yAxis === 'string' ? yAxis : yAxis[0];
  1137. }
  1138. return defaultOption;
  1139. }
  1140. getDisplayOptions(): SelectValue<string>[] {
  1141. return DISPLAY_MODE_OPTIONS.map(item => {
  1142. if (item.value === DisplayModes.PREVIOUS) {
  1143. if (this.start || this.end) {
  1144. return {...item, disabled: true};
  1145. }
  1146. }
  1147. if (item.value === DisplayModes.TOP5 || item.value === DisplayModes.DAILYTOP5) {
  1148. if (this.getAggregateFields().length === 0) {
  1149. return {
  1150. ...item,
  1151. disabled: true,
  1152. tooltip: t('Add a function that groups events to use this view.'),
  1153. };
  1154. }
  1155. }
  1156. if (item.value === DisplayModes.DAILY || item.value === DisplayModes.DAILYTOP5) {
  1157. if (this.getDays() < 1) {
  1158. return {
  1159. ...item,
  1160. disabled: true,
  1161. tooltip: t('Change the date rage to at least 1 day to use this view.'),
  1162. };
  1163. }
  1164. }
  1165. return item;
  1166. });
  1167. }
  1168. getDisplayMode() {
  1169. const mode = this.display ?? DisplayModes.DEFAULT;
  1170. const displayOptions = this.getDisplayOptions();
  1171. let display = (Object.values(DisplayModes) as string[]).includes(mode)
  1172. ? mode
  1173. : DisplayModes.DEFAULT;
  1174. const cond = option => option.value === display;
  1175. // Just in case we define a fallback chain that results in an infinite loop.
  1176. // The number 5 isn't anything special, its just larger than the longest fallback
  1177. // chain that exists and isn't too big.
  1178. for (let i = 0; i < 5; i++) {
  1179. const selectedOption = displayOptions.find(cond);
  1180. if (selectedOption && !selectedOption.disabled) {
  1181. return display;
  1182. }
  1183. display = DISPLAY_MODE_FALLBACK_OPTIONS[display];
  1184. }
  1185. // after trying to find an enabled display mode and failing to find one,
  1186. // we just use the default display mode
  1187. return DisplayModes.DEFAULT;
  1188. }
  1189. getQueryWithAdditionalConditions() {
  1190. const {query} = this;
  1191. if (this.additionalConditions.isEmpty()) {
  1192. return query;
  1193. }
  1194. const conditions = new MutableSearch(query);
  1195. Object.entries(this.additionalConditions.filters).forEach(([tag, tagValues]) => {
  1196. const existingTagValues = conditions.getFilterValues(tag);
  1197. const newTagValues = tagValues.filter(
  1198. tagValue => !existingTagValues.includes(tagValue)
  1199. );
  1200. if (newTagValues.length) {
  1201. conditions.addFilterValues(tag, newTagValues);
  1202. }
  1203. });
  1204. return conditions.formatString();
  1205. }
  1206. /**
  1207. * Eventview usually just holds onto a project id for selected projects.
  1208. * Sometimes we need to iterate over the related project objects, this will give you the full projects if the Projects list is passed in.
  1209. * Also covers the 'My Projects' case which is sometimes missed, tries using the 'isMember' property of projects to pick the right list.
  1210. */
  1211. getFullSelectedProjects(fullProjectList: Project[]) {
  1212. const selectedProjectIds = this.project;
  1213. const isMyProjects = selectedProjectIds.length === 0;
  1214. if (isMyProjects) {
  1215. return fullProjectList.filter(p => p.isMember);
  1216. }
  1217. const isAllProjects =
  1218. selectedProjectIds.length === 1 && selectedProjectIds[0] === ALL_ACCESS_PROJECTS;
  1219. if (isAllProjects) {
  1220. return fullProjectList;
  1221. }
  1222. const projectMap = Object.fromEntries(fullProjectList.map(p => [String(p.id), p]));
  1223. return selectedProjectIds.map(id => projectMap[String(id)]);
  1224. }
  1225. }
  1226. export type ImmutableEventView = Readonly<Omit<EventView, 'additionalConditions'>>;
  1227. const isFieldsSimilar = (
  1228. currentValue: Array<string>,
  1229. otherValue: Array<string>
  1230. ): boolean => {
  1231. // For equation's their order matters because we alias them based on index
  1232. const currentEquations = currentValue.filter(isEquation);
  1233. const otherEquations = otherValue.filter(isEquation);
  1234. // Field orders don't matter, so using a set for comparison
  1235. const currentFields = new Set(currentValue.filter(value => !isEquation(value)));
  1236. const otherFields = new Set(otherValue.filter(value => !isEquation(value)));
  1237. if (!isEqual(currentEquations, otherEquations)) {
  1238. return false;
  1239. }
  1240. if (!isEqual(currentFields, otherFields)) {
  1241. return false;
  1242. }
  1243. return true;
  1244. };
  1245. export const isAPIPayloadSimilar = (
  1246. current: EventQuery & LocationQuery,
  1247. other: EventQuery & LocationQuery
  1248. ): boolean => {
  1249. const currentKeys = new Set(Object.keys(current));
  1250. const otherKeys = new Set(Object.keys(other));
  1251. if (!isEqual(currentKeys, otherKeys)) {
  1252. return false;
  1253. }
  1254. for (const key of currentKeys) {
  1255. const currentValue = current[key];
  1256. const otherValue = other[key];
  1257. if (key === 'field') {
  1258. if (!isFieldsSimilar(currentValue, otherValue)) {
  1259. return false;
  1260. }
  1261. } else {
  1262. const currentTarget = Array.isArray(currentValue)
  1263. ? new Set(currentValue)
  1264. : currentValue;
  1265. const otherTarget = Array.isArray(otherValue) ? new Set(otherValue) : otherValue;
  1266. if (!isEqual(currentTarget, otherTarget)) {
  1267. return false;
  1268. }
  1269. }
  1270. }
  1271. return true;
  1272. };
  1273. export function pickRelevantLocationQueryStrings(location: Location) {
  1274. const query = location.query || {};
  1275. const picked = pick(query || {}, EXTERNAL_QUERY_STRING_KEYS);
  1276. return picked;
  1277. }
  1278. export default EventView;