Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

web: added the base for the web project

Carl-Gerhard Lindesvärd8a87fff68942
diff --git a/README.md b/README.md
index a919bb313..42e782425 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,26 @@
Mixan is a simple analytics tool for logging events on web and react-native. My goal is to make a minimal mixpanel copy with the most basic features (for now).
+## Whats left?
+
+* [ ] Real time data (mostly screen_views stats)
+ * [ ] Active users (5min, 10min, 30min)
+* [ ] Save report to a specific dashboard
+* [ ] View events in a list
+* [ ] View profiles in a list
+* [ ] Invite users
+* [ ] Drag n Drop reports on dashboard
+* [ ] Manage dashboards
+* [ ] Support more chart types
+ * [ ] Bar
+ * [ ] Pie
+ * [ ] Area
+* [ ] Support funnels
+* [ ] Create native sdk
+* [ ] Create web sdk
+* [ ] Support multiple breakdowns
+* [ ] Aggregations (sum, average...)
+
## @mixan/sdk
For pushing events
diff --git a/apps/web/.eslintrc.cjs b/apps/web/.eslintrc.cjs
index 2ba001970..3898ad565 100644
--- a/apps/web/.eslintrc.cjs
+++ b/apps/web/.eslintrc.cjs
@@ -22,6 +22,8 @@ const config = {
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-call": "off",
+ "@typescript-eslint/no-misused-promises": "off",
+ "@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/consistent-type-imports": [
"warn",
{
diff --git a/apps/web/components.json b/apps/web/components.json
index b25b509fe..9078e0448 100644
--- a/apps/web/components.json
+++ b/apps/web/components.json
@@ -4,7 +4,7 @@
"rsc": false,
"tsx": true,
"tailwind": {
- "config": "tailwind.config.js",
+ "config": "tailwind.config.ts",
"css": "src/styles/globals.css",
"baseColor": "slate",
"cssVariables": true
diff --git a/apps/web/package.json b/apps/web/package.json
index bedcd065c..d928b143e 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -11,19 +11,25 @@
"start": "next start"
},
"dependencies": {
+ "@hookform/resolvers": "^3.3.2",
"@mixan/types": "^0.0.2-alpha",
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.1.1",
+ "@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-aspect-ratio": "^1.0.3",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
+ "@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-toast": "^1.1.5",
+ "@radix-ui/react-tooltip": "^1.0.7",
"@reduxjs/toolkit": "^1.9.7",
"@t3-oss/env-nextjs": "^0.7.0",
"@tanstack/react-query": "^4.32.6",
+ "@tanstack/react-table": "^8.10.7",
"@trpc/client": "^10.37.1",
"@trpc/next": "^10.37.1",
"@trpc/react-query": "^10.37.1",
@@ -33,13 +39,16 @@
"clsx": "^2.0.0",
"cmdk": "^0.2.0",
"lucide-react": "^0.286.0",
+ "mitt": "^3.0.1",
"next": "^13.5.4",
"next-auth": "^4.23.0",
"ramda": "^0.29.1",
"random-animal-name": "^0.1.1",
"react": "18.2.0",
"react-dom": "18.2.0",
+ "react-hook-form": "^7.47.0",
"react-redux": "^8.1.3",
+ "react-syntax-highlighter": "^15.5.0",
"react-virtualized-auto-sizer": "^1.0.20",
"recharts": "^2.8.0",
"superjson": "^1.13.1",
@@ -55,6 +64,7 @@
"@types/ramda": "^0.29.6",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
+ "@types/react-syntax-highlighter": "^15.5.9",
"@typescript-eslint/eslint-plugin": "^6.3.0",
"@typescript-eslint/parser": "^6.3.0",
"autoprefixer": "^10.4.14",
diff --git a/apps/web/prisma/migrations/20231023172003_org_to_clients/migration.sql b/apps/web/prisma/migrations/20231023172003_org_to_clients/migration.sql
new file mode 100644
index 000000000..f19f019f3
--- /dev/null
+++ b/apps/web/prisma/migrations/20231023172003_org_to_clients/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "clients" ADD COLUMN "organization_id" UUID;
+
+-- AddForeignKey
+ALTER TABLE "clients" ADD CONSTRAINT "clients_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/apps/web/prisma/migrations/20231023172105_org_required_for_client/migration.sql b/apps/web/prisma/migrations/20231023172105_org_required_for_client/migration.sql
new file mode 100644
index 000000000..4ec880f93
--- /dev/null
+++ b/apps/web/prisma/migrations/20231023172105_org_required_for_client/migration.sql
@@ -0,0 +1,14 @@
+/*
+ Warnings:
+
+ - Made the column `organization_id` on table `clients` required. This step will fail if there are existing NULL values in that column.
+
+*/
+-- DropForeignKey
+ALTER TABLE "clients" DROP CONSTRAINT "clients_organization_id_fkey";
+
+-- AlterTable
+ALTER TABLE "clients" ALTER COLUMN "organization_id" SET NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "clients" ADD CONSTRAINT "clients_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/apps/web/prisma/migrations/20231024074846_add_slugs/migration.sql b/apps/web/prisma/migrations/20231024074846_add_slugs/migration.sql
new file mode 100644
index 000000000..fec4a484f
--- /dev/null
+++ b/apps/web/prisma/migrations/20231024074846_add_slugs/migration.sql
@@ -0,0 +1,25 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[slug]` on the table `dashboards` will be added. If there are existing duplicate values, this will fail.
+ - A unique constraint covering the columns `[slug]` on the table `organizations` will be added. If there are existing duplicate values, this will fail.
+ - A unique constraint covering the columns `[slug]` on the table `projects` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "dashboards" ADD COLUMN "slug" TEXT NOT NULL DEFAULT gen_random_uuid();
+
+-- AlterTable
+ALTER TABLE "organizations" ADD COLUMN "slug" TEXT NOT NULL DEFAULT gen_random_uuid();
+
+-- AlterTable
+ALTER TABLE "projects" ADD COLUMN "slug" TEXT NOT NULL DEFAULT gen_random_uuid();
+
+-- CreateIndex
+CREATE UNIQUE INDEX "dashboards_slug_key" ON "dashboards"("slug");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "organizations_slug_key" ON "organizations"("slug");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "projects_slug_key" ON "projects"("slug");
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 646f9af63..57a1366e8 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -13,11 +13,13 @@ datasource db {
model Organization {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
+ slug String @unique @default(dbgenerated("gen_random_uuid()"))
projects Project[]
users User[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
+ clients Client[]
@@map("organizations")
}
@@ -25,6 +27,7 @@ model Organization {
model Project {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
+ slug String @unique @default(dbgenerated("gen_random_uuid()"))
organization_id String @db.Uuid
organization Organization @relation(fields: [organization_id], references: [id])
events Event[]
@@ -88,11 +91,13 @@ model Profile {
}
model Client {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- name String
- secret String
- project_id String @db.Uuid
- project Project @relation(fields: [project_id], references: [id])
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ name String
+ secret String
+ project_id String @db.Uuid
+ project Project @relation(fields: [project_id], references: [id])
+ organization_id String @db.Uuid
+ organization Organization @relation(fields: [organization_id], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
@@ -117,6 +122,7 @@ enum ChartType {
model Dashboard {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
+ slug String @unique @default(dbgenerated("gen_random_uuid()"))
project_id String @db.Uuid
project Project @relation(fields: [project_id], references: [id])
reports Report[]
diff --git a/apps/web/src/_middleware.ts b/apps/web/src/_middleware.ts
new file mode 100644
index 000000000..a127de59e
--- /dev/null
+++ b/apps/web/src/_middleware.ts
@@ -0,0 +1,3 @@
+export { default } from "next-auth/middleware"
+
+export const config = { matcher: ["/dashboard"] }
\ No newline at end of file
diff --git a/apps/web/src/components/ButtonContainer.tsx b/apps/web/src/components/ButtonContainer.tsx
new file mode 100644
index 000000000..d8bd6c715
--- /dev/null
+++ b/apps/web/src/components/ButtonContainer.tsx
@@ -0,0 +1,8 @@
+import { type HtmlProps } from "@/types";
+import { cn } from "@/utils/cn";
+
+export function ButtonContainer({className,...props}: HtmlProps<HTMLDivElement>) {
+ return (
+ <div className={cn("flex justify-between mt-6", className)} {...props} />
+ );
+}
diff --git a/apps/web/src/components/Card.tsx b/apps/web/src/components/Card.tsx
new file mode 100644
index 000000000..67ba3155e
--- /dev/null
+++ b/apps/web/src/components/Card.tsx
@@ -0,0 +1,9 @@
+import { type HtmlProps } from "@/types";
+
+export function Card({children}: HtmlProps<HTMLDivElement>) {
+ return (
+ <div className="border border-border rounded">
+ {children}
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/apps/web/src/components/Container.tsx b/apps/web/src/components/Container.tsx
index 7bdede157..2647fb526 100644
--- a/apps/web/src/components/Container.tsx
+++ b/apps/web/src/components/Container.tsx
@@ -3,6 +3,6 @@ import { cn } from "@/utils/cn";
export function Container({className,...props}: HtmlProps<HTMLDivElement>) {
return (
- <div className={cn("mx-auto w-full max-w-4xl", className)} {...props} />
+ <div className={cn("mx-auto w-full max-w-4xl px-4", className)} {...props} />
);
}
diff --git a/apps/web/src/components/Content.tsx b/apps/web/src/components/Content.tsx
new file mode 100644
index 000000000..9818b9368
--- /dev/null
+++ b/apps/web/src/components/Content.tsx
@@ -0,0 +1,50 @@
+import { cn } from "@/utils/cn";
+
+type ContentHeaderProps = {
+ title: string;
+ text: string;
+ children?: React.ReactNode;
+};
+
+export function ContentHeader({ title, text, children }: ContentHeaderProps) {
+ return (
+ <div className="flex items-center justify-between py-6 first:pt-0">
+ <div>
+ <h2 className="h2">{title}</h2>
+ <p className="text-sm text-muted-foreground">{text}</p>
+ </div>
+ <div>{children}</div>
+ </div>
+ );
+}
+
+type ContentSectionProps = {
+ title: string;
+ text: string;
+ children: React.ReactNode;
+ asCol?: boolean;
+};
+
+export function ContentSection({
+ title,
+ text,
+ children,
+ asCol,
+}: ContentSectionProps) {
+ return (
+ <div
+ className={cn(
+ "first:pt-0] flex py-6",
+ asCol ? "col flex" : "justify-between",
+ )}
+ >
+ {title && (
+ <div className="max-w-[50%]">
+ <h4 className="h4">{title}</h4>
+ <p className="text-sm text-muted-foreground">{text}</p>
+ </div>
+ )}
+ <div>{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/DataTable.tsx b/apps/web/src/components/DataTable.tsx
new file mode 100644
index 000000000..57f832a36
--- /dev/null
+++ b/apps/web/src/components/DataTable.tsx
@@ -0,0 +1,66 @@
+import { type ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table"
+
+interface DataTableProps<TData, TValue> {
+ columns: ColumnDef<TData, TValue>[]
+ data: TData[]
+}
+
+export function DataTable<TData, TValue>({
+ columns,
+ data,
+}: DataTableProps<TData, TValue>) {
+ const table = useReactTable({
+ data,
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ })
+
+ return (
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => {
+ return (
+ <TableHead key={header.id}>
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ </TableHead>
+ )
+ })}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() && "selected"}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-24 text-center">
+ No results.
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ )
+}
+
diff --git a/apps/web/src/components/Dropdown.tsx b/apps/web/src/components/Dropdown.tsx
new file mode 100644
index 000000000..a9f34cc46
--- /dev/null
+++ b/apps/web/src/components/Dropdown.tsx
@@ -0,0 +1,49 @@
+import { cloneElement } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "./ui/dropdown-menu";
+
+type DropdownProps<Value> = {
+ children: React.ReactNode;
+ label?: string;
+ items: Array<{
+ label: string;
+ value: Value;
+ }>;
+ onChange?: (value: Value) => void;
+};
+
+export function Dropdown<Value extends string>({ children, label, items, onChange }: DropdownProps<Value>) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" align="start">
+ {label && (
+ <>
+ <DropdownMenuLabel>{label}</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <DropdownMenuGroup>
+ {items.map((item) => (
+ <DropdownMenuItem
+ className="cursor-pointer"
+ key={item.value}
+ onClick={() => {
+ onChange?.(item.value);
+ }}
+ >
+ {item.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/Navbar.tsx b/apps/web/src/components/Navbar.tsx
deleted file mode 100644
index 9f1cdd5f5..000000000
--- a/apps/web/src/components/Navbar.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import Link from "next/link";
-
-export function Navbar() {
- return (
- <div className="flex gap-4 text-sm uppercase">
- <Link href="/">Dashboards</Link>
- <Link href="/reports">Reports</Link>
- </div>
- );
-}
diff --git a/apps/web/src/components/PageTitle.tsx b/apps/web/src/components/PageTitle.tsx
new file mode 100644
index 000000000..234703384
--- /dev/null
+++ b/apps/web/src/components/PageTitle.tsx
@@ -0,0 +1,11 @@
+import { type HtmlProps } from "@/types";
+
+type PageTitleProps = HtmlProps<HTMLDivElement>;
+
+export function PageTitle({ children }: PageTitleProps) {
+ return (
+ <div className="my-8 flex justify-between border-b border-border py-4">
+ <h1 className="h1">{children}</h1>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/Syntax.tsx b/apps/web/src/components/Syntax.tsx
new file mode 100644
index 000000000..9df05e139
--- /dev/null
+++ b/apps/web/src/components/Syntax.tsx
@@ -0,0 +1,13 @@
+import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
+import ts from "react-syntax-highlighter/dist/cjs/languages/hljs/typescript";
+import docco from "react-syntax-highlighter/dist/cjs/styles/hljs/docco";
+
+SyntaxHighlighter.registerLanguage("typescript", ts);
+
+type SyntaxProps = {
+ code: string;
+};
+
+export default function Syntax({ code }: SyntaxProps) {
+ return <SyntaxHighlighter style={docco}>{code}</SyntaxHighlighter>;
+}
diff --git a/apps/web/src/components/UserDropdown.tsx b/apps/web/src/components/UserDropdown.tsx
deleted file mode 100644
index 3b67adf87..000000000
--- a/apps/web/src/components/UserDropdown.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Avatar, AvatarFallback } from "@/components/ui/avatar";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
-import { User } from "lucide-react";
-
-export function UserDropdown() {
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button>
- <Avatar>
- <AvatarFallback>CL</AvatarFallback>
- </Avatar>
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-[200px]">
- <DropdownMenuGroup>
- <DropdownMenuItem>
- <User className="mr-2 h-4 w-4" />
- Profile
- </DropdownMenuItem>
- <DropdownMenuItem>
- <User className="mr-2 h-4 w-4" />
- Organization
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem className="text-red-600">
- <User className="mr-2 h-4 w-4" />
- Logout
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- )
-}
\ No newline at end of file
diff --git a/apps/web/src/components/WithSidebar.tsx b/apps/web/src/components/WithSidebar.tsx
new file mode 100644
index 000000000..e566d83fc
--- /dev/null
+++ b/apps/web/src/components/WithSidebar.tsx
@@ -0,0 +1,21 @@
+import { type HtmlProps } from "@/types";
+
+type WithSidebarProps = HtmlProps<HTMLDivElement>
+
+export function WithSidebar({children}: WithSidebarProps) {
+ return (
+ <div className="grid grid-cols-[200px_minmax(0,1fr)] gap-8">
+ {children}
+ </div>
+ )
+}
+
+type SidebarProps = HtmlProps<HTMLDivElement>
+
+export function Sidebar({children}: SidebarProps) {
+ return (
+ <div className="flex flex-col gap-1">
+ {children}
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/apps/web/src/components/clients/ClientActions.tsx b/apps/web/src/components/clients/ClientActions.tsx
new file mode 100644
index 000000000..dba20f84e
--- /dev/null
+++ b/apps/web/src/components/clients/ClientActions.tsx
@@ -0,0 +1,69 @@
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { Button } from "../ui/button";
+import { MoreHorizontal } from "lucide-react";
+import { pushModal, showConfirm } from "@/modals";
+import { type IClientWithProject } from "@/types";
+import { clipboard } from "@/utils/clipboard";
+import { api } from "@/utils/api";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+import { toast } from "../ui/use-toast";
+
+export function ClientActions({ id }: IClientWithProject) {
+ const refetch = useRefetchActive()
+ const deletion = api.client.remove.useMutation({
+ onSuccess() {
+ toast({
+ title: 'Success',
+ description: 'Client revoked, incoming requests will be rejected.',
+ })
+ refetch()
+ }
+ })
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" className="h-8 w-8 p-0">
+ <span className="sr-only">Open menu</span>
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem onClick={() => clipboard(id)}>
+ Copy client ID
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ pushModal("EditClient", { id });
+ }}
+ >
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={() => {
+ showConfirm({
+ title: 'Revoke client',
+ text: 'Are you sure you want to revoke this client? This action cannot be undone.',
+ onConfirm() {
+ deletion.mutate({
+ id,
+ })
+ }
+ })
+ }}
+ >
+ Revoke
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/clients/table.tsx b/apps/web/src/components/clients/table.tsx
new file mode 100644
index 000000000..16adabb11
--- /dev/null
+++ b/apps/web/src/components/clients/table.tsx
@@ -0,0 +1,43 @@
+import { formatDate } from "@/utils/date";
+import { type ColumnDef } from "@tanstack/react-table";
+import { type IClientWithProject } from "@/types";
+import { ClientActions } from "./ClientActions";
+
+export const columns: ColumnDef<IClientWithProject>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => {
+ return (
+ <div>
+ <div>{row.original.name}</div>
+ <div className="text-sm text-muted-foreground">
+ {row.original.project.name}
+ </div>
+ </div>
+ );
+ },
+ },
+ {
+ accessorKey: "id",
+ header: "Client ID",
+ },
+ {
+ accessorKey: "secret",
+ header: "Secret",
+ cell: () => <div className="italic text-muted-foreground">Hidden</div>,
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created at",
+ cell({ row }) {
+ const date = row.original.createdAt;
+ return <div>{formatDate(date)}</div>;
+ },
+ },
+ {
+ id: "actions",
+ header: "Actions",
+ cell: ({ row }) => <ClientActions {...row.original} />,
+ },
+];
diff --git a/apps/web/src/components/forms/InputWithLabel.tsx b/apps/web/src/components/forms/InputWithLabel.tsx
new file mode 100644
index 000000000..2a89fcaa7
--- /dev/null
+++ b/apps/web/src/components/forms/InputWithLabel.tsx
@@ -0,0 +1,18 @@
+import { forwardRef } from "react";
+import { Input, type InputProps } from "../ui/input";
+import { Label } from "../ui/label";
+
+type InputWithLabelProps = InputProps & {
+ label: string;
+};
+
+export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(({ label, ...props }, ref) => {
+ return (
+ <div>
+ <Label htmlFor={label} className="block mb-2">{label}</Label>
+ <Input ref={ref} id={label} {...props} />
+ </div>
+ );
+});
+
+InputWithLabel.displayName = "InputWithLabel";
diff --git a/apps/web/src/components/layouts/Main.tsx b/apps/web/src/components/layouts/Main.tsx
deleted file mode 100644
index 7b8f0cbd9..000000000
--- a/apps/web/src/components/layouts/Main.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import Head from "next/head";
-import { UserDropdown } from "../UserDropdown";
-import { Navbar } from "../Navbar";
-
-type MainLayoutProps = {
- children: React.ReactNode;
- className?: string;
-}
-
-export function MainLayout({ children, className }: MainLayoutProps) {
- return (
- <>
- <Head>
- <title>Create T3 App</title>
- <meta name="description" content="Generated by create-t3-app" />
- <link rel="icon" href="/favicon.ico" />
- </Head>
- <nav className="flex h-20 items-center justify-between border-b border-border bg-gradient-to-r from-blue-900 to-purple-600 px-8 text-white">
- <div className="flex flex-col [&_*]:leading-tight">
- <span className="text-2xl font-extrabold">MIXAN</span>
- <span className="text-xs text-gray-500">v0.0.1</span>
- </div>
-
- <Navbar />
-
- <div>
- <UserDropdown />
- </div>
- </nav>
- <main className={className}>
- {children}
- </main>
- </>
- );
-}
diff --git a/apps/web/src/components/layouts/MainLayout.tsx b/apps/web/src/components/layouts/MainLayout.tsx
new file mode 100644
index 000000000..8739ecf43
--- /dev/null
+++ b/apps/web/src/components/layouts/MainLayout.tsx
@@ -0,0 +1,29 @@
+import { NavbarUserDropdown } from "../navbar/NavbarUserDropdown";
+import { NavbarMenu } from "../navbar/NavbarMenu";
+import { Container } from "../Container";
+import Link from "next/link";
+
+type MainLayoutProps = {
+ children: React.ReactNode;
+ className?: string;
+};
+
+export function MainLayout({ children, className }: MainLayoutProps) {
+ return (
+ <>
+ <div className="h-2 w-full bg-gradient-to-r from-blue-900 to-purple-600"></div>
+ <nav className="border-b border-border">
+ <Container className="flex h-20 items-center justify-between ">
+ <Link href="/" className="text-3xl">mixan</Link>
+ <div className="flex items-center gap-8">
+ <NavbarMenu />
+ <div>
+ <NavbarUserDropdown />
+ </div>
+ </div>
+ </Container>
+ </nav>
+ <main className={className}>{children}</main>
+ </>
+ );
+}
diff --git a/apps/web/src/components/layouts/SettingsLayout.tsx b/apps/web/src/components/layouts/SettingsLayout.tsx
new file mode 100644
index 000000000..e24d1b046
--- /dev/null
+++ b/apps/web/src/components/layouts/SettingsLayout.tsx
@@ -0,0 +1,52 @@
+import { Container } from "../Container";
+import { MainLayout } from "./MainLayout";
+import { usePathname } from "next/navigation";
+import { Sidebar, WithSidebar } from "../WithSidebar";
+import Link from "next/link";
+import { cn } from "@/utils/cn";
+import { PageTitle } from "../PageTitle";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+
+type SettingsLayoutProps = {
+ children: React.ReactNode;
+ className?: string;
+};
+
+export function SettingsLayout({ children, className }: SettingsLayoutProps) {
+ const params = useOrganizationParams();
+ const pathname = usePathname();
+ const links = [
+ { href: `/${params.organization}/settings/organization`, label: "Organization" },
+ { href: `/${params.organization}/settings/projects`, label: "Projects" },
+ { href: `/${params.organization}/settings/clients`, label: "Clients" },
+ { href: `/${params.organization}/settings/profile`, label: "Profile" },
+ ];
+ return (
+ <MainLayout>
+ <Container>
+ <PageTitle>Settings</PageTitle>
+ <WithSidebar>
+ <Sidebar>
+ {links.map(({ href, label }) => (
+ <Link
+ key={href}
+ href={href}
+ className={cn(
+ "p-4 py-3 leading-none rounded-lg transition-colors",
+ pathname.startsWith(href)
+ ? "bg-slate-100"
+ : "hover:bg-slate-100",
+ )}
+ >
+ {label}
+ </Link>
+ ))}
+ </Sidebar>
+ <div className={cn('flex flex-col', className)}>
+ {children}
+ </div>
+ </WithSidebar>
+ </Container>
+ </MainLayout>
+ );
+}
diff --git a/apps/web/src/components/navbar/NavbarCreate.tsx b/apps/web/src/components/navbar/NavbarCreate.tsx
new file mode 100644
index 000000000..53d7d0fbe
--- /dev/null
+++ b/apps/web/src/components/navbar/NavbarCreate.tsx
@@ -0,0 +1,36 @@
+import { LineChart } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import Link from "next/link";
+
+export function NavbarCreate() {
+ const params = useOrganizationParams();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button size="sm">Create</Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem asChild>
+ <Link href={`/${params.organization}/reports`}>
+ <LineChart className="mr-2 h-4 w-4" />
+ <span>Create a report</span>
+ </Link>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/navbar/NavbarMenu.tsx b/apps/web/src/components/navbar/NavbarMenu.tsx
new file mode 100644
index 000000000..7dca2029d
--- /dev/null
+++ b/apps/web/src/components/navbar/NavbarMenu.tsx
@@ -0,0 +1,13 @@
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import Link from "next/link";
+import { NavbarCreate } from "./NavbarCreate";
+
+export function NavbarMenu() {
+ const params = useOrganizationParams()
+ return (
+ <div className="flex gap-6 items-center">
+ <Link href={`/${params.organization}`}>Home</Link>
+ <NavbarCreate />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/navbar/NavbarUserDropdown.tsx b/apps/web/src/components/navbar/NavbarUserDropdown.tsx
new file mode 100644
index 000000000..939574c0f
--- /dev/null
+++ b/apps/web/src/components/navbar/NavbarUserDropdown.tsx
@@ -0,0 +1,67 @@
+import { Avatar, AvatarFallback } from "@/components/ui/avatar";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import { User } from "lucide-react";
+import { signOut } from "next-auth/react";
+import Link from "next/link";
+
+export function NavbarUserDropdown() {
+ const params = useOrganizationParams();
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button>
+ <Avatar>
+ <AvatarFallback>CL</AvatarFallback>
+ </Avatar>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[200px]">
+ <DropdownMenuGroup>
+ <DropdownMenuItem asChild className="cursor-pointer">
+ <Link href={`/${params.organization}/settings/organization`}>
+ <User className="mr-2 h-4 w-4" />
+ Organization
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild className="cursor-pointer">
+ <Link href={`/${params.organization}/settings/projects`}>
+ <User className="mr-2 h-4 w-4" />
+ Projects
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild className="cursor-pointer">
+ <Link href={`/${params.organization}/settings/clients`}>
+ <User className="mr-2 h-4 w-4" />
+ Clients
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild className="cursor-pointer">
+ <Link href={`/${params.organization}/settings/profile`}>
+ <User className="mr-2 h-4 w-4" />
+ Profile
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-red-600 cursor-pointer"
+ onClick={() => {
+ signOut().catch(console.error);
+ }}
+ >
+ <User className="mr-2 h-4 w-4" />
+ Logout
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/projects/ProjectActions.tsx b/apps/web/src/components/projects/ProjectActions.tsx
new file mode 100644
index 000000000..9163e7bbc
--- /dev/null
+++ b/apps/web/src/components/projects/ProjectActions.tsx
@@ -0,0 +1,70 @@
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { Button } from "../ui/button";
+import { MoreHorizontal } from "lucide-react";
+import { pushModal, showConfirm } from "@/modals";
+import { type IProject } from "@/types";
+import { clipboard } from "@/utils/clipboard";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+import { api } from "@/utils/api";
+import { toast } from "../ui/use-toast";
+
+export function ProjectActions({ id }: IProject) {
+ const refetch = useRefetchActive()
+ const deletion = api.project.remove.useMutation({
+ onSuccess() {
+ toast({
+ title: 'Success',
+ description: 'Project deleted successfully.',
+ })
+ refetch()
+ }
+ })
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" className="h-8 w-8 p-0">
+ <span className="sr-only">Open menu</span>
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem onClick={() => clipboard(id)}>
+ Copy project ID
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ pushModal("EditProject", { id });
+ }}
+ >
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={() => {
+ showConfirm({
+ title: 'Delete project',
+ text: 'This will delete all events for this project. This action cannot be undone.',
+ onConfirm() {
+ deletion.mutate({
+ id,
+ })
+ }
+ })
+ }}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/components/projects/table.tsx b/apps/web/src/components/projects/table.tsx
new file mode 100644
index 000000000..d967505b7
--- /dev/null
+++ b/apps/web/src/components/projects/table.tsx
@@ -0,0 +1,26 @@
+import { formatDate } from "@/utils/date";
+import { type ColumnDef } from "@tanstack/react-table";
+import { type Project as IProject } from "@prisma/client";
+import { ProjectActions } from "./ProjectActions";
+
+export type Project = IProject;
+
+export const columns: ColumnDef<Project>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created at",
+ cell({ row }) {
+ const date = row.original.createdAt;
+ return <div>{formatDate(date)}</div>;
+ },
+ },
+ {
+ id: "actions",
+ header: "Actions",
+ cell: ({ row }) => <ProjectActions {...row.original} />,
+ },
+];
diff --git a/apps/web/src/components/report/ReportDateRange.tsx b/apps/web/src/components/report/ReportDateRange.tsx
index 938e8740c..cf96683c0 100644
--- a/apps/web/src/components/report/ReportDateRange.tsx
+++ b/apps/web/src/components/report/ReportDateRange.tsx
@@ -13,11 +13,18 @@ export function ReportDateRange() {
<RadioGroup>
<RadioGroupItem
onClick={() => {
- dispatch(changeDateRanges(1));
+ dispatch(changeDateRanges('today'));
}}
>
Today
</RadioGroupItem>
+ <RadioGroupItem
+ onClick={() => {
+ dispatch(changeDateRanges(1));
+ }}
+ >
+ 24 hours
+ </RadioGroupItem>
<RadioGroupItem
onClick={() => {
dispatch(changeDateRanges(7));
diff --git a/apps/web/src/components/report/chart/ReportLineChart.tsx b/apps/web/src/components/report/chart/ReportLineChart.tsx
index 486d67bb6..dcd49ce09 100644
--- a/apps/web/src/components/report/chart/ReportLineChart.tsx
+++ b/apps/web/src/components/report/chart/ReportLineChart.tsx
@@ -31,7 +31,9 @@ export function ReportLineChart({
}: ReportLineChartProps) {
const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
- const chart = api.chartMeta.chart.useQuery(
+ const hasEmptyFilters = events.some((event) => event.filters.some((filter) => filter.value.length === 0));
+
+ const chart = api.chart.chart.useQuery(
{
interval,
chartType,
@@ -42,7 +44,7 @@ export function ReportLineChart({
name,
},
{
- enabled: events.length > 0,
+ enabled: events.length > 0 && !hasEmptyFilters,
},
);
@@ -67,10 +69,11 @@ export function ReportLineChart({
<AutoSizer disableHeight>
{({ width }) => (
<LineChart width={width} height={Math.min(width * 0.5, 400)}>
- <YAxis dataKey={"count"}></YAxis>
+ <YAxis dataKey={"count"} width={30} fontSize={12}></YAxis>
<Tooltip content={<ReportLineChartTooltip />} />
<CartesianGrid strokeDasharray="3 3" />
<XAxis
+ fontSize={12}
dataKey="date"
tickFormatter={(m: Date) => {
return formatDate(m);
diff --git a/apps/web/src/components/report/chart/ReportLineChartTooltop.tsx b/apps/web/src/components/report/chart/ReportLineChartTooltop.tsx
index a45208c82..3fa06eae0 100644
--- a/apps/web/src/components/report/chart/ReportLineChartTooltop.tsx
+++ b/apps/web/src/components/report/chart/ReportLineChartTooltop.tsx
@@ -1,3 +1,4 @@
+import { useMappings } from "@/hooks/useMappings";
import { type IToolTipProps } from "@/types";
type ReportLineChartTooltipProps = IToolTipProps<{
@@ -8,13 +9,15 @@ type ReportLineChartTooltipProps = IToolTipProps<{
count: number;
label: string;
};
-}>
+}>;
export function ReportLineChartTooltip({
active,
payload,
}: ReportLineChartTooltipProps) {
- if (!active || !payload) {
+ const getLabel = useMappings();
+
+ if (!active || !payload) {
return null;
}
@@ -22,7 +25,6 @@ export function ReportLineChartTooltip({
return null;
}
-
const limit = 3;
const sorted = payload.slice(0).sort((a, b) => b.value - a.value);
const visible = sorted.slice(0, limit);
@@ -39,7 +41,7 @@ export function ReportLineChartTooltip({
></div>
<div className="flex flex-col">
<div className="min-w-0 max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap font-medium">
- {item.payload.label}
+ {getLabel(item.payload.label)}
</div>
<div>{item.payload.count}</div>
</div>
diff --git a/apps/web/src/components/report/chart/ReportTable.tsx b/apps/web/src/components/report/chart/ReportTable.tsx
index cfdf5708b..fc43f5899 100644
--- a/apps/web/src/components/report/chart/ReportTable.tsx
+++ b/apps/web/src/components/report/chart/ReportTable.tsx
@@ -5,9 +5,11 @@ import { useSelector } from "@/redux";
import { Checkbox } from "@/components/ui/checkbox";
import { getChartColor } from "@/utils/theme";
import { cn } from "@/utils/cn";
+import { useMappings } from "@/hooks/useMappings";
+
type ReportTableProps = {
- data: RouterOutputs["chartMeta"]["chart"];
+ data: RouterOutputs["chart"]["chart"];
visibleSeries: string[];
setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;
};
@@ -19,6 +21,7 @@ export function ReportTable({
}: ReportTableProps) {
const interval = useSelector((state) => state.report.interval);
const formatDate = useFormatDateInterval(interval);
+ const getLabel = useMappings()
function handleChange(name: string, checked: boolean) {
setVisibleSeries((prev) => {
@@ -34,7 +37,7 @@ export function ReportTable({
const cell = "p-2 last:pr-8 last:w-[8rem]";
const value = "min-w-[6rem] text-right";
const header = "text-sm font-medium";
- const total = 'bg-gray-50 text-emerald-600 font-bold border-r border-border'
+ const total = 'bg-gray-50 text-emerald-600 font-medium border-r border-border'
return (
<div className="flex w-fit max-w-full rounded-md border border-border">
{/* Labels */}
@@ -63,7 +66,7 @@ export function ReportTable({
checked={checked}
/>
<div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
- {serie.name}
+ {getLabel(serie.name)}
</div>
</div>
);
diff --git a/apps/web/src/components/report/reportSlice.ts b/apps/web/src/components/report/reportSlice.ts
index cd100eac7..8e0438be4 100644
--- a/apps/web/src/components/report/reportSlice.ts
+++ b/apps/web/src/components/report/reportSlice.ts
@@ -11,7 +11,7 @@ type InitialState = IChartInput;
// First approach: define the initial state using that type
const initialState: InitialState = {
- name: "",
+ name: "screen_view",
chartType: "linear",
startDate: getDaysOldDate(7),
endDate: new Date(),
@@ -102,7 +102,18 @@ export const reportSlice = createSlice({
state.endDate = action.payload;
},
- changeDateRanges: (state, action: PayloadAction<number>) => {
+ changeDateRanges: (state, action: PayloadAction<number | 'today'>) => {
+ if(action.payload === 'today') {
+ state.startDate = new Date();
+ state.endDate = new Date();
+ state.startDate.setHours(0,0,0,0)
+ state.interval = 'hour'
+ return state
+ }
+
+ state.startDate = getDaysOldDate(action.payload);
+ state.endDate = new Date();
+
if (action.payload === 1) {
state.interval = "hour";
} else if (action.payload <= 30) {
@@ -110,8 +121,6 @@ export const reportSlice = createSlice({
} else {
state.interval = "month";
}
- state.startDate = getDaysOldDate(action.payload);
- state.endDate = new Date();
},
},
});
diff --git a/apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx b/apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx
index 324baaf12..3f65ce608 100644
--- a/apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx
+++ b/apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx
@@ -34,7 +34,7 @@ export function ReportBreakdownMore({ onClick }: ReportBreakdownMoreProps) {
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-[200px]">
+ <DropdownMenuContent align="start" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem className="text-red-600" onClick={() => onClick('remove')}>
<Trash className="mr-2 h-4 w-4" />
diff --git a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
index e03e7947f..ecc80a829 100644
--- a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -5,14 +5,15 @@ import { addBreakdown, changeBreakdown, removeBreakdown } from "../reportSlice";
import { type ReportEventMoreProps } from "./ReportEventMore";
import { type IChartBreakdown } from "@/types";
import { ReportBreakdownMore } from "./ReportBreakdownMore";
+import { RenderDots } from "@/components/ui/RenderDots";
export function ReportBreakdowns() {
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
const dispatch = useDispatch();
- const propertiesQuery = api.chartMeta.properties.useQuery();
+ const propertiesQuery = api.chart.properties.useQuery();
const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({
value: item,
- label: item,
+ label: item, // <RenderDots truncate>{item}</RenderDots>,
}));
const handleMore = (breakdown: IChartBreakdown) => {
diff --git a/apps/web/src/components/report/sidebar/ReportEventFilters.tsx b/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
index b5c94edc1..24d70e455 100644
--- a/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
+++ b/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
@@ -1,10 +1,10 @@
import { api } from "@/utils/api";
-import { type IChartEvent } from "@/types";
import {
- CreditCard,
- SlidersHorizontal,
- Trash,
-} from "lucide-react";
+ type IChartEvent,
+ type IChartEventFilterValue,
+ type IChartEventFilter,
+} from "@/types";
+import { CreditCard, SlidersHorizontal, Trash } from "lucide-react";
import {
CommandDialog,
CommandEmpty,
@@ -18,8 +18,11 @@ import { type Dispatch } from "react";
import { RenderDots } from "@/components/ui/RenderDots";
import { useDispatch } from "@/redux";
import { changeEvent } from "../reportSlice";
-import { Combobox } from "@/components/ui/combobox";
import { Button } from "@/components/ui/button";
+import { ComboboxMulti } from "@/components/ui/combobox-multi";
+import { Dropdown } from "@/components/Dropdown";
+import { operators } from "@/utils/constants";
+import { useMappings } from "@/hooks/useMappings";
type ReportEventFiltersProps = {
event: IChartEvent;
@@ -33,7 +36,7 @@ export function ReportEventFilters({
setIsCreating,
}: ReportEventFiltersProps) {
const dispatch = useDispatch();
- const propertiesQuery = api.chartMeta.properties.useQuery(
+ const propertiesQuery = api.chart.properties.useQuery(
{
event: event.name,
},
@@ -50,7 +53,7 @@ export function ReportEventFilters({
})}
<CommandDialog open={isCreating} onOpenChange={setIsCreating} modal>
- <CommandInput placeholder="Type a command or search..." />
+ <CommandInput placeholder="Search properties" />
<CommandList>
<CommandEmpty>Such emptyness 🤨</CommandEmpty>
<CommandGroup heading="Properties">
@@ -67,7 +70,8 @@ export function ReportEventFilters({
{
id: (event.filters.length + 1).toString(),
name: item,
- value: "",
+ operator: "is",
+ value: [],
},
],
}),
@@ -93,8 +97,9 @@ type FilterProps = {
};
function Filter({ filter, event }: FilterProps) {
+ const getLabel = useMappings()
const dispatch = useDispatch();
- const potentialValues = api.chartMeta.values.useQuery({
+ const potentialValues = api.chart.values.useQuery({
event: event.name,
property: filter.name,
});
@@ -102,7 +107,7 @@ function Filter({ filter, event }: FilterProps) {
const valuesCombobox =
potentialValues.data?.values?.map((item) => ({
value: item,
- label: item,
+ label: getLabel(item),
})) ?? [];
const removeFilter = () => {
@@ -114,7 +119,9 @@ function Filter({ filter, event }: FilterProps) {
);
};
- const changeFilter = (value: string) => {
+ const changeFilterValue = (
+ value: IChartEventFilterValue | IChartEventFilterValue[],
+ ) => {
dispatch(
changeEvent({
...event,
@@ -122,7 +129,25 @@ function Filter({ filter, event }: FilterProps) {
if (item.id === filter.id) {
return {
...item,
- value,
+ value: Array.isArray(value) ? value : [value],
+ };
+ }
+
+ return item;
+ }),
+ }),
+ );
+ };
+
+ const changeFilterOperator = (operator: IChartEventFilter["operator"]) => {
+ dispatch(
+ changeEvent({
+ ...event,
+ filters: event.filters.map((item) => {
+ if (item.id === filter.id) {
+ return {
+ ...item,
+ operator,
};
}
@@ -141,21 +166,54 @@ function Filter({ filter, event }: FilterProps) {
<div className="flex h-5 w-5 flex-shrink-0 items-center justify-center rounded bg-emerald-600 text-xs font-medium text-white">
<SlidersHorizontal size={10} />
</div>
- <RenderDots className="text-sm flex-1">{filter.name}</RenderDots>
+ <div className="flex flex-1 text-sm">
+ <RenderDots truncate>{filter.name}</RenderDots>
+ </div>
<Button variant="ghost" size="sm" onClick={removeFilter}>
<Trash size={16} />
</Button>
</div>
- {/* <ComboboxMulti items={valuesCombobox} selected={[]} setSelected={(fn) => {
- return fn(filter.value)
- //
- }} /> */}
- <Combobox
+ <div className="flex gap-1">
+ <Dropdown
+ onChange={changeFilterOperator}
+ items={Object.entries(operators).map(([key, value]) => ({
+ value: key as IChartEventFilter["operator"],
+ label: value,
+ }))}
+ label="Segment"
+ >
+ <Button variant={"ghost"} className="whitespace-nowrap">
+ {operators[filter.operator]}
+ </Button>
+ </Dropdown>
+ <ComboboxMulti
+ placeholder="Select values"
+ items={valuesCombobox}
+ selected={filter.value.map((item) => ({
+ value: item?.toString() ?? "__filter_value_null__",
+ label: getLabel(item?.toString() ?? "__filter_value_null__"),
+ }))}
+ setSelected={(setFn) => {
+ if(typeof setFn === "function") {
+ const newValues = setFn(
+ filter.value.map((item) => ({
+ value: item?.toString() ?? "__filter_value_null__",
+ label: getLabel(item?.toString() ?? "__filter_value_null__"),
+ })),
+ );
+ changeFilterValue(newValues.map((item) => item.value));
+ } else {
+ changeFilterValue(setFn.map((item) => item.value));
+ }
+ }}
+ />
+ </div>
+ {/* <Combobox
items={valuesCombobox}
value={filter.value}
placeholder="Select value"
onChange={changeFilter}
- />
+ /> */}
{/* <Input
value={filter.value}
onChange={(e) => {
diff --git a/apps/web/src/components/report/sidebar/ReportEvents.tsx b/apps/web/src/components/report/sidebar/ReportEvents.tsx
index d0fdecf94..6b0b5a354 100644
--- a/apps/web/src/components/report/sidebar/ReportEvents.tsx
+++ b/apps/web/src/components/report/sidebar/ReportEvents.tsx
@@ -6,12 +6,14 @@ import { ReportEventFilters } from "./ReportEventFilters";
import { useState } from "react";
import { ReportEventMore, type ReportEventMoreProps } from "./ReportEventMore";
import { type IChartEvent } from "@/types";
+import { Filter, GanttChart, Users } from "lucide-react";
+import { Dropdown } from "@/components/Dropdown";
export function ReportEvents() {
const [isCreating, setIsCreating] = useState(false);
const selectedEvents = useSelector((state) => state.report.events);
const dispatch = useDispatch();
- const eventsQuery = api.chartMeta.events.useQuery();
+ const eventsQuery = api.chart.events.useQuery();
const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({
value: item.name,
label: item.name,
@@ -38,9 +40,11 @@ export function ReportEvents() {
<div className="flex flex-col gap-4">
{selectedEvents.map((event) => {
return (
- <div key={event.name} className="border rounded-lg">
- <div className="flex gap-2 items-center p-2 px-4">
- <div className="flex-shrink-0 bg-purple-500 w-5 h-5 rounded text-xs flex items-center justify-center text-white font-medium">{event.id}</div>
+ <div key={event.name} className="rounded-lg border">
+ <div className="flex items-center gap-2 p-2">
+ <div className="flex h-5 w-5 flex-shrink-0 items-center justify-center rounded bg-purple-500 text-xs font-medium text-white">
+ {event.id}
+ </div>
<Combobox
value={event.name}
onChange={(value) => {
@@ -57,10 +61,50 @@ export function ReportEvents() {
/>
<ReportEventMore onClick={handleMore(event)} />
</div>
- <ReportEventFilters
- {...{ isCreating, setIsCreating, event }}
- />
+ {/* Segment and Filter buttons */}
+ <div className="flex gap-2 p-2 pt-0 text-sm">
+ <Dropdown
+ onChange={(segment) => {
+ dispatch(
+ changeEvent({
+ ...event,
+ segment,
+ }),
+ );
+ }}
+ items={[
+ {
+ value: "event",
+ label: "All events",
+ },
+ {
+ value: "user",
+ label: "Unique users",
+ },
+ ]}
+ label="Segment"
+ >
+ <button className="flex items-center gap-1 rounded-md border border-border p-1 px-2 font-medium leading-none text-xs">
+ {event.segment === "user" ? (
+ <><Users size={12} /> Unique users</>
+ ) : (
+ <><GanttChart size={12} /> All events</>
+ )}
+ </button>
+ </Dropdown>
+ <button
+ onClick={() => {
+ handleMore(event)("createFilter");
+ }}
+ className="flex items-center gap-1 rounded-md border border-border p-1 px-2 font-medium leading-none text-xs"
+ >
+ <Filter size={12} /> Filter
+ </button>
+ </div>
+
+ {/* Filters */}
+ <ReportEventFilters {...{ isCreating, setIsCreating, event }} />
</div>
);
})}
@@ -71,6 +115,7 @@ export function ReportEvents() {
dispatch(
addEvent({
name: value,
+ segment: "event",
filters: [],
}),
);
diff --git a/apps/web/src/components/ui/RenderDots.tsx b/apps/web/src/components/ui/RenderDots.tsx
index dfa8577c5..b4db94686 100644
--- a/apps/web/src/components/ui/RenderDots.tsx
+++ b/apps/web/src/components/ui/RenderDots.tsx
@@ -1,21 +1,51 @@
import { cn } from "@/utils/cn";
-import { ChevronRight } from "lucide-react";
+import { Asterisk, ChevronRight } from "lucide-react";
+import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
interface RenderDotsProps extends React.HTMLAttributes<HTMLDivElement> {
children: string;
+ truncate?: boolean;
}
-export function RenderDots({ children, className, ...props }: RenderDotsProps) {
+export function RenderDots({
+ children,
+ className,
+ truncate,
+ ...props
+}: RenderDotsProps) {
+ const parts = children.split(".");
+ const sliceAt = truncate && parts.length > 3 ? 3 : 0;
return (
- <div {...props} className={cn('flex gap-1', className)}>
- {children.split(".").map((str, index) => {
- return (
- <div className="flex items-center gap-1" key={str + index}>
- {index !== 0 && <ChevronRight className="flex-shrink-0 !w-3 !h-3 top-[0.5px] relative" />}
- <span>{str}</span>
- </div>
- );
- })}
- </div>
+ <Tooltip disableHoverableContent={true} open={sliceAt === 0 ? false : undefined}>
+ <TooltipTrigger>
+ <div
+ {...props}
+ className={cn("flex items-center gap-1", className)}
+ >
+ {parts.slice(-sliceAt).map((str, index) => {
+ return (
+ <div className="flex items-center gap-1" key={str + index}>
+ {index !== 0 && (
+ <ChevronRight className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
+ )}
+ {str.includes("[*]") ? (
+ <>
+ {str.replace("[*]", "")}
+ <Asterisk className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
+ </>
+ ) : str === "*" ? (
+ <Asterisk className="relative top-[0.9px] !h-3 !w-3 flex-shrink-0" />
+ ) : (
+ str
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent align="start">
+ <p>{children}</p>
+ </TooltipContent>
+ </Tooltip>
);
}
diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/web/src/components/ui/alert-dialog.tsx
new file mode 100644
index 000000000..b6ec12ef4
--- /dev/null
+++ b/apps/web/src/components/ui/alert-dialog.tsx
@@ -0,0 +1,139 @@
+import * as React from "react"
+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
+
+import { cn } from "@/utils/cn"
+import { buttonVariants } from "@/components/ui/button"
+
+const AlertDialog = AlertDialogPrimitive.Root
+
+const AlertDialogTrigger = AlertDialogPrimitive.Trigger
+
+const AlertDialogPortal = AlertDialogPrimitive.Portal
+
+const AlertDialogOverlay = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
+>(({ className, children, ...props }, ref) => (
+ <AlertDialogPrimitive.Overlay
+ className={cn(
+ "fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className
+ )}
+ {...props}
+ ref={ref}
+ />
+))
+AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
+
+const AlertDialogContent = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
+ className
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+))
+AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
+
+const AlertDialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-2 text-center sm:text-left",
+ className
+ )}
+ {...props}
+ />
+)
+AlertDialogHeader.displayName = "AlertDialogHeader"
+
+const AlertDialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className
+ )}
+ {...props}
+ />
+)
+AlertDialogFooter.displayName = "AlertDialogFooter"
+
+const AlertDialogTitle = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Title
+ ref={ref}
+ className={cn("text-lg font-semibold", className)}
+ {...props}
+ />
+))
+AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
+
+const AlertDialogDescription = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+))
+AlertDialogDescription.displayName =
+ AlertDialogPrimitive.Description.displayName
+
+const AlertDialogAction = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Action>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Action
+ ref={ref}
+ className={cn(buttonVariants(), className)}
+ {...props}
+ />
+))
+AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
+
+const AlertDialogCancel = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Cancel
+ ref={ref}
+ className={cn(
+ buttonVariants({ variant: "outline" }),
+ "mt-2 sm:mt-0",
+ className
+ )}
+ {...props}
+ />
+))
+AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
+
+export {
+ AlertDialog,
+ AlertDialogPortal,
+ AlertDialogOverlay,
+ AlertDialogTrigger,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogFooter,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogAction,
+ AlertDialogCancel,
+}
diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx
index 9c2f50822..39932cc09 100644
--- a/apps/web/src/components/ui/button.tsx
+++ b/apps/web/src/components/ui/button.tsx
@@ -52,5 +52,8 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
}
)
Button.displayName = "Button"
+Button.defaultProps = {
+ type: 'button'
+}
export { Button, buttonVariants }
diff --git a/apps/web/src/components/ui/combobox-multi.tsx b/apps/web/src/components/ui/combobox-multi.tsx
index 0d4fdf37b..0f1ec6aec 100644
--- a/apps/web/src/components/ui/combobox-multi.tsx
+++ b/apps/web/src/components/ui/combobox-multi.tsx
@@ -9,21 +9,22 @@ import {
} from "@/components/ui/command";
import { Command as CommandPrimitive } from "cmdk";
-type Framework = Record<"value" | "label", string>;
+type Item = Record<"value" | "label", string>;
type ComboboxMultiProps = {
- selected: Framework[];
- setSelected: React.Dispatch<React.SetStateAction<Framework[]>>;
- items: Framework[];
+ selected: Item[];
+ setSelected: React.Dispatch<React.SetStateAction<Item[]>>;
+ items: Item[];
+ placeholder: string
}
-export function ComboboxMulti({ items, selected, setSelected, ...props }: ComboboxMultiProps) {
+export function ComboboxMulti({ items, selected, setSelected, placeholder, ...props }: ComboboxMultiProps) {
const inputRef = React.useRef<HTMLInputElement>(null);
const [open, setOpen] = React.useState(false);
const [inputValue, setInputValue] = React.useState("");
- const handleUnselect = React.useCallback((framework: Framework) => {
- setSelected(prev => prev.filter(s => s.value !== framework.value));
+ const handleUnselect = React.useCallback((item: Item) => {
+ setSelected(prev => prev.filter(s => s.value !== item.value));
}, []);
const handleKeyDown = React.useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
@@ -45,30 +46,30 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
}
}, []);
- const selectables = items.filter(framework => !selected.includes(framework));
-
+ const selectables = items.filter(item => !selected.find(s => s.value === item.value));
+
return (
<Command onKeyDown={handleKeyDown} className="overflow-visible bg-white">
<div
className="group border border-input px-3 py-2 text-sm ring-offset-background rounded-md focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2"
>
<div className="flex gap-1 flex-wrap">
- {selected.map((framework) => {
+ {selected.map((item) => {
return (
- <Badge key={framework.value} variant="secondary">
- {framework.label}
+ <Badge key={item.value} variant="secondary">
+ {item.label}
<button
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
onKeyDown={(e) => {
if (e.key === "Enter") {
- handleUnselect(framework);
+ handleUnselect(item);
}
}}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
- onClick={() => handleUnselect(framework)}
+ onClick={() => handleUnselect(item)}
>
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
</button>
@@ -82,7 +83,7 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
onValueChange={setInputValue}
onBlur={() => setOpen(false)}
onFocus={() => setOpen(true)}
- placeholder="Select frameworks..."
+ placeholder={placeholder}
className="ml-2 bg-transparent outline-none placeholder:text-muted-foreground flex-1"
/>
</div>
@@ -91,21 +92,21 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
{open && selectables.length > 0 ?
<div className="absolute w-full z-10 top-0 rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in">
<CommandGroup className="h-full overflow-auto">
- {selectables.map((framework) => {
+ {selectables.map((item) => {
return (
<CommandItem
- key={framework.value}
+ key={item.value}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onSelect={(value) => {
setInputValue("")
- setSelected(prev => [...prev, framework])
+ setSelected(prev => [...prev, item])
}}
className={"cursor-pointer"}
>
- {framework.label}
+ {item.label}
</CommandItem>
);
})}
diff --git a/apps/web/src/components/ui/combobox.tsx b/apps/web/src/components/ui/combobox.tsx
index f16ff41ca..9f09540fd 100644
--- a/apps/web/src/components/ui/combobox.tsx
+++ b/apps/web/src/components/ui/combobox.tsx
@@ -24,6 +24,7 @@ type ComboboxProps = {
}>;
value: string;
onChange: (value: string) => void;
+ children?: React.ReactNode
};
export function Combobox({
@@ -31,6 +32,7 @@ export function Combobox({
items,
value,
onChange,
+ children
}: ComboboxProps) {
const [open, setOpen] = React.useState(false);
@@ -43,17 +45,17 @@ export function Combobox({
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
- <Button
+ {children ?? <Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-full min-w-0 justify-between"
>
- {value ? find(value)?.label ?? "No match" : placeholder}
+ <span className="overflow-hidden text-ellipsis">{value ? find(value)?.label ?? "No match" : placeholder}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
+ </Button>}
</PopoverTrigger>
- <PopoverContent className="w-full min-w-0 p-0">
+ <PopoverContent className="w-full min-w-0 p-0" align="start">
<Command>
<CommandInput placeholder="Search item..." />
<CommandEmpty>Nothing selected</CommandEmpty>
@@ -61,8 +63,9 @@ export function Combobox({
{items.map((item) => (
<CommandItem
key={item.value}
+ value={item.value}
onSelect={(currentValue) => {
- const value = find(currentValue)?.value ?? "";
+ const value = find(currentValue)?.value ?? currentValue;
onChange(value);
setOpen(false);
}}
diff --git a/apps/web/src/components/ui/label.tsx b/apps/web/src/components/ui/label.tsx
new file mode 100644
index 000000000..d69b724e0
--- /dev/null
+++ b/apps/web/src/components/ui/label.tsx
@@ -0,0 +1,24 @@
+import * as React from "react"
+import * as LabelPrimitive from "@radix-ui/react-label"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/utils/cn"
+
+const labelVariants = cva(
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 block mb-2"
+)
+
+const Label = React.forwardRef<
+ React.ElementRef<typeof LabelPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
+ VariantProps<typeof labelVariants>
+>(({ className, ...props }, ref) => (
+ <LabelPrimitive.Root
+ ref={ref}
+ className={cn(labelVariants(), className)}
+ {...props}
+ />
+))
+Label.displayName = LabelPrimitive.Root.displayName
+
+export { Label }
diff --git a/apps/web/src/components/ui/radio-group.tsx b/apps/web/src/components/ui/radio-group.tsx
index 585853ae0..3f7b7ead9 100644
--- a/apps/web/src/components/ui/radio-group.tsx
+++ b/apps/web/src/components/ui/radio-group.tsx
@@ -10,7 +10,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
return (
<div
className={cn(
- "flex h-10 w-full divide-x rounded-md border border-input bg-background text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-10 divide-x rounded-md border border-input bg-background text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
@@ -22,7 +22,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
const RadioGroupItem = React.forwardRef<HTMLButtonElement, RadioGroupItemProps>(({className, ...props}, ref) => {
return (
- <button {...props} className={cn('flex-1 hover:bg-slate-100 transition-colors font-medium', className)} type="button" ref={ref} />
+ <button {...props} className={cn('flex-1 px-3 whitespace-nowrap leading-none hover:bg-slate-100 transition-colors font-medium', className)} type="button" ref={ref} />
)
})
diff --git a/apps/web/src/components/ui/table.tsx b/apps/web/src/components/ui/table.tsx
new file mode 100644
index 000000000..5ae70b6b2
--- /dev/null
+++ b/apps/web/src/components/ui/table.tsx
@@ -0,0 +1,114 @@
+import * as React from "react"
+
+import { cn } from "@/utils/cn"
+
+const Table = React.forwardRef<
+ HTMLTableElement,
+ React.HTMLAttributes<HTMLTableElement>
+>(({ className, ...props }, ref) => (
+ <div className="relative w-full overflow-auto">
+ <table
+ ref={ref}
+ className={cn("w-full caption-bottom text-sm", className)}
+ {...props}
+ />
+ </div>
+))
+Table.displayName = "Table"
+
+const TableHeader = React.forwardRef<
+ HTMLTableSectionElement,
+ React.HTMLAttributes<HTMLTableSectionElement>
+>(({ className, ...props }, ref) => (
+ <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
+))
+TableHeader.displayName = "TableHeader"
+
+const TableBody = React.forwardRef<
+ HTMLTableSectionElement,
+ React.HTMLAttributes<HTMLTableSectionElement>
+>(({ className, ...props }, ref) => (
+ <tbody
+ ref={ref}
+ className={cn("[&_tr:last-child]:border-0", className)}
+ {...props}
+ />
+))
+TableBody.displayName = "TableBody"
+
+const TableFooter = React.forwardRef<
+ HTMLTableSectionElement,
+ React.HTMLAttributes<HTMLTableSectionElement>
+>(({ className, ...props }, ref) => (
+ <tfoot
+ ref={ref}
+ className={cn("bg-primary font-medium text-primary-foreground", className)}
+ {...props}
+ />
+))
+TableFooter.displayName = "TableFooter"
+
+const TableRow = React.forwardRef<
+ HTMLTableRowElement,
+ React.HTMLAttributes<HTMLTableRowElement>
+>(({ className, ...props }, ref) => (
+ <tr
+ ref={ref}
+ className={cn(
+ "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
+ className
+ )}
+ {...props}
+ />
+))
+TableRow.displayName = "TableRow"
+
+const TableHead = React.forwardRef<
+ HTMLTableCellElement,
+ React.ThHTMLAttributes<HTMLTableCellElement>
+>(({ className, ...props }, ref) => (
+ <th
+ ref={ref}
+ className={cn(
+ "h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
+ className
+ )}
+ {...props}
+ />
+))
+TableHead.displayName = "TableHead"
+
+const TableCell = React.forwardRef<
+ HTMLTableCellElement,
+ React.TdHTMLAttributes<HTMLTableCellElement>
+>(({ className, ...props }, ref) => (
+ <td
+ ref={ref}
+ className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
+ {...props}
+ />
+))
+TableCell.displayName = "TableCell"
+
+const TableCaption = React.forwardRef<
+ HTMLTableCaptionElement,
+ React.HTMLAttributes<HTMLTableCaptionElement>
+>(({ className, ...props }, ref) => (
+ <caption
+ ref={ref}
+ className={cn("mt-4 text-sm text-muted-foreground", className)}
+ {...props}
+ />
+))
+TableCaption.displayName = "TableCaption"
+
+export {
+ Table,
+ TableHeader,
+ TableBody,
+ TableFooter,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableCaption,
+}
diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx
new file mode 100644
index 000000000..f421a7f2c
--- /dev/null
+++ b/apps/web/src/components/ui/toast.tsx
@@ -0,0 +1,127 @@
+import * as React from "react"
+import * as ToastPrimitives from "@radix-ui/react-toast"
+import { cva, type VariantProps } from "class-variance-authority"
+import { X } from "lucide-react"
+
+import { cn } from "@/utils/cn"
+
+const ToastProvider = ToastPrimitives.Provider
+
+const ToastViewport = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Viewport>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Viewport
+ ref={ref}
+ className={cn(
+ "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
+ className
+ )}
+ {...props}
+ />
+))
+ToastViewport.displayName = ToastPrimitives.Viewport.displayName
+
+const toastVariants = cva(
+ "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
+ {
+ variants: {
+ variant: {
+ default: "border bg-background text-foreground",
+ destructive:
+ "destructive group border-destructive bg-destructive text-destructive-foreground",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+const Toast = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Root>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
+ VariantProps<typeof toastVariants>
+>(({ className, variant, ...props }, ref) => {
+ return (
+ <ToastPrimitives.Root
+ ref={ref}
+ className={cn(toastVariants({ variant }), className)}
+ {...props}
+ />
+ )
+})
+Toast.displayName = ToastPrimitives.Root.displayName
+
+const ToastAction = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Action>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Action
+ ref={ref}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
+ className
+ )}
+ {...props}
+ />
+))
+ToastAction.displayName = ToastPrimitives.Action.displayName
+
+const ToastClose = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Close>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Close
+ ref={ref}
+ className={cn(
+ "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
+ className
+ )}
+ toast-close=""
+ {...props}
+ >
+ <X className="h-4 w-4" />
+ </ToastPrimitives.Close>
+))
+ToastClose.displayName = ToastPrimitives.Close.displayName
+
+const ToastTitle = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Title>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Title
+ ref={ref}
+ className={cn("text-sm font-semibold", className)}
+ {...props}
+ />
+))
+ToastTitle.displayName = ToastPrimitives.Title.displayName
+
+const ToastDescription = React.forwardRef<
+ React.ElementRef<typeof ToastPrimitives.Description>,
+ React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
+>(({ className, ...props }, ref) => (
+ <ToastPrimitives.Description
+ ref={ref}
+ className={cn("text-sm opacity-90", className)}
+ {...props}
+ />
+))
+ToastDescription.displayName = ToastPrimitives.Description.displayName
+
+type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
+
+type ToastActionElement = React.ReactElement<typeof ToastAction>
+
+export {
+ type ToastProps,
+ type ToastActionElement,
+ ToastProvider,
+ ToastViewport,
+ Toast,
+ ToastTitle,
+ ToastDescription,
+ ToastClose,
+ ToastAction,
+}
diff --git a/apps/web/src/components/ui/toaster.tsx b/apps/web/src/components/ui/toaster.tsx
new file mode 100644
index 000000000..a2209ba58
--- /dev/null
+++ b/apps/web/src/components/ui/toaster.tsx
@@ -0,0 +1,33 @@
+import {
+ Toast,
+ ToastClose,
+ ToastDescription,
+ ToastProvider,
+ ToastTitle,
+ ToastViewport,
+} from "@/components/ui/toast"
+import { useToast } from "@/components/ui/use-toast"
+
+export function Toaster() {
+ const { toasts } = useToast()
+
+ return (
+ <ToastProvider>
+ {toasts.map(function ({ id, title, description, action, ...props }) {
+ return (
+ <Toast key={id} {...props}>
+ <div className="grid gap-1">
+ {title && <ToastTitle>{title}</ToastTitle>}
+ {description && (
+ <ToastDescription>{description}</ToastDescription>
+ )}
+ </div>
+ {action}
+ <ToastClose />
+ </Toast>
+ )
+ })}
+ <ToastViewport />
+ </ToastProvider>
+ )
+}
diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx
new file mode 100644
index 000000000..e7a5e08f5
--- /dev/null
+++ b/apps/web/src/components/ui/tooltip.tsx
@@ -0,0 +1,28 @@
+import * as React from "react"
+import * as TooltipPrimitive from "@radix-ui/react-tooltip"
+
+import { cn } from "@/utils/cn"
+
+const TooltipProvider = TooltipPrimitive.Provider
+
+const Tooltip = TooltipPrimitive.Root
+
+const TooltipTrigger = TooltipPrimitive.Trigger
+
+const TooltipContent = React.forwardRef<
+ React.ElementRef<typeof TooltipPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <TooltipPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+))
+TooltipContent.displayName = TooltipPrimitive.Content.displayName
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/apps/web/src/components/ui/use-toast.ts b/apps/web/src/components/ui/use-toast.ts
new file mode 100644
index 000000000..90d8959bf
--- /dev/null
+++ b/apps/web/src/components/ui/use-toast.ts
@@ -0,0 +1,192 @@
+// Inspired by react-hot-toast library
+import * as React from "react"
+
+import type {
+ ToastActionElement,
+ ToastProps,
+} from "@/components/ui/toast"
+
+const TOAST_LIMIT = 1
+const TOAST_REMOVE_DELAY = 1000000
+
+type ToasterToast = ToastProps & {
+ id: string
+ title?: React.ReactNode
+ description?: React.ReactNode
+ action?: ToastActionElement
+}
+
+const actionTypes = {
+ ADD_TOAST: "ADD_TOAST",
+ UPDATE_TOAST: "UPDATE_TOAST",
+ DISMISS_TOAST: "DISMISS_TOAST",
+ REMOVE_TOAST: "REMOVE_TOAST",
+} as const
+
+let count = 0
+
+function genId() {
+ count = (count + 1) % Number.MAX_VALUE
+ return count.toString()
+}
+
+type ActionType = typeof actionTypes
+
+type Action =
+ | {
+ type: ActionType["ADD_TOAST"]
+ toast: ToasterToast
+ }
+ | {
+ type: ActionType["UPDATE_TOAST"]
+ toast: Partial<ToasterToast>
+ }
+ | {
+ type: ActionType["DISMISS_TOAST"]
+ toastId?: ToasterToast["id"]
+ }
+ | {
+ type: ActionType["REMOVE_TOAST"]
+ toastId?: ToasterToast["id"]
+ }
+
+interface State {
+ toasts: ToasterToast[]
+}
+
+const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
+
+const addToRemoveQueue = (toastId: string) => {
+ if (toastTimeouts.has(toastId)) {
+ return
+ }
+
+ const timeout = setTimeout(() => {
+ toastTimeouts.delete(toastId)
+ dispatch({
+ type: "REMOVE_TOAST",
+ toastId: toastId,
+ })
+ }, TOAST_REMOVE_DELAY)
+
+ toastTimeouts.set(toastId, timeout)
+}
+
+export const reducer = (state: State, action: Action): State => {
+ switch (action.type) {
+ case "ADD_TOAST":
+ return {
+ ...state,
+ toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
+ }
+
+ case "UPDATE_TOAST":
+ return {
+ ...state,
+ toasts: state.toasts.map((t) =>
+ t.id === action.toast.id ? { ...t, ...action.toast } : t
+ ),
+ }
+
+ case "DISMISS_TOAST": {
+ const { toastId } = action
+
+ // ! Side effects ! - This could be extracted into a dismissToast() action,
+ // but I'll keep it here for simplicity
+ if (toastId) {
+ addToRemoveQueue(toastId)
+ } else {
+ state.toasts.forEach((toast) => {
+ addToRemoveQueue(toast.id)
+ })
+ }
+
+ return {
+ ...state,
+ toasts: state.toasts.map((t) =>
+ t.id === toastId || toastId === undefined
+ ? {
+ ...t,
+ open: false,
+ }
+ : t
+ ),
+ }
+ }
+ case "REMOVE_TOAST":
+ if (action.toastId === undefined) {
+ return {
+ ...state,
+ toasts: [],
+ }
+ }
+ return {
+ ...state,
+ toasts: state.toasts.filter((t) => t.id !== action.toastId),
+ }
+ }
+}
+
+const listeners: Array<(state: State) => void> = []
+
+let memoryState: State = { toasts: [] }
+
+function dispatch(action: Action) {
+ memoryState = reducer(memoryState, action)
+ listeners.forEach((listener) => {
+ listener(memoryState)
+ })
+}
+
+type Toast = Omit<ToasterToast, "id">
+
+function toast({ ...props }: Toast) {
+ const id = genId()
+
+ const update = (props: ToasterToast) =>
+ dispatch({
+ type: "UPDATE_TOAST",
+ toast: { ...props, id },
+ })
+ const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
+
+ dispatch({
+ type: "ADD_TOAST",
+ toast: {
+ ...props,
+ id,
+ open: true,
+ onOpenChange: (open) => {
+ if (!open) dismiss()
+ },
+ },
+ })
+
+ return {
+ id: id,
+ dismiss,
+ update,
+ }
+}
+
+function useToast() {
+ const [state, setState] = React.useState<State>(memoryState)
+
+ React.useEffect(() => {
+ listeners.push(setState)
+ return () => {
+ const index = listeners.indexOf(setState)
+ if (index > -1) {
+ listeners.splice(index, 1)
+ }
+ }
+ }, [state])
+
+ return {
+ ...state,
+ toast,
+ dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
+ }
+}
+
+export { useToast, toast }
diff --git a/apps/web/src/hooks/useMappings.ts b/apps/web/src/hooks/useMappings.ts
new file mode 100644
index 000000000..43942bcf1
--- /dev/null
+++ b/apps/web/src/hooks/useMappings.ts
@@ -0,0 +1,7 @@
+import mappings from '@/mappings.json'
+
+export function useMappings() {
+ return (val: string) => {
+ return mappings.find((item) => item.id === val)?.name ?? val
+ }
+}
\ No newline at end of file
diff --git a/apps/web/src/hooks/useOrganizationParams.ts b/apps/web/src/hooks/useOrganizationParams.ts
new file mode 100644
index 000000000..adc175487
--- /dev/null
+++ b/apps/web/src/hooks/useOrganizationParams.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+import { useQueryParams } from "./useQueryParams";
+
+export function useOrganizationParams() {
+ return useQueryParams(
+ z.object({
+ organization: z.string(),
+ project: z.string(),
+ dashboard: z.string(),
+ }),
+ );
+}
\ No newline at end of file
diff --git a/apps/web/src/hooks/useRefetchActive.ts b/apps/web/src/hooks/useRefetchActive.ts
new file mode 100644
index 000000000..f11d64ec8
--- /dev/null
+++ b/apps/web/src/hooks/useRefetchActive.ts
@@ -0,0 +1,6 @@
+import { useQueryClient } from "@tanstack/react-query";
+
+export function useRefetchActive() {
+ const client = useQueryClient()
+ return () => client.refetchQueries({type: 'active'})
+}
\ No newline at end of file
diff --git a/apps/web/src/mappings.json b/apps/web/src/mappings.json
new file mode 100644
index 000000000..f7c535afc
--- /dev/null
+++ b/apps/web/src/mappings.json
@@ -0,0 +1,146 @@
+[
+ {
+ "id": "clbow140n0228u99ui1t24l85",
+ "name": "Mjölkproteinfritt"
+ },
+ {
+ "id": "cl04a3trn0015ix50tzy40pyf",
+ "name": "Måltider"
+ },
+ {
+ "id": "cl04a5p7s0401ix505n75yfcn",
+ "name": "Svårighetsgrad"
+ },
+ {
+ "id": "cl04a7k3i0813ix50aau6yxqg",
+ "name": "Tid"
+ },
+ {
+ "id": "cl04a47fu0103ix50dqckz2vc",
+ "name": "Frukost"
+ },
+ {
+ "id": "cl04a4hvu0152ix50o0w4iy8l",
+ "name": "Mellis"
+ },
+ {
+ "id": "cl04a58ju0281ix50kdmcwst6",
+ "name": "Dessert"
+ },
+ {
+ "id": "cl04a5fjc0321ix50xiwhuydy",
+ "name": "Smakportioner"
+ },
+ {
+ "id": "cl04a5kcu0361ix50bnmbhoxz",
+ "name": "Plockmat"
+ },
+ {
+ "id": "cl04a60sk0496ix50et419drf",
+ "name": "Medium"
+ },
+ {
+ "id": "cl04a67lx0536ix50sstoxnhi",
+ "name": "Avancerat"
+ },
+ {
+ "id": "cl04a7qi60850ix50je7vaxo3",
+ "name": "0-10 min"
+ },
+ {
+ "id": "cl04a7vxi0890ix50veumcuyu",
+ "name": "10-20 min"
+ },
+ {
+ "id": "cl04a82bj0930ix50bboh3tl9",
+ "name": "20-30 min"
+ },
+ {
+ "id": "cl04a8a7a0970ix50uet02cqh",
+ "name": "30-40 min"
+ },
+ {
+ "id": "cl04a8g151010ix50z4cnf2kg",
+ "name": "40-50 min"
+ },
+ {
+ "id": "cl04a8mqy1050ix50z0d1ho1a",
+ "name": "50-60 min"
+ },
+ {
+ "id": "cl04a5ujg0447ix50vd3vor87",
+ "name": "Lätt"
+ },
+ {
+ "id": "cl04a4qv60201ix50b8q5kn9r",
+ "name": "Lunch & Middag"
+ },
+ {
+ "id": "clak50jem0072ri9ugwygg5ko",
+ "name": "Annat"
+ },
+ {
+ "id": "clak510qm0120ri9upqkca39s",
+ "name": "För hela familjen"
+ },
+ {
+ "id": "clak59l8x0085yd9uzllcuci5",
+ "name": "Under 3 ingredienser"
+ },
+ {
+ "id": "clak59l8y0087yd9u53qperp8",
+ "name": "Under 5 ingredienser"
+ },
+ {
+ "id": "claslo2sg0404no9uo2tckm5i",
+ "name": "Huvudingredienser"
+ },
+ {
+ "id": "claslv9s20491no9ugo4fd9ns",
+ "name": "Fisk"
+ },
+ {
+ "id": "claslv9s30493no9umug5po29",
+ "name": "Kyckling"
+ },
+ {
+ "id": "claslv9s40495no9umor61pql",
+ "name": "Kött"
+ },
+ {
+ "id": "claslv9s40497no9uttwkt47n",
+ "name": "Korv"
+ },
+ {
+ "id": "claslv9s50499no9uch0lhs9i",
+ "name": "Vegetariskt"
+ },
+ {
+ "id": "clb1y44f40128np9uufck0iqf",
+ "name": "Årstider"
+ },
+ {
+ "id": "clb1y4ks80202np9uh43c84ts",
+ "name": "Jul"
+ },
+ {
+ "id": "clbovy0fd0081u99u8dr0yplr",
+ "name": "Allergier"
+ },
+ {
+ "id": "clbow140p0230u99uk9e7g1u1",
+ "name": "Äggfritt"
+ },
+ {
+ "id": "clbow140q0232u99uy3lwukvc",
+ "name": "Vetefritt"
+ },
+ {
+ "id": "clbow140q0234u99uiyrujxd4",
+ "name": "Glutenfritt"
+ },
+ {
+ "id": "clbow140r0236u99u5333gpei",
+ "name": "Nötfritt"
+ }
+]
\ No newline at end of file
diff --git a/apps/web/src/modals/AddClient.tsx b/apps/web/src/modals/AddClient.tsx
new file mode 100644
index 000000000..508e92816
--- /dev/null
+++ b/apps/web/src/modals/AddClient.tsx
@@ -0,0 +1,153 @@
+import { api, handleError } from "@/utils/api";
+import { ModalContent, ModalHeader } from "./Modal/Container";
+import { Controller, useForm } from "react-hook-form";
+import { z } from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@/components/ui/button";
+import { ButtonContainer } from "@/components/ButtonContainer";
+import { popModal } from ".";
+import { toast } from "@/components/ui/use-toast";
+import { InputWithLabel } from "@/components/forms/InputWithLabel";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+import { Combobox } from "@/components/ui/combobox";
+import { Label } from "@/components/ui/label";
+import { Copy } from "lucide-react";
+import { clipboard } from "@/utils/clipboard";
+import dynamic from "next/dynamic";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+
+const Syntax = dynamic(import('@/components/Syntax'))
+
+const validator = z.object({
+ name: z.string().min(1, "Required"),
+ projectId: z.string().min(1, "Required"),
+});
+
+type IForm = z.infer<typeof validator>;
+
+export default function CreateProject() {
+ const params = useOrganizationParams()
+ const refetch = useRefetchActive();
+ const query = api.project.list.useQuery({
+ organizationSlug: params.organization,
+ });
+ const mutation = api.client.create.useMutation({
+ onError: handleError,
+ onSuccess() {
+ toast({
+ title: "Success",
+ description: "Client created!",
+ });
+ refetch();
+ },
+ });
+ const { register, handleSubmit, formState, control } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ name: "",
+ projectId: "",
+ },
+ });
+
+ if (mutation.isSuccess && mutation.data) {
+ const { clientId, clientSecret } = mutation.data;
+ return (
+ <ModalContent>
+ <ModalHeader title="Client created 🚀" />
+ <p>
+ Your client has been created! You will only see the client secret once
+ so keep it safe 🫣
+ </p>
+
+ <button className="mt-4 text-left" onClick={() => clipboard(clientId)}>
+ <Label>Client ID</Label>
+ <div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
+ {clientId}
+ <Copy size={16} />
+ </div>
+ </button>
+ <button
+ className="mt-4 text-left"
+ onClick={() => clipboard(clientSecret)}
+ >
+ <Label>Client Secret</Label>
+ <div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
+ {clientSecret}
+ <Copy size={16} />
+ </div>
+ </button>
+ <div className="mt-4">
+ <Label>Code snippet</Label>
+ <div className="overflow-x-auto [&_pre]:!rounded [&_pre]:!bg-gray-100 [&_pre]:text-sm">
+ <Syntax
+ code={`const mixan = new Mixan({
+ clientId: "${clientId}",
+ clientSecret: "${clientSecret}",
+})`}
+ />
+ </div>
+ </div>
+
+ <ButtonContainer>
+ <div />
+ <Button onClick={() => popModal()}>Done</Button>
+ </ButtonContainer>
+ </ModalContent>
+ );
+ }
+
+ return (
+ <ModalContent>
+ <ModalHeader title="Create client" />
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate({
+ ...values,
+ organizationSlug: params.organization,
+ });
+ })}
+ >
+ <InputWithLabel
+ label="Name"
+ placeholder="Name"
+ {...register("name")}
+ className="mb-4"
+ />
+ <Controller
+ control={control}
+ name="projectId"
+ render={({ field }) => {
+ return (
+ <div>
+ <Label className="mb-2 block">Project</Label>
+ <Combobox
+ {...field}
+ onChange={(value) => {
+ console.log("wtf?", value);
+
+ field.onChange(value);
+ }}
+ items={
+ query.data?.map((item) => ({
+ value: item.id,
+ label: item.name,
+ })) ?? []
+ }
+ placeholder="Select a project"
+ />
+ </div>
+ );
+ }}
+ />
+ <ButtonContainer>
+ <Button type="button" variant="outline" onClick={() => popModal()}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={!formState.isDirty}>
+ Create
+ </Button>
+ </ButtonContainer>
+ </form>
+ </ModalContent>
+ );
+}
diff --git a/apps/web/src/modals/AddProject.tsx b/apps/web/src/modals/AddProject.tsx
new file mode 100644
index 000000000..2543b48bb
--- /dev/null
+++ b/apps/web/src/modals/AddProject.tsx
@@ -0,0 +1,55 @@
+import { api, handleError } from "@/utils/api";
+import { ModalContent, ModalHeader } from "./Modal/Container";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@/components/ui/button";
+import { ButtonContainer } from "@/components/ButtonContainer";
+import { popModal } from ".";
+import { toast } from "@/components/ui/use-toast";
+import { InputWithLabel } from "@/components/forms/InputWithLabel";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+
+const validator = z.object({
+ name: z.string().min(1),
+});
+
+type IForm = z.infer<typeof validator>;
+
+export default function AddProject() {
+ const refetch = useRefetchActive()
+ const mutation = api.project.create.useMutation({
+ onError: handleError,
+ onSuccess() {
+ toast({
+ title: 'Success',
+ description: 'Project created! Lets create a client for it 🤘',
+ })
+ refetch()
+ popModal()
+ }
+ });
+ const { register, handleSubmit, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ name: "",
+ },
+ });
+
+ return (
+ <ModalContent>
+ <ModalHeader title="Create project" />
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate(values);
+ })}
+ >
+ <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <ButtonContainer>
+ <Button type="button" variant="outline" onClick={() => popModal()}>Cancel</Button>
+ <Button type="submit" disabled={!formState.isDirty}>Create</Button>
+ </ButtonContainer>
+ </form>
+ </ModalContent>
+ );
+}
diff --git a/apps/web/src/modals/Confirm.tsx b/apps/web/src/modals/Confirm.tsx
new file mode 100644
index 000000000..145eea5a0
--- /dev/null
+++ b/apps/web/src/modals/Confirm.tsx
@@ -0,0 +1,44 @@
+import { ModalContent, ModalHeader } from "./Modal/Container";
+import { Button } from "@/components/ui/button";
+import { ButtonContainer } from "@/components/ButtonContainer";
+import { popModal } from ".";
+
+export type ConfirmProps = {
+ title: string;
+ text: string;
+ onConfirm: () => void;
+ onCancel?: () => void;
+};
+
+export default function Confirm({
+ title,
+ text,
+ onConfirm,
+ onCancel,
+}: ConfirmProps) {
+ return (
+ <ModalContent>
+ <ModalHeader title={title} />
+ <p>{text}</p>
+ <ButtonContainer>
+ <Button
+ variant="outline"
+ onClick={() => {
+ popModal("Confirm");
+ onCancel?.();
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={() => {
+ popModal("Confirm");
+ onConfirm();
+ }}
+ >
+ Yes
+ </Button>
+ </ButtonContainer>
+ </ModalContent>
+ );
+}
diff --git a/apps/web/src/modals/EditClient.tsx b/apps/web/src/modals/EditClient.tsx
new file mode 100644
index 000000000..a8bbb76f9
--- /dev/null
+++ b/apps/web/src/modals/EditClient.tsx
@@ -0,0 +1,70 @@
+import { api, handleError } from "@/utils/api";
+import { ModalContent, ModalHeader } from "./Modal/Container";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { Button } from "@/components/ui/button";
+import { ButtonContainer } from "@/components/ButtonContainer";
+import { popModal } from ".";
+import { toast } from "@/components/ui/use-toast";
+import { InputWithLabel } from "@/components/forms/InputWithLabel";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+
+type EditClientProps = {
+ id: string;
+};
+
+const validator = z.object({
+ id: z.string().min(1),
+ name: z.string().min(1),
+});
+
+type IForm = z.infer<typeof validator>;
+
+export default function EditClient({ id }: EditClientProps) {
+ const refetch = useRefetchActive()
+ const mutation = api.client.update.useMutation({
+ onError: handleError,
+ onSuccess() {
+ toast({
+ title: 'Success',
+ description: 'Client updated.',
+ })
+ popModal()
+ refetch()
+ }
+ });
+ const query = api.client.get.useQuery({ id });
+ const data = query.data;
+ const { register, handleSubmit, reset, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ id: "",
+ name: "",
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ reset(data);
+ }
+ }, [data, reset]);
+
+ return (
+ <ModalContent>
+ <ModalHeader title="Edit client" />
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate(values);
+ })}
+ >
+ <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <ButtonContainer>
+ <Button type="button" variant="outline" onClick={() => popModal()}>Cancel</Button>
+ <Button type="submit" disabled={!formState.isDirty}>Save</Button>
+ </ButtonContainer>
+ </form>
+ </ModalContent>
+ );
+}
diff --git a/apps/web/src/modals/EditProject.tsx b/apps/web/src/modals/EditProject.tsx
new file mode 100644
index 000000000..9fb3a85d3
--- /dev/null
+++ b/apps/web/src/modals/EditProject.tsx
@@ -0,0 +1,70 @@
+import { api, handleError } from "@/utils/api";
+import { ModalContent, ModalHeader } from "./Modal/Container";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { Button } from "@/components/ui/button";
+import { ButtonContainer } from "@/components/ButtonContainer";
+import { popModal } from ".";
+import { toast } from "@/components/ui/use-toast";
+import { InputWithLabel } from "@/components/forms/InputWithLabel";
+import { useRefetchActive } from "@/hooks/useRefetchActive";
+
+type EditProjectProps = {
+ id: string;
+};
+
+const validator = z.object({
+ id: z.string().min(1),
+ name: z.string().min(1),
+});
+
+type IForm = z.infer<typeof validator>;
+
+export default function EditProject({ id }: EditProjectProps) {
+ const refetch = useRefetchActive()
+ const mutation = api.project.update.useMutation({
+ onError: handleError,
+ onSuccess() {
+ toast({
+ title: 'Success',
+ description: 'Project updated.',
+ })
+ popModal()
+ refetch()
+ }
+ });
+ const query = api.project.get.useQuery({ id });
+ const data = query.data;
+ const { register, handleSubmit, reset,formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ id: "",
+ name: "",
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ reset(data);
+ }
+ }, [data, reset]);
+
+ return (
+ <ModalContent>
+ <ModalHeader title="Edit project" />
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate(values);
+ })}
+ >
+ <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <ButtonContainer>
+ <Button type="button" variant="outline" onClick={() => popModal()}>Cancel</Button>
+ <Button type="submit" disabled={!formState.isDirty}>Save</Button>
+ </ButtonContainer>
+ </form>
+ </ModalContent>
+ );
+}
diff --git a/apps/web/src/modals/Modal/Container.tsx b/apps/web/src/modals/Modal/Container.tsx
new file mode 100644
index 000000000..1c8cb33e2
--- /dev/null
+++ b/apps/web/src/modals/Modal/Container.tsx
@@ -0,0 +1,31 @@
+import { Button } from "@/components/ui/button";
+import { X } from "lucide-react";
+import { popModal } from "..";
+
+type ModalContentProps = {
+ children: React.ReactNode;
+};
+
+export function ModalContent({ children }: ModalContentProps) {
+ return (
+ <div className="fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 sm:rounded-lg md:w-full">
+ {children}
+ </div>
+ );
+}
+
+type ModalHeaderProps = {
+ title: string | React.ReactNode;
+};
+
+export function ModalHeader({ title }: ModalHeaderProps) {
+ return (
+ <div className="flex items-center justify-between">
+ <div className="font-medium">{title}</div>
+ <Button variant="ghost" size="sm" onClick={() => popModal()}>
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/modals/index.tsx b/apps/web/src/modals/index.tsx
new file mode 100644
index 000000000..7f4170cff
--- /dev/null
+++ b/apps/web/src/modals/index.tsx
@@ -0,0 +1,197 @@
+import { Suspense, useEffect, useRef, useState } from 'react';
+
+import { Loader } from 'lucide-react';
+import mitt from 'mitt';
+import dynamic from 'next/dynamic';
+import { useOnClickOutside } from 'usehooks-ts';
+import { type ConfirmProps } from './Confirm';
+
+const Loading = () => (
+ <div className='fixed top-0 z-50 flex h-screen w-screen items-center justify-center overflow-auto bg-backdrop'>
+ <Loader className='mb-8 animate-spin' size={40} />
+ </div>
+);
+
+const modals = {
+ EditProject: dynamic(() => import('./EditProject'), {
+ loading: Loading,
+ }),
+ EditClient: dynamic(() => import('./EditClient'), {
+ loading: Loading,
+ }),
+ AddProject: dynamic(() => import('./AddProject'), {
+ loading: Loading,
+ }),
+ AddClient: dynamic(() => import('./AddClient'), {
+ loading: Loading,
+ }),
+ Confirm: dynamic(() => import('./Confirm'), {
+ loading: Loading,
+ }),
+};
+
+const emitter = mitt<{
+ push: {
+ name: ModalRoutes;
+ props: Record<string, unknown>;
+ };
+ replace: {
+ name: ModalRoutes;
+ props: Record<string, unknown>;
+ };
+ pop: { name?: ModalRoutes };
+ unshift: { name: ModalRoutes };
+}>();
+
+type ModalRoutes = keyof typeof modals;
+
+type StateItem = {
+ key: string;
+ name: ModalRoutes;
+ props: Record<string, unknown>;
+};
+
+type ModalWrapperProps = {
+ children: React.ReactNode;
+ name: ModalRoutes;
+ isOnTop: boolean;
+};
+
+function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useOnClickOutside(ref, (event) => {
+ const target = event.target as HTMLElement;
+ const isPortal = typeof target.closest === 'function' ? !!target.closest('[data-radix-popper-content-wrapper]') : false
+
+ if (isOnTop && !isPortal) {
+ emitter.emit('pop', {
+ name,
+ });
+ }
+ });
+
+ return (
+ <div className='fixed top-0 z-50 flex h-screen w-screen items-center justify-center overflow-auto'>
+ <div ref={ref} className='w-inherit m-auto py-4'>
+ <Suspense>{children}</Suspense>
+ </div>
+ </div>
+ );
+}
+
+export function ModalProvider() {
+ const [state, setState] = useState<StateItem[]>([]);
+
+ useEffect(() => {
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && state.length > 0) {
+ setState((p) => {
+ p.pop();
+ return [...p];
+ });
+ }
+ });
+ }, [state]);
+
+ useEffect(() => {
+ emitter.on('push', ({ name, props }) => {
+ setState((p) => [
+ ...p,
+ {
+ key: Math.random().toString(),
+ name,
+ props,
+ },
+ ]);
+ });
+
+ emitter.on('replace', ({ name, props }) => {
+ setState([
+ {
+ key: Math.random().toString(),
+ name,
+ props,
+ },
+ ]);
+ });
+
+ emitter.on('pop', ({ name }) => {
+ setState((items) => {
+ const match =
+ name === undefined
+ ? // Pick last item if no name is provided
+ items.length - 1
+ : items.findLastIndex((item) => item.name === name);
+ return items.filter((_, index) => index !== match);
+ });
+ });
+
+ emitter.on('unshift', ({ name }) => {
+ setState((items) => {
+ const match = items.findIndex((item) => item.name === name);
+ return items.filter((_, index) => index !== match);
+ });
+ });
+
+ return () => emitter.all.clear();
+ });
+ return (
+ <>
+ {!!state.length && <div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)]"></div>}
+ {state.map((item, index) => {
+ const Modal = modals[item.name];
+ return (
+ <ModalWrapper
+ key={item.key}
+ name={item.name}
+ isOnTop={state.length - 1 === index}
+ >
+ {/* @ts-expect-error */}
+ <Modal {...item.props} />
+ </ModalWrapper>
+ );
+ })}
+ </>
+ );
+}
+
+type GetComponentProps<T> = T extends
+ | React.ComponentType<infer P>
+ | React.Component<infer P>
+ ? P
+ : never;
+type OrUndefined<T> = T extends Record<string, never> ? undefined : T;
+
+export const pushModal = <
+ T extends StateItem['name'],
+ B extends OrUndefined<GetComponentProps<(typeof modals)[T]>>
+>(
+ name: T,
+ ...rest: B extends undefined ? [] : [B]
+) =>
+ emitter.emit('push', {
+ name,
+ props: Array.isArray(rest) && rest[0] ? rest[0] : {},
+ });
+export const replaceModal = <
+ T extends StateItem['name'],
+ B extends OrUndefined<GetComponentProps<(typeof modals)[T]>>
+>(
+ name: T,
+ ...rest: B extends undefined ? [] : [B]
+) =>
+ emitter.emit('replace', {
+ name,
+ props: Array.isArray(rest) && rest[0] ? rest[0] : {},
+ });
+export const popModal = (name?: StateItem['name']) =>
+ emitter.emit('pop', {
+ name,
+ });
+export const unshiftModal = (name: StateItem['name']) =>
+ emitter.emit('unshift', {
+ name,
+ });
+
+export const showConfirm = (props: ConfirmProps) => pushModal('Confirm', props);
\ No newline at end of file
diff --git a/apps/web/src/pages/[organization]/[project]/[dashboard].tsx b/apps/web/src/pages/[organization]/[project]/[dashboard].tsx
new file mode 100644
index 000000000..b1da1c451
--- /dev/null
+++ b/apps/web/src/pages/[organization]/[project]/[dashboard].tsx
@@ -0,0 +1,51 @@
+import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
+import { MainLayout } from "@/components/layouts/MainLayout";
+import { Container } from "@/components/Container";
+import { api } from "@/utils/api";
+import Link from "next/link";
+import { PageTitle } from "@/components/PageTitle";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import { Suspense } from "react";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Dashboard() {
+ const params = useOrganizationParams();
+
+ const query = api.report.list.useQuery({
+ projectSlug: params.project,
+ dashboardSlug: params.dashboard,
+ });
+
+ const dashboard = query.data?.dashboard ?? null;
+ const reports = query.data?.reports ?? [];
+
+ return (
+ <MainLayout>
+ <Container>
+ <Suspense fallback="Loading">
+ <PageTitle>{dashboard?.name}</PageTitle>
+ <div className="grid grid-cols-2 gap-4">
+ {reports.map((report) => (
+ <div
+ className="rounded-md border border-border bg-white shadow"
+ key={report.id}
+ >
+ <Link
+ href={`/${params.organization}/reports/${report.id}`}
+ className="block border-b border-border p-4 font-medium leading-none hover:underline"
+ >
+ {report.name}
+ </Link>
+ <div className="p-4 pl-2">
+ <ReportLineChart {...report} showTable={false} />
+ </div>
+ </div>
+ ))}
+ </div>
+ </Suspense>
+ </Container>
+ </MainLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/[project]/index.tsx b/apps/web/src/pages/[organization]/[project]/index.tsx
new file mode 100644
index 000000000..bcf4e32a8
--- /dev/null
+++ b/apps/web/src/pages/[organization]/[project]/index.tsx
@@ -0,0 +1,41 @@
+import { MainLayout } from "@/components/layouts/MainLayout";
+import { Container } from "@/components/Container";
+import { api } from "@/utils/api";
+import Link from "next/link";
+import { PageTitle } from "@/components/PageTitle";
+import { Card } from "@/components/Card";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Home() {
+ const params = useOrganizationParams();
+ const query = api.dashboard.list.useQuery({
+ organizationSlug: params.organization,
+ projectSlug: params.project,
+ }, {
+ enabled: Boolean(params.organization && params.project),
+ });
+ const dashboards = query.data ?? [];
+
+ return (
+ <MainLayout>
+ <Container>
+ <PageTitle>Dashboards</PageTitle>
+ <div className="grid grid-cols-2 gap-4">
+ {dashboards.map((item) => (
+ <Card key={item.id}>
+ <Link
+ href={`/${params.organization}/${params.project}/${item.slug}`}
+ className="block p-4 font-medium leading-none hover:underline"
+ >
+ {item.name}
+ </Link>
+ </Card>
+ ))}
+ </div>
+ </Container>
+ </MainLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/index.tsx b/apps/web/src/pages/[organization]/index.tsx
new file mode 100644
index 000000000..6088cc932
--- /dev/null
+++ b/apps/web/src/pages/[organization]/index.tsx
@@ -0,0 +1,43 @@
+import { MainLayout } from "@/components/layouts/MainLayout";
+import { Container } from "@/components/Container";
+import { api } from "@/utils/api";
+import Link from "next/link";
+import { PageTitle } from "@/components/PageTitle";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import { Card } from "@/components/Card";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Home() {
+ const params = useOrganizationParams(
+ );
+
+ const query = api.project.list.useQuery({
+ organizationSlug: params.organization,
+ }, {
+ enabled: !!params.organization,
+ });
+
+ const projects = query.data ?? [];
+
+ return (
+ <MainLayout>
+ <Container>
+ <PageTitle>Reports</PageTitle>
+ <div className="grid grid-cols-2 gap-4">
+ {projects.map((item) => (
+ <Card key={item.id}>
+ <Link
+ href={`/${params.organization}/${item.slug}`}
+ className="block p-4 font-medium leading-none hover:underline"
+ >
+ {item.name}
+ </Link>
+ </Card>
+ ))}
+ </div>
+ </Container>
+ </MainLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/reports/[reportId].tsx b/apps/web/src/pages/[organization]/reports/[reportId].tsx
new file mode 100644
index 000000000..35dd1a543
--- /dev/null
+++ b/apps/web/src/pages/[organization]/reports/[reportId].tsx
@@ -0,0 +1,5 @@
+export { default } from "./index";
+
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
\ No newline at end of file
diff --git a/apps/web/src/pages/reports/index.tsx b/apps/web/src/pages/[organization]/reports/index.tsx
similarity index 88%
rename from apps/web/src/pages/reports/index.tsx
rename to apps/web/src/pages/[organization]/reports/index.tsx
index 4490927f8..5ccfc1df8 100644
--- a/apps/web/src/pages/reports/index.tsx
+++ b/apps/web/src/pages/[organization]/reports/index.tsx
@@ -1,13 +1,16 @@
import { ReportSidebar } from "@/components/report/sidebar/ReportSidebar";
import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
import { useDispatch, useSelector } from "@/redux";
-import { MainLayout } from "@/components/layouts/Main";
+import { MainLayout } from "@/components/layouts/MainLayout";
import { ReportDateRange } from "@/components/report/ReportDateRange";
import { useCallback, useEffect } from "react";
import { reset, setReport } from "@/components/report/reportSlice";
import { useReportId } from "@/components/report/hooks/useReportId";
import { api } from "@/utils/api";
import { useRouterBeforeLeave } from "@/hooks/useRouterBeforeLeave";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
export default function Page() {
const { reportId } = useReportId();
diff --git a/apps/web/src/pages/[organization]/settings/clients.tsx b/apps/web/src/pages/[organization]/settings/clients.tsx
new file mode 100644
index 000000000..3a9244270
--- /dev/null
+++ b/apps/web/src/pages/[organization]/settings/clients.tsx
@@ -0,0 +1,27 @@
+import { api } from "@/utils/api";
+import { ContentHeader } from "@/components/Content";
+import { SettingsLayout } from "@/components/layouts/SettingsLayout";
+import { DataTable } from "@/components/DataTable";
+import { columns } from "@/components/clients/table";
+import { Button } from "@/components/ui/button";
+import { pushModal } from "@/modals";
+import { createServerSideProps } from "@/server/getServerSideProps";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Clients() {
+ const params = useOrganizationParams();
+ const query = api.client.list.useQuery({
+ organizationSlug: params.organization,
+ });
+ const data = query.data ?? [];
+ return (
+ <SettingsLayout>
+ <ContentHeader title="Clients" text="List of your clients">
+ <Button onClick={() => pushModal("AddClient")}>Create</Button>
+ </ContentHeader>
+ <DataTable data={data} columns={columns} />
+ </SettingsLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/settings/organization.tsx b/apps/web/src/pages/[organization]/settings/organization.tsx
new file mode 100644
index 000000000..7dd8f6cff
--- /dev/null
+++ b/apps/web/src/pages/[organization]/settings/organization.tsx
@@ -0,0 +1,69 @@
+import { api, handleError } from "@/utils/api";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import { ContentHeader, ContentSection } from "@/components/Content";
+import { useForm } from "react-hook-form";
+import { useEffect } from "react";
+import { SettingsLayout } from "@/components/layouts/SettingsLayout";
+import { toast } from "@/components/ui/use-toast";
+import { createServerSideProps } from "@/server/getServerSideProps";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+
+export const getServerSideProps = createServerSideProps();
+
+export default function Organization() {
+ const params = useOrganizationParams();
+ const query = api.organization.get.useQuery({
+ slug: params.organization,
+ });
+ const mutation = api.organization.update.useMutation({
+ onSuccess() {
+ toast({
+ title: "Organization updated",
+ description: "Your organization has been updated.",
+ });
+ query.refetch();
+ },
+ onError: handleError,
+ });
+ const data = query.data;
+
+ const { register, handleSubmit, reset, formState, getValues } = useForm({
+ defaultValues: {
+ name: "",
+ slug: "",
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ reset(data);
+ }
+ }, [data, reset]);
+
+
+ return (
+ <SettingsLayout>
+ <form
+ onSubmit={handleSubmit((values) => mutation.mutate(values))}
+ className="flex flex-col divide-y divide-border"
+ >
+ <ContentHeader
+ title="Organization"
+ text="View and update your organization"
+ >
+ <Button type="submit" disabled={!formState.isDirty}>Save</Button>
+ </ContentHeader>
+ <ContentSection title="Name" text="The name of your organization.">
+ <Input {...register("name")} />
+ </ContentSection>
+ <ContentSection
+ title="Invite user"
+ text="Invite users to this organization. You can invite several users with (,)"
+ >
+ <Input disabled />
+ </ContentSection>
+ </form>
+ </SettingsLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/settings/profile.tsx b/apps/web/src/pages/[organization]/settings/profile.tsx
new file mode 100644
index 000000000..4a5d0025e
--- /dev/null
+++ b/apps/web/src/pages/[organization]/settings/profile.tsx
@@ -0,0 +1,73 @@
+import { api, handleError } from "@/utils/api";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import { ContentHeader, ContentSection } from "@/components/Content";
+import { useForm } from "react-hook-form";
+import { useEffect } from "react";
+import { SettingsLayout } from "@/components/layouts/SettingsLayout";
+import { toast } from "@/components/ui/use-toast";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Profile() {
+ const query = api.user.current.useQuery();
+ const mutation = api.user.update.useMutation({
+ onSuccess() {
+ toast({
+ title: 'Profile updated',
+ description: 'Your profile has been updated.',
+ })
+ query.refetch()
+ },
+ onError: handleError,
+ });
+ const data = query.data;
+
+ const { register, handleSubmit, reset, formState } = useForm({
+ defaultValues: {
+ name: "",
+ email: "",
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ reset(data);
+ }
+ }, [data, reset]);
+
+ return (
+ <SettingsLayout>
+ <form onSubmit={handleSubmit((values) => mutation.mutate(values))} className="flex flex-col divide-y divide-border">
+ <ContentHeader
+ title="Profile"
+ text="View and update your profile"
+ >
+ <Button type="submit" disabled={!formState.isDirty}>Save</Button>
+ </ContentHeader>
+ <ContentSection title="Name" text="Your full name">
+ <Input {...register("name")} />
+ </ContentSection>
+ <ContentSection title="Mail" text="Your email address">
+ <Input {...register("email")} />
+ </ContentSection>
+ </form>
+
+ {/* <form onSubmit={handleSubmit((values) => mutation.mutate(values))} className="flex flex-col divide-y divide-border">
+ <ContentHeader
+ title="Change password"
+ text="Need to change your password?"
+ >
+ <Button disabled={!formState.isDirty}>Change it!</Button>
+ </ContentHeader>
+ <ContentSection title="Name" text="Your full name">
+ <Input {...register("name")} />
+ </ContentSection>
+ <ContentSection title="Mail" text="Your email address">
+ <Input {...register("email")} />
+ </ContentSection>
+ </form> */}
+ </SettingsLayout>
+ );
+}
diff --git a/apps/web/src/pages/[organization]/settings/projects.tsx b/apps/web/src/pages/[organization]/settings/projects.tsx
new file mode 100644
index 000000000..73a598f71
--- /dev/null
+++ b/apps/web/src/pages/[organization]/settings/projects.tsx
@@ -0,0 +1,27 @@
+import { api } from "@/utils/api";
+import { ContentHeader } from "@/components/Content";
+import { SettingsLayout } from "@/components/layouts/SettingsLayout";
+import { DataTable } from "@/components/DataTable";
+import { columns } from "@/components/projects/table";
+import { Button } from "@/components/ui/button";
+import { pushModal } from "@/modals";
+import { useOrganizationParams } from "@/hooks/useOrganizationParams";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
+
+export default function Projects() {
+ const params = useOrganizationParams()
+ const query = api.project.list.useQuery({
+ organizationSlug: params.organization
+ });
+ const data = query.data ?? [];
+ return (
+ <SettingsLayout>
+ <ContentHeader title="Projects" text="List of your projects">
+ <Button onClick={() => pushModal('AddProject')}>Create</Button>
+ </ContentHeader>
+ <DataTable data={data} columns={columns} />
+ </SettingsLayout>
+ );
+}
diff --git a/apps/web/src/pages/_app.tsx b/apps/web/src/pages/_app.tsx
index c9b49dd4b..ee8702491 100644
--- a/apps/web/src/pages/_app.tsx
+++ b/apps/web/src/pages/_app.tsx
@@ -1,24 +1,49 @@
import { type Session } from "next-auth";
-import { SessionProvider } from "next-auth/react";
-import { type AppType } from "next/app";
+import { SessionProvider, getSession } from "next-auth/react";
+import App, {
+ type AppContext,
+ type AppInitialProps,
+ type AppType,
+} from "next/app";
import store from "@/redux";
import { Provider as ReduxProvider } from "react-redux";
+import { Suspense } from "react";
+import { Space_Grotesk } from "next/font/google";
+import { Toaster } from "@/components/ui/toaster";
import { api } from "@/utils/api";
import "@/styles/globals.css";
+import { ModalProvider } from "@/modals";
+import { TooltipProvider } from "@/components/ui/tooltip";
-const MyApp: AppType<{ session: Session | null }> = ({
+const font = Space_Grotesk({
+ subsets: ["latin"],
+ display: "swap",
+ variable: "--text",
+});
+
+const MixanApp: AppType<{ session: Session | null }> = ({
Component,
pageProps: { session, ...pageProps },
}) => {
+ console.log('session',session);
+
return (
- <SessionProvider session={session}>
- <ReduxProvider store={store}>
- <Component {...pageProps} />
- </ReduxProvider>
- </SessionProvider>
+ <div className={font.className}>
+ <SessionProvider session={session}>
+ <ReduxProvider store={store}>
+ <Suspense fallback="Loading">
+ <TooltipProvider delayDuration={200}>
+ <Component {...pageProps} />
+ </TooltipProvider>
+ <Toaster />
+ <ModalProvider />
+ </Suspense>
+ </ReduxProvider>
+ </SessionProvider>
+ </div>
);
};
-export default api.withTRPC(MyApp);
+export default api.withTRPC(MixanApp);
diff --git a/apps/web/src/pages/api/sdk/profiles/[profileId]/decrement.ts b/apps/web/src/pages/api/sdk/profiles/[profileId]/decrement.ts
index 7ebad717f..494baa613 100644
--- a/apps/web/src/pages/api/sdk/profiles/[profileId]/decrement.ts
+++ b/apps/web/src/pages/api/sdk/profiles/[profileId]/decrement.ts
@@ -1,6 +1,6 @@
import { validateSdkRequest } from "@/server/auth";
import { createError, handleError } from "@/server/exceptions";
-import { tickProfileProperty } from "@/services/profile.service";
+import { tickProfileProperty } from "@/server/services/profile.service";
import { type ProfileIncrementPayload } from "@mixan/types";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -15,7 +15,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
try {
// Check client id & secret
- await validateSdkRequest(req)
+ await validateSdkRequest(req);
const profileId = req.query.profileId as string;
diff --git a/apps/web/src/pages/api/sdk/profiles/[profileId]/increment.ts b/apps/web/src/pages/api/sdk/profiles/[profileId]/increment.ts
index e48036a41..78133cd11 100644
--- a/apps/web/src/pages/api/sdk/profiles/[profileId]/increment.ts
+++ b/apps/web/src/pages/api/sdk/profiles/[profileId]/increment.ts
@@ -1,6 +1,6 @@
import { validateSdkRequest } from "@/server/auth";
import { createError, handleError } from "@/server/exceptions";
-import { tickProfileProperty } from "@/services/profile.service";
+import { tickProfileProperty } from "@/server/services/profile.service";
import { type ProfileIncrementPayload } from "@mixan/types";
import type { NextApiRequest, NextApiResponse } from "next";
diff --git a/apps/web/src/pages/api/sdk/profiles/[profileId]/index.ts b/apps/web/src/pages/api/sdk/profiles/[profileId]/index.ts
index 778e89ddd..4ca9b03ef 100644
--- a/apps/web/src/pages/api/sdk/profiles/[profileId]/index.ts
+++ b/apps/web/src/pages/api/sdk/profiles/[profileId]/index.ts
@@ -1,7 +1,7 @@
import { validateSdkRequest } from "@/server/auth";
import { db } from "@/server/db";
import { createError, handleError } from "@/server/exceptions";
-import { getProfile } from "@/services/profile.service";
+import { getProfile } from "@/server/services/profile.service";
import { type ProfilePayload } from "@mixan/types";
import type { NextApiRequest, NextApiResponse } from "next";
diff --git a/apps/web/src/pages/api/setup.ts b/apps/web/src/pages/api/setup.ts
index f28da1a83..bcce7793c 100644
--- a/apps/web/src/pages/api/setup.ts
+++ b/apps/web/src/pages/api/setup.ts
@@ -1,6 +1,6 @@
import { db } from "@/server/db";
import { handleError } from "@/server/exceptions";
-import { hashPassword } from "@/services/hash.service";
+import { hashPassword } from "@/server/services/hash.service";
import { randomUUID } from "crypto";
import { type NextApiRequest, type NextApiResponse } from "next";
@@ -33,6 +33,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
data: {
name: "Acme Website Client",
project_id: project.id,
+ organization_id: organization.id,
secret: await hashPassword(secret),
},
});
diff --git a/apps/web/src/pages/index.tsx b/apps/web/src/pages/index.tsx
index 2cc8d5348..275eb8d2f 100644
--- a/apps/web/src/pages/index.tsx
+++ b/apps/web/src/pages/index.tsx
@@ -1,33 +1,25 @@
-import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
-import { MainLayout } from "@/components/layouts/Main";
-import { Container } from "@/components/Container";
+import { MainLayout } from "@/components/layouts/MainLayout";
import { api } from "@/utils/api";
-import Link from "next/link";
+import { useEffect } from "react";
+import { useRouter } from "next/router";
+import { createServerSideProps } from "@/server/getServerSideProps";
+
+export const getServerSideProps = createServerSideProps()
export default function Home() {
- const reportsQuery = api.report.getDashboard.useQuery({
- projectId: 'f7eabf0c-e0b0-4ac0-940f-1589715b0c3d',
- dashboardId: '9227feb4-ad59-40f3-b887-3501685733dd',
- }, {
- staleTime: 1000 * 60 * 5,
- })
- const reports = reportsQuery.data ?? []
+ const router = useRouter()
+ const query = api.organization.current.useQuery();
+ const organization = query.data ?? null;
+
+ useEffect(() => {
+ if(organization) {
+ router.replace(`/${organization.slug}`)
+ }
+ }, [organization])
return (
- <MainLayout className="bg-slate-50 py-8">
- <Container className="flex flex-col gap-8">
- {reports.map((report) => (
- <div
- className="rounded-xl border border-border bg-white shadow"
- key={report.id}
- >
- <Link href={`/reports/${report.id}`} className="block border-b border-border p-4 font-bold hover:underline">{report.name}</Link>
- <div className="p-4">
- <ReportLineChart {...report} showTable={false} />
- </div>
- </div>
- ))}
- </Container>
+ <MainLayout>
+ <div />
</MainLayout>
);
}
diff --git a/apps/web/src/pages/reports/[reportId].tsx b/apps/web/src/pages/reports/[reportId].tsx
deleted file mode 100644
index 19f46dd70..000000000
--- a/apps/web/src/pages/reports/[reportId].tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "./index";
diff --git a/apps/web/src/server/api/root.ts b/apps/web/src/server/api/root.ts
index da5634942..bcb178584 100644
--- a/apps/web/src/server/api/root.ts
+++ b/apps/web/src/server/api/root.ts
@@ -1,7 +1,11 @@
-import { exampleRouter } from "@/server/api/routers/example";
import { createTRPCRouter } from "@/server/api/trpc";
-import { chartMetaRouter } from "./routers/chartMeta";
+import { chartRouter } from "./routers/chart";
import { reportRouter } from "./routers/report";
+import { organizationRouter } from "./routers/organization";
+import { userRouter } from "./routers/user";
+import { projectRouter } from "./routers/project";
+import { clientRouter } from "./routers/client";
+import { dashboardRouter } from "./routers/dashboard";
/**
* This is the primary router for your server.
@@ -9,9 +13,13 @@ import { reportRouter } from "./routers/report";
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
- example: exampleRouter,
- chartMeta: chartMetaRouter,
+ chart: chartRouter,
report: reportRouter,
+ dashboard: dashboardRouter,
+ organization: organizationRouter,
+ user: userRouter,
+ project: projectRouter,
+ client: clientRouter,
});
// export type definition of API
diff --git a/apps/web/src/server/api/routers/chartMeta.ts b/apps/web/src/server/api/routers/chart.ts
similarity index 60%
rename from apps/web/src/server/api/routers/chartMeta.ts
rename to apps/web/src/server/api/routers/chart.ts
index 05e74ab48..ee5fe441b 100644
--- a/apps/web/src/server/api/routers/chartMeta.ts
+++ b/apps/web/src/server/api/routers/chart.ts
@@ -1,12 +1,131 @@
import { z } from "zod";
-
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
import { db } from "@/server/db";
-import { map, path, pipe, sort, uniq } from "ramda";
+import { pipe, sort, uniq } from "ramda";
import { toDots } from "@/utils/object";
-import { Prisma } from "@prisma/client";
import { zChartInput } from "@/utils/validation";
-import { type IChartBreakdown, type IChartEvent } from "@/types";
+import { type IChartInput, type IChartEvent } from "@/types";
+
+export const config = {
+ api: {
+ responseLimit: false,
+ },
+};
+
+export const chartRouter = createTRPCRouter({
+ events: protectedProcedure
+ .query(async () => {
+ const events = await db.event.findMany({
+ take: 500,
+ distinct: ["name"],
+ });
+
+ return events;
+ }),
+
+ properties: protectedProcedure
+ .input(z.object({ event: z.string() }).optional())
+ .query(async ({ input }) => {
+ const events = await db.event.findMany({
+ take: 500,
+ where: {
+ ...(input?.event
+ ? {
+ name: input.event,
+ }
+ : {}),
+ },
+ });
+
+ const properties = events
+ .reduce((acc, event) => {
+ const properties = event as Record<string, unknown>;
+ const dotNotation = toDots(properties);
+ return [...acc, ...Object.keys(dotNotation)];
+ }, [] as string[])
+ .map((item) => item.replace(/\.([0-9]+)\./g, ".*."))
+ .map((item) => item.replace(/\.([0-9]+)/g, "[*]"));
+
+ return pipe(
+ sort<string>((a, b) => a.length - b.length),
+ uniq,
+ )(properties);
+ }),
+
+ values: protectedProcedure
+ .input(z.object({ event: z.string(), property: z.string() }))
+ .query(async ({ input }) => {
+ if (isJsonPath(input.property)) {
+ const events = await db.$queryRawUnsafe<{ value: string }[]>(
+ `SELECT ${selectJsonPath(
+ input.property,
+ )} AS value from events WHERE name = '${
+ input.event
+ }' AND "createdAt" >= NOW() - INTERVAL '30 days'`,
+ );
+ return {
+ values: uniq(events.map((item) => item.value)),
+ };
+ } else {
+ const events = await db.event.findMany({
+ where: {
+ name: input.event,
+ [input.property]: {
+ not: null,
+ },
+ createdAt: {
+ gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30),
+ },
+ },
+ distinct: input.property as any,
+ select: {
+ [input.property]: true,
+ },
+ });
+
+ return {
+ values: uniq(events.map((item) => item[input.property]!)),
+ };
+ }
+ }),
+
+ chart: protectedProcedure
+ .input(zChartInput)
+ .query(async ({ input: { events, ...input } }) => {
+ const startDate = input.startDate ?? new Date();
+ const endDate = input.endDate ?? new Date();
+ const series: Awaited<ReturnType<typeof getChartData>> = [];
+ for (const event of events) {
+ series.push(
+ ...(await getChartData({
+ ...input,
+ event,
+ startDate,
+ endDate,
+ })),
+ );
+ }
+
+ return {
+ series: series.sort((a, b) => {
+ const sumA = a.data.reduce((acc, item) => acc + item.count, 0);
+ const sumB = b.data.reduce((acc, item) => acc + item.count, 0);
+ return sumB - sumA;
+ }),
+ };
+ }),
+});
+
+function selectJsonPath(property: string) {
+ const jsonPath = property
+ .replace(/^properties\./, "")
+ .replace(/\.\*\./g, ".**.");
+ return `jsonb_path_query(properties, '$.${jsonPath}')`;
+}
+
+function isJsonPath(property: string) {
+ return property.startsWith("properties");
+}
type ResultItem = {
label: string | null;
@@ -20,14 +139,14 @@ function propertyNameToSql(name: string) {
.split(".")
.map((item, index) => (index === 0 ? item : `'${item}'`))
.join("->");
- const findLastOf = "->"
+ const findLastOf = "->";
const lastArrow = str.lastIndexOf(findLastOf);
- if(lastArrow === -1) {
+ if (lastArrow === -1) {
return str;
- }
+ }
const first = str.slice(0, lastArrow);
const last = str.slice(lastArrow + findLastOf.length);
- return `${first}->>${last}`
+ return `${first}->>${last}`;
}
return name;
@@ -41,12 +160,6 @@ function getTotalCount(arr: ResultItem[]) {
return arr.reduce((acc, item) => acc + item.count, 0);
}
-export const config = {
- api: {
- responseLimit: false,
- },
-};
-
async function getChartData({
chartType,
event,
@@ -55,18 +168,19 @@ async function getChartData({
startDate,
endDate,
}: {
- chartType: string;
event: IChartEvent;
- breakdowns: IChartBreakdown[];
- interval: string;
- startDate: Date;
- endDate: Date;
-}) {
- const select = [`count(*)::int as count`];
+} & Omit<IChartInput, 'events'>) {
+ const select = [];
const where = [];
const groupBy = [];
const orderBy = [];
+ if (event.segment === "event") {
+ select.push(`count(*)::int as count`);
+ } else {
+ select.push(`count(DISTINCT profile_id)::int as count`);
+ }
+
switch (chartType) {
case "bar": {
orderBy.push("count DESC");
@@ -86,10 +200,43 @@ async function getChartData({
if (filters.length > 0) {
filters.forEach((filter) => {
const { name, value } = filter;
- if (name.includes(".")) {
- where.push(`${propertyNameToSql(name)} = '${value}'`);
- } else {
- where.push(`${name} = '${value}'`);
+ switch (filter.operator) {
+ case "is": {
+ if (name.includes(".*.") || name.endsWith("[*]")) {
+ where.push(
+ `properties @? '$.${name
+ .replace(/^properties\./, "")
+ .replace(/\.\*\./g, "[*].")} ? (${value
+ .map((val) => `@ == "${val}"`)
+ .join(" || ")})'`,
+ );
+ } else {
+ where.push(
+ `${propertyNameToSql(name)} in (${value
+ .map((val) => `'${val}'`)
+ .join(", ")})`,
+ );
+ }
+ break;
+ }
+ case "isNot": {
+ if (name.includes(".*.") || name.endsWith("[*]")) {
+ where.push(
+ `properties @? '$.${name
+ .replace(/^properties\./, "")
+ .replace(/\.\*\./g, "[*].")} ? (${value
+ .map((val) => `@ != "${val}"`)
+ .join(" && ")})'`,
+ );
+ } else if (name.includes(".")) {
+ where.push(
+ `${propertyNameToSql(name)} not in (${value
+ .map((val) => `'${val}'`)
+ .join(", ")})`,
+ );
+ }
+ break;
+ }
}
});
}
@@ -98,7 +245,11 @@ async function getChartData({
if (breakdowns.length) {
const breakdown = breakdowns[0];
if (breakdown) {
- select.push(`${propertyNameToSql(breakdown.name)} as label`);
+ if (isJsonPath(breakdown.name)) {
+ select.push(`${selectJsonPath(breakdown.name)} as label`);
+ } else {
+ select.push(`${breakdown.name} as label`);
+ }
groupBy.push(`label`);
}
} else {
@@ -123,7 +274,7 @@ async function getChartData({
ORDER BY ${orderBy.join(", ")}
`;
- const result = await db.$queryRawUnsafe<ResultItem[]>(sql);
+ const result = await db.$queryRawUnsafe<ResultItem[]>(sql);
// group by sql label
const series = result.reduce(
@@ -166,108 +317,6 @@ async function getChartData({
});
}
-export const chartMetaRouter = createTRPCRouter({
- events: protectedProcedure
- // .input(z.object())
- .query(async ({ input }) => {
- const events = await db.event.findMany({
- take: 500,
- distinct: ["name"],
- });
-
- return events;
- }),
-
- properties: protectedProcedure
- .input(z.object({ event: z.string() }).optional())
- .query(async ({ input }) => {
- const events = await db.event.findMany({
- take: 500,
- where: {
- ...(input?.event
- ? {
- name: input.event,
- }
- : {}),
- },
- });
-
- const properties = events.reduce((acc, event) => {
- const properties = event as Record<string, unknown>;
- const dotNotation = toDots(properties);
- return [...acc, ...Object.keys(dotNotation)];
- }, [] as string[]);
-
- return pipe(
- sort<string>((a, b) => a.length - b.length),
- uniq,
- )(properties);
- }),
-
- values: protectedProcedure
- .input(z.object({ event: z.string(), property: z.string() }))
- .query(async ({ input }) => {
- const events = await db.event.findMany({
- where: {
- name: input.event,
- properties: {
- path: input.property.split(".").slice(1),
- not: Prisma.DbNull,
- },
- createdAt: {
- // Take last 30 days
- gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30),
- },
- },
- });
-
- const values = uniq(
- map(path(input.property.split(".")), events),
- ) as string[];
-
- return {
- types: uniq(
- values.map((value) =>
- Array.isArray(value) ? "array" : typeof value,
- ),
- ),
- values,
- };
- }),
-
- chart: protectedProcedure
- .input(zChartInput)
- .query(
- async ({
- input: { chartType, events, breakdowns, interval, ...input },
- }) => {
- const startDate = input.startDate ?? new Date();
- const endDate = input.endDate ?? new Date();
- const series: Awaited<ReturnType<typeof getChartData>> = [];
- for (const event of events) {
- series.push(
- ...(await getChartData({
- chartType,
- event,
- breakdowns,
- interval,
- startDate,
- endDate,
- })),
- );
- }
-
- return {
- series: series.sort((a, b) => {
- const sumA = a.data.reduce((acc, item) => acc + item.count, 0);
- const sumB = b.data.reduce((acc, item) => acc + item.count, 0);
- return sumB - sumA;
- }),
- };
- },
- ),
-});
-
function fillEmptySpotsInTimeline(
items: ResultItem[],
interval: string,
@@ -277,14 +326,14 @@ function fillEmptySpotsInTimeline(
const result = [];
const clonedStartDate = new Date(startDate);
const clonedEndDate = new Date(endDate);
- if(interval === 'hour') {
+ if (interval === "hour") {
clonedStartDate.setMinutes(0, 0, 0);
- clonedEndDate.setMinutes(0, 0, 0)
+ clonedEndDate.setMinutes(0, 0, 0);
} else {
clonedStartDate.setHours(2, 0, 0, 0);
clonedEndDate.setHours(2, 0, 0, 0);
}
-
+
while (clonedStartDate.getTime() <= clonedEndDate.getTime()) {
const getYear = (date: Date) => date.getFullYear();
const getMonth = (date: Date) => date.getMonth();
diff --git a/apps/web/src/server/api/routers/client.ts b/apps/web/src/server/api/routers/client.ts
new file mode 100644
index 000000000..6b6f28eb1
--- /dev/null
+++ b/apps/web/src/server/api/routers/client.ts
@@ -0,0 +1,96 @@
+import { z } from "zod";
+
+import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
+import { db } from "@/server/db";
+import { hashPassword } from "@/server/services/hash.service";
+import { randomUUID } from "crypto";
+import { getOrganizationBySlug } from "@/server/services/organization.service";
+
+export const clientRouter = createTRPCRouter({
+ list: protectedProcedure
+ .input(
+ z.object({
+ organizationSlug: z.string(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const organization = await getOrganizationBySlug(input.organizationSlug);
+ return db.client.findMany({
+ where: {
+ organization_id: organization.id,
+ },
+ include: {
+ project: true,
+ },
+ });
+ }),
+ get: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .query(({ input }) => {
+ return db.client.findUniqueOrThrow({
+ where: {
+ id: input.id,
+ },
+ });
+ }),
+ update: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ }),
+ )
+ .mutation(({ input }) => {
+ return db.client.update({
+ where: {
+ id: input.id,
+ },
+ data: {
+ name: input.name,
+ },
+ });
+ }),
+ create: protectedProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ projectId: z.string(),
+ organizationSlug: z.string(),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ const organization = await getOrganizationBySlug(input.organizationSlug);
+ const secret = randomUUID();
+ const client = await db.client.create({
+ data: {
+ organization_id: organization.id,
+ project_id: input.projectId,
+ name: input.name,
+ secret: await hashPassword(secret),
+ },
+ });
+
+ return {
+ clientSecret: secret,
+ clientId: client.id,
+ };
+ }),
+ remove: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ await db.client.delete({
+ where: {
+ id: input.id,
+ },
+ });
+ return true;
+ }),
+});
diff --git a/apps/web/src/server/api/routers/dashboard.ts b/apps/web/src/server/api/routers/dashboard.ts
new file mode 100644
index 000000000..092bdbfa8
--- /dev/null
+++ b/apps/web/src/server/api/routers/dashboard.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
+import { db } from "@/server/db";
+import { getProjectBySlug } from "@/server/services/project.service";
+
+
+
+export const dashboardRouter = createTRPCRouter({
+ list: protectedProcedure
+ .input(
+ z.object({
+ organizationSlug: z.string(),
+ projectSlug: z.string(),
+ }),
+ )
+ .query(async ({ input: { projectSlug } }) => {
+ const project = await getProjectBySlug(projectSlug)
+ return db.dashboard.findMany({
+ where: {
+ project_id: project.id,
+ },
+ });
+ }),
+});
diff --git a/apps/web/src/server/api/routers/example.ts b/apps/web/src/server/api/routers/example.ts
deleted file mode 100644
index b07caa760..000000000
--- a/apps/web/src/server/api/routers/example.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { z } from "zod";
-
-import {
- createTRPCRouter,
- protectedProcedure,
- publicProcedure,
-} from "@/server/api/trpc";
-
-export const exampleRouter = createTRPCRouter({
- hello: publicProcedure
- .input(z.object({ text: z.string() }))
- .query(({ input }) => {
- return {
- greeting: `Hello ${input.text}`,
- };
- }),
-
- getAll: publicProcedure.query(() => {
- return []
- }),
-
- getSecretMessage: protectedProcedure.query(() => {
- return "you can now see this secret message!";
- }),
-});
diff --git a/apps/web/src/server/api/routers/organization.ts b/apps/web/src/server/api/routers/organization.ts
new file mode 100644
index 000000000..7e043bb91
--- /dev/null
+++ b/apps/web/src/server/api/routers/organization.ts
@@ -0,0 +1,45 @@
+import { z } from "zod";
+
+import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
+import { db } from "@/server/db";
+import { getOrganizationBySlug } from "@/server/services/organization.service";
+
+export const organizationRouter = createTRPCRouter({
+ first: protectedProcedure.query(({ ctx }) => {
+ return db.organization.findFirst({
+ where: {
+ users: {
+ some: {
+ id: ctx.session.user.id,
+ },
+ },
+ },
+ });
+ }),
+ get: protectedProcedure
+ .input(
+ z.object({
+ slug: z.string(),
+ }),
+ )
+ .query(({ input }) => {
+ return getOrganizationBySlug(input.slug)
+ }),
+ update: protectedProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ slug: z.string(),
+ }),
+ )
+ .mutation(({ input }) => {
+ return db.organization.update({
+ where: {
+ slug: input.slug,
+ },
+ data: {
+ name: input.name,
+ },
+ });
+ }),
+});
diff --git a/apps/web/src/server/api/routers/project.ts b/apps/web/src/server/api/routers/project.ts
new file mode 100644
index 000000000..a6c98d771
--- /dev/null
+++ b/apps/web/src/server/api/routers/project.ts
@@ -0,0 +1,81 @@
+import { z } from "zod";
+
+import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
+import { db } from "@/server/db";
+import { getOrganizationBySlug } from "@/server/services/organization.service";
+
+export const projectRouter = createTRPCRouter({
+ list: protectedProcedure
+ .input(z.object({
+ organizationSlug: z.string()
+ }))
+ .query(async ({ input }) => {
+ const organization = await getOrganizationBySlug(input.organizationSlug)
+ return db.project.findMany({
+ where: {
+ organization_id: organization.id,
+ },
+ });
+ }),
+ get: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .query(({ input }) => {
+ return db.project.findUniqueOrThrow({
+ where: {
+ id: input.id,
+ organization_id: "d433c614-69f9-443a-8961-92a662869929",
+ },
+ });
+ }),
+ update: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ }),
+ )
+ .mutation(({ input }) => {
+ return db.project.update({
+ where: {
+ id: input.id,
+ organization_id: "d433c614-69f9-443a-8961-92a662869929",
+ },
+ data: {
+ name: input.name,
+ },
+ });
+ }),
+ create: protectedProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ }),
+ )
+ .mutation(({ input }) => {
+ return db.project.create({
+ data: {
+ organization_id: "d433c614-69f9-443a-8961-92a662869929",
+ name: input.name,
+ },
+ });
+ }),
+ remove: protectedProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ await db.project.delete({
+ where: {
+ id: input.id,
+ organization_id: "d433c614-69f9-443a-8961-92a662869929",
+ },
+ });
+ return true
+ }),
+});
diff --git a/apps/web/src/server/api/routers/report.ts b/apps/web/src/server/api/routers/report.ts
index 6fe328940..2dae9378d 100644
--- a/apps/web/src/server/api/routers/report.ts
+++ b/apps/web/src/server/api/routers/report.ts
@@ -10,6 +10,8 @@ import {
type IChartEvent,
} from "@/types";
import { type Report as DbReport } from "@prisma/client";
+import { getProjectBySlug } from "@/server/services/project.service";
+import { getDashboardBySlug } from "@/server/services/dashboard.service";
function transform(report: DbReport): IChartInput & { id: string } {
return {
@@ -40,22 +42,27 @@ export const reportRouter = createTRPCRouter({
})
.then(transform);
}),
- getDashboard: protectedProcedure
+ list: protectedProcedure
.input(
z.object({
- projectId: z.string(),
- dashboardId: z.string(),
+ projectSlug: z.string(),
+ dashboardSlug: z.string(),
}),
)
- .query(async ({ input: { projectId, dashboardId } }) => {
+ .query(async ({ input: { projectSlug, dashboardSlug } }) => {
+ const project = await getProjectBySlug(projectSlug);
+ const dashboard = await getDashboardBySlug(dashboardSlug);
const reports = await db.report.findMany({
where: {
- project_id: projectId,
- dashboard_id: dashboardId,
+ project_id: project.id,
+ dashboard_id: dashboard.id,
},
});
- return reports.map(transform);
+ return {
+ reports: reports.map(transform),
+ dashboard,
+ }
}),
save: protectedProcedure
.input(
diff --git a/apps/web/src/server/api/routers/user.ts b/apps/web/src/server/api/routers/user.ts
new file mode 100644
index 000000000..af731224f
--- /dev/null
+++ b/apps/web/src/server/api/routers/user.ts
@@ -0,0 +1,67 @@
+import { z } from "zod";
+
+import {
+ createTRPCRouter,
+ protectedProcedure,
+} from "@/server/api/trpc";
+import { db } from "@/server/db";
+import { hashPassword } from "@/server/services/hash.service";
+
+export const userRouter = createTRPCRouter({
+ current: protectedProcedure.query(({ ctx }) => {
+ return db.user.findUniqueOrThrow({
+ where: {
+ id: ctx.session.user.id
+ }
+ })
+ }),
+ update: protectedProcedure
+ .input(
+ z.object({
+ name: z.string(),
+ email: z.string(),
+ }),
+ )
+ .mutation(({ input, ctx }) => {
+ return db.user.update({
+ where: {
+ id: ctx.session.user.id
+ },
+ data: {
+ name: input.name,
+ email: input.email,
+ }
+ })
+ }),
+ changePassword: protectedProcedure
+ .input(
+ z.object({
+ password: z.string(),
+ oldPassword: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const user = await db.user.findUniqueOrThrow({
+ where: {
+ id: ctx.session.user.id
+ }
+ })
+
+ if(user.password !== input.oldPassword) {
+ throw new Error('Old password is incorrect')
+ }
+
+ if(user.password === input.password) {
+ throw new Error('New password cannot be the same as old password')
+ }
+
+ return db.user.update({
+ where: {
+ id: ctx.session.user.id
+ },
+ data: {
+ password: await hashPassword(input.password),
+ }
+ })
+ }),
+});
diff --git a/apps/web/src/server/api/trpc.ts b/apps/web/src/server/api/trpc.ts
index b76514249..23300729e 100644
--- a/apps/web/src/server/api/trpc.ts
+++ b/apps/web/src/server/api/trpc.ts
@@ -53,7 +53,6 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
*/
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;
-
// Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });
diff --git a/apps/web/src/server/auth.ts b/apps/web/src/server/auth.ts
index f8f3bf943..3324d23e3 100644
--- a/apps/web/src/server/auth.ts
+++ b/apps/web/src/server/auth.ts
@@ -8,7 +8,7 @@ import {
import { db } from "@/server/db";
import Credentials from "next-auth/providers/credentials";
import { createError } from "./exceptions";
-import { verifyPassword } from "@/services/hash.service";
+import { verifyPassword } from "@/server/services/hash.service";
/**
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
@@ -46,7 +46,9 @@ export const authOptions: NextAuthOptions = {
},
}),
},
- // adapter: PrismaAdapter(db),
+ session: {
+ strategy: "jwt",
+ },
providers: [
Credentials({
name: "Credentials",
@@ -60,7 +62,10 @@ export const authOptions: NextAuthOptions = {
});
if (user) {
- return user;
+ return {
+ ...user,
+ image: 'https://avatars.githubusercontent.com/u/18133?v=4'
+ };
} else {
return null;
}
diff --git a/apps/web/src/server/getServerSideProps.ts b/apps/web/src/server/getServerSideProps.ts
new file mode 100644
index 000000000..6c7c97eb2
--- /dev/null
+++ b/apps/web/src/server/getServerSideProps.ts
@@ -0,0 +1,35 @@
+import {
+ type GetServerSidePropsContext,
+ type GetServerSidePropsResult,
+} from "next";
+import { getServerAuthSession } from "./auth";
+
+export function createServerSideProps(
+ cb?: (context: GetServerSidePropsContext) => Promise<any>,
+) {
+ return async function getServerSideProps(
+ context: GetServerSidePropsContext,
+ ): Promise<GetServerSidePropsResult<any>> {
+ const session = await getServerAuthSession(context);
+
+ if(!session) {
+ return {
+ redirect: {
+ destination: "/api/auth/signin",
+ permanent: false,
+ },
+ }
+ }
+
+ const res = await (typeof cb === "function"
+ ? cb(context)
+ : Promise.resolve({}));
+ return {
+ ...(res ?? {}),
+ props: {
+ session,
+ ...(res?.props ?? {}),
+ },
+ };
+ };
+}
diff --git a/apps/web/src/server/services/dashboard.service.ts b/apps/web/src/server/services/dashboard.service.ts
new file mode 100644
index 000000000..c00740765
--- /dev/null
+++ b/apps/web/src/server/services/dashboard.service.ts
@@ -0,0 +1,9 @@
+import { db } from "../db";
+
+export function getDashboardBySlug(slug: string) {
+ return db.dashboard.findUniqueOrThrow({
+ where: {
+ slug
+ },
+ });
+}
\ No newline at end of file
diff --git a/apps/web/src/services/hash.service.ts b/apps/web/src/server/services/hash.service.ts
similarity index 100%
rename from apps/web/src/services/hash.service.ts
rename to apps/web/src/server/services/hash.service.ts
diff --git a/apps/web/src/server/services/organization.service.ts b/apps/web/src/server/services/organization.service.ts
new file mode 100644
index 000000000..15f4b6c9f
--- /dev/null
+++ b/apps/web/src/server/services/organization.service.ts
@@ -0,0 +1,9 @@
+import { db } from "../db";
+
+export function getOrganizationBySlug(slug: string) {
+ return db.organization.findUniqueOrThrow({
+ where: {
+ slug
+ },
+ });
+}
\ No newline at end of file
diff --git a/apps/web/src/services/profile.service.ts b/apps/web/src/server/services/profile.service.ts
similarity index 100%
rename from apps/web/src/services/profile.service.ts
rename to apps/web/src/server/services/profile.service.ts
diff --git a/apps/web/src/server/services/project.service.ts b/apps/web/src/server/services/project.service.ts
new file mode 100644
index 000000000..a08f390fc
--- /dev/null
+++ b/apps/web/src/server/services/project.service.ts
@@ -0,0 +1,9 @@
+import { db } from "../db";
+
+export function getProjectBySlug(slug: string) {
+ return db.project.findUniqueOrThrow({
+ where: {
+ slug
+ },
+ });
+}
\ No newline at end of file
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index 6a7572500..c5b393315 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -73,4 +73,20 @@
body {
@apply bg-background text-foreground;
}
-}
\ No newline at end of file
+
+ .h1 {
+ @apply text-3xl font-medium;
+ }
+
+ .h2 {
+ @apply text-xl font-medium;
+ }
+
+ .h3 {
+ @apply text-lg font-medium;
+ }
+
+ .h4 {
+ @apply font-medium;
+ }
+}
diff --git a/apps/web/src/types/index.ts b/apps/web/src/types/index.ts
index dcba7ba2c..c9a11c16e 100644
--- a/apps/web/src/types/index.ts
+++ b/apps/web/src/types/index.ts
@@ -1,4 +1,5 @@
import { type zTimeInterval, type zChartBreakdown, type zChartEvent, type zChartInput } from "@/utils/validation";
+import { type Client, type Project } from "@prisma/client";
import { type TooltipProps } from "recharts";
import { type z } from "zod";
@@ -7,6 +8,7 @@ export type HtmlProps<T> = React.DetailedHTMLProps<React.HTMLAttributes<T>, T>;
export type IChartInput = z.infer<typeof zChartInput>
export type IChartEvent = z.infer<typeof zChartEvent>
export type IChartEventFilter = IChartEvent['filters'][number]
+export type IChartEventFilterValue = IChartEvent['filters'][number]['value'][number]
export type IChartBreakdown = z.infer<typeof zChartBreakdown>
export type IInterval = z.infer<typeof zTimeInterval>
@@ -14,3 +16,9 @@ export type IInterval = z.infer<typeof zTimeInterval>
export type IToolTipProps<T> = Omit<TooltipProps<number, string>, 'payload'> & {
payload?: Array<T>
}
+
+
+export type IProject = Project
+export type IClientWithProject = Client & {
+ project: IProject
+}
\ No newline at end of file
diff --git a/apps/web/src/utils/api.ts b/apps/web/src/utils/api.ts
index a6f032edd..5f06f7b27 100644
--- a/apps/web/src/utils/api.ts
+++ b/apps/web/src/utils/api.ts
@@ -4,12 +4,13 @@
*
* We also create a few inference helpers for input and output types.
*/
-import { httpBatchLink, httpLink, loggerLink } from "@trpc/client";
+import { type TRPCClientErrorBase, httpLink, loggerLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import superjson from "superjson";
import { type AppRouter } from "@/server/api/root";
+import { toast } from "@/components/ui/use-toast";
const getBaseUrl = () => {
if (typeof window !== "undefined") return ""; // browser should use relative url
@@ -27,7 +28,8 @@ export const api = createTRPCNext<AppRouter>({
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
- }
+ enabled: typeof window !== "undefined",
+ },
}
},
/**
@@ -75,3 +77,11 @@ export type RouterInputs = inferRouterInputs<AppRouter>;
* @example type HelloOutput = RouterOutputs['example']['hello']
*/
export type RouterOutputs = inferRouterOutputs<AppRouter>;
+
+
+export function handleError(error: TRPCClientErrorBase<any>) {
+ toast({
+ title: 'Error',
+ description: error.message,
+ })
+}
\ No newline at end of file
diff --git a/apps/web/src/utils/clipboard.ts b/apps/web/src/utils/clipboard.ts
new file mode 100644
index 000000000..23615ca82
--- /dev/null
+++ b/apps/web/src/utils/clipboard.ts
@@ -0,0 +1,9 @@
+import { toast } from "@/components/ui/use-toast"
+
+export function clipboard(value: string | number) {
+ navigator.clipboard.writeText(value.toString())
+ toast({
+ title: "Copied to clipboard",
+ description: value.toString(),
+ })
+}
\ No newline at end of file
diff --git a/apps/web/src/utils/constants.ts b/apps/web/src/utils/constants.ts
new file mode 100644
index 000000000..525e45a4b
--- /dev/null
+++ b/apps/web/src/utils/constants.ts
@@ -0,0 +1,7 @@
+
+export const operators = {
+ is: "Is",
+ isNot: "Is not",
+ contains: 'Contains',
+ doesNotContain: 'Not contains',
+}
\ No newline at end of file
diff --git a/apps/web/src/utils/date.ts b/apps/web/src/utils/date.ts
index 2586f5738..f8aa43471 100644
--- a/apps/web/src/utils/date.ts
+++ b/apps/web/src/utils/date.ts
@@ -8,4 +8,15 @@ export function dateDifferanceInDays(date1: Date, date2: Date) {
const diffTime = Math.abs(date2.getTime() - date1.getTime());
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}
+
+export function getLocale() {
+ if(typeof navigator === 'undefined') {
+ return 'en-US'
+ }
+
+ return navigator.language ?? 'en-US';
+}
+
+export function formatDate(date: Date) {
+ return new Intl.DateTimeFormat(getLocale()).format(date)
}
\ No newline at end of file
diff --git a/apps/web/src/utils/theme.ts b/apps/web/src/utils/theme.ts
index 9e3b3b28a..83907e18d 100644
--- a/apps/web/src/utils/theme.ts
+++ b/apps/web/src/utils/theme.ts
@@ -1,5 +1,5 @@
import resolveConfig from "tailwindcss/resolveConfig";
-import tailwinConfig from "../../tailwind.config.js";
+import tailwinConfig from "../../tailwind.config";
const config = resolveConfig(tailwinConfig);
export const theme = config.theme as any;
diff --git a/apps/web/src/utils/validation.ts b/apps/web/src/utils/validation.ts
index 2613e8339..59192e9d3 100644
--- a/apps/web/src/utils/validation.ts
+++ b/apps/web/src/utils/validation.ts
@@ -1,14 +1,27 @@
-import { ChartType } from "@prisma/client";
import { z } from "zod";
+import { operators } from "./constants";
+
+function objectToZodEnums<K extends string> ( obj: Record<K, any> ): [ K, ...K[] ] {
+ const [ firstKey, ...otherKeys ] = Object.keys( obj ) as K[]
+ return [ firstKey!, ...otherKeys ]
+}
export const zChartEvent = z.object({
id: z.string(),
name: z.string(),
+ segment: z.enum(["event", "user"]),
filters: z.array(
z.object({
id: z.string(),
name: z.string(),
- value: z.string(),
+ operator: z.enum(objectToZodEnums(operators)),
+ value: z.array(
+ z
+ .string()
+ .or(z.number())
+ .or(z.boolean())
+ .or(z.null())
+ ),
}),
),
});
@@ -20,7 +33,7 @@ export const zChartBreakdown = z.object({
export const zChartEvents = z.array(zChartEvent);
export const zChartBreakdowns = z.array(zChartBreakdown);
-export const zChartType = z.enum(['linear', 'bar', 'pie', 'metric', 'area']);
+export const zChartType = z.enum(["linear", "bar", "pie", "metric", "area"]);
export const zTimeInterval = z.enum(["day", "hour", "month"]);
@@ -32,4 +45,4 @@ export const zChartInput = z.object({
interval: zTimeInterval,
events: zChartEvents,
breakdowns: zChartBreakdowns,
-})
\ No newline at end of file
+});
diff --git a/apps/web/tailwind.config.js b/apps/web/tailwind.config.js
deleted file mode 100644
index 477dd3240..000000000
--- a/apps/web/tailwind.config.js
+++ /dev/null
@@ -1,100 +0,0 @@
-const colors = [
- "#7856ff",
- "#ff7557",
- "#7fe1d8",
- "#f8bc3c",
- "#b3596e",
- "#72bef4",
- "#ffb27a",
- "#0f7ea0",
- "#3ba974",
- "#febbb2",
- "#cb80dc",
- "#5cb7af",
-];
-
-/** @type {import('tailwindcss').Config} */
-module.exports = {
- safelist: [
- ...colors.map((color) => `chart-${color}`),
- ],
- darkMode: ["class"],
- content: [
- "./pages/**/*.{ts,tsx}",
- "./components/**/*.{ts,tsx}",
- "./app/**/*.{ts,tsx}",
- "./src/**/*.{ts,tsx}",
- ],
- theme: {
- container: {
- center: true,
- padding: "2rem",
- screens: {
- "2xl": "1400px",
- },
- },
- extend: {
- colors: {
- border: "hsl(var(--border))",
- input: "hsl(var(--input))",
- ring: "hsl(var(--ring))",
- background: "hsl(var(--background))",
- foreground: "hsl(var(--foreground))",
- primary: {
- DEFAULT: "hsl(var(--primary))",
- foreground: "hsl(var(--primary-foreground))",
- },
- secondary: {
- DEFAULT: "hsl(var(--secondary))",
- foreground: "hsl(var(--secondary-foreground))",
- },
- destructive: {
- DEFAULT: "hsl(var(--destructive))",
- foreground: "hsl(var(--destructive-foreground))",
- },
- muted: {
- DEFAULT: "hsl(var(--muted))",
- foreground: "hsl(var(--muted-foreground))",
- },
- accent: {
- DEFAULT: "hsl(var(--accent))",
- foreground: "hsl(var(--accent-foreground))",
- },
- popover: {
- DEFAULT: "hsl(var(--popover))",
- foreground: "hsl(var(--popover-foreground))",
- },
- card: {
- DEFAULT: "hsl(var(--card))",
- foreground: "hsl(var(--card-foreground))",
- },
- ...colors.reduce((acc, color, index) => {
- return {
- ...acc,
- [`chart-${index}`]: color,
- };
- }, {}),
- },
- borderRadius: {
- lg: "var(--radius)",
- md: "calc(var(--radius) - 2px)",
- sm: "calc(var(--radius) - 4px)",
- },
- keyframes: {
- "accordion-down": {
- from: { height: 0 },
- to: { height: "var(--radix-accordion-content-height)" },
- },
- "accordion-up": {
- from: { height: "var(--radix-accordion-content-height)" },
- to: { height: 0 },
- },
- },
- animation: {
- "accordion-down": "accordion-down 0.2s ease-out",
- "accordion-up": "accordion-up 0.2s ease-out",
- },
- },
- },
- plugins: [require("tailwindcss-animate")],
-};
diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.ts
index cc45ec94f..351278955 100644
--- a/apps/web/tailwind.config.ts
+++ b/apps/web/tailwind.config.ts
@@ -1,28 +1,105 @@
-import { type Config } from "tailwindcss";
+const colors = [
+ "#7856ff",
+ "#ff7557",
+ "#7fe1d8",
+ "#f8bc3c",
+ "#b3596e",
+ "#72bef4",
+ "#ffb27a",
+ "#0f7ea0",
+ "#3ba974",
+ "#febbb2",
+ "#cb80dc",
+ "#5cb7af",
+];
-export default {
- content: ["./src/**/*.{js,ts,jsx,tsx}"],
+/** @type {import('tailwindcss').Config} */
+const config = {
+ safelist: [
+ ...colors.map((color) => `chart-${color}`),
+ ],
+ darkMode: ["class"],
+ content: [
+ "./pages/**/*.{ts,tsx}",
+ "./components/**/*.{ts,tsx}",
+ "./app/**/*.{ts,tsx}",
+ "./src/**/*.{ts,tsx}",
+ ],
theme: {
+ container: {
+ center: true,
+ padding: "2rem",
+ screens: {
+ "2xl": "1400px",
+ },
+ },
extend: {
colors: {
- 'chart-0': '',
- 'chart-1': '',
- 'chart-2': '',
- 'chart-3': '',
- 'chart-4': '',
- 'chart-5': '',
- 'chart-6': '',
- 'chart-7': '',
- 'chart-8': '',
- 'chart-9': '',
- 'chart-10': '',
- 'chart-11': '',
- 'chart-12': '',
- 'chart-13': '',
- 'chart-14': '',
- 'chart-15': '',
- }
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ ...colors.reduce((acc, color, index) => {
+ return {
+ ...acc,
+ [`chart-${index}`]: color,
+ };
+ }, {}),
+ },
+ borderRadius: {
+ lg: "var(--radius)",
+ md: "calc(var(--radius) - 2px)",
+ sm: "calc(var(--radius) - 4px)",
+ },
+ boxShadow: {
+ DEFAULT: '0 5px 10px rgb(0 0 0 / 5%)'
+ },
+ keyframes: {
+ "accordion-down": {
+ from: { height: 0 },
+ to: { height: "var(--radix-accordion-content-height)" },
+ },
+ "accordion-up": {
+ from: { height: "var(--radix-accordion-content-height)" },
+ to: { height: 0 },
+ },
+ },
+ animation: {
+ "accordion-down": "accordion-down 0.2s ease-out",
+ "accordion-up": "accordion-up 0.2s ease-out",
+ },
},
},
- plugins: [],
-} satisfies Config;
+ plugins: [require("tailwindcss-animate")],
+};
+
+export default config
\ No newline at end of file
diff --git a/bun.lockb b/bun.lockb
index df7657807..104b8443e 100755
Binary files a/bun.lockb and b/bun.lockb differ