web: added the base for the web project
This commit is contained in:
20
README.md
20
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).
|
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
|
## @mixan/sdk
|
||||||
|
|
||||||
For pushing events
|
For pushing events
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ const config = {
|
|||||||
"@typescript-eslint/no-unsafe-argument": "off",
|
"@typescript-eslint/no-unsafe-argument": "off",
|
||||||
"@typescript-eslint/no-unsafe-return": "off",
|
"@typescript-eslint/no-unsafe-return": "off",
|
||||||
"@typescript-eslint/no-unsafe-call": "off",
|
"@typescript-eslint/no-unsafe-call": "off",
|
||||||
|
"@typescript-eslint/no-misused-promises": "off",
|
||||||
|
"@typescript-eslint/no-floating-promises": "off",
|
||||||
"@typescript-eslint/consistent-type-imports": [
|
"@typescript-eslint/consistent-type-imports": [
|
||||||
"warn",
|
"warn",
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
"rsc": false,
|
"rsc": false,
|
||||||
"tsx": true,
|
"tsx": true,
|
||||||
"tailwind": {
|
"tailwind": {
|
||||||
"config": "tailwind.config.js",
|
"config": "tailwind.config.ts",
|
||||||
"css": "src/styles/globals.css",
|
"css": "src/styles/globals.css",
|
||||||
"baseColor": "slate",
|
"baseColor": "slate",
|
||||||
"cssVariables": true
|
"cssVariables": true
|
||||||
|
|||||||
@@ -11,19 +11,25 @@
|
|||||||
"start": "next start"
|
"start": "next start"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@hookform/resolvers": "^3.3.2",
|
||||||
"@mixan/types": "^0.0.2-alpha",
|
"@mixan/types": "^0.0.2-alpha",
|
||||||
"@next-auth/prisma-adapter": "^1.0.7",
|
"@next-auth/prisma-adapter": "^1.0.7",
|
||||||
"@prisma/client": "^5.1.1",
|
"@prisma/client": "^5.1.1",
|
||||||
|
"@radix-ui/react-alert-dialog": "^1.0.5",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.0.3",
|
"@radix-ui/react-aspect-ratio": "^1.0.3",
|
||||||
"@radix-ui/react-avatar": "^1.0.4",
|
"@radix-ui/react-avatar": "^1.0.4",
|
||||||
"@radix-ui/react-checkbox": "^1.0.4",
|
"@radix-ui/react-checkbox": "^1.0.4",
|
||||||
"@radix-ui/react-dialog": "^1.0.5",
|
"@radix-ui/react-dialog": "^1.0.5",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.0.6",
|
"@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-popover": "^1.0.7",
|
||||||
"@radix-ui/react-slot": "^1.0.2",
|
"@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",
|
"@reduxjs/toolkit": "^1.9.7",
|
||||||
"@t3-oss/env-nextjs": "^0.7.0",
|
"@t3-oss/env-nextjs": "^0.7.0",
|
||||||
"@tanstack/react-query": "^4.32.6",
|
"@tanstack/react-query": "^4.32.6",
|
||||||
|
"@tanstack/react-table": "^8.10.7",
|
||||||
"@trpc/client": "^10.37.1",
|
"@trpc/client": "^10.37.1",
|
||||||
"@trpc/next": "^10.37.1",
|
"@trpc/next": "^10.37.1",
|
||||||
"@trpc/react-query": "^10.37.1",
|
"@trpc/react-query": "^10.37.1",
|
||||||
@@ -33,13 +39,16 @@
|
|||||||
"clsx": "^2.0.0",
|
"clsx": "^2.0.0",
|
||||||
"cmdk": "^0.2.0",
|
"cmdk": "^0.2.0",
|
||||||
"lucide-react": "^0.286.0",
|
"lucide-react": "^0.286.0",
|
||||||
|
"mitt": "^3.0.1",
|
||||||
"next": "^13.5.4",
|
"next": "^13.5.4",
|
||||||
"next-auth": "^4.23.0",
|
"next-auth": "^4.23.0",
|
||||||
"ramda": "^0.29.1",
|
"ramda": "^0.29.1",
|
||||||
"random-animal-name": "^0.1.1",
|
"random-animal-name": "^0.1.1",
|
||||||
"react": "18.2.0",
|
"react": "18.2.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.2.0",
|
||||||
|
"react-hook-form": "^7.47.0",
|
||||||
"react-redux": "^8.1.3",
|
"react-redux": "^8.1.3",
|
||||||
|
"react-syntax-highlighter": "^15.5.0",
|
||||||
"react-virtualized-auto-sizer": "^1.0.20",
|
"react-virtualized-auto-sizer": "^1.0.20",
|
||||||
"recharts": "^2.8.0",
|
"recharts": "^2.8.0",
|
||||||
"superjson": "^1.13.1",
|
"superjson": "^1.13.1",
|
||||||
@@ -55,6 +64,7 @@
|
|||||||
"@types/ramda": "^0.29.6",
|
"@types/ramda": "^0.29.6",
|
||||||
"@types/react": "^18.2.20",
|
"@types/react": "^18.2.20",
|
||||||
"@types/react-dom": "^18.2.7",
|
"@types/react-dom": "^18.2.7",
|
||||||
|
"@types/react-syntax-highlighter": "^15.5.9",
|
||||||
"@typescript-eslint/eslint-plugin": "^6.3.0",
|
"@typescript-eslint/eslint-plugin": "^6.3.0",
|
||||||
"@typescript-eslint/parser": "^6.3.0",
|
"@typescript-eslint/parser": "^6.3.0",
|
||||||
"autoprefixer": "^10.4.14",
|
"autoprefixer": "^10.4.14",
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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;
|
||||||
@@ -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");
|
||||||
@@ -13,11 +13,13 @@ datasource db {
|
|||||||
model Organization {
|
model Organization {
|
||||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
name String
|
name String
|
||||||
|
slug String @unique @default(dbgenerated("gen_random_uuid()"))
|
||||||
projects Project[]
|
projects Project[]
|
||||||
users User[]
|
users User[]
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @default(now()) @updatedAt
|
updatedAt DateTime @default(now()) @updatedAt
|
||||||
|
clients Client[]
|
||||||
|
|
||||||
@@map("organizations")
|
@@map("organizations")
|
||||||
}
|
}
|
||||||
@@ -25,6 +27,7 @@ model Organization {
|
|||||||
model Project {
|
model Project {
|
||||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
name String
|
name String
|
||||||
|
slug String @unique @default(dbgenerated("gen_random_uuid()"))
|
||||||
organization_id String @db.Uuid
|
organization_id String @db.Uuid
|
||||||
organization Organization @relation(fields: [organization_id], references: [id])
|
organization Organization @relation(fields: [organization_id], references: [id])
|
||||||
events Event[]
|
events Event[]
|
||||||
@@ -88,11 +91,13 @@ model Profile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model Client {
|
model Client {
|
||||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
name String
|
name String
|
||||||
secret String
|
secret String
|
||||||
project_id String @db.Uuid
|
project_id String @db.Uuid
|
||||||
project Project @relation(fields: [project_id], references: [id])
|
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())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @default(now()) @updatedAt
|
updatedAt DateTime @default(now()) @updatedAt
|
||||||
@@ -117,6 +122,7 @@ enum ChartType {
|
|||||||
model Dashboard {
|
model Dashboard {
|
||||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
name String
|
name String
|
||||||
|
slug String @unique @default(dbgenerated("gen_random_uuid()"))
|
||||||
project_id String @db.Uuid
|
project_id String @db.Uuid
|
||||||
project Project @relation(fields: [project_id], references: [id])
|
project Project @relation(fields: [project_id], references: [id])
|
||||||
reports Report[]
|
reports Report[]
|
||||||
|
|||||||
3
apps/web/src/_middleware.ts
Normal file
3
apps/web/src/_middleware.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export { default } from "next-auth/middleware"
|
||||||
|
|
||||||
|
export const config = { matcher: ["/dashboard"] }
|
||||||
8
apps/web/src/components/ButtonContainer.tsx
Normal file
8
apps/web/src/components/ButtonContainer.tsx
Normal file
@@ -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} />
|
||||||
|
);
|
||||||
|
}
|
||||||
9
apps/web/src/components/Card.tsx
Normal file
9
apps/web/src/components/Card.tsx
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { type HtmlProps } from "@/types";
|
||||||
|
|
||||||
|
export function Card({children}: HtmlProps<HTMLDivElement>) {
|
||||||
|
return (
|
||||||
|
<div className="border border-border rounded">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,6 +3,6 @@ import { cn } from "@/utils/cn";
|
|||||||
|
|
||||||
export function Container({className,...props}: HtmlProps<HTMLDivElement>) {
|
export function Container({className,...props}: HtmlProps<HTMLDivElement>) {
|
||||||
return (
|
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} />
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
50
apps/web/src/components/Content.tsx
Normal file
50
apps/web/src/components/Content.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
66
apps/web/src/components/DataTable.tsx
Normal file
66
apps/web/src/components/DataTable.tsx
Normal file
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
49
apps/web/src/components/Dropdown.tsx
Normal file
49
apps/web/src/components/Dropdown.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
11
apps/web/src/components/PageTitle.tsx
Normal file
11
apps/web/src/components/PageTitle.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
13
apps/web/src/components/Syntax.tsx
Normal file
13
apps/web/src/components/Syntax.tsx
Normal file
@@ -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>;
|
||||||
|
}
|
||||||
@@ -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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
21
apps/web/src/components/WithSidebar.tsx
Normal file
21
apps/web/src/components/WithSidebar.tsx
Normal file
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
69
apps/web/src/components/clients/ClientActions.tsx
Normal file
69
apps/web/src/components/clients/ClientActions.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
43
apps/web/src/components/clients/table.tsx
Normal file
43
apps/web/src/components/clients/table.tsx
Normal file
@@ -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} />,
|
||||||
|
},
|
||||||
|
];
|
||||||
18
apps/web/src/components/forms/InputWithLabel.tsx
Normal file
18
apps/web/src/components/forms/InputWithLabel.tsx
Normal file
@@ -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";
|
||||||
@@ -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>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
29
apps/web/src/components/layouts/MainLayout.tsx
Normal file
29
apps/web/src/components/layouts/MainLayout.tsx
Normal file
@@ -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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
52
apps/web/src/components/layouts/SettingsLayout.tsx
Normal file
52
apps/web/src/components/layouts/SettingsLayout.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
36
apps/web/src/components/navbar/NavbarCreate.tsx
Normal file
36
apps/web/src/components/navbar/NavbarCreate.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
13
apps/web/src/components/navbar/NavbarMenu.tsx
Normal file
13
apps/web/src/components/navbar/NavbarMenu.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
67
apps/web/src/components/navbar/NavbarUserDropdown.tsx
Normal file
67
apps/web/src/components/navbar/NavbarUserDropdown.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
70
apps/web/src/components/projects/ProjectActions.tsx
Normal file
70
apps/web/src/components/projects/ProjectActions.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
26
apps/web/src/components/projects/table.tsx
Normal file
26
apps/web/src/components/projects/table.tsx
Normal file
@@ -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} />,
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -13,11 +13,18 @@ export function ReportDateRange() {
|
|||||||
<RadioGroup>
|
<RadioGroup>
|
||||||
<RadioGroupItem
|
<RadioGroupItem
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
dispatch(changeDateRanges(1));
|
dispatch(changeDateRanges('today'));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Today
|
Today
|
||||||
</RadioGroupItem>
|
</RadioGroupItem>
|
||||||
|
<RadioGroupItem
|
||||||
|
onClick={() => {
|
||||||
|
dispatch(changeDateRanges(1));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
24 hours
|
||||||
|
</RadioGroupItem>
|
||||||
<RadioGroupItem
|
<RadioGroupItem
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
dispatch(changeDateRanges(7));
|
dispatch(changeDateRanges(7));
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ export function ReportLineChart({
|
|||||||
}: ReportLineChartProps) {
|
}: ReportLineChartProps) {
|
||||||
const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
|
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,
|
interval,
|
||||||
chartType,
|
chartType,
|
||||||
@@ -42,7 +44,7 @@ export function ReportLineChart({
|
|||||||
name,
|
name,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
enabled: events.length > 0,
|
enabled: events.length > 0 && !hasEmptyFilters,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -67,10 +69,11 @@ export function ReportLineChart({
|
|||||||
<AutoSizer disableHeight>
|
<AutoSizer disableHeight>
|
||||||
{({ width }) => (
|
{({ width }) => (
|
||||||
<LineChart width={width} height={Math.min(width * 0.5, 400)}>
|
<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 />} />
|
<Tooltip content={<ReportLineChartTooltip />} />
|
||||||
<CartesianGrid strokeDasharray="3 3" />
|
<CartesianGrid strokeDasharray="3 3" />
|
||||||
<XAxis
|
<XAxis
|
||||||
|
fontSize={12}
|
||||||
dataKey="date"
|
dataKey="date"
|
||||||
tickFormatter={(m: Date) => {
|
tickFormatter={(m: Date) => {
|
||||||
return formatDate(m);
|
return formatDate(m);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useMappings } from "@/hooks/useMappings";
|
||||||
import { type IToolTipProps } from "@/types";
|
import { type IToolTipProps } from "@/types";
|
||||||
|
|
||||||
type ReportLineChartTooltipProps = IToolTipProps<{
|
type ReportLineChartTooltipProps = IToolTipProps<{
|
||||||
@@ -8,13 +9,15 @@ type ReportLineChartTooltipProps = IToolTipProps<{
|
|||||||
count: number;
|
count: number;
|
||||||
label: string;
|
label: string;
|
||||||
};
|
};
|
||||||
}>
|
}>;
|
||||||
|
|
||||||
export function ReportLineChartTooltip({
|
export function ReportLineChartTooltip({
|
||||||
active,
|
active,
|
||||||
payload,
|
payload,
|
||||||
}: ReportLineChartTooltipProps) {
|
}: ReportLineChartTooltipProps) {
|
||||||
if (!active || !payload) {
|
const getLabel = useMappings();
|
||||||
|
|
||||||
|
if (!active || !payload) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,7 +25,6 @@ export function ReportLineChartTooltip({
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const limit = 3;
|
const limit = 3;
|
||||||
const sorted = payload.slice(0).sort((a, b) => b.value - a.value);
|
const sorted = payload.slice(0).sort((a, b) => b.value - a.value);
|
||||||
const visible = sorted.slice(0, limit);
|
const visible = sorted.slice(0, limit);
|
||||||
@@ -39,7 +41,7 @@ export function ReportLineChartTooltip({
|
|||||||
></div>
|
></div>
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<div className="min-w-0 max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap font-medium">
|
<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>
|
||||||
<div>{item.payload.count}</div>
|
<div>{item.payload.count}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ import { useSelector } from "@/redux";
|
|||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { getChartColor } from "@/utils/theme";
|
import { getChartColor } from "@/utils/theme";
|
||||||
import { cn } from "@/utils/cn";
|
import { cn } from "@/utils/cn";
|
||||||
|
import { useMappings } from "@/hooks/useMappings";
|
||||||
|
|
||||||
|
|
||||||
type ReportTableProps = {
|
type ReportTableProps = {
|
||||||
data: RouterOutputs["chartMeta"]["chart"];
|
data: RouterOutputs["chart"]["chart"];
|
||||||
visibleSeries: string[];
|
visibleSeries: string[];
|
||||||
setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;
|
setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;
|
||||||
};
|
};
|
||||||
@@ -19,6 +21,7 @@ export function ReportTable({
|
|||||||
}: ReportTableProps) {
|
}: ReportTableProps) {
|
||||||
const interval = useSelector((state) => state.report.interval);
|
const interval = useSelector((state) => state.report.interval);
|
||||||
const formatDate = useFormatDateInterval(interval);
|
const formatDate = useFormatDateInterval(interval);
|
||||||
|
const getLabel = useMappings()
|
||||||
|
|
||||||
function handleChange(name: string, checked: boolean) {
|
function handleChange(name: string, checked: boolean) {
|
||||||
setVisibleSeries((prev) => {
|
setVisibleSeries((prev) => {
|
||||||
@@ -34,7 +37,7 @@ export function ReportTable({
|
|||||||
const cell = "p-2 last:pr-8 last:w-[8rem]";
|
const cell = "p-2 last:pr-8 last:w-[8rem]";
|
||||||
const value = "min-w-[6rem] text-right";
|
const value = "min-w-[6rem] text-right";
|
||||||
const header = "text-sm font-medium";
|
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 (
|
return (
|
||||||
<div className="flex w-fit max-w-full rounded-md border border-border">
|
<div className="flex w-fit max-w-full rounded-md border border-border">
|
||||||
{/* Labels */}
|
{/* Labels */}
|
||||||
@@ -63,7 +66,7 @@ export function ReportTable({
|
|||||||
checked={checked}
|
checked={checked}
|
||||||
/>
|
/>
|
||||||
<div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
|
<div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
|
||||||
{serie.name}
|
{getLabel(serie.name)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ type InitialState = IChartInput;
|
|||||||
|
|
||||||
// First approach: define the initial state using that type
|
// First approach: define the initial state using that type
|
||||||
const initialState: InitialState = {
|
const initialState: InitialState = {
|
||||||
name: "",
|
name: "screen_view",
|
||||||
chartType: "linear",
|
chartType: "linear",
|
||||||
startDate: getDaysOldDate(7),
|
startDate: getDaysOldDate(7),
|
||||||
endDate: new Date(),
|
endDate: new Date(),
|
||||||
@@ -102,7 +102,18 @@ export const reportSlice = createSlice({
|
|||||||
state.endDate = action.payload;
|
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) {
|
if (action.payload === 1) {
|
||||||
state.interval = "hour";
|
state.interval = "hour";
|
||||||
} else if (action.payload <= 30) {
|
} else if (action.payload <= 30) {
|
||||||
@@ -110,8 +121,6 @@ export const reportSlice = createSlice({
|
|||||||
} else {
|
} else {
|
||||||
state.interval = "month";
|
state.interval = "month";
|
||||||
}
|
}
|
||||||
state.startDate = getDaysOldDate(action.payload);
|
|
||||||
state.endDate = new Date();
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ export function ReportBreakdownMore({ onClick }: ReportBreakdownMoreProps) {
|
|||||||
<MoreHorizontal />
|
<MoreHorizontal />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-[200px]">
|
<DropdownMenuContent align="start" className="w-[200px]">
|
||||||
<DropdownMenuGroup>
|
<DropdownMenuGroup>
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => onClick('remove')}>
|
<DropdownMenuItem className="text-red-600" onClick={() => onClick('remove')}>
|
||||||
<Trash className="mr-2 h-4 w-4" />
|
<Trash className="mr-2 h-4 w-4" />
|
||||||
|
|||||||
@@ -5,14 +5,15 @@ import { addBreakdown, changeBreakdown, removeBreakdown } from "../reportSlice";
|
|||||||
import { type ReportEventMoreProps } from "./ReportEventMore";
|
import { type ReportEventMoreProps } from "./ReportEventMore";
|
||||||
import { type IChartBreakdown } from "@/types";
|
import { type IChartBreakdown } from "@/types";
|
||||||
import { ReportBreakdownMore } from "./ReportBreakdownMore";
|
import { ReportBreakdownMore } from "./ReportBreakdownMore";
|
||||||
|
import { RenderDots } from "@/components/ui/RenderDots";
|
||||||
|
|
||||||
export function ReportBreakdowns() {
|
export function ReportBreakdowns() {
|
||||||
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
|
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
const propertiesQuery = api.chartMeta.properties.useQuery();
|
const propertiesQuery = api.chart.properties.useQuery();
|
||||||
const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({
|
const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({
|
||||||
value: item,
|
value: item,
|
||||||
label: item,
|
label: item, // <RenderDots truncate>{item}</RenderDots>,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const handleMore = (breakdown: IChartBreakdown) => {
|
const handleMore = (breakdown: IChartBreakdown) => {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import { type IChartEvent } from "@/types";
|
|
||||||
import {
|
import {
|
||||||
CreditCard,
|
type IChartEvent,
|
||||||
SlidersHorizontal,
|
type IChartEventFilterValue,
|
||||||
Trash,
|
type IChartEventFilter,
|
||||||
} from "lucide-react";
|
} from "@/types";
|
||||||
|
import { CreditCard, SlidersHorizontal, Trash } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
CommandDialog,
|
CommandDialog,
|
||||||
CommandEmpty,
|
CommandEmpty,
|
||||||
@@ -18,8 +18,11 @@ import { type Dispatch } from "react";
|
|||||||
import { RenderDots } from "@/components/ui/RenderDots";
|
import { RenderDots } from "@/components/ui/RenderDots";
|
||||||
import { useDispatch } from "@/redux";
|
import { useDispatch } from "@/redux";
|
||||||
import { changeEvent } from "../reportSlice";
|
import { changeEvent } from "../reportSlice";
|
||||||
import { Combobox } from "@/components/ui/combobox";
|
|
||||||
import { Button } from "@/components/ui/button";
|
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 = {
|
type ReportEventFiltersProps = {
|
||||||
event: IChartEvent;
|
event: IChartEvent;
|
||||||
@@ -33,7 +36,7 @@ export function ReportEventFilters({
|
|||||||
setIsCreating,
|
setIsCreating,
|
||||||
}: ReportEventFiltersProps) {
|
}: ReportEventFiltersProps) {
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
const propertiesQuery = api.chartMeta.properties.useQuery(
|
const propertiesQuery = api.chart.properties.useQuery(
|
||||||
{
|
{
|
||||||
event: event.name,
|
event: event.name,
|
||||||
},
|
},
|
||||||
@@ -50,7 +53,7 @@ export function ReportEventFilters({
|
|||||||
})}
|
})}
|
||||||
|
|
||||||
<CommandDialog open={isCreating} onOpenChange={setIsCreating} modal>
|
<CommandDialog open={isCreating} onOpenChange={setIsCreating} modal>
|
||||||
<CommandInput placeholder="Type a command or search..." />
|
<CommandInput placeholder="Search properties" />
|
||||||
<CommandList>
|
<CommandList>
|
||||||
<CommandEmpty>Such emptyness 🤨</CommandEmpty>
|
<CommandEmpty>Such emptyness 🤨</CommandEmpty>
|
||||||
<CommandGroup heading="Properties">
|
<CommandGroup heading="Properties">
|
||||||
@@ -67,7 +70,8 @@ export function ReportEventFilters({
|
|||||||
{
|
{
|
||||||
id: (event.filters.length + 1).toString(),
|
id: (event.filters.length + 1).toString(),
|
||||||
name: item,
|
name: item,
|
||||||
value: "",
|
operator: "is",
|
||||||
|
value: [],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
@@ -93,8 +97,9 @@ type FilterProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function Filter({ filter, event }: FilterProps) {
|
function Filter({ filter, event }: FilterProps) {
|
||||||
|
const getLabel = useMappings()
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
const potentialValues = api.chartMeta.values.useQuery({
|
const potentialValues = api.chart.values.useQuery({
|
||||||
event: event.name,
|
event: event.name,
|
||||||
property: filter.name,
|
property: filter.name,
|
||||||
});
|
});
|
||||||
@@ -102,7 +107,7 @@ function Filter({ filter, event }: FilterProps) {
|
|||||||
const valuesCombobox =
|
const valuesCombobox =
|
||||||
potentialValues.data?.values?.map((item) => ({
|
potentialValues.data?.values?.map((item) => ({
|
||||||
value: item,
|
value: item,
|
||||||
label: item,
|
label: getLabel(item),
|
||||||
})) ?? [];
|
})) ?? [];
|
||||||
|
|
||||||
const removeFilter = () => {
|
const removeFilter = () => {
|
||||||
@@ -114,7 +119,9 @@ function Filter({ filter, event }: FilterProps) {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const changeFilter = (value: string) => {
|
const changeFilterValue = (
|
||||||
|
value: IChartEventFilterValue | IChartEventFilterValue[],
|
||||||
|
) => {
|
||||||
dispatch(
|
dispatch(
|
||||||
changeEvent({
|
changeEvent({
|
||||||
...event,
|
...event,
|
||||||
@@ -122,7 +129,25 @@ function Filter({ filter, event }: FilterProps) {
|
|||||||
if (item.id === filter.id) {
|
if (item.id === filter.id) {
|
||||||
return {
|
return {
|
||||||
...item,
|
...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">
|
<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} />
|
<SlidersHorizontal size={10} />
|
||||||
</div>
|
</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}>
|
<Button variant="ghost" size="sm" onClick={removeFilter}>
|
||||||
<Trash size={16} />
|
<Trash size={16} />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{/* <ComboboxMulti items={valuesCombobox} selected={[]} setSelected={(fn) => {
|
<div className="flex gap-1">
|
||||||
return fn(filter.value)
|
<Dropdown
|
||||||
//
|
onChange={changeFilterOperator}
|
||||||
}} /> */}
|
items={Object.entries(operators).map(([key, value]) => ({
|
||||||
<Combobox
|
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}
|
items={valuesCombobox}
|
||||||
value={filter.value}
|
value={filter.value}
|
||||||
placeholder="Select value"
|
placeholder="Select value"
|
||||||
onChange={changeFilter}
|
onChange={changeFilter}
|
||||||
/>
|
/> */}
|
||||||
{/* <Input
|
{/* <Input
|
||||||
value={filter.value}
|
value={filter.value}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import { ReportEventFilters } from "./ReportEventFilters";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { ReportEventMore, type ReportEventMoreProps } from "./ReportEventMore";
|
import { ReportEventMore, type ReportEventMoreProps } from "./ReportEventMore";
|
||||||
import { type IChartEvent } from "@/types";
|
import { type IChartEvent } from "@/types";
|
||||||
|
import { Filter, GanttChart, Users } from "lucide-react";
|
||||||
|
import { Dropdown } from "@/components/Dropdown";
|
||||||
|
|
||||||
export function ReportEvents() {
|
export function ReportEvents() {
|
||||||
const [isCreating, setIsCreating] = useState(false);
|
const [isCreating, setIsCreating] = useState(false);
|
||||||
const selectedEvents = useSelector((state) => state.report.events);
|
const selectedEvents = useSelector((state) => state.report.events);
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
const eventsQuery = api.chartMeta.events.useQuery();
|
const eventsQuery = api.chart.events.useQuery();
|
||||||
const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({
|
const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({
|
||||||
value: item.name,
|
value: item.name,
|
||||||
label: item.name,
|
label: item.name,
|
||||||
@@ -38,9 +40,11 @@ export function ReportEvents() {
|
|||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
{selectedEvents.map((event) => {
|
{selectedEvents.map((event) => {
|
||||||
return (
|
return (
|
||||||
<div key={event.name} className="border rounded-lg">
|
<div key={event.name} className="rounded-lg border">
|
||||||
<div className="flex gap-2 items-center p-2 px-4">
|
<div className="flex items-center gap-2 p-2">
|
||||||
<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 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
|
<Combobox
|
||||||
value={event.name}
|
value={event.name}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
@@ -57,10 +61,50 @@ export function ReportEvents() {
|
|||||||
/>
|
/>
|
||||||
<ReportEventMore onClick={handleMore(event)} />
|
<ReportEventMore onClick={handleMore(event)} />
|
||||||
</div>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -71,6 +115,7 @@ export function ReportEvents() {
|
|||||||
dispatch(
|
dispatch(
|
||||||
addEvent({
|
addEvent({
|
||||||
name: value,
|
name: value,
|
||||||
|
segment: "event",
|
||||||
filters: [],
|
filters: [],
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,21 +1,51 @@
|
|||||||
import { cn } from "@/utils/cn";
|
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> {
|
interface RenderDotsProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||||
children: string;
|
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 (
|
return (
|
||||||
<div {...props} className={cn('flex gap-1', className)}>
|
<Tooltip disableHoverableContent={true} open={sliceAt === 0 ? false : undefined}>
|
||||||
{children.split(".").map((str, index) => {
|
<TooltipTrigger>
|
||||||
return (
|
<div
|
||||||
<div className="flex items-center gap-1" key={str + index}>
|
{...props}
|
||||||
{index !== 0 && <ChevronRight className="flex-shrink-0 !w-3 !h-3 top-[0.5px] relative" />}
|
className={cn("flex items-center gap-1", className)}
|
||||||
<span>{str}</span>
|
>
|
||||||
</div>
|
{parts.slice(-sliceAt).map((str, index) => {
|
||||||
);
|
return (
|
||||||
})}
|
<div className="flex items-center gap-1" key={str + index}>
|
||||||
</div>
|
{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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
139
apps/web/src/components/ui/alert-dialog.tsx
Normal file
139
apps/web/src/components/ui/alert-dialog.tsx
Normal file
@@ -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,
|
||||||
|
}
|
||||||
@@ -52,5 +52,8 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
Button.displayName = "Button"
|
Button.displayName = "Button"
|
||||||
|
Button.defaultProps = {
|
||||||
|
type: 'button'
|
||||||
|
}
|
||||||
|
|
||||||
export { Button, buttonVariants }
|
export { Button, buttonVariants }
|
||||||
|
|||||||
@@ -9,21 +9,22 @@ import {
|
|||||||
} from "@/components/ui/command";
|
} from "@/components/ui/command";
|
||||||
import { Command as CommandPrimitive } from "cmdk";
|
import { Command as CommandPrimitive } from "cmdk";
|
||||||
|
|
||||||
type Framework = Record<"value" | "label", string>;
|
type Item = Record<"value" | "label", string>;
|
||||||
|
|
||||||
type ComboboxMultiProps = {
|
type ComboboxMultiProps = {
|
||||||
selected: Framework[];
|
selected: Item[];
|
||||||
setSelected: React.Dispatch<React.SetStateAction<Framework[]>>;
|
setSelected: React.Dispatch<React.SetStateAction<Item[]>>;
|
||||||
items: Framework[];
|
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 inputRef = React.useRef<HTMLInputElement>(null);
|
||||||
const [open, setOpen] = React.useState(false);
|
const [open, setOpen] = React.useState(false);
|
||||||
const [inputValue, setInputValue] = React.useState("");
|
const [inputValue, setInputValue] = React.useState("");
|
||||||
|
|
||||||
const handleUnselect = React.useCallback((framework: Framework) => {
|
const handleUnselect = React.useCallback((item: Item) => {
|
||||||
setSelected(prev => prev.filter(s => s.value !== framework.value));
|
setSelected(prev => prev.filter(s => s.value !== item.value));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleKeyDown = React.useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
|
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 (
|
return (
|
||||||
<Command onKeyDown={handleKeyDown} className="overflow-visible bg-white">
|
<Command onKeyDown={handleKeyDown} className="overflow-visible bg-white">
|
||||||
<div
|
<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"
|
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">
|
<div className="flex gap-1 flex-wrap">
|
||||||
{selected.map((framework) => {
|
{selected.map((item) => {
|
||||||
return (
|
return (
|
||||||
<Badge key={framework.value} variant="secondary">
|
<Badge key={item.value} variant="secondary">
|
||||||
{framework.label}
|
{item.label}
|
||||||
<button
|
<button
|
||||||
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
handleUnselect(framework);
|
handleUnselect(item);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onMouseDown={(e) => {
|
onMouseDown={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
}}
|
}}
|
||||||
onClick={() => handleUnselect(framework)}
|
onClick={() => handleUnselect(item)}
|
||||||
>
|
>
|
||||||
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
|
<X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
|
||||||
</button>
|
</button>
|
||||||
@@ -82,7 +83,7 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
|
|||||||
onValueChange={setInputValue}
|
onValueChange={setInputValue}
|
||||||
onBlur={() => setOpen(false)}
|
onBlur={() => setOpen(false)}
|
||||||
onFocus={() => setOpen(true)}
|
onFocus={() => setOpen(true)}
|
||||||
placeholder="Select frameworks..."
|
placeholder={placeholder}
|
||||||
className="ml-2 bg-transparent outline-none placeholder:text-muted-foreground flex-1"
|
className="ml-2 bg-transparent outline-none placeholder:text-muted-foreground flex-1"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -91,21 +92,21 @@ export function ComboboxMulti({ items, selected, setSelected, ...props }: Combob
|
|||||||
{open && selectables.length > 0 ?
|
{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">
|
<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">
|
<CommandGroup className="h-full overflow-auto">
|
||||||
{selectables.map((framework) => {
|
{selectables.map((item) => {
|
||||||
return (
|
return (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
key={framework.value}
|
key={item.value}
|
||||||
onMouseDown={(e) => {
|
onMouseDown={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
}}
|
}}
|
||||||
onSelect={(value) => {
|
onSelect={(value) => {
|
||||||
setInputValue("")
|
setInputValue("")
|
||||||
setSelected(prev => [...prev, framework])
|
setSelected(prev => [...prev, item])
|
||||||
}}
|
}}
|
||||||
className={"cursor-pointer"}
|
className={"cursor-pointer"}
|
||||||
>
|
>
|
||||||
{framework.label}
|
{item.label}
|
||||||
</CommandItem>
|
</CommandItem>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ type ComboboxProps = {
|
|||||||
}>;
|
}>;
|
||||||
value: string;
|
value: string;
|
||||||
onChange: (value: string) => void;
|
onChange: (value: string) => void;
|
||||||
|
children?: React.ReactNode
|
||||||
};
|
};
|
||||||
|
|
||||||
export function Combobox({
|
export function Combobox({
|
||||||
@@ -31,6 +32,7 @@ export function Combobox({
|
|||||||
items,
|
items,
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
|
children
|
||||||
}: ComboboxProps) {
|
}: ComboboxProps) {
|
||||||
const [open, setOpen] = React.useState(false);
|
const [open, setOpen] = React.useState(false);
|
||||||
|
|
||||||
@@ -43,17 +45,17 @@ export function Combobox({
|
|||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
{children ?? <Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
role="combobox"
|
role="combobox"
|
||||||
aria-expanded={open}
|
aria-expanded={open}
|
||||||
className="w-full min-w-0 justify-between"
|
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" />
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
</Button>
|
</Button>}
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-full min-w-0 p-0">
|
<PopoverContent className="w-full min-w-0 p-0" align="start">
|
||||||
<Command>
|
<Command>
|
||||||
<CommandInput placeholder="Search item..." />
|
<CommandInput placeholder="Search item..." />
|
||||||
<CommandEmpty>Nothing selected</CommandEmpty>
|
<CommandEmpty>Nothing selected</CommandEmpty>
|
||||||
@@ -61,8 +63,9 @@ export function Combobox({
|
|||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
key={item.value}
|
key={item.value}
|
||||||
|
value={item.value}
|
||||||
onSelect={(currentValue) => {
|
onSelect={(currentValue) => {
|
||||||
const value = find(currentValue)?.value ?? "";
|
const value = find(currentValue)?.value ?? currentValue;
|
||||||
onChange(value);
|
onChange(value);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
}}
|
}}
|
||||||
|
|||||||
24
apps/web/src/components/ui/label.tsx
Normal file
24
apps/web/src/components/ui/label.tsx
Normal file
@@ -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 }
|
||||||
@@ -10,7 +10,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
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
|
className
|
||||||
)}
|
)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -22,7 +22,7 @@ const RadioGroup = React.forwardRef<HTMLDivElement, RadioGroupProps>(
|
|||||||
|
|
||||||
const RadioGroupItem = React.forwardRef<HTMLButtonElement, RadioGroupItemProps>(({className, ...props}, ref) => {
|
const RadioGroupItem = React.forwardRef<HTMLButtonElement, RadioGroupItemProps>(({className, ...props}, ref) => {
|
||||||
return (
|
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} />
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
114
apps/web/src/components/ui/table.tsx
Normal file
114
apps/web/src/components/ui/table.tsx
Normal file
@@ -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,
|
||||||
|
}
|
||||||
127
apps/web/src/components/ui/toast.tsx
Normal file
127
apps/web/src/components/ui/toast.tsx
Normal file
@@ -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,
|
||||||
|
}
|
||||||
33
apps/web/src/components/ui/toaster.tsx
Normal file
33
apps/web/src/components/ui/toaster.tsx
Normal file
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
28
apps/web/src/components/ui/tooltip.tsx
Normal file
28
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -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 }
|
||||||
192
apps/web/src/components/ui/use-toast.ts
Normal file
192
apps/web/src/components/ui/use-toast.ts
Normal file
@@ -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 }
|
||||||
7
apps/web/src/hooks/useMappings.ts
Normal file
7
apps/web/src/hooks/useMappings.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import mappings from '@/mappings.json'
|
||||||
|
|
||||||
|
export function useMappings() {
|
||||||
|
return (val: string) => {
|
||||||
|
return mappings.find((item) => item.id === val)?.name ?? val
|
||||||
|
}
|
||||||
|
}
|
||||||
12
apps/web/src/hooks/useOrganizationParams.ts
Normal file
12
apps/web/src/hooks/useOrganizationParams.ts
Normal file
@@ -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(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
6
apps/web/src/hooks/useRefetchActive.ts
Normal file
6
apps/web/src/hooks/useRefetchActive.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
export function useRefetchActive() {
|
||||||
|
const client = useQueryClient()
|
||||||
|
return () => client.refetchQueries({type: 'active'})
|
||||||
|
}
|
||||||
146
apps/web/src/mappings.json
Normal file
146
apps/web/src/mappings.json
Normal file
@@ -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"
|
||||||
|
}
|
||||||
|
]
|
||||||
153
apps/web/src/modals/AddClient.tsx
Normal file
153
apps/web/src/modals/AddClient.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
55
apps/web/src/modals/AddProject.tsx
Normal file
55
apps/web/src/modals/AddProject.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
44
apps/web/src/modals/Confirm.tsx
Normal file
44
apps/web/src/modals/Confirm.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
70
apps/web/src/modals/EditClient.tsx
Normal file
70
apps/web/src/modals/EditClient.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
70
apps/web/src/modals/EditProject.tsx
Normal file
70
apps/web/src/modals/EditProject.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
apps/web/src/modals/Modal/Container.tsx
Normal file
31
apps/web/src/modals/Modal/Container.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
197
apps/web/src/modals/index.tsx
Normal file
197
apps/web/src/modals/index.tsx
Normal file
@@ -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);
|
||||||
51
apps/web/src/pages/[organization]/[project]/[dashboard].tsx
Normal file
51
apps/web/src/pages/[organization]/[project]/[dashboard].tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
41
apps/web/src/pages/[organization]/[project]/index.tsx
Normal file
41
apps/web/src/pages/[organization]/[project]/index.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
43
apps/web/src/pages/[organization]/index.tsx
Normal file
43
apps/web/src/pages/[organization]/index.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
5
apps/web/src/pages/[organization]/reports/[reportId].tsx
Normal file
5
apps/web/src/pages/[organization]/reports/[reportId].tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export { default } from "./index";
|
||||||
|
|
||||||
|
import { createServerSideProps } from "@/server/getServerSideProps";
|
||||||
|
|
||||||
|
export const getServerSideProps = createServerSideProps()
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
import { ReportSidebar } from "@/components/report/sidebar/ReportSidebar";
|
import { ReportSidebar } from "@/components/report/sidebar/ReportSidebar";
|
||||||
import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
|
import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
|
||||||
import { useDispatch, useSelector } from "@/redux";
|
import { useDispatch, useSelector } from "@/redux";
|
||||||
import { MainLayout } from "@/components/layouts/Main";
|
import { MainLayout } from "@/components/layouts/MainLayout";
|
||||||
import { ReportDateRange } from "@/components/report/ReportDateRange";
|
import { ReportDateRange } from "@/components/report/ReportDateRange";
|
||||||
import { useCallback, useEffect } from "react";
|
import { useCallback, useEffect } from "react";
|
||||||
import { reset, setReport } from "@/components/report/reportSlice";
|
import { reset, setReport } from "@/components/report/reportSlice";
|
||||||
import { useReportId } from "@/components/report/hooks/useReportId";
|
import { useReportId } from "@/components/report/hooks/useReportId";
|
||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import { useRouterBeforeLeave } from "@/hooks/useRouterBeforeLeave";
|
import { useRouterBeforeLeave } from "@/hooks/useRouterBeforeLeave";
|
||||||
|
import { createServerSideProps } from "@/server/getServerSideProps";
|
||||||
|
|
||||||
|
export const getServerSideProps = createServerSideProps()
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const { reportId } = useReportId();
|
const { reportId } = useReportId();
|
||||||
27
apps/web/src/pages/[organization]/settings/clients.tsx
Normal file
27
apps/web/src/pages/[organization]/settings/clients.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
69
apps/web/src/pages/[organization]/settings/organization.tsx
Normal file
69
apps/web/src/pages/[organization]/settings/organization.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
73
apps/web/src/pages/[organization]/settings/profile.tsx
Normal file
73
apps/web/src/pages/[organization]/settings/profile.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
apps/web/src/pages/[organization]/settings/projects.tsx
Normal file
27
apps/web/src/pages/[organization]/settings/projects.tsx
Normal file
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,24 +1,49 @@
|
|||||||
import { type Session } from "next-auth";
|
import { type Session } from "next-auth";
|
||||||
import { SessionProvider } from "next-auth/react";
|
import { SessionProvider, getSession } from "next-auth/react";
|
||||||
import { type AppType } from "next/app";
|
import App, {
|
||||||
|
type AppContext,
|
||||||
|
type AppInitialProps,
|
||||||
|
type AppType,
|
||||||
|
} from "next/app";
|
||||||
import store from "@/redux";
|
import store from "@/redux";
|
||||||
import { Provider as ReduxProvider } from "react-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 { api } from "@/utils/api";
|
||||||
|
|
||||||
import "@/styles/globals.css";
|
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,
|
Component,
|
||||||
pageProps: { session, ...pageProps },
|
pageProps: { session, ...pageProps },
|
||||||
}) => {
|
}) => {
|
||||||
|
console.log('session',session);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SessionProvider session={session}>
|
<div className={font.className}>
|
||||||
<ReduxProvider store={store}>
|
<SessionProvider session={session}>
|
||||||
<Component {...pageProps} />
|
<ReduxProvider store={store}>
|
||||||
</ReduxProvider>
|
<Suspense fallback="Loading">
|
||||||
</SessionProvider>
|
<TooltipProvider delayDuration={200}>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</TooltipProvider>
|
||||||
|
<Toaster />
|
||||||
|
<ModalProvider />
|
||||||
|
</Suspense>
|
||||||
|
</ReduxProvider>
|
||||||
|
</SessionProvider>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default api.withTRPC(MyApp);
|
export default api.withTRPC(MixanApp);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { validateSdkRequest } from "@/server/auth";
|
import { validateSdkRequest } from "@/server/auth";
|
||||||
import { createError, handleError } from "@/server/exceptions";
|
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 ProfileIncrementPayload } from "@mixan/types";
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Check client id & secret
|
// Check client id & secret
|
||||||
await validateSdkRequest(req)
|
await validateSdkRequest(req);
|
||||||
|
|
||||||
const profileId = req.query.profileId as string;
|
const profileId = req.query.profileId as string;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { validateSdkRequest } from "@/server/auth";
|
import { validateSdkRequest } from "@/server/auth";
|
||||||
import { createError, handleError } from "@/server/exceptions";
|
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 ProfileIncrementPayload } from "@mixan/types";
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { validateSdkRequest } from "@/server/auth";
|
import { validateSdkRequest } from "@/server/auth";
|
||||||
import { db } from "@/server/db";
|
import { db } from "@/server/db";
|
||||||
import { createError, handleError } from "@/server/exceptions";
|
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 ProfilePayload } from "@mixan/types";
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { db } from "@/server/db";
|
import { db } from "@/server/db";
|
||||||
import { handleError } from "@/server/exceptions";
|
import { handleError } from "@/server/exceptions";
|
||||||
import { hashPassword } from "@/services/hash.service";
|
import { hashPassword } from "@/server/services/hash.service";
|
||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
import { type NextApiRequest, type NextApiResponse } from "next";
|
import { type NextApiRequest, type NextApiResponse } from "next";
|
||||||
|
|
||||||
@@ -33,6 +33,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
|||||||
data: {
|
data: {
|
||||||
name: "Acme Website Client",
|
name: "Acme Website Client",
|
||||||
project_id: project.id,
|
project_id: project.id,
|
||||||
|
organization_id: organization.id,
|
||||||
secret: await hashPassword(secret),
|
secret: await hashPassword(secret),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,33 +1,25 @@
|
|||||||
import { ReportLineChart } from "@/components/report/chart/ReportLineChart";
|
import { MainLayout } from "@/components/layouts/MainLayout";
|
||||||
import { MainLayout } from "@/components/layouts/Main";
|
|
||||||
import { Container } from "@/components/Container";
|
|
||||||
import { api } from "@/utils/api";
|
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() {
|
export default function Home() {
|
||||||
const reportsQuery = api.report.getDashboard.useQuery({
|
const router = useRouter()
|
||||||
projectId: 'f7eabf0c-e0b0-4ac0-940f-1589715b0c3d',
|
const query = api.organization.current.useQuery();
|
||||||
dashboardId: '9227feb4-ad59-40f3-b887-3501685733dd',
|
const organization = query.data ?? null;
|
||||||
}, {
|
|
||||||
staleTime: 1000 * 60 * 5,
|
useEffect(() => {
|
||||||
})
|
if(organization) {
|
||||||
const reports = reportsQuery.data ?? []
|
router.replace(`/${organization.slug}`)
|
||||||
|
}
|
||||||
|
}, [organization])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MainLayout className="bg-slate-50 py-8">
|
<MainLayout>
|
||||||
<Container className="flex flex-col gap-8">
|
<div />
|
||||||
{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>
|
</MainLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
export { default } from "./index";
|
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { exampleRouter } from "@/server/api/routers/example";
|
|
||||||
import { createTRPCRouter } from "@/server/api/trpc";
|
import { createTRPCRouter } from "@/server/api/trpc";
|
||||||
import { chartMetaRouter } from "./routers/chartMeta";
|
import { chartRouter } from "./routers/chart";
|
||||||
import { reportRouter } from "./routers/report";
|
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.
|
* 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.
|
* All routers added in /api/routers should be manually added here.
|
||||||
*/
|
*/
|
||||||
export const appRouter = createTRPCRouter({
|
export const appRouter = createTRPCRouter({
|
||||||
example: exampleRouter,
|
chart: chartRouter,
|
||||||
chartMeta: chartMetaRouter,
|
|
||||||
report: reportRouter,
|
report: reportRouter,
|
||||||
|
dashboard: dashboardRouter,
|
||||||
|
organization: organizationRouter,
|
||||||
|
user: userRouter,
|
||||||
|
project: projectRouter,
|
||||||
|
client: clientRouter,
|
||||||
});
|
});
|
||||||
|
|
||||||
// export type definition of API
|
// export type definition of API
|
||||||
|
|||||||
@@ -1,12 +1,131 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
|
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
|
||||||
import { db } from "@/server/db";
|
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 { toDots } from "@/utils/object";
|
||||||
import { Prisma } from "@prisma/client";
|
|
||||||
import { zChartInput } from "@/utils/validation";
|
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 = {
|
type ResultItem = {
|
||||||
label: string | null;
|
label: string | null;
|
||||||
@@ -20,14 +139,14 @@ function propertyNameToSql(name: string) {
|
|||||||
.split(".")
|
.split(".")
|
||||||
.map((item, index) => (index === 0 ? item : `'${item}'`))
|
.map((item, index) => (index === 0 ? item : `'${item}'`))
|
||||||
.join("->");
|
.join("->");
|
||||||
const findLastOf = "->"
|
const findLastOf = "->";
|
||||||
const lastArrow = str.lastIndexOf(findLastOf);
|
const lastArrow = str.lastIndexOf(findLastOf);
|
||||||
if(lastArrow === -1) {
|
if (lastArrow === -1) {
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
const first = str.slice(0, lastArrow);
|
const first = str.slice(0, lastArrow);
|
||||||
const last = str.slice(lastArrow + findLastOf.length);
|
const last = str.slice(lastArrow + findLastOf.length);
|
||||||
return `${first}->>${last}`
|
return `${first}->>${last}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return name;
|
return name;
|
||||||
@@ -41,12 +160,6 @@ function getTotalCount(arr: ResultItem[]) {
|
|||||||
return arr.reduce((acc, item) => acc + item.count, 0);
|
return arr.reduce((acc, item) => acc + item.count, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
|
||||||
api: {
|
|
||||||
responseLimit: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
async function getChartData({
|
async function getChartData({
|
||||||
chartType,
|
chartType,
|
||||||
event,
|
event,
|
||||||
@@ -55,18 +168,19 @@ async function getChartData({
|
|||||||
startDate,
|
startDate,
|
||||||
endDate,
|
endDate,
|
||||||
}: {
|
}: {
|
||||||
chartType: string;
|
|
||||||
event: IChartEvent;
|
event: IChartEvent;
|
||||||
breakdowns: IChartBreakdown[];
|
} & Omit<IChartInput, 'events'>) {
|
||||||
interval: string;
|
const select = [];
|
||||||
startDate: Date;
|
|
||||||
endDate: Date;
|
|
||||||
}) {
|
|
||||||
const select = [`count(*)::int as count`];
|
|
||||||
const where = [];
|
const where = [];
|
||||||
const groupBy = [];
|
const groupBy = [];
|
||||||
const orderBy = [];
|
const orderBy = [];
|
||||||
|
|
||||||
|
if (event.segment === "event") {
|
||||||
|
select.push(`count(*)::int as count`);
|
||||||
|
} else {
|
||||||
|
select.push(`count(DISTINCT profile_id)::int as count`);
|
||||||
|
}
|
||||||
|
|
||||||
switch (chartType) {
|
switch (chartType) {
|
||||||
case "bar": {
|
case "bar": {
|
||||||
orderBy.push("count DESC");
|
orderBy.push("count DESC");
|
||||||
@@ -86,10 +200,43 @@ async function getChartData({
|
|||||||
if (filters.length > 0) {
|
if (filters.length > 0) {
|
||||||
filters.forEach((filter) => {
|
filters.forEach((filter) => {
|
||||||
const { name, value } = filter;
|
const { name, value } = filter;
|
||||||
if (name.includes(".")) {
|
switch (filter.operator) {
|
||||||
where.push(`${propertyNameToSql(name)} = '${value}'`);
|
case "is": {
|
||||||
} else {
|
if (name.includes(".*.") || name.endsWith("[*]")) {
|
||||||
where.push(`${name} = '${value}'`);
|
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) {
|
if (breakdowns.length) {
|
||||||
const breakdown = breakdowns[0];
|
const breakdown = breakdowns[0];
|
||||||
if (breakdown) {
|
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`);
|
groupBy.push(`label`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -123,7 +274,7 @@ async function getChartData({
|
|||||||
ORDER BY ${orderBy.join(", ")}
|
ORDER BY ${orderBy.join(", ")}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await db.$queryRawUnsafe<ResultItem[]>(sql);
|
const result = await db.$queryRawUnsafe<ResultItem[]>(sql);
|
||||||
|
|
||||||
// group by sql label
|
// group by sql label
|
||||||
const series = result.reduce(
|
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(
|
function fillEmptySpotsInTimeline(
|
||||||
items: ResultItem[],
|
items: ResultItem[],
|
||||||
interval: string,
|
interval: string,
|
||||||
@@ -277,14 +326,14 @@ function fillEmptySpotsInTimeline(
|
|||||||
const result = [];
|
const result = [];
|
||||||
const clonedStartDate = new Date(startDate);
|
const clonedStartDate = new Date(startDate);
|
||||||
const clonedEndDate = new Date(endDate);
|
const clonedEndDate = new Date(endDate);
|
||||||
if(interval === 'hour') {
|
if (interval === "hour") {
|
||||||
clonedStartDate.setMinutes(0, 0, 0);
|
clonedStartDate.setMinutes(0, 0, 0);
|
||||||
clonedEndDate.setMinutes(0, 0, 0)
|
clonedEndDate.setMinutes(0, 0, 0);
|
||||||
} else {
|
} else {
|
||||||
clonedStartDate.setHours(2, 0, 0, 0);
|
clonedStartDate.setHours(2, 0, 0, 0);
|
||||||
clonedEndDate.setHours(2, 0, 0, 0);
|
clonedEndDate.setHours(2, 0, 0, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (clonedStartDate.getTime() <= clonedEndDate.getTime()) {
|
while (clonedStartDate.getTime() <= clonedEndDate.getTime()) {
|
||||||
const getYear = (date: Date) => date.getFullYear();
|
const getYear = (date: Date) => date.getFullYear();
|
||||||
const getMonth = (date: Date) => date.getMonth();
|
const getMonth = (date: Date) => date.getMonth();
|
||||||
96
apps/web/src/server/api/routers/client.ts
Normal file
96
apps/web/src/server/api/routers/client.ts
Normal file
@@ -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;
|
||||||
|
}),
|
||||||
|
});
|
||||||
25
apps/web/src/server/api/routers/dashboard.ts
Normal file
25
apps/web/src/server/api/routers/dashboard.ts
Normal file
@@ -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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -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!";
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
45
apps/web/src/server/api/routers/organization.ts
Normal file
45
apps/web/src/server/api/routers/organization.ts
Normal file
@@ -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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
});
|
||||||
81
apps/web/src/server/api/routers/project.ts
Normal file
81
apps/web/src/server/api/routers/project.ts
Normal file
@@ -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
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
type IChartEvent,
|
type IChartEvent,
|
||||||
} from "@/types";
|
} from "@/types";
|
||||||
import { type Report as DbReport } from "@prisma/client";
|
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 } {
|
function transform(report: DbReport): IChartInput & { id: string } {
|
||||||
return {
|
return {
|
||||||
@@ -40,22 +42,27 @@ export const reportRouter = createTRPCRouter({
|
|||||||
})
|
})
|
||||||
.then(transform);
|
.then(transform);
|
||||||
}),
|
}),
|
||||||
getDashboard: protectedProcedure
|
list: protectedProcedure
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
projectId: z.string(),
|
projectSlug: z.string(),
|
||||||
dashboardId: 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({
|
const reports = await db.report.findMany({
|
||||||
where: {
|
where: {
|
||||||
project_id: projectId,
|
project_id: project.id,
|
||||||
dashboard_id: dashboardId,
|
dashboard_id: dashboard.id,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return reports.map(transform);
|
return {
|
||||||
|
reports: reports.map(transform),
|
||||||
|
dashboard,
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
save: protectedProcedure
|
save: protectedProcedure
|
||||||
.input(
|
.input(
|
||||||
|
|||||||
67
apps/web/src/server/api/routers/user.ts
Normal file
67
apps/web/src/server/api/routers/user.ts
Normal file
@@ -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),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -53,7 +53,6 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
|
|||||||
*/
|
*/
|
||||||
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
|
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
|
||||||
const { req, res } = opts;
|
const { req, res } = opts;
|
||||||
|
|
||||||
// Get the session from the server using the getServerSession wrapper function
|
// Get the session from the server using the getServerSession wrapper function
|
||||||
const session = await getServerAuthSession({ req, res });
|
const session = await getServerAuthSession({ req, res });
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
import { db } from "@/server/db";
|
import { db } from "@/server/db";
|
||||||
import Credentials from "next-auth/providers/credentials";
|
import Credentials from "next-auth/providers/credentials";
|
||||||
import { createError } from "./exceptions";
|
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`
|
* 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: [
|
providers: [
|
||||||
Credentials({
|
Credentials({
|
||||||
name: "Credentials",
|
name: "Credentials",
|
||||||
@@ -60,7 +62,10 @@ export const authOptions: NextAuthOptions = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
return user;
|
return {
|
||||||
|
...user,
|
||||||
|
image: 'https://avatars.githubusercontent.com/u/18133?v=4'
|
||||||
|
};
|
||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
35
apps/web/src/server/getServerSideProps.ts
Normal file
35
apps/web/src/server/getServerSideProps.ts
Normal file
@@ -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 ?? {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
9
apps/web/src/server/services/dashboard.service.ts
Normal file
9
apps/web/src/server/services/dashboard.service.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { db } from "../db";
|
||||||
|
|
||||||
|
export function getDashboardBySlug(slug: string) {
|
||||||
|
return db.dashboard.findUniqueOrThrow({
|
||||||
|
where: {
|
||||||
|
slug
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
9
apps/web/src/server/services/organization.service.ts
Normal file
9
apps/web/src/server/services/organization.service.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { db } from "../db";
|
||||||
|
|
||||||
|
export function getOrganizationBySlug(slug: string) {
|
||||||
|
return db.organization.findUniqueOrThrow({
|
||||||
|
where: {
|
||||||
|
slug
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
9
apps/web/src/server/services/project.service.ts
Normal file
9
apps/web/src/server/services/project.service.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { db } from "../db";
|
||||||
|
|
||||||
|
export function getProjectBySlug(slug: string) {
|
||||||
|
return db.project.findUniqueOrThrow({
|
||||||
|
where: {
|
||||||
|
slug
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -73,4 +73,20 @@
|
|||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
.h1 {
|
||||||
|
@apply text-3xl font-medium;
|
||||||
|
}
|
||||||
|
|
||||||
|
.h2 {
|
||||||
|
@apply text-xl font-medium;
|
||||||
|
}
|
||||||
|
|
||||||
|
.h3 {
|
||||||
|
@apply text-lg font-medium;
|
||||||
|
}
|
||||||
|
|
||||||
|
.h4 {
|
||||||
|
@apply font-medium;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { type zTimeInterval, type zChartBreakdown, type zChartEvent, type zChartInput } from "@/utils/validation";
|
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 TooltipProps } from "recharts";
|
||||||
import { type z } from "zod";
|
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 IChartInput = z.infer<typeof zChartInput>
|
||||||
export type IChartEvent = z.infer<typeof zChartEvent>
|
export type IChartEvent = z.infer<typeof zChartEvent>
|
||||||
export type IChartEventFilter = IChartEvent['filters'][number]
|
export type IChartEventFilter = IChartEvent['filters'][number]
|
||||||
|
export type IChartEventFilterValue = IChartEvent['filters'][number]['value'][number]
|
||||||
export type IChartBreakdown = z.infer<typeof zChartBreakdown>
|
export type IChartBreakdown = z.infer<typeof zChartBreakdown>
|
||||||
export type IInterval = z.infer<typeof zTimeInterval>
|
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'> & {
|
export type IToolTipProps<T> = Omit<TooltipProps<number, string>, 'payload'> & {
|
||||||
payload?: Array<T>
|
payload?: Array<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type IProject = Project
|
||||||
|
export type IClientWithProject = Client & {
|
||||||
|
project: IProject
|
||||||
|
}
|
||||||
@@ -4,12 +4,13 @@
|
|||||||
*
|
*
|
||||||
* We also create a few inference helpers for input and output types.
|
* 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 { createTRPCNext } from "@trpc/next";
|
||||||
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
|
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
|
||||||
import superjson from "superjson";
|
import superjson from "superjson";
|
||||||
|
|
||||||
import { type AppRouter } from "@/server/api/root";
|
import { type AppRouter } from "@/server/api/root";
|
||||||
|
import { toast } from "@/components/ui/use-toast";
|
||||||
|
|
||||||
const getBaseUrl = () => {
|
const getBaseUrl = () => {
|
||||||
if (typeof window !== "undefined") return ""; // browser should use relative url
|
if (typeof window !== "undefined") return ""; // browser should use relative url
|
||||||
@@ -27,7 +28,8 @@ export const api = createTRPCNext<AppRouter>({
|
|||||||
refetchOnWindowFocus: false,
|
refetchOnWindowFocus: false,
|
||||||
refetchOnReconnect: false,
|
refetchOnReconnect: false,
|
||||||
refetchOnMount: false,
|
refetchOnMount: false,
|
||||||
}
|
enabled: typeof window !== "undefined",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
@@ -75,3 +77,11 @@ export type RouterInputs = inferRouterInputs<AppRouter>;
|
|||||||
* @example type HelloOutput = RouterOutputs['example']['hello']
|
* @example type HelloOutput = RouterOutputs['example']['hello']
|
||||||
*/
|
*/
|
||||||
export type RouterOutputs = inferRouterOutputs<AppRouter>;
|
export type RouterOutputs = inferRouterOutputs<AppRouter>;
|
||||||
|
|
||||||
|
|
||||||
|
export function handleError(error: TRPCClientErrorBase<any>) {
|
||||||
|
toast({
|
||||||
|
title: 'Error',
|
||||||
|
description: error.message,
|
||||||
|
})
|
||||||
|
}
|
||||||
9
apps/web/src/utils/clipboard.ts
Normal file
9
apps/web/src/utils/clipboard.ts
Normal file
@@ -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(),
|
||||||
|
})
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user