Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

segments implementation and migration update. update getRequestFilters to include filter groups.

Francis Caof61421b74262
diff --git a/db/postgresql/migrations/11_add_segment/migration.sql b/db/postgresql/migrations/11_add_segment/migration.sql
index 7fbb0867d..cf4bc244b 100644
--- a/db/postgresql/migrations/11_add_segment/migration.sql
+++ b/db/postgresql/migrations/11_add_segment/migration.sql
@@ -2,6 +2,7 @@
CREATE TABLE "segment" (
"segment_id" UUID NOT NULL,
"website_id" UUID NOT NULL,
+ "type" VARCHAR(200) NOT NULL,
"name" VARCHAR(200) NOT NULL,
"filters" JSONB NOT NULL,
"created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
diff --git a/db/postgresql/migrations/13_add_revenue/migration.sql b/db/postgresql/migrations/13_add_revenue/migration.sql
index 96e11661e..47f5db22b 100644
--- a/db/postgresql/migrations/13_add_revenue/migration.sql
+++ b/db/postgresql/migrations/13_add_revenue/migration.sql
@@ -1,6 +1,3 @@
--- AlterTable
-ALTER TABLE "segment" ADD COLUMN "type" VARCHAR(200) NOT NULL;
-
-- CreateTable
CREATE TABLE "revenue" (
"revenue_id" UUID NOT NULL,
diff --git a/src/app/api/segments/[segmentId]/route.ts b/src/app/api/segments/[segmentId]/route.ts
new file mode 100644
index 000000000..ba90ee082
--- /dev/null
+++ b/src/app/api/segments/[segmentId]/route.ts
@@ -0,0 +1,91 @@
+import { z } from 'zod';
+import { parseRequest } from '@/lib/request';
+import { deleteReport, getReport, updateReport } from '@/queries';
+import { canDeleteReport, canUpdateReport, canViewReport } from '@/lib/auth';
+import { unauthorized, json, notFound, ok } from '@/lib/response';
+import { reportTypeParam } from '@/lib/schema';
+
+export async function GET(request: Request, { params }: { params: Promise<{ reportId: string }> }) {
+ const { auth, error } = await parseRequest(request);
+
+ if (error) {
+ return error();
+ }
+
+ const { reportId } = await params;
+
+ const report = await getReport(reportId);
+
+ if (!(await canViewReport(auth, report))) {
+ return unauthorized();
+ }
+
+ report.parameters = JSON.parse(report.parameters);
+
+ return json(report);
+}
+
+export async function POST(
+ request: Request,
+ { params }: { params: Promise<{ reportId: string }> },
+) {
+ const schema = z.object({
+ websiteId: z.string().uuid(),
+ type: reportTypeParam,
+ name: z.string().max(200),
+ description: z.string().max(500),
+ parameters: z.object({}).passthrough(),
+ });
+
+ const { auth, body, error } = await parseRequest(request, schema);
+
+ if (error) {
+ return error();
+ }
+
+ const { reportId } = await params;
+ const { websiteId, type, name, description, parameters } = body;
+
+ const report = await getReport(reportId);
+
+ if (!report) {
+ return notFound();
+ }
+
+ if (!(await canUpdateReport(auth, report))) {
+ return unauthorized();
+ }
+
+ const result = await updateReport(reportId, {
+ websiteId,
+ userId: auth.user.id,
+ type,
+ name,
+ description,
+ parameters: JSON.stringify(parameters),
+ } as any);
+
+ return json(result);
+}
+
+export async function DELETE(
+ request: Request,
+ { params }: { params: Promise<{ reportId: string }> },
+) {
+ const { auth, error } = await parseRequest(request);
+
+ if (error) {
+ return error();
+ }
+
+ const { reportId } = await params;
+ const report = await getReport(reportId);
+
+ if (!(await canDeleteReport(auth, report))) {
+ return unauthorized();
+ }
+
+ await deleteReport(reportId);
+
+ return ok();
+}
diff --git a/src/app/api/segments/route.ts b/src/app/api/segments/route.ts
new file mode 100644
index 000000000..c5896f892
--- /dev/null
+++ b/src/app/api/segments/route.ts
@@ -0,0 +1,43 @@
+import { z } from 'zod';
+import { hashPassword, canCreateUser } from '@/lib/auth';
+import { ROLES } from '@/lib/constants';
+import { uuid } from '@/lib/crypto';
+import { parseRequest } from '@/lib/request';
+import { unauthorized, json, badRequest } from '@/lib/response';
+import { createUser, getUserByUsername } from '@/queries';
+
+export async function POST(request: Request) {
+ const schema = z.object({
+ id: z.string().uuid().optional(),
+ username: z.string().max(255),
+ password: z.string(),
+ role: z.string().regex(/admin|user|view-only/i),
+ });
+
+ const { auth, body, error } = await parseRequest(request, schema);
+
+ if (error) {
+ return error();
+ }
+
+ if (!(await canCreateUser(auth))) {
+ return unauthorized();
+ }
+
+ const { id, username, password, role } = body;
+
+ const existingUser = await getUserByUsername(username, { showDeleted: true });
+
+ if (existingUser) {
+ return badRequest('User already exists');
+ }
+
+ const user = await createUser({
+ id: id || uuid(),
+ username,
+ password: hashPassword(password),
+ role: role ?? ROLES.user,
+ });
+
+ return json(user);
+}
diff --git a/src/app/api/websites/[websiteId]/events/series/route.ts b/src/app/api/websites/[websiteId]/events/series/route.ts
index da4b0d4f8..5b5bc88c5 100644
--- a/src/app/api/websites/[websiteId]/events/series/route.ts
+++ b/src/app/api/websites/[websiteId]/events/series/route.ts
@@ -32,7 +32,7 @@ export async function GET(
}
const filters = {
- ...getRequestFilters(query),
+ ...(await getRequestFilters(query)),
startDate,
endDate,
timezone,
diff --git a/src/app/api/websites/[websiteId]/metrics/route.ts b/src/app/api/websites/[websiteId]/metrics/route.ts
index 854339041..5bc4e5224 100644
--- a/src/app/api/websites/[websiteId]/metrics/route.ts
+++ b/src/app/api/websites/[websiteId]/metrics/route.ts
@@ -48,7 +48,7 @@ export async function GET(
const { startDate, endDate } = await getRequestDateRange(query);
const column = FILTER_COLUMNS[type] || type;
const filters = {
- ...getRequestFilters(query),
+ ...(await getRequestFilters(query)),
startDate,
endDate,
};
diff --git a/src/app/api/websites/[websiteId]/pageviews/route.ts b/src/app/api/websites/[websiteId]/pageviews/route.ts
index e603ae9c0..eaa618797 100644
--- a/src/app/api/websites/[websiteId]/pageviews/route.ts
+++ b/src/app/api/websites/[websiteId]/pageviews/route.ts
@@ -35,7 +35,7 @@ export async function GET(
const { startDate, endDate, unit } = await getRequestDateRange(query);
const filters = {
- ...getRequestFilters(query),
+ ...(await getRequestFilters(query)),
startDate,
endDate,
timezone,
diff --git a/src/app/api/websites/[websiteId]/sessions/stats/route.ts b/src/app/api/websites/[websiteId]/sessions/stats/route.ts
index e8e8e6c86..8ea62ae89 100644
--- a/src/app/api/websites/[websiteId]/sessions/stats/route.ts
+++ b/src/app/api/websites/[websiteId]/sessions/stats/route.ts
@@ -29,7 +29,7 @@ export async function GET(
const { startDate, endDate } = await getRequestDateRange(query);
- const filters = getRequestFilters(query);
+ const filters = await getRequestFilters(query);
const metrics = await getWebsiteSessionStats(websiteId, {
...filters,
diff --git a/src/app/api/websites/[websiteId]/stats/route.ts b/src/app/api/websites/[websiteId]/stats/route.ts
index c146271f9..ffe9a3672 100644
--- a/src/app/api/websites/[websiteId]/stats/route.ts
+++ b/src/app/api/websites/[websiteId]/stats/route.ts
@@ -37,7 +37,7 @@ export async function GET(
endDate,
);
- const filters = getRequestFilters(query);
+ const filters = await getRequestFilters(query);
const metrics = await getWebsiteStats(websiteId, {
...filters,
diff --git a/src/app/api/websites/[websiteId]/values/route.ts b/src/app/api/websites/[websiteId]/values/route.ts
index 21bc18abe..7afa391b4 100644
--- a/src/app/api/websites/[websiteId]/values/route.ts
+++ b/src/app/api/websites/[websiteId]/values/route.ts
@@ -1,9 +1,9 @@
-import { z } from 'zod';
import { canViewWebsite } from '@/lib/auth';
-import { EVENT_COLUMNS, FILTER_COLUMNS, GROUP_FILTERS, SESSION_COLUMNS } from '@/lib/constants';
-import { getValues } from '@/queries';
-import { parseRequest, getRequestDateRange } from '@/lib/request';
+import { EVENT_COLUMNS, FILTER_COLUMNS, FILTER_GROUPS, SESSION_COLUMNS } from '@/lib/constants';
+import { getRequestDateRange, parseRequest } from '@/lib/request';
import { badRequest, json, unauthorized } from '@/lib/response';
+import { getWebsiteSegments, getValues } from '@/queries';
+import { z } from 'zod';
export async function GET(
request: Request,
@@ -33,12 +33,18 @@ export async function GET(
if (
!SESSION_COLUMNS.includes(type) &&
!EVENT_COLUMNS.includes(type) &&
- !GROUP_FILTERS.includes(type)
+ !FILTER_GROUPS.includes(type)
) {
return badRequest('Invalid type.');
}
- const values = await getValues(websiteId, FILTER_COLUMNS[type], startDate, endDate, search);
+ let values;
+
+ if (FILTER_GROUPS.includes(type)) {
+ values = (await getWebsiteSegments(websiteId, type)).map(segment => ({ value: segment.name }));
+ } else {
+ values = await getValues(websiteId, FILTER_COLUMNS[type], startDate, endDate, search);
+ }
return json(values.filter(n => n).sort());
}
diff --git a/src/components/hooks/useFilterParams.ts b/src/components/hooks/useFilterParams.ts
index 55deed141..89ae87bce 100644
--- a/src/components/hooks/useFilterParams.ts
+++ b/src/components/hooks/useFilterParams.ts
@@ -21,6 +21,8 @@ export function useFilterParams(websiteId: string) {
city,
event,
tag,
+ segment,
+ cohort,
},
} = useNavigation();
@@ -42,5 +44,7 @@ export function useFilterParams(websiteId: string) {
city,
event,
tag,
+ segment,
+ cohort,
};
}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 8b97bb04a..57e31aa3a 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -47,7 +47,7 @@ export const SESSION_COLUMNS = [
'host',
];
-export const GROUP_FILTERS = ['segment', 'cohort'];
+export const FILTER_GROUPS = ['segment', 'cohort'];
export const FILTER_COLUMNS = {
url: 'url_path',
@@ -67,6 +67,7 @@ export const FILTER_COLUMNS = {
event: 'event_name',
tag: 'tag',
segment: 'segment',
+ cohort: 'cohort',
};
export const COLLECTION_TYPE = {
diff --git a/src/lib/request.ts b/src/lib/request.ts
index 374f1cbc1..e5c529cf0 100644
--- a/src/lib/request.ts
+++ b/src/lib/request.ts
@@ -1,9 +1,9 @@
import { z, ZodSchema } from 'zod';
-import { FILTER_COLUMNS } from '@/lib/constants';
+import { FILTER_COLUMNS, FILTER_GROUPS } from '@/lib/constants';
import { badRequest, unauthorized } from '@/lib/response';
import { getAllowedUnits, getMinimumUnit } from '@/lib/date';
import { checkAuth } from '@/lib/auth';
-import { getWebsiteDateRange } from '@/queries';
+import { getWebsiteSegment, getWebsiteDateRange } from '@/queries';
export async function getJsonBody(request: Request) {
try {
@@ -85,14 +85,21 @@ export async function getRequestDateRange(query: Record<string, any>) {
};
}
-export function getRequestFilters(query: Record<string, any>) {
- return Object.keys(FILTER_COLUMNS).reduce((obj, key) => {
- const value = query[key];
+export async function getRequestFilters(query: Record<string, any>, websiteId?: string) {
+ const result: Record<string, any> = {};
+ for (const key of Object.keys(FILTER_COLUMNS)) {
+ const value = query[key];
if (value !== undefined) {
- obj[key] = value;
+ if (FILTER_GROUPS.includes(key)) {
+ const segment = await getWebsiteSegment(websiteId, value);
+ // merge filters into result
+ Object.assign(result, segment.filters);
+ } else {
+ result[key] = value;
+ }
}
+ }
- return obj;
- }, {});
+ return result;
}
diff --git a/src/lib/schema.ts b/src/lib/schema.ts
index 1997a54ca..41394fd29 100644
--- a/src/lib/schema.ts
+++ b/src/lib/schema.ts
@@ -17,6 +17,8 @@ export const filterParams = {
host: z.string().optional(),
language: z.string().optional(),
event: z.string().optional(),
+ segment: z.string().optional(),
+ cohort: z.string().optional(),
};
export const pagingParams = {
diff --git a/src/queries/index.ts b/src/queries/index.ts
index 2f7855282..b9495bcd8 100644
--- a/src/queries/index.ts
+++ b/src/queries/index.ts
@@ -1,4 +1,5 @@
export * from '@/queries/prisma/report';
+export * from '@/queries/prisma/segment';
export * from '@/queries/prisma/team';
export * from '@/queries/prisma/teamUser';
export * from '@/queries/prisma/user';
diff --git a/src/queries/prisma/segment.ts b/src/queries/prisma/segment.ts
index 892fd513e..7b7c9d9fe 100644
--- a/src/queries/prisma/segment.ts
+++ b/src/queries/prisma/segment.ts
@@ -13,6 +13,18 @@ export async function getSegment(segmentId: string): Promise<Segment> {
});
}
+export async function getWebsiteSegment(websiteId: string, name: string): Promise<Segment> {
+ return prisma.client.segment.findFirst({
+ where: { websiteId, name },
+ });
+}
+
+export async function getWebsiteSegments(websiteId: string, type: string): Promise<Segment[]> {
+ return prisma.client.Segment.findMany({
+ where: { websiteId, type },
+ });
+}
+
export async function createSegment(data: Prisma.SegmentUncheckedCreateInput): Promise<Segment> {
return prisma.client.Segment.create({ data });
}