Merge branch 'dev' of https://github.com/umami-software/umami into dev
This commit is contained in:
commit
6c2155d496
157 files changed
+1389
-643
No files matched your search
@@ -0,0 +1,246 @@
|
||||
import { DATA_TYPE } from '../constants';
|
||||
import {
|
||||
flattenJSON,
|
||||
createKeyValue,
|
||||
isValidDateValue,
|
||||
getDataType,
|
||||
getStringValue,
|
||||
objectToArray,
|
||||
type KeyValueData,
|
||||
} from '../data';
|
||||
|
||||
describe('isValidDateValue', () => {
|
||||
test.each([
|
||||
['2024-01-15T10:30:00Z', true],
|
||||
['2024-01-15T10:30:00.123Z', true],
|
||||
['2024-01-15T10:30:00+02:00', true],
|
||||
['not-a-date', false],
|
||||
['2024/01/15', false],
|
||||
['', false],
|
||||
])('validates datetime strings correctly (%s → %s)', (input, expected) => {
|
||||
expect(isValidDateValue(input)).toBe(expected);
|
||||
});
|
||||
|
||||
test('returns false for non-string values', () => {
|
||||
expect(isValidDateValue(123 as any)).toBe(false);
|
||||
expect(isValidDateValue(null as any)).toBe(false);
|
||||
expect(isValidDateValue(undefined as any)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDataType', () => {
|
||||
test.each([
|
||||
['string', 'string'],
|
||||
[123, 'number'],
|
||||
[true, 'boolean'],
|
||||
[null, 'object'],
|
||||
[[], 'object'],
|
||||
[{}, 'object'],
|
||||
['2024-01-15T10:30:00Z', 'date'],
|
||||
])('detects type correctly (%s → %s)', (input, expected) => {
|
||||
expect(getDataType(input)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createKeyValue', () => {
|
||||
test('handles string values', () => {
|
||||
const result = createKeyValue('name', 'test');
|
||||
expect(result).toEqual({
|
||||
key: 'name',
|
||||
value: 'test',
|
||||
dataType: DATA_TYPE.string,
|
||||
});
|
||||
});
|
||||
|
||||
test('handles number values', () => {
|
||||
const result = createKeyValue('count', 42);
|
||||
expect(result).toEqual({
|
||||
key: 'count',
|
||||
value: 42,
|
||||
dataType: DATA_TYPE.number,
|
||||
});
|
||||
});
|
||||
|
||||
test('handles boolean values and converts to string', () => {
|
||||
expect(createKeyValue('active', true)).toEqual({
|
||||
key: 'active',
|
||||
value: 'true',
|
||||
dataType: DATA_TYPE.boolean,
|
||||
});
|
||||
expect(createKeyValue('active', false)).toEqual({
|
||||
key: 'active',
|
||||
value: 'false',
|
||||
dataType: DATA_TYPE.boolean,
|
||||
});
|
||||
});
|
||||
|
||||
test('handles date strings', () => {
|
||||
const dateStr = '2024-01-15T10:30:00Z';
|
||||
const result = createKeyValue('timestamp', dateStr);
|
||||
expect(result).toEqual({
|
||||
key: 'timestamp',
|
||||
value: dateStr,
|
||||
dataType: DATA_TYPE.date,
|
||||
});
|
||||
});
|
||||
|
||||
test('handles arrays and converts to JSON string', () => {
|
||||
const arr = [1, 2, 3];
|
||||
const result = createKeyValue('items', arr);
|
||||
expect(result).toEqual({
|
||||
key: 'items',
|
||||
value: '[1,2,3]',
|
||||
dataType: DATA_TYPE.array,
|
||||
});
|
||||
});
|
||||
|
||||
test('handles null values', () => {
|
||||
const result = createKeyValue('nullable', null);
|
||||
expect(result.dataType).toBe(DATA_TYPE.array);
|
||||
expect(result.value).toBe('null');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStringValue', () => {
|
||||
test('formats number values with 4 decimal places', () => {
|
||||
expect(getStringValue('42', DATA_TYPE.number)).toBe('42.0000');
|
||||
expect(getStringValue('3.14159', DATA_TYPE.number)).toBe('3.1416');
|
||||
});
|
||||
|
||||
test('converts date values to ISO string', () => {
|
||||
const result = getStringValue('2024-01-15T10:30:00', DATA_TYPE.date);
|
||||
expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
|
||||
});
|
||||
|
||||
test('returns string values as-is for other types', () => {
|
||||
expect(getStringValue('test', DATA_TYPE.string)).toBe('test');
|
||||
expect(getStringValue('true', DATA_TYPE.boolean)).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('objectToArray', () => {
|
||||
test('converts object values to array', () => {
|
||||
const obj = { a: 1, b: 2, c: 3 };
|
||||
const result = objectToArray(obj);
|
||||
expect(result).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
test('returns empty array for empty object', () => {
|
||||
expect(objectToArray({})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flattenJSON', () => {
|
||||
test('flattens simple object', () => {
|
||||
const input = {
|
||||
name: 'test',
|
||||
count: 42,
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toContainEqual(expect.objectContaining({ key: 'name', value: 'test' }));
|
||||
expect(result).toContainEqual(expect.objectContaining({ key: 'count', value: 42 }));
|
||||
});
|
||||
|
||||
test('flattens nested object with dot notation', () => {
|
||||
const input = {
|
||||
user: {
|
||||
name: 'John',
|
||||
age: 30,
|
||||
},
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toContainEqual(expect.objectContaining({ key: 'user.name', value: 'John' }));
|
||||
expect(result).toContainEqual(expect.objectContaining({ key: 'user.age', value: 30 }));
|
||||
});
|
||||
|
||||
test('flattens deeply nested object', () => {
|
||||
const input = {
|
||||
level1: {
|
||||
level2: {
|
||||
level3: {
|
||||
value: 'deep',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].key).toBe('level1.level2.level3.value');
|
||||
expect(result[0].value).toBe('deep');
|
||||
});
|
||||
|
||||
test('treats arrays as leaf values (converts to JSON string)', () => {
|
||||
const input = {
|
||||
tags: ['a', 'b', 'c'],
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].key).toBe('tags');
|
||||
expect(result[0].value).toBe('["a","b","c"]');
|
||||
expect(result[0].dataType).toBe(DATA_TYPE.array);
|
||||
});
|
||||
|
||||
test('treats date strings as leaf values', () => {
|
||||
const input = {
|
||||
createdAt: '2024-01-15T10:30:00Z',
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].key).toBe('createdAt');
|
||||
expect(result[0].dataType).toBe(DATA_TYPE.date);
|
||||
});
|
||||
|
||||
test('handles mixed nested and flat structure', () => {
|
||||
const input = {
|
||||
id: '123',
|
||||
metadata: {
|
||||
timestamp: '2024-01-15T10:30:00Z',
|
||||
source: 'web',
|
||||
details: {
|
||||
referrer: 'google',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
const keys = result.map(r => r.key);
|
||||
|
||||
expect(result).toHaveLength(4);
|
||||
expect(keys).toContain('id');
|
||||
expect(keys).toContain('metadata.timestamp');
|
||||
expect(keys).toContain('metadata.source');
|
||||
expect(keys).toContain('metadata.details.referrer');
|
||||
});
|
||||
|
||||
test('returns empty array for empty object', () => {
|
||||
expect(flattenJSON({})).toEqual([]);
|
||||
});
|
||||
|
||||
test('converts boolean values to strings', () => {
|
||||
const input = {
|
||||
isActive: true,
|
||||
isAdmin: false,
|
||||
};
|
||||
|
||||
const result = flattenJSON(input);
|
||||
|
||||
expect(result).toContainEqual(
|
||||
expect.objectContaining({ key: 'isActive', value: 'true', dataType: DATA_TYPE.boolean }),
|
||||
);
|
||||
expect(result).toContainEqual(
|
||||
expect.objectContaining({ key: 'isAdmin', value: 'false', dataType: DATA_TYPE.boolean }),
|
||||
);
|
||||
});
|
||||
});
|
||||
+24
-7
@@ -253,6 +253,10 @@ function getPropertyFilterQuery(
|
||||
const table = propertyType === 'event' ? 'event_data' : 'session_data final';
|
||||
const column = propertyType === 'event' ? 'event_id' : 'session_id';
|
||||
const outerColumn = propertyType === 'event' ? 'event_id' : 'website_event.session_id';
|
||||
const dateFilter =
|
||||
propertyType === 'event'
|
||||
? `and created_at between {startDate:DateTime64} and {endDate:DateTime64}`
|
||||
: '';
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, i) => {
|
||||
const keyParam = `pf_key_${i}`;
|
||||
@@ -333,15 +337,26 @@ function getPropertyFilterQuery(
|
||||
}
|
||||
}
|
||||
|
||||
parts.push(`and ${outerColumn} in (
|
||||
select ${column}
|
||||
if (propertyType === 'session') {
|
||||
parts.push(`and tuple(website_event.website_id, website_event.session_id) in (
|
||||
select website_id, session_id
|
||||
from ${table}
|
||||
where website_id = {websiteId:UUID}
|
||||
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
|
||||
and data_key = {${keyParam}:String}
|
||||
and data_type = ${dataType}
|
||||
and ${condition}
|
||||
)`);
|
||||
} else {
|
||||
parts.push(`and ${outerColumn} in (
|
||||
select ${column}
|
||||
from ${table}
|
||||
where website_id = {websiteId:UUID}
|
||||
${dateFilter}
|
||||
and data_key = {${keyParam}:String}
|
||||
and data_type = ${dataType}
|
||||
and ${condition}
|
||||
)`);
|
||||
}
|
||||
});
|
||||
|
||||
return { sql: parts.join('\n'), params };
|
||||
@@ -365,13 +380,15 @@ async function pagedRawQuery(
|
||||
.filter(n => n)
|
||||
.join('\n');
|
||||
|
||||
const count = await rawQuery(`select count(*) as num from (${query}) t`, queryParams).then(
|
||||
res => res[0].num,
|
||||
);
|
||||
const { maxResults } = filters;
|
||||
const countQuery = maxResults
|
||||
? `select count(*) as num from (select 1 from (${query}) t limit ${+maxResults}) t2`
|
||||
: `select count(*) as num from (${query}) t`;
|
||||
|
||||
const count = await rawQuery(countQuery, queryParams).then(res => res[0].num);
|
||||
const data = await rawQuery(`${query}${statements}`, queryParams, name);
|
||||
|
||||
return { data, count, page: +page, pageSize: size, orderBy, search };
|
||||
return { data, count, page: +page, pageSize: size, orderBy, search, isCapped: !!maxResults && +count >= +maxResults };
|
||||
}
|
||||
|
||||
async function rawQuery<T = unknown>(
|
||||
|
||||
@@ -26,6 +26,7 @@ export const DEFAULT_DATE_RANGE_VALUE = '24hour';
|
||||
export const DEFAULT_WEBSITE_LIMIT = 10;
|
||||
export const DEFAULT_RESET_DATE = '2000-01-01';
|
||||
export const DEFAULT_PAGE_SIZE = 20;
|
||||
export const MAX_PAGING_RESULTS = 10000;
|
||||
export const DEFAULT_DATE_COMPARE = 'prev';
|
||||
export const DEFAULT_CURRENCY = 'USD';
|
||||
|
||||
|
||||
+23
-32
@@ -1,27 +1,26 @@
|
||||
import { DATA_TYPE, DATETIME_REGEX } from './constants';
|
||||
import type { DynamicDataType } from './types';
|
||||
|
||||
export function flattenJSON(
|
||||
eventData: Record<string, any>,
|
||||
keyValues: { key: string; value: any; dataType: DynamicDataType }[] = [],
|
||||
parentKey = '',
|
||||
): { key: string; value: any; dataType: DynamicDataType }[] {
|
||||
return Object.keys(eventData).reduce(
|
||||
(acc, key) => {
|
||||
const value = eventData[key];
|
||||
const type = typeof eventData[key];
|
||||
export interface KeyValueData {
|
||||
key: string;
|
||||
value: any;
|
||||
dataType: DynamicDataType;
|
||||
}
|
||||
|
||||
// nested object
|
||||
if (value && type === 'object' && !Array.isArray(value) && !isValidDateValue(value)) {
|
||||
flattenJSON(value, acc.keyValues, getKeyName(key, parentKey));
|
||||
} else {
|
||||
createKey(getKeyName(key, parentKey), value, acc);
|
||||
export function flattenJSON(eventData: Record<string, any>): KeyValueData[] {
|
||||
function flatten(obj: Record<string, any>, parentKey: string): KeyValueData[] {
|
||||
return Object.entries(obj).flatMap(([key, value]) => {
|
||||
const fullKey = parentKey ? `${parentKey}.${key}` : key;
|
||||
|
||||
if (value && typeof value === 'object' && !Array.isArray(value) && !isValidDateValue(value)) {
|
||||
return flatten(value, fullKey);
|
||||
}
|
||||
|
||||
return acc;
|
||||
},
|
||||
{ keyValues, parentKey },
|
||||
).keyValues;
|
||||
return [createKeyValue(fullKey, value)];
|
||||
});
|
||||
}
|
||||
|
||||
return flatten(eventData, '');
|
||||
}
|
||||
|
||||
export function isValidDateValue(value: string) {
|
||||
@@ -50,10 +49,10 @@ export function getStringValue(value: string, dataType: number) {
|
||||
return value;
|
||||
}
|
||||
|
||||
function createKey(key: string, value: string, acc: { keyValues: any[]; parentKey: string }) {
|
||||
export function createKeyValue(key: string, value: any): KeyValueData {
|
||||
const type = getDataType(value);
|
||||
|
||||
let dataType = null;
|
||||
let dataType: DynamicDataType;
|
||||
let processedValue = value;
|
||||
|
||||
switch (type) {
|
||||
case 'number':
|
||||
@@ -64,29 +63,21 @@ function createKey(key: string, value: string, acc: { keyValues: any[]; parentKe
|
||||
break;
|
||||
case 'boolean':
|
||||
dataType = DATA_TYPE.boolean;
|
||||
value = value ? 'true' : 'false';
|
||||
processedValue = value ? 'true' : 'false';
|
||||
break;
|
||||
case 'date':
|
||||
dataType = DATA_TYPE.date;
|
||||
break;
|
||||
case 'object':
|
||||
dataType = DATA_TYPE.array;
|
||||
value = JSON.stringify(value);
|
||||
processedValue = JSON.stringify(value);
|
||||
break;
|
||||
default:
|
||||
dataType = DATA_TYPE.string;
|
||||
break;
|
||||
}
|
||||
|
||||
acc.keyValues.push({ key, value, dataType });
|
||||
}
|
||||
|
||||
function getKeyName(key: string, parentKey: string) {
|
||||
if (!parentKey) {
|
||||
return key;
|
||||
}
|
||||
|
||||
return `${parentKey}.${key}`;
|
||||
return { key, value: processedValue, dataType };
|
||||
}
|
||||
|
||||
export function objectToArray(obj: object) {
|
||||
|
||||
+24
-8
@@ -289,6 +289,8 @@ function getPropertyFilterQuery(
|
||||
const column = propertyType === 'event' ? 'website_event_id' : 'session_id';
|
||||
const outerColumn =
|
||||
propertyType === 'event' ? 'website_event.event_id' : 'website_event.session_id';
|
||||
const dateFilter =
|
||||
propertyType === 'event' ? `and created_at between {{startDate}} and {{endDate}}` : '';
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, i) => {
|
||||
const keyParam = `pf_key_${i}`;
|
||||
@@ -372,15 +374,27 @@ function getPropertyFilterQuery(
|
||||
}
|
||||
}
|
||||
|
||||
parts.push(`and ${outerColumn} in (
|
||||
select ${column}
|
||||
if (propertyType === 'session') {
|
||||
parts.push(`and exists (
|
||||
select 1
|
||||
from ${table}
|
||||
where website_id = {{websiteId::uuid}}
|
||||
and created_at between {{startDate}} and {{endDate}}
|
||||
where website_id = website_event.website_id
|
||||
and session_id = website_event.session_id
|
||||
and data_key = {{${keyParam}}}
|
||||
and data_type = ${dataType}
|
||||
and ${condition}
|
||||
)`);
|
||||
} else {
|
||||
parts.push(`and ${outerColumn} in (
|
||||
select ${column}
|
||||
from ${table}
|
||||
where website_id = {{websiteId::uuid}}
|
||||
${dateFilter}
|
||||
and data_key = {{${keyParam}}}
|
||||
and data_type = ${dataType}
|
||||
and ${condition}
|
||||
)`);
|
||||
}
|
||||
});
|
||||
|
||||
return { sql: parts.join('\n'), params };
|
||||
@@ -456,13 +470,15 @@ async function pagedRawQuery(
|
||||
.filter(n => n)
|
||||
.join('\n');
|
||||
|
||||
const count = await rawQuery(`select count(*) as num from (${query}) t`, queryParams).then(
|
||||
res => res[0].num,
|
||||
);
|
||||
const { maxResults } = filters;
|
||||
const countQuery = maxResults
|
||||
? `select count(*) as num from (select 1 from (${query}) t limit ${+maxResults}) t2`
|
||||
: `select count(*) as num from (${query}) t`;
|
||||
|
||||
const count = await rawQuery(countQuery, queryParams).then(res => Number(res[0].num));
|
||||
const data = await rawQuery(`${query}${statements}`, queryParams, name);
|
||||
|
||||
return { data, count, page: +page, pageSize: size, orderBy };
|
||||
return { data, count, page: +page, pageSize: size, orderBy, isCapped: !!maxResults && +count >= +maxResults };
|
||||
}
|
||||
|
||||
function getSearchParameters(query: string, filters: Record<string, any>[]) {
|
||||
|
||||
@@ -174,5 +174,6 @@ export async function getQueryFilters(
|
||||
sortDescending: params?.sortDescending,
|
||||
search: params?.search,
|
||||
compare: params?.compare,
|
||||
maxResults: params?.maxResults,
|
||||
};
|
||||
}
|
||||
@@ -77,10 +77,21 @@ export const searchParams = {
|
||||
export const pagingParams = {
|
||||
page: z.coerce.number().int().positive().optional(),
|
||||
pageSize: z.coerce.number().int().positive().optional(),
|
||||
maxResults: z.coerce.number().int().positive().optional(),
|
||||
};
|
||||
|
||||
export const sortingParams = {
|
||||
orderBy: z.string().optional(),
|
||||
sortDescending: z
|
||||
.enum(['true', 'false'])
|
||||
.optional()
|
||||
.transform(value => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return value === 'true';
|
||||
}),
|
||||
};
|
||||
|
||||
export const userRoleParam = z.enum(['admin', 'user', 'view-only']);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { FILTER_COLUMNS } from './constants';
|
||||
import type { ShareParameters, ShareTheme } from './types';
|
||||
|
||||
const FILTER_QUERY_PARAMS = new Set(['cohort', 'excludeBounce', 'match', 'segment']);
|
||||
|
||||
export function allowShareFilter(parameters?: ShareParameters | null) {
|
||||
return parameters?.allowFilter !== false;
|
||||
}
|
||||
|
||||
export function getShareTheme(parameters?: ShareParameters | null): ShareTheme | undefined {
|
||||
return parameters?.theme === 'light' || parameters?.theme === 'dark'
|
||||
? parameters.theme
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function excludeShareFilterParam(key: string) {
|
||||
const baseName = key.replace(/\d+$/, '');
|
||||
|
||||
return baseName in FILTER_COLUMNS || FILTER_QUERY_PARAMS.has(key);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { QueryFilters } from './types';
|
||||
|
||||
export function sanitizeSortFilters<const T extends readonly string[]>(
|
||||
filters: QueryFilters = {},
|
||||
allowedFields: T,
|
||||
defaults: Partial<Pick<QueryFilters, 'orderBy' | 'sortDescending'>> = {},
|
||||
): QueryFilters {
|
||||
const { orderBy, sortDescending, ...rest } = filters;
|
||||
const fallbackOrderBy = defaults.orderBy;
|
||||
const fallbackSortDescending = defaults.sortDescending;
|
||||
const isAllowed = orderBy ? allowedFields.includes(orderBy as T[number]) : false;
|
||||
|
||||
return {
|
||||
...rest,
|
||||
...(isAllowed
|
||||
? {
|
||||
orderBy,
|
||||
sortDescending,
|
||||
}
|
||||
: {
|
||||
...(fallbackOrderBy && { orderBy: fallbackOrderBy }),
|
||||
...(fallbackSortDescending !== undefined && {
|
||||
sortDescending: fallbackSortDescending,
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
+11
-1
@@ -27,9 +27,18 @@ export interface Auth {
|
||||
pixelIds?: string[];
|
||||
linkId?: string;
|
||||
linkIds?: string[];
|
||||
parameters?: ShareParameters;
|
||||
};
|
||||
}
|
||||
|
||||
export type ShareTheme = 'light' | 'dark';
|
||||
|
||||
export interface ShareParameters {
|
||||
allowFilter?: boolean;
|
||||
theme?: ShareTheme;
|
||||
[key: string]: boolean | ShareTheme | undefined;
|
||||
}
|
||||
|
||||
export interface PropertyFilter {
|
||||
propertyName: string;
|
||||
dataType: number;
|
||||
@@ -96,7 +105,6 @@ export interface PropertyLeaderboardRow {
|
||||
visits: number;
|
||||
views: number;
|
||||
events: number;
|
||||
totaltime: number;
|
||||
}
|
||||
|
||||
export interface QueryOptions {
|
||||
@@ -158,6 +166,7 @@ export interface SortParams {
|
||||
export interface PageParams {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
maxResults?: number;
|
||||
}
|
||||
|
||||
export interface SegmentParams {
|
||||
@@ -173,6 +182,7 @@ export interface PageResult<T> {
|
||||
orderBy?: string;
|
||||
sortDescending?: boolean;
|
||||
search?: string;
|
||||
isCapped?: boolean;
|
||||
}
|
||||
|
||||
export interface RealtimeData {
|
||||
|
||||
Reference in new issue
Block a user