diff --git a/db/postgresql/migrations/11_add_segment/migration.sql b/db/postgresql/migrations/11_add_segment/migration.sql index 7fbb0867..cf4bc244 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 96e11661..47f5db22 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 00000000..ba90ee08 --- /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 00000000..c5896f89 --- /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 da4b0d4f..5b5bc88c 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 85433904..5bc4e522 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 e603ae9c..eaa61879 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 e8e8e6c8..8ea62ae8 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 c146271f..ffe9a367 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 21bc18ab..7afa391b 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 55deed14..89ae87bc 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 8b97bb04..57e31aa3 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 374f1cbc..e5c529cf 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) { }; } -export function getRequestFilters(query: Record) { - return Object.keys(FILTER_COLUMNS).reduce((obj, key) => { +export async function getRequestFilters(query: Record, websiteId?: string) { + const result: Record = {}; + + 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 1997a54c..41394fd2 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 2f785528..b9495bcd 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 892fd513..7b7c9d9f 100644 --- a/src/queries/prisma/segment.ts +++ b/src/queries/prisma/segment.ts @@ -13,6 +13,18 @@ export async function getSegment(segmentId: string): Promise { }); } +export async function getWebsiteSegment(websiteId: string, name: string): Promise { + return prisma.client.segment.findFirst({ + where: { websiteId, name }, + }); +} + +export async function getWebsiteSegments(websiteId: string, type: string): Promise { + return prisma.client.Segment.findMany({ + where: { websiteId, type }, + }); +} + export async function createSegment(data: Prisma.SegmentUncheckedCreateInput): Promise { return prisma.client.Segment.create({ data }); }