Skip to content

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

migrate to app dir and ssr

Carl-Gerhard Lindesvärd308ae98472e9
diff --git a/README.md b/README.md
index 20400406c..841a2fe01 100644
--- a/README.md
+++ b/README.md
@@ -17,10 +17,23 @@ Mixan is a simple analytics tool for logging events on web and react-native. My
### Speed/Benchmark
-As of today (2023-12-12) I have more then 1.2 million events in PSQL and performance is smooth as butter 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`.
+As of today (~~2023-12-12~~ 2024-01-16) I have more then ~~1.2~~ 2.8 million events and 20 thousand profiles in postgres and performance is smooth as butter\* 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`.
+
+\* Smooth as butter is somewhat exaggerated but I would say it still fast! It takes 1.4 sec to search through all events (3 million) with advanced where clause. I think this performance is absolutly good enough.
### GUI
+- [x] Fix design for report editor
+- [x] Fix profiles
+ - [x] Pagination
+ - [x] Filter by event name
+- [x] Fix [profileId]
+ - [x] Add events
+ - [x] Improve design for properties and linked profiles
+- [x] New design for events
+- [ ] Map events to convertions
+- [ ] Map ids
+- [x] Fix menu links when projectId is undefined
- [x] Fix tables on settings
- [x] Rename event label
- [ ] Common web dashboard
@@ -36,14 +49,16 @@ As of today (2023-12-12) I have more then 1.2 million events in PSQL and perform
- [x] View events in a list
- [x] Simple filters
- [x] View profiles in a list
-- [ ] Invite users
+- [x] Invite users
- [ ] Drag n Drop reports on dashboard
- [x] Manage dashboards
-- [ ] Support more chart types
+- [x] Support more chart types
- [x] Bar
- [x] Histogram
- - [ ] Pie
- - [ ] Area
+ - [x] Pie
+ - [x] Area
+ - [x] Metric
+ - [x] Line
- [ ] Support funnels
- [ ] Support multiple breakdowns
- [x] Aggregations (sum, average...)
diff --git a/apps/web/package.json b/apps/web/package.json
index 3ccb662dd..b96a50efb 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
- "dev": "pnpm with-env next dev",
+ "dev": "rm -rf .next && pnpm with-env next dev",
"build": "next build",
"start": "next start",
"lint": "eslint .",
@@ -40,16 +40,19 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cmdk": "^0.2.0",
+ "hamburger-react": "^2.5.0",
"lodash.debounce": "^4.0.8",
"lottie-react": "^2.4.0",
"lucide-react": "^0.286.0",
"mitt": "^3.0.1",
- "next": "13.4",
+ "next": "~14.0.4",
"next-auth": "^4.23.0",
+ "nuqs": "^1.15.2",
"prisma-error-enum": "^0.1.3",
"ramda": "^0.29.1",
"random-animal-name": "^0.1.1",
"react": "18.2.0",
+ "react-animate-height": "^3.2.3",
"react-dom": "18.2.0",
"react-hook-form": "^7.47.0",
"react-in-viewport": "1.0.0-alpha.30",
@@ -93,8 +96,8 @@
"root": true,
"extends": [
"@mixan/eslint-config/base",
- "@mixan/eslint-config/nextjs",
- "@mixan/eslint-config/react"
+ "@mixan/eslint-config/react",
+ "@mixan/eslint-config/nextjs"
]
},
"prettier": "@mixan/prettier-config"
diff --git a/apps/web/public/logo.svg b/apps/web/public/logo.svg
new file mode 100644
index 000000000..264890a2f
--- /dev/null
+++ b/apps/web/public/logo.svg
@@ -0,0 +1,15 @@
+<svg width="824" height="824" viewBox="0 0 824 824" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="824" height="824" fill="#007BFF" fill-opacity="0.3"/>
+<path d="M0 0L824 0V824H0L0 0Z" fill="url(#paint0_linear_0_131)"/>
+<path d="M436 220H508C520.73 220 532.939 225.057 541.941 234.059C550.943 243.061 556 255.27 556 268V604" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M172 604H244" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M436 604H652" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M364 412V412.24" stroke="white" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M436 233.488V621.256C435.999 624.902 435.168 628.499 433.569 631.775C431.97 635.052 429.646 637.92 426.772 640.164C423.899 642.408 420.553 643.968 416.987 644.726C413.421 645.483 409.729 645.418 406.192 644.536L244 604V257.488C244.002 246.784 247.581 236.388 254.169 227.952C260.757 219.516 269.976 213.524 280.36 210.928L376.36 186.928C383.434 185.16 390.818 185.026 397.951 186.538C405.084 188.05 411.779 191.167 417.528 195.652C423.277 200.138 427.928 205.874 431.129 212.426C434.329 218.978 435.995 226.196 436 233.488Z" stroke="white" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
+<defs>
+<linearGradient id="paint0_linear_0_131" x1="353" y1="93.0001" x2="528" y2="747.5" gradientUnits="userSpaceOnUse">
+<stop stop-color="#2563EB"/>
+<stop offset="1" stop-color="#1D54CD"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/list-reports.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/list-reports.tsx
new file mode 100644
index 000000000..d4c5059b3
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/list-reports.tsx
@@ -0,0 +1,137 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { LazyChart } from '@/components/report/chart/LazyChart';
+import { Button } from '@/components/ui/button';
+import { Combobox } from '@/components/ui/combobox';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useAppParams } from '@/hooks/useAppParams';
+import type { getReportsByDashboardId } from '@/server/services/reports.service';
+import type { IChartRange } from '@/types';
+import { cn } from '@/utils/cn';
+import { getDefaultIntervalByRange, timeRanges } from '@/utils/constants';
+import { ChevronRight, MoreHorizontal, PlusIcon, Trash } from 'lucide-react';
+import Link from 'next/link';
+import { useParams, useRouter } from 'next/navigation';
+
+interface ListReportsProps {
+ reports: Awaited<ReturnType<typeof getReportsByDashboardId>>;
+}
+
+export function ListReports({ reports }: ListReportsProps) {
+ const router = useRouter();
+ const params = useAppParams<{ dashboardId: string }>();
+ const [range, setRange] = useState<null | IChartRange>(null);
+
+ return (
+ <>
+ <StickyBelowHeader className="p-4 items-center justify-between flex">
+ <Combobox
+ className="min-w-0"
+ placeholder="Override range"
+ value={range}
+ onChange={(value) => {
+ setRange((p) => (p === value ? null : value));
+ }}
+ items={Object.values(timeRanges).map((key) => ({
+ label: key,
+ value: key,
+ }))}
+ />
+ <Button
+ icon={PlusIcon}
+ onClick={() => {
+ router.push(
+ `/${params.organizationId}/${
+ params.projectId
+ }/reports?${new URLSearchParams({
+ dashboardId: params.dashboardId,
+ }).toString()}`
+ );
+ }}
+ >
+ <span className="max-sm:hidden">Create report</span>
+ <span className="sm:hidden">Report</span>
+ </Button>
+ </StickyBelowHeader>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4">
+ {reports.map((report) => {
+ const chartRange = report.range; // timeRanges[report.range];
+ return (
+ <div
+ className="rounded-md border border-border bg-white shadow"
+ key={report.id}
+ >
+ <Link
+ href={`/${params.organizationId}/${params.projectId}/reports/${report.id}`}
+ className="flex border-b border-border p-4 leading-none [&_svg]:hover:opacity-100 items-center justify-between"
+ shallow
+ >
+ <div>
+ <div className="font-medium">{report.name}</div>
+ {chartRange !== null && (
+ <div className="mt-2 text-sm flex gap-2">
+ <span className={range !== null ? 'line-through' : ''}>
+ {chartRange}
+ </span>
+ {range !== null && <span>{range}</span>}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-4">
+ <DropdownMenu>
+ <DropdownMenuTrigger className="h-8 w-8 hover:border rounded justify-center items-center flex">
+ <MoreHorizontal size={16} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[200px]">
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={(event) => {
+ // event.stopPropagation();
+ // deletion.mutate({
+ // reportId: report.id,
+ // });
+ }}
+ >
+ <Trash size={16} className="mr-2" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <ChevronRight
+ className="opacity-10 transition-opacity"
+ size={16}
+ />
+ </div>
+ </Link>
+ <div
+ className={cn(
+ 'p-4 pl-2',
+ report.chartType === 'bar' && 'overflow-auto max-h-[300px]'
+ )}
+ >
+ <LazyChart
+ {...report}
+ range={range ?? report.range}
+ interval={
+ range ? getDefaultIntervalByRange(range) : report.interval
+ }
+ editMode={false}
+ />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/page.tsx
new file mode 100644
index 000000000..7740aeab8
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/[dashboardId]/page.tsx
@@ -0,0 +1,42 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getSession } from '@/server/auth';
+import {
+ createRecentDashboard,
+ getDashboardById,
+} from '@/server/services/dashboard.service';
+import { getReportsByDashboardId } from '@/server/services/reports.service';
+import { revalidateTag } from 'next/cache';
+
+import { ListReports } from './list-reports';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ dashboardId: string;
+ };
+}
+
+export default async function Page({
+ params: { organizationId, projectId, dashboardId },
+}: PageProps) {
+ const session = await getSession();
+ const dashboard = await getDashboardById(dashboardId);
+ const reports = await getReportsByDashboardId(dashboardId);
+ const userId = session?.user.id;
+ if (userId && dashboard) {
+ await createRecentDashboard({
+ userId,
+ organizationId,
+ projectId,
+ dashboardId,
+ });
+ revalidateTag(`recentDashboards__${userId}`);
+ }
+
+ return (
+ <PageLayout title={dashboard.name} organizationId={organizationId}>
+ <ListReports reports={reports} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx
new file mode 100644
index 000000000..fa6a44c11
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx
@@ -0,0 +1,46 @@
+import { cn } from '@/utils/cn';
+import type { VariantProps } from 'class-variance-authority';
+import { cva } from 'class-variance-authority';
+import { ActivityIcon, BotIcon, MonitorPlayIcon } from 'lucide-react';
+
+const variants = cva('flex items-center justify-center shrink-0', {
+ variants: {
+ size: {
+ sm: 'w-6 h-6 rounded',
+ default: 'w-12 h-12 rounded-xl',
+ },
+ },
+ defaultVariants: {
+ size: 'default',
+ },
+});
+
+type EventIconProps = VariantProps<typeof variants> & {
+ name: string;
+ className?: string;
+};
+
+const records = {
+ default: { Icon: BotIcon, text: 'text-chart-0', bg: 'bg-chart-0/10' },
+ screen_view: {
+ Icon: MonitorPlayIcon,
+ text: 'text-chart-3',
+ bg: 'bg-chart-3/10',
+ },
+ session_start: {
+ Icon: ActivityIcon,
+ text: 'text-chart-2',
+ bg: 'bg-chart-2/10',
+ },
+};
+
+export function EventIcon({ className, name, size }: EventIconProps) {
+ const { Icon, text, bg } =
+ name in records ? records[name as keyof typeof records] : records.default;
+
+ return (
+ <div className={cn(variants({ size }), bg, className)}>
+ <Icon size={20} className={text} />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx
new file mode 100644
index 000000000..9eb88849a
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { useMemo } from 'react';
+import type { RouterOutputs } from '@/app/_trpc/client';
+import { ListProperties } from '@/components/events/ListProperties';
+import { ExpandableListItem } from '@/components/general/ExpandableListItem';
+import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
+import { useAppParams } from '@/hooks/useAppParams';
+import { cn } from '@/utils/cn';
+import { formatDateTime } from '@/utils/date';
+import { getProfileName } from '@/utils/getters';
+import { round } from '@/utils/math';
+import { Activity, BotIcon, MonitorPlay } from 'lucide-react';
+import Link from 'next/link';
+
+import { EventIcon } from './event-icon';
+
+type EventListItemProps = RouterOutputs['event']['list'][number];
+
+export function EventListItem({
+ profile,
+ createdAt,
+ name,
+ properties,
+}: EventListItemProps) {
+ const params = useAppParams();
+
+ const bullets = useMemo(() => {
+ const bullets: React.ReactNode[] = [
+ <span>{formatDateTime(createdAt)}</span>,
+ ];
+
+ if (profile) {
+ bullets.push(
+ <Link
+ href={`/${params.organizationId}/${params.projectId}/profiles/${profile.id}`}
+ className="flex items-center gap-1 text-black font-medium hover:underline"
+ >
+ <ProfileAvatar size="xs" {...(profile ?? {})}></ProfileAvatar>
+ {getProfileName(profile)}
+ </Link>
+ );
+ }
+
+ if (typeof properties.duration === 'number') {
+ bullets.push(`${round(properties.duration / 1000, 1)}s`);
+ }
+
+ switch (name) {
+ case 'screen_view': {
+ const route = (properties?.route || properties?.path) as string;
+ if (route) {
+ bullets.push(route);
+ }
+ break;
+ }
+ }
+
+ return bullets;
+ }, [name, createdAt, profile, properties, params]);
+
+ return (
+ <ExpandableListItem
+ title={name.split('_').join(' ')}
+ bullets={bullets}
+ image={<EventIcon name={name} />}
+ >
+ <ListProperties data={properties} className="rounded-none border-none" />
+ </ExpandableListItem>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/events/list-events.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/list-events.tsx
new file mode 100644
index 000000000..515d7ea7d
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/list-events.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { useMemo, useState } from 'react';
+import { api } from '@/app/_trpc/client';
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { Pagination, usePagination } from '@/components/Pagination';
+import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+
+import { EventListItem } from './event-list-item';
+
+interface ListEventsProps {
+ projectId: string;
+}
+export function ListEvents({ projectId }: ListEventsProps) {
+ const pagination = usePagination();
+ const [eventFilters, setEventFilters] = useState<string[]>([]);
+ const eventsQuery = api.event.list.useQuery(
+ {
+ events: eventFilters,
+ projectId: projectId,
+ ...pagination,
+ },
+ {
+ keepPreviousData: true,
+ }
+ );
+ const events = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
+
+ const filterEventsQuery = api.chart.events.useQuery({
+ projectId: projectId,
+ });
+ const filterEvents = (filterEventsQuery.data ?? []).map((item) => ({
+ value: item.name,
+ label: item.name,
+ }));
+
+ return (
+ <>
+ <StickyBelowHeader className="p-4 flex justify-between">
+ <div>
+ <ComboboxAdvanced
+ items={filterEvents}
+ value={eventFilters}
+ onChange={setEventFilters}
+ placeholder="Filter by event"
+ />
+ </div>
+ </StickyBelowHeader>
+ <div className="p-4">
+ <div className="flex flex-col gap-4">
+ {events.map((item) => (
+ <EventListItem key={item.id} {...item} />
+ ))}
+ </div>
+ <div className="mt-2">
+ <Pagination {...pagination} />
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/events/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/page.tsx
new file mode 100644
index 000000000..9c8c2b491
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/events/page.tsx
@@ -0,0 +1,19 @@
+import PageLayout from '@/app/(app)/page-layout';
+
+import { ListEvents } from './list-events';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ };
+}
+export default function Page({
+ params: { organizationId, projectId },
+}: PageProps) {
+ return (
+ <PageLayout title="Events" organizationId={organizationId}>
+ <ListEvents projectId={projectId} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/header-dashboards.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/header-dashboards.tsx
new file mode 100644
index 000000000..5ff732004
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/header-dashboards.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { Button } from '@/components/ui/button';
+import { pushModal } from '@/modals';
+import { PlusIcon } from 'lucide-react';
+
+import { StickyBelowHeader } from '../../layout-sticky-below-header';
+
+interface HeaderDashboardsProps {
+ projectId: string;
+}
+
+export function HeaderDashboards({ projectId }: HeaderDashboardsProps) {
+ return (
+ <StickyBelowHeader>
+ <div className="p-4 flex justify-between items-center">
+ <div />
+ <Button
+ icon={PlusIcon}
+ onClick={() => {
+ pushModal('AddDashboard', {
+ projectId,
+ });
+ }}
+ >
+ <span className="max-sm:hidden">Create dashboard</span>
+ <span className="sm:hidden">Dashboard</span>
+ </Button>
+ </div>
+ </StickyBelowHeader>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/list-dashboards.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/list-dashboards.tsx
new file mode 100644
index 000000000..c1c780233
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/list-dashboards.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import { api, handleError, handleErrorToastOptions } from '@/app/_trpc/client';
+import { Card, CardActions, CardActionsItem } from '@/components/Card';
+import { ToastAction } from '@/components/ui/toast';
+import { toast } from '@/components/ui/use-toast';
+import { pushModal } from '@/modals';
+import type { getDashboardsByProjectId } from '@/server/services/dashboard.service';
+import { Pencil, Plus, Trash } from 'lucide-react';
+import Link from 'next/link';
+import { useParams, useRouter } from 'next/navigation';
+
+interface ListDashboardsProps {
+ dashboards: Awaited<ReturnType<typeof getDashboardsByProjectId>>;
+}
+
+export function ListDashboards({ dashboards }: ListDashboardsProps) {
+ const router = useRouter();
+ const params = useParams();
+ const { organizationId, projectId } = params;
+ const deletion = api.dashboard.delete.useMutation({
+ onError: (error, variables) => {
+ return handleErrorToastOptions({
+ action: (
+ <ToastAction
+ altText="Force delete"
+ onClick={() => {
+ deletion.mutate({
+ forceDelete: true,
+ id: variables.id,
+ });
+ }}
+ >
+ Force delete
+ </ToastAction>
+ ),
+ })(error);
+ },
+ onSuccess() {
+ router.refresh();
+ toast({
+ title: 'Success',
+ description: 'Dashboard deleted.',
+ });
+ },
+ });
+
+ return (
+ <>
+ <div className="grid sm:grid-cols-2 gap-4 p-4">
+ {dashboards.map((item) => (
+ <Card key={item.id} hover>
+ <div>
+ <Link
+ href={`/${organizationId}/${projectId}/${item.id}`}
+ className="block p-4 flex flex-col"
+ >
+ <span className="font-medium">{item.name}</span>
+ <span className="text-muted-foreground text-sm">
+ {item.project.name}
+ </span>
+ </Link>
+ </div>
+
+ <CardActions>
+ <CardActionsItem className="w-full" asChild>
+ <button
+ onClick={() => {
+ pushModal('EditDashboard', item);
+ }}
+ >
+ <Pencil size={16} />
+ Edit
+ </button>
+ </CardActionsItem>
+ <CardActionsItem className="text-destructive w-full" asChild>
+ <button
+ onClick={() => {
+ deletion.mutate({
+ id: item.id,
+ });
+ }}
+ >
+ <Trash size={16} />
+ Delete
+ </button>
+ </CardActionsItem>
+ </CardActions>
+ </Card>
+ ))}
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/page.tsx
new file mode 100644
index 000000000..77e7f4bad
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/page.tsx
@@ -0,0 +1,25 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getDashboardsByProjectId } from '@/server/services/dashboard.service';
+
+import { HeaderDashboards } from './header-dashboards';
+import { ListDashboards } from './list-dashboards';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ };
+}
+
+export default async function Page({
+ params: { organizationId, projectId },
+}: PageProps) {
+ const dashboards = await getDashboardsByProjectId(projectId);
+
+ return (
+ <PageLayout title="Dashboards" organizationId={organizationId}>
+ <HeaderDashboards projectId={projectId} />
+ <ListDashboards dashboards={dashboards} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/list-profile-events.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/list-profile-events.tsx
new file mode 100644
index 000000000..0f18e4cae
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/list-profile-events.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { useMemo } from 'react';
+import { api } from '@/app/_trpc/client';
+import { Pagination, usePagination } from '@/components/Pagination';
+import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import { useEventNames } from '@/hooks/useEventNames';
+import { parseAsJson, useQueryState } from 'nuqs';
+
+import { EventListItem } from '../../events/event-list-item';
+
+interface ListProfileEvents {
+ projectId: string;
+ profileId: string;
+}
+
+export default function ListProfileEvents({
+ projectId,
+ profileId,
+}: ListProfileEvents) {
+ const pagination = usePagination();
+ const [eventFilters, setEventFilters] = useQueryState(
+ 'events',
+ parseAsJson<string[]>().withDefault([])
+ );
+
+ const eventNames = useEventNames(projectId);
+ const eventsQuery = api.event.list.useQuery(
+ {
+ projectId,
+ profileId,
+ events: eventFilters,
+ ...pagination,
+ },
+ {
+ keepPreviousData: true,
+ }
+ );
+ const events = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
+
+ return (
+ <>
+ <div className="flex items-center justify-between mb-4">
+ <ComboboxAdvanced
+ placeholder="Filter events"
+ items={eventNames}
+ value={eventFilters}
+ onChange={setEventFilters}
+ />
+ </div>
+ <div className="flex flex-col gap-4">
+ {events.map((item) => (
+ <EventListItem key={item.id} {...item} />
+ ))}
+ </div>
+ <div className="mt-2">
+ <Pagination {...pagination} />
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/page.tsx
new file mode 100644
index 000000000..ce7fdf29c
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/[profileId]/page.tsx
@@ -0,0 +1,87 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { ListProperties } from '@/components/events/ListProperties';
+import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
+import { Avatar } from '@/components/ui/avatar';
+import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
+import {
+ getProfileById,
+ getProfilesByExternalId,
+} from '@/server/services/profile.service';
+import { formatDateTime } from '@/utils/date';
+import { getProfileName } from '@/utils/getters';
+
+import ListProfileEvents from './list-profile-events';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ profileId: string;
+ };
+}
+
+export default async function Page({
+ params: { organizationId, projectId, profileId },
+}: PageProps) {
+ const profile = await getProfileById(profileId);
+ const profiles = (
+ await getProfilesByExternalId(profile.external_id, profile.project_id)
+ ).filter((item) => item.id !== profile.id);
+ return (
+ <PageLayout
+ title={
+ <div className="flex items-center gap-2">
+ <ProfileAvatar {...profile} size="sm" className="hidden sm:block" />
+ {getProfileName(profile)}
+ </div>
+ }
+ organizationId={organizationId}
+ >
+ <div className="p-4">
+ <div className="grid gap-4 grid-cols-1 md:grid-cols-2 mb-8">
+ <Widget>
+ <WidgetHead>
+ <span className="title">Properties</span>
+ </WidgetHead>
+ <ListProperties
+ data={profile.properties}
+ className="rounded-none border-none"
+ />
+ </Widget>
+ <Widget>
+ <WidgetHead>
+ <span className="title">Linked profile</span>
+ </WidgetHead>
+ {profiles.length > 0 ? (
+ <div className="flex flex-col gap-4">
+ {profiles.map((profile) => (
+ <div key={profile.id} className="border-b border-border">
+ <WidgetBody className="flex gap-4">
+ <ProfileAvatar {...profile} />
+ <div>
+ <div className="font-medium mt-1">
+ {getProfileName(profile)}
+ </div>
+ <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2 text-muted-foreground text-xs">
+ <span>{profile.id}</span>
+ <span>{formatDateTime(profile.createdAt)}</span>
+ </div>
+ </div>
+ </WidgetBody>
+ <ListProperties
+ data={profile.properties}
+ className="rounded-none border-none"
+ />
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="p-4">No linked profiles</div>
+ )}
+ </Widget>
+ </div>
+ <ListProfileEvents projectId={projectId} profileId={profileId} />
+ </div>
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/list-profiles.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/list-profiles.tsx
new file mode 100644
index 000000000..a5bd3f21d
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/list-profiles.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { useMemo } from 'react';
+import { api } from '@/app/_trpc/client';
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { Pagination, usePagination } from '@/components/Pagination';
+import { Input } from '@/components/ui/input';
+import { useQueryState } from 'nuqs';
+
+import { ProfileListItem } from './profile-list-item';
+
+interface ListProfilesProps {
+ projectId: string;
+ organizationId: string;
+}
+export function ListProfiles({ organizationId, projectId }: ListProfilesProps) {
+ const [query, setQuery] = useQueryState('q');
+ const pagination = usePagination();
+ const eventsQuery = api.profile.list.useQuery(
+ {
+ projectId,
+ query,
+ ...pagination,
+ },
+ {
+ keepPreviousData: true,
+ }
+ );
+ const profiles = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
+
+ return (
+ <>
+ <StickyBelowHeader className="p-4 flex justify-between">
+ <Input
+ placeholder="Search by name"
+ value={query ?? ''}
+ onChange={(event) => setQuery(event.target.value || null)}
+ />
+ </StickyBelowHeader>
+ <div className="p-4">
+ <div className="flex flex-col gap-4">
+ {profiles.map((item) => (
+ <ProfileListItem key={item.id} {...item} />
+ ))}
+ </div>
+ <div className="mt-2">
+ <Pagination {...pagination} />
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/page.tsx
new file mode 100644
index 000000000..dcb0c41d6
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/page.tsx
@@ -0,0 +1,19 @@
+import PageLayout from '@/app/(app)/page-layout';
+
+import { ListProfiles } from './list-profiles';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ };
+}
+export default function Page({
+ params: { organizationId, projectId },
+}: PageProps) {
+ return (
+ <PageLayout title="Events" organizationId={organizationId}>
+ <ListProfiles projectId={projectId} organizationId={organizationId} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/profile-list-item.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/profile-list-item.tsx
new file mode 100644
index 000000000..374ea9b1f
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/profiles/profile-list-item.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { useMemo } from 'react';
+import type { RouterOutputs } from '@/app/_trpc/client';
+import { ListProperties } from '@/components/events/ListProperties';
+import { ExpandableListItem } from '@/components/general/ExpandableListItem';
+import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
+import { useAppParams } from '@/hooks/useAppParams';
+import { formatDateTime } from '@/utils/date';
+import { getProfileName } from '@/utils/getters';
+import Link from 'next/link';
+
+type ProfileListItemProps = RouterOutputs['profile']['list'][number];
+
+export function ProfileListItem(props: ProfileListItemProps) {
+ const { id, properties, createdAt } = props;
+ const params = useAppParams();
+
+ const bullets = useMemo(() => {
+ const bullets: React.ReactNode[] = [
+ <span>{formatDateTime(createdAt)}</span>,
+ <Link
+ href={`/${params.organizationId}/${params.projectId}/profiles/${id}`}
+ className="text-black font-medium hover:underline"
+ >
+ See profile
+ </Link>,
+ ];
+
+ return bullets;
+ }, [createdAt, id, params]);
+
+ return (
+ <ExpandableListItem
+ title={getProfileName(props)}
+ bullets={bullets}
+ image={<ProfileAvatar {...props} />}
+ >
+ <ListProperties data={properties} className="rounded-none border-none" />
+ </ExpandableListItem>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx
new file mode 100644
index 000000000..e2674c054
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx
@@ -0,0 +1,32 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getReportById } from '@/server/services/reports.service';
+import { Pencil } from 'lucide-react';
+
+import ReportEditor from '../report-editor';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ reportId: string;
+ };
+}
+
+export default async function Page({
+ params: { organizationId, reportId },
+}: PageProps) {
+ const report = await getReportById(reportId);
+ return (
+ <PageLayout
+ title={
+ <div className="flex gap-2 items-center cursor-pointer">
+ {report.name}
+ <Pencil size={16} />
+ </div>
+ }
+ organizationId={organizationId}
+ >
+ <ReportEditor report={report} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx
new file mode 100644
index 000000000..2b3308ce5
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx
@@ -0,0 +1,27 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { Pencil } from 'lucide-react';
+
+import ReportEditor from './report-editor';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ projectId: string;
+ };
+}
+
+export default function Page({ params: { organizationId } }: PageProps) {
+ return (
+ <PageLayout
+ title={
+ <div className="flex gap-2 items-center cursor-pointer">
+ Unnamed report
+ <Pencil size={16} />
+ </div>
+ }
+ organizationId={organizationId}
+ >
+ <ReportEditor reportId={null} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx
new file mode 100644
index 000000000..0687f4448
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import { useEffect, useRef } from 'react';
+import { api } from '@/app/_trpc/client';
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { Chart } from '@/components/report/chart';
+import { ReportChartType } from '@/components/report/ReportChartType';
+import { ReportInterval } from '@/components/report/ReportInterval';
+import { ReportLineType } from '@/components/report/ReportLineType';
+import { ReportSaveButton } from '@/components/report/ReportSaveButton';
+import {
+ changeDateRanges,
+ ready,
+ reset,
+ setReport,
+} from '@/components/report/reportSlice';
+import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar';
+import { Button } from '@/components/ui/button';
+import { Combobox } from '@/components/ui/combobox';
+import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
+import { useDispatch, useSelector } from '@/redux';
+import type { IServiceReport } from '@/server/services/reports.service';
+import { timeRanges } from '@/utils/constants';
+import { GanttChartSquareIcon } from 'lucide-react';
+
+interface ReportEditorProps {
+ report: IServiceReport | null;
+}
+
+export default function ReportEditor({
+ report: initialReport,
+}: ReportEditorProps) {
+ const dispatch = useDispatch();
+ const report = useSelector((state) => state.report);
+
+ // Set report if reportId exists
+ useEffect(() => {
+ if (initialReport) {
+ dispatch(setReport(initialReport));
+ } else {
+ dispatch(ready());
+ }
+
+ return () => {
+ dispatch(reset());
+ };
+ }, [initialReport, dispatch]);
+
+ return (
+ <Sheet>
+ <StickyBelowHeader className="p-4 grid grid-cols-2 gap-2 md:grid-cols-6">
+ <SheetTrigger asChild>
+ <div>
+ <Button icon={GanttChartSquareIcon} variant="cta">
+ Pick events
+ </Button>
+ </div>
+ </SheetTrigger>
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-2 col-span-4">
+ <Combobox
+ className="min-w-0 flex-1"
+ placeholder="Range"
+ value={report.range}
+ onChange={(value) => {
+ dispatch(changeDateRanges(value));
+ }}
+ items={Object.values(timeRanges).map((key) => ({
+ label: key,
+ value: key,
+ }))}
+ />
+ <ReportInterval className="min-w-0 flex-1" />
+ <ReportChartType className="min-w-0 flex-1" />
+ <ReportLineType className="min-w-0 flex-1" />
+ </div>
+ <div className="col-start-2 md:col-start-6 row-start-1 text-right">
+ <ReportSaveButton />
+ </div>
+ </StickyBelowHeader>
+ <div className="flex flex-col gap-4 p-4">
+ {report.ready && <Chart {...report} editMode />}
+ </div>
+ <SheetContent className="!max-w-lg w-full" side="left">
+ <ReportSidebar />
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/list-projects.tsx b/apps/web/src/app/(app)/[organizationId]/list-projects.tsx
new file mode 100644
index 000000000..4817c8ed9
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/list-projects.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { Card } from '@/components/Card';
+import { pushModal } from '@/modals';
+import type { getProjectsByOrganizationId } from '@/server/services/project.service';
+import { Plus } from 'lucide-react';
+import Link from 'next/link';
+import { useParams } from 'next/navigation';
+
+interface ListProjectsProps {
+ projects: Awaited<ReturnType<typeof getProjectsByOrganizationId>>;
+}
+
+export function ListProjects({ projects }: ListProjectsProps) {
+ const params = useParams();
+ const organizationId = params.organizationId as string;
+
+ return (
+ <>
+ <div className="grid sm:grid-cols-2 gap-4 p-4">
+ {projects.map((item) => (
+ <Card key={item.id} hover>
+ <div>
+ <Link
+ href={`/${organizationId}/${item.id}`}
+ className="block p-4 flex flex-col"
+ >
+ <span className="font-medium">{item.name}</span>
+ </Link>
+ </div>
+ </Card>
+ ))}
+ <Card hover className="border-dashed">
+ <button
+ className="flex items-center justify-between w-full p-4 font-medium leading-none"
+ onClick={() => {
+ pushModal('AddProject', {
+ organizationId,
+ });
+ }}
+ >
+ Create new project
+ <Plus size={16} />
+ </button>
+ </Card>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/page.tsx b/apps/web/src/app/(app)/[organizationId]/page.tsx
new file mode 100644
index 000000000..f20d5435f
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/page.tsx
@@ -0,0 +1,17 @@
+import { getFirstProjectByOrganizationId } from '@/server/services/project.service';
+import { redirect } from 'next/navigation';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ };
+}
+
+export default async function Page({ params: { organizationId } }: PageProps) {
+ const project = await getFirstProjectByOrganizationId(organizationId);
+ if (project) {
+ return redirect(`/${organizationId}/${project.id}`);
+ }
+
+ return <p>List projects maybe?</p>;
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/clients/list-clients.tsx b/apps/web/src/app/(app)/[organizationId]/settings/clients/list-clients.tsx
new file mode 100644
index 000000000..fb2d18f59
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/clients/list-clients.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { columns } from '@/components/clients/table';
+import { ContentHeader } from '@/components/Content';
+import { DataTable } from '@/components/DataTable';
+import { Button } from '@/components/ui/button';
+import { pushModal } from '@/modals';
+import type { getClientsByOrganizationId } from '@/server/services/clients.service';
+import { KeySquareIcon, PlusIcon } from 'lucide-react';
+import { useParams } from 'next/navigation';
+
+interface ListClientsProps {
+ clients: Awaited<ReturnType<typeof getClientsByOrganizationId>>;
+}
+export default function ListClients({ clients }: ListClientsProps) {
+ const organizationId = useParams().organizationId as string;
+
+ return (
+ <>
+ <StickyBelowHeader>
+ <div className="p-4 flex items-center justify-between">
+ <div />
+ <Button
+ icon={PlusIcon}
+ onClick={() => pushModal('AddClient', { organizationId })}
+ >
+ <span className="max-sm:hidden">Create client</span>
+ <span className="sm:hidden">Client</span>
+ </Button>
+ </div>
+ </StickyBelowHeader>
+ <div className="p-4">
+ <DataTable data={clients} columns={columns} />
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/clients/page.tsx b/apps/web/src/app/(app)/[organizationId]/settings/clients/page.tsx
new file mode 100644
index 000000000..497f900c7
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/clients/page.tsx
@@ -0,0 +1,20 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getClientsByOrganizationId } from '@/server/services/clients.service';
+
+import ListClients from './list-clients';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ };
+}
+
+export default async function Page({ params: { organizationId } }: PageProps) {
+ const clients = await getClientsByOrganizationId(organizationId);
+
+ return (
+ <PageLayout title="Clients" organizationId={organizationId}>
+ <ListClients clients={clients} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/organization/edit-organization.tsx b/apps/web/src/app/(app)/[organizationId]/settings/organization/edit-organization.tsx
new file mode 100644
index 000000000..c5671767a
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/organization/edit-organization.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
+import { InputWithLabel } from '@/components/forms/InputWithLabel';
+import { Button } from '@/components/ui/button';
+import { toast } from '@/components/ui/use-toast';
+import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
+import type { getOrganizationById } from '@/server/services/organization.service';
+import { useRouter } from 'next/navigation';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
+
+const validator = z.object({
+ id: z.string().min(2),
+ name: z.string().min(2),
+});
+
+type IForm = z.infer<typeof validator>;
+interface EditOrganizationProps {
+ organization: Awaited<ReturnType<typeof getOrganizationById>>;
+}
+export default function EditOrganization({
+ organization,
+}: EditOrganizationProps) {
+ const router = useRouter();
+
+ const { register, handleSubmit, formState, reset } = useForm<IForm>({
+ defaultValues: organization,
+ });
+
+ const mutation = api.organization.update.useMutation({
+ onSuccess(res) {
+ toast({
+ title: 'Organization updated',
+ description: 'Your organization has been updated.',
+ });
+ reset(res);
+ router.refresh();
+ },
+ onError: handleError,
+ });
+
+ return (
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate(values);
+ })}
+ >
+ <Widget>
+ <WidgetHead className="flex items-center justify-between">
+ <span className="title">Org. details</span>
+ <Button size="sm" type="submit" disabled={!formState.isDirty}>
+ Save
+ </Button>
+ </WidgetHead>
+ <WidgetBody>
+ <InputWithLabel
+ label="Name"
+ {...register('name')}
+ defaultValue={organization.name}
+ />
+ </WidgetBody>
+ </Widget>
+ </form>
+ );
+}
+
+// <ContentSection
+// title="Invite user"
+// text="Invite users to this organization. You can invite several users with (,)"
+// >
+
+// </ContentSection>
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/organization/invited-users.tsx b/apps/web/src/app/(app)/[organizationId]/settings/organization/invited-users.tsx
new file mode 100644
index 000000000..cc579f9dc
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/organization/invited-users.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
+import { InputWithLabel } from '@/components/forms/InputWithLabel';
+import { Button } from '@/components/ui/button';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { toast } from '@/components/ui/use-toast';
+import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
+import type { IServiceInvite } from '@/server/services/user.service';
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
+
+const validator = z.object({
+ email: z.string().email(),
+});
+
+type IForm = z.infer<typeof validator>;
+
+interface InvitedUsersProps {
+ invites: IServiceInvite[];
+ organizationId: string;
+}
+export default function InvitedUsers({
+ invites,
+ organizationId,
+}: InvitedUsersProps) {
+ const router = useRouter();
+
+ const { register, handleSubmit, formState, reset } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ email: '',
+ },
+ });
+
+ const mutation = api.user.invite.useMutation({
+ onSuccess() {
+ toast({
+ title: 'User invited',
+ description: "We have sent an invitation to the user's email",
+ });
+ reset();
+ router.refresh();
+ },
+ onError: handleError,
+ });
+
+ return (
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate({
+ ...values,
+ organizationId,
+ });
+ })}
+ >
+ <Widget>
+ <WidgetHead className="flex items-center justify-between">
+ <span className="title">Invites</span>
+ <Button size="sm" type="submit" disabled={!formState.isDirty}>
+ Invite
+ </Button>
+ </WidgetHead>
+ <WidgetBody>
+ <InputWithLabel
+ label="Email"
+ placeholder="Who do you want to invite?"
+ {...register('email')}
+ />
+
+ <div className="font-medium mt-8 mb-2">Invited users</div>
+ <Table className="mini">
+ <TableHeader>
+ <TableRow>
+ <TableHead>Email</TableHead>
+ <TableHead>Accepted</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {invites.map((item) => {
+ return (
+ <TableRow key={item.id}>
+ <TableCell className="font-medium">{item.email}</TableCell>
+ <TableCell>{item.accepted ? 'Yes' : 'No'}</TableCell>
+ </TableRow>
+ );
+ })}
+
+ {invites.length === 0 && (
+ <TableRow>
+ <TableCell colSpan={2} className="italic">
+ No invites
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </WidgetBody>
+ </Widget>
+ </form>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/organization/page.tsx b/apps/web/src/app/(app)/[organizationId]/settings/organization/page.tsx
new file mode 100644
index 000000000..f70e44a6b
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/organization/page.tsx
@@ -0,0 +1,26 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getOrganizationById } from '@/server/services/organization.service';
+import { getInvitesByOrganizationId } from '@/server/services/user.service';
+
+import EditOrganization from './edit-organization';
+import InvitedUsers from './invited-users';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ };
+}
+
+export default async function Page({ params: { organizationId } }: PageProps) {
+ const organization = await getOrganizationById(organizationId);
+ const invites = await getInvitesByOrganizationId(organizationId);
+
+ return (
+ <PageLayout title={organization.name} organizationId={organizationId}>
+ <div className="p-4 grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <EditOrganization organization={organization} />
+ <InvitedUsers invites={invites} organizationId={organizationId} />
+ </div>
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/page.tsx b/apps/web/src/app/(app)/[organizationId]/settings/page.tsx
new file mode 100644
index 000000000..22b9c8b12
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/page.tsx
@@ -0,0 +1 @@
+export { default } from './organization/page';
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/profile/edit-profile.tsx b/apps/web/src/app/(app)/[organizationId]/settings/profile/edit-profile.tsx
new file mode 100644
index 000000000..600f1791a
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/profile/edit-profile.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
+import { ContentHeader, ContentSection } from '@/components/Content';
+import { InputError } from '@/components/forms/InputError';
+import { InputWithLabel } from '@/components/forms/InputWithLabel';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { toast } from '@/components/ui/use-toast';
+import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
+import type { getOrganizationById } from '@/server/services/organization.service';
+import type { getProfileById } from '@/server/services/profile.service';
+import type { getUserById } from '@/server/services/user.service';
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
+
+const validator = z.object({
+ name: z.string().min(2),
+ email: z.string().email(),
+});
+
+type IForm = z.infer<typeof validator>;
+interface EditProfileProps {
+ profile: Awaited<ReturnType<typeof getUserById>>;
+}
+export default function EditProfile({ profile }: EditProfileProps) {
+ const router = useRouter();
+
+ const { register, handleSubmit, reset, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ name: profile.name ?? '',
+ email: profile.email ?? '',
+ },
+ });
+
+ const mutation = api.user.update.useMutation({
+ onSuccess(res) {
+ toast({
+ title: 'Profile updated',
+ description: 'Your profile has been updated.',
+ });
+ reset(res);
+ router.refresh();
+ },
+ onError: handleError,
+ });
+
+ return (
+ <form
+ onSubmit={handleSubmit((values) => {
+ mutation.mutate(values);
+ })}
+ >
+ <Widget>
+ <WidgetHead className="flex items-center justify-between">
+ <span className="title">Your profile</span>
+ <Button size="sm" type="submit" disabled={!formState.isDirty}>
+ Save
+ </Button>
+ </WidgetHead>
+ <WidgetBody className="flex flex-col gap-4">
+ <InputWithLabel
+ label="Name"
+ placeholder="Your name"
+ defaultValue={profile.name ?? ''}
+ {...register('name')}
+ />
+ <InputWithLabel
+ label="Email"
+ placeholder="Your email"
+ defaultValue={profile.email ?? ''}
+ {...register('email')}
+ />
+ </WidgetBody>
+ </Widget>
+ </form>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/profile/logout.tsx b/apps/web/src/app/(app)/[organizationId]/settings/profile/logout.tsx
new file mode 100644
index 000000000..af14ce102
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/profile/logout.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@/components/ui/button';
+import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
+import { signOut } from 'next-auth/react';
+
+export function Logout() {
+ return (
+ <Widget className="border-destructive">
+ <WidgetHead className="border-destructive">
+ <span className="title text-destructive">Sad part</span>
+ </WidgetHead>
+ <WidgetBody>
+ <p className="mb-4">
+ Sometime&apos;s you need to go. See you next time
+ </p>
+ <Button
+ variant={'destructive'}
+ onClick={() => {
+ signOut();
+ }}
+ >
+ Logout 🤨
+ </Button>
+ </WidgetBody>
+ </Widget>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/profile/page.tsx b/apps/web/src/app/(app)/[organizationId]/settings/profile/page.tsx
new file mode 100644
index 000000000..7487073c2
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/profile/page.tsx
@@ -0,0 +1,26 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getSession } from '@/server/auth';
+import { getUserById } from '@/server/services/user.service';
+
+import EditProfile from './edit-profile';
+import { Logout } from './logout';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ };
+}
+
+export default async function Page({ params: { organizationId } }: PageProps) {
+ const session = await getSession();
+ const profile = await getUserById(session?.user.id!);
+
+ return (
+ <PageLayout title={profile.name} organizationId={organizationId}>
+ <div className="p-4 flex flex-col gap-4">
+ <EditProfile profile={profile} />
+ <Logout />
+ </div>
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/projects/list-projects.tsx b/apps/web/src/app/(app)/[organizationId]/settings/projects/list-projects.tsx
new file mode 100644
index 000000000..78b7515d9
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/projects/list-projects.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { StickyBelowHeader } from '@/app/(app)/layout-sticky-below-header';
+import { DataTable } from '@/components/DataTable';
+import { columns } from '@/components/projects/table';
+import { Button } from '@/components/ui/button';
+import { pushModal } from '@/modals';
+import type { getProjectsByOrganizationId } from '@/server/services/project.service';
+import { PlusIcon, WarehouseIcon } from 'lucide-react';
+import { useParams } from 'next/navigation';
+
+interface ListProjectsProps {
+ projects: Awaited<ReturnType<typeof getProjectsByOrganizationId>>;
+}
+export default function ListProjects({ projects }: ListProjectsProps) {
+ const organizationId = useParams().organizationId as string;
+ return (
+ <>
+ <StickyBelowHeader>
+ <div className="p-4 flex items-center justify-between">
+ <div />
+ <Button
+ icon={PlusIcon}
+ onClick={() =>
+ pushModal('AddProject', {
+ organizationId,
+ })
+ }
+ >
+ <span className="max-sm:hidden">Create project</span>
+ <span className="sm:hidden">Project</span>
+ </Button>
+ </div>
+ </StickyBelowHeader>
+ <div className="p-4">
+ <DataTable data={projects} columns={columns} />
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/[organizationId]/settings/projects/page.tsx b/apps/web/src/app/(app)/[organizationId]/settings/projects/page.tsx
new file mode 100644
index 000000000..b80e357f5
--- /dev/null
+++ b/apps/web/src/app/(app)/[organizationId]/settings/projects/page.tsx
@@ -0,0 +1,20 @@
+import PageLayout from '@/app/(app)/page-layout';
+import { getProjectsByOrganizationId } from '@/server/services/project.service';
+
+import ListProjects from './list-projects';
+
+interface PageProps {
+ params: {
+ organizationId: string;
+ };
+}
+
+export default async function Page({ params: { organizationId } }: PageProps) {
+ const projects = await getProjectsByOrganizationId(organizationId);
+
+ return (
+ <PageLayout title="Projects" organizationId={organizationId}>
+ <ListProjects projects={projects} />
+ </PageLayout>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout-menu.tsx b/apps/web/src/app/(app)/layout-menu.tsx
new file mode 100644
index 000000000..4d6eeb8cd
--- /dev/null
+++ b/apps/web/src/app/(app)/layout-menu.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import type { IServiceRecentDashboards } from '@/server/services/dashboard.service';
+import {
+ BuildingIcon,
+ CogIcon,
+ GanttChartIcon,
+ KeySquareIcon,
+ LayoutPanelTopIcon,
+ UserIcon,
+ UsersIcon,
+ WarehouseIcon,
+} from 'lucide-react';
+import type { LucideProps } from 'lucide-react';
+import Link from 'next/link';
+import { useParams, usePathname } from 'next/navigation';
+
+function LinkWithIcon({
+ href,
+ icon: Icon,
+ label,
+}: {
+ href: string;
+ icon: React.ElementType<LucideProps>;
+ label: React.ReactNode;
+}) {
+ return (
+ <Link
+ className="flex gap-2 items-center px-3 py-3 transition-colors hover:bg-slate-100 leading-none rounded-lg"
+ href={href}
+ >
+ <Icon size={20} />
+ {label}
+ </Link>
+ );
+}
+
+interface LayoutMenuProps {
+ recentDashboards: IServiceRecentDashboards;
+ fallbackProjectId: string | null;
+}
+export default function LayoutMenu({
+ recentDashboards,
+ fallbackProjectId,
+}: LayoutMenuProps) {
+ const pathname = usePathname();
+ const params = useParams();
+ const projectId = (
+ !params.projectId || params.projectId === 'undefined'
+ ? fallbackProjectId
+ : params.projectId
+ ) as string | null;
+
+ return (
+ <>
+ <LinkWithIcon
+ icon={LayoutPanelTopIcon}
+ label="Dashboards"
+ href={`/${params.organizationId}/${projectId}`}
+ />
+ <LinkWithIcon
+ icon={GanttChartIcon}
+ label="Events"
+ href={`/${params.organizationId}/${projectId}/events`}
+ />
+ <LinkWithIcon
+ icon={UsersIcon}
+ label="Profiles"
+ href={`/${params.organizationId}/${projectId}/profiles`}
+ />
+ <LinkWithIcon
+ icon={CogIcon}
+ label="Settings"
+ href={`/${params.organizationId}/settings/organization`}
+ />
+ {pathname.includes('/settings/') && (
+ <div className="pl-7">
+ <LinkWithIcon
+ icon={BuildingIcon}
+ label="Organization"
+ href={`/${params.organizationId}/settings/organization`}
+ />
+ <LinkWithIcon
+ icon={WarehouseIcon}
+ label="Projects"
+ href={`/${params.organizationId}/settings/projects`}
+ />
+ <LinkWithIcon
+ icon={KeySquareIcon}
+ label="Clients"
+ href={`/${params.organizationId}/settings/clients`}
+ />
+ <LinkWithIcon
+ icon={UserIcon}
+ label="Profile (yours)"
+ href={`/${params.organizationId}/settings/profile`}
+ />
+ </div>
+ )}
+ {recentDashboards.length > 0 && (
+ <div className="mt-8">
+ <div className="font-medium mb-2">Recent dashboards</div>
+ {recentDashboards.map((item) => (
+ <LinkWithIcon
+ key={item.id}
+ icon={LayoutPanelTopIcon}
+ label={
+ <div className="flex flex-col">
+ <span>{item.dashboard.name}</span>
+ <span className="text-xs text-muted-foreground">
+ {item.project.name}
+ </span>
+ </div>
+ }
+ href={`/${item.organization_id}/${item.project_id}/${item.dashboard_id}`}
+ />
+ ))}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout-organization-selector.tsx b/apps/web/src/app/(app)/layout-organization-selector.tsx
new file mode 100644
index 000000000..012803d27
--- /dev/null
+++ b/apps/web/src/app/(app)/layout-organization-selector.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import type { IServiceOrganization } from '@/server/services/organization.service';
+import { Building } from 'lucide-react';
+import { useParams } from 'next/navigation';
+
+interface LayoutOrganizationSelectorProps {
+ organizations: IServiceOrganization[];
+}
+
+export default function LayoutOrganizationSelector({
+ organizations,
+}: LayoutOrganizationSelectorProps) {
+ const params = useParams();
+
+ const organization = organizations.find(
+ (item) => item.id === params.organizationId
+ );
+
+ if (!organization) {
+ return null;
+ }
+
+ return (
+ <div className="border border-border p-3 flex gap-2 rounded items-center">
+ <Building size={20} />
+ <span className="font-medium text-sm">{organization.name}</span>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout-project-selector.tsx b/apps/web/src/app/(app)/layout-project-selector.tsx
new file mode 100644
index 000000000..5b83d3c8d
--- /dev/null
+++ b/apps/web/src/app/(app)/layout-project-selector.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { Combobox } from '@/components/ui/combobox';
+import type { getProjectsByOrganizationId } from '@/server/services/project.service';
+import { useParams, usePathname, useRouter } from 'next/navigation';
+
+interface LayoutProjectSelectorProps {
+ projects: Awaited<ReturnType<typeof getProjectsByOrganizationId>>;
+ organizationId: string | null;
+}
+export default function LayoutProjectSelector({
+ projects,
+ organizationId,
+}: LayoutProjectSelectorProps) {
+ const router = useRouter();
+ const params = useParams<{ projectId: string }>();
+ const projectId = params?.projectId ? params.projectId : null;
+ const pathname = usePathname() || '';
+
+ return (
+ <div>
+ <Combobox
+ className="w-auto min-w-0 max-sm:max-w-[100px]"
+ placeholder={'Select project'}
+ onChange={(value) => {
+ // If we are on a page with only organizationId and projectId (as params)
+ // we know its safe to just replace the current projectId
+ // since the rest of the url is to a static page
+ // e.g. /[organizationId]/[projectId]/events
+ if (params && projectId && Object.keys(params).length === 2) {
+ router.push(pathname.replace(projectId, value));
+ } else {
+ router.push(`/${organizationId}/${value}`);
+ }
+ }}
+ value={projectId}
+ items={
+ projects.map((item) => ({
+ label: item.name,
+ value: item.id,
+ })) ?? []
+ }
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout-sidebar.tsx b/apps/web/src/app/(app)/layout-sidebar.tsx
new file mode 100644
index 000000000..2bc74c3a0
--- /dev/null
+++ b/apps/web/src/app/(app)/layout-sidebar.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { Logo } from '@/components/Logo';
+import type { IServiceRecentDashboards } from '@/server/services/dashboard.service';
+import type { IServiceOrganization } from '@/server/services/organization.service';
+import { cn } from '@/utils/cn';
+import { Rotate as Hamburger } from 'hamburger-react';
+import Link from 'next/link';
+import { usePathname } from 'next/navigation';
+
+import LayoutMenu from './layout-menu';
+import LayoutOrganizationSelector from './layout-organization-selector';
+
+interface LayoutSidebarProps {
+ recentDashboards: IServiceRecentDashboards;
+ organizations: IServiceOrganization[];
+}
+export function LayoutSidebar({
+ organizations,
+ recentDashboards,
+}: LayoutSidebarProps) {
+ const [active, setActive] = useState(false);
+ const fallbackProjectId = recentDashboards[0]?.project_id ?? null;
+ const pathname = usePathname();
+ useEffect(() => {
+ setActive(false);
+ }, [pathname]);
+ return (
+ <>
+ <button
+ onClick={() => setActive(false)}
+ className={cn(
+ 'fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm z-30 transition-opacity',
+ active
+ ? 'opacity-100 pointer-events-auto'
+ : 'opacity-0 pointer-events-none'
+ )}
+ />
+ <div
+ className={cn(
+ 'fixed top-0 left-0 h-screen border-r border-border w-72 bg-white flex flex-col z-30 transition-transform',
+ '-translate-x-72 lg:-translate-x-0', // responsive
+ active && 'translate-x-0' // force active on mobile
+ )}
+ >
+ <div className="absolute -right-12 h-16 flex items-center lg:hidden">
+ <Hamburger toggled={active} onToggle={setActive} size={20} />
+ </div>
+ <div className="h-16 border-b border-border px-4 shrink-0 flex items-center">
+ <Link href="/">
+ <Logo />
+ </Link>
+ </div>
+ <div className="flex flex-col p-4 gap-2 flex-grow overflow-auto">
+ <LayoutMenu
+ recentDashboards={recentDashboards}
+ fallbackProjectId={fallbackProjectId}
+ />
+ {/* Placeholder for LayoutOrganizationSelector */}
+ <div className="h-16 block shrink-0"></div>
+ </div>
+ <div className="fixed bottom-0 left-0 right-0">
+ <div className="bg-gradient-to-t from-white to-white/0 h-8 w-full"></div>
+ <div className="bg-white p-4 pt-0">
+ <LayoutOrganizationSelector organizations={organizations} />
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout-sticky-below-header.tsx b/apps/web/src/app/(app)/layout-sticky-below-header.tsx
new file mode 100644
index 000000000..c93a0c6f1
--- /dev/null
+++ b/apps/web/src/app/(app)/layout-sticky-below-header.tsx
@@ -0,0 +1,22 @@
+import { cn } from '@/utils/cn';
+
+interface StickyBelowHeaderProps {
+ children: React.ReactNode;
+ className?: string;
+}
+
+export function StickyBelowHeader({
+ children,
+ className,
+}: StickyBelowHeaderProps) {
+ return (
+ <div
+ className={cn(
+ 'md:sticky top-16 bg-white border-b border-border z-10',
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/layout.tsx b/apps/web/src/app/(app)/layout.tsx
new file mode 100644
index 000000000..5a2c9c145
--- /dev/null
+++ b/apps/web/src/app/(app)/layout.tsx
@@ -0,0 +1,24 @@
+import { getSession } from '@/server/auth';
+import { getRecentDashboardsByUserId } from '@/server/services/dashboard.service';
+import { getOrganizations } from '@/server/services/organization.service';
+
+import { LayoutSidebar } from './layout-sidebar';
+
+interface AppLayoutProps {
+ children: React.ReactNode;
+}
+
+export default async function AppLayout({ children }: AppLayoutProps) {
+ const session = await getSession();
+ const organizations = await getOrganizations();
+ const recentDashboards = session?.user.id
+ ? await getRecentDashboardsByUserId(session?.user.id)
+ : [];
+
+ return (
+ <div>
+ <LayoutSidebar {...{ organizations, recentDashboards }} />
+ <div className="lg:pl-72 transition-all">{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/list-organizations.tsx b/apps/web/src/app/(app)/list-organizations.tsx
new file mode 100644
index 000000000..79efa8927
--- /dev/null
+++ b/apps/web/src/app/(app)/list-organizations.tsx
@@ -0,0 +1,25 @@
+import { ChevronRight } from 'lucide-react';
+import Link from 'next/link';
+
+interface ListOrganizationsProps {
+ organizations: any[];
+}
+
+export function ListOrganizations({ organizations }: ListOrganizationsProps) {
+ return (
+ <>
+ <div className="flex flex-col gap-4 -mx-6">
+ {organizations.map((item) => (
+ <Link
+ key={item.id}
+ href={`/${item.id}`}
+ className="block px-6 py-3 flex items-center justify-between border-b border-border last:border-b-0 hover:bg-slate-100"
+ >
+ <span className="font-medium">{item.name}</span>
+ <ChevronRight size={20} />
+ </Link>
+ ))}
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/page-layout.tsx b/apps/web/src/app/(app)/page-layout.tsx
new file mode 100644
index 000000000..b1cd93292
--- /dev/null
+++ b/apps/web/src/app/(app)/page-layout.tsx
@@ -0,0 +1,34 @@
+import { getProjectsByOrganizationId } from '@/server/services/project.service';
+
+import LayoutProjectSelector from './layout-project-selector';
+
+interface PageLayoutProps {
+ children: React.ReactNode;
+ title: React.ReactNode;
+ organizationId: string | null;
+}
+
+export default async function PageLayout({
+ children,
+ title,
+ organizationId,
+}: PageLayoutProps) {
+ const projects = organizationId
+ ? await getProjectsByOrganizationId(organizationId)
+ : [];
+ return (
+ <>
+ <div className="h-16 border-b border-border flex-shrink-0 sticky top-0 bg-white px-4 flex items-center justify-between z-20 pl-12 lg:pl-4">
+ <div className="text-xl font-medium">{title}</div>
+
+ {projects.length > 0 && (
+ <LayoutProjectSelector
+ projects={projects}
+ organizationId={organizationId}
+ />
+ )}
+ </div>
+ <div>{children}</div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/(app)/page.tsx b/apps/web/src/app/(app)/page.tsx
new file mode 100644
index 000000000..5fb88bda0
--- /dev/null
+++ b/apps/web/src/app/(app)/page.tsx
@@ -0,0 +1,26 @@
+import { ModalWrapper } from '@/modals';
+import { ModalContent, ModalHeader } from '@/modals/Modal/Container';
+import { redirect } from 'next/navigation';
+
+import { db } from '@mixan/db';
+
+import { ListOrganizations } from './list-organizations';
+
+export default async function Page() {
+ const organizations = await db.organization.findMany();
+
+ if (organizations.length === 1 && organizations[0]?.id) {
+ redirect(`/${organizations[0].id}`);
+ }
+
+ return (
+ <div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)] z-50">
+ <ModalWrapper>
+ <ModalContent>
+ <ModalHeader title="Select organization" onClose={false} />
+ <ListOrganizations organizations={organizations} />
+ </ModalContent>
+ </ModalWrapper>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/_trpc/client.tsx b/apps/web/src/app/_trpc/client.tsx
new file mode 100644
index 000000000..40ac14525
--- /dev/null
+++ b/apps/web/src/app/_trpc/client.tsx
@@ -0,0 +1,40 @@
+import type { Toast } from '@/components/ui/use-toast';
+import { toast } from '@/components/ui/use-toast';
+import type { AppRouter } from '@/server/api/root';
+import type { TRPCClientErrorBase } from '@trpc/react-query';
+import { createTRPCReact } from '@trpc/react-query';
+import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
+
+export const api = createTRPCReact<AppRouter>({});
+
+/**
+ * Inference helper for inputs.
+ *
+ * @example type HelloInput = RouterInputs['example']['hello']
+ */
+export type RouterInputs = inferRouterInputs<AppRouter>;
+
+/**
+ * Inference helper for outputs.
+ *
+ * @example type HelloOutput = RouterOutputs['example']['hello']
+ */
+export type RouterOutputs = inferRouterOutputs<AppRouter>;
+export type IChartData = RouterOutputs['chart']['chart'];
+
+export function handleError(error: TRPCClientErrorBase<any>) {
+ toast({
+ title: 'Error',
+ description: error.message,
+ });
+}
+
+export function handleErrorToastOptions(options: Toast) {
+ return function (error: TRPCClientErrorBase<any>) {
+ toast({
+ title: 'Error',
+ description: error.message,
+ ...options,
+ });
+ };
+}
diff --git a/apps/web/src/app/api/auth/[...nextauth]/route.ts b/apps/web/src/app/api/auth/[...nextauth]/route.ts
new file mode 100644
index 000000000..58672cf54
--- /dev/null
+++ b/apps/web/src/app/api/auth/[...nextauth]/route.ts
@@ -0,0 +1,6 @@
+import { authOptions } from '@/server/auth';
+import NextAuth from 'next-auth/next';
+
+const handler = NextAuth(authOptions);
+
+export { handler as GET, handler as POST };
diff --git a/apps/web/src/app/api/cookie/route.ts b/apps/web/src/app/api/cookie/route.ts
new file mode 100644
index 000000000..521c496c0
--- /dev/null
+++ b/apps/web/src/app/api/cookie/route.ts
@@ -0,0 +1,20 @@
+import { cookies } from 'next/headers';
+import { NextResponse } from 'next/server';
+
+export const dynamic = 'force-dynamic'; // defaults to auto
+export function GET(req: Request) {
+ const qwe = new URL(req.url);
+ const item = qwe.searchParams.entries();
+ const {
+ value: [key, value],
+ } = item.next();
+
+ if (key && value) {
+ cookies().set(`@mixan-${key}`, JSON.stringify(value), {
+ httpOnly: true,
+ expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
+ });
+ }
+
+ return NextResponse.json({ key, value });
+}
diff --git a/apps/web/src/app/api/fml/route.ts b/apps/web/src/app/api/fml/route.ts
new file mode 100644
index 000000000..5dd8ea536
--- /dev/null
+++ b/apps/web/src/app/api/fml/route.ts
@@ -0,0 +1,10 @@
+import { createRecentDashboard } from '@/server/services/dashboard.service';
+import { revalidatePath } from 'next/cache';
+import { NextResponse } from 'next/server';
+
+export const dynamic = 'force-dynamic'; // defaults to auto
+export async function POST(req: Request) {
+ await createRecentDashboard(await req.json());
+ revalidatePath('/', 'layout');
+ return NextResponse.json({ ok: 'qe' });
+}
diff --git a/apps/web/src/pages/api/setup.ts b/apps/web/src/app/api/setup.ts
similarity index 70%
rename from apps/web/src/pages/api/setup.ts
rename to apps/web/src/app/api/setup.ts
index f6dfd7f31..15f60e31d 100644
--- a/apps/web/src/pages/api/setup.ts
+++ b/apps/web/src/app/api/setup.ts
@@ -1,9 +1,15 @@
import { randomUUID } from 'crypto';
-import { db } from '@/server/db';
+import { db, getId } from '@/server/db';
import { handleError } from '@/server/exceptions';
import { hashPassword } from '@/server/services/hash.service';
import type { NextApiRequest, NextApiResponse } from 'next';
+const userName = 'Admin';
+const userPassword = 'password';
+const userEmail = '[email protected]';
+const organizationName = 'Acme Inc.';
+const projectName = 'Website';
+
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
@@ -22,29 +28,31 @@ export default async function handler(
const organization = await db.organization.create({
data: {
- name: 'Acme Inc.',
+ id: await getId('organization', organizationName),
+ name: organizationName,
},
});
const user = await db.user.create({
data: {
- name: 'Carl',
- password: await hashPassword('password'),
- email: '[email protected]',
+ name: userName,
+ password: await hashPassword(userPassword),
+ email: userEmail,
organization_id: organization.id,
},
});
const project = await db.project.create({
data: {
- name: 'Acme Website',
+ id: await getId('project', projectName),
+ name: projectName,
organization_id: organization.id,
},
});
const secret = randomUUID();
const client = await db.client.create({
data: {
- name: 'Acme Website Client',
+ name: `${projectName} Client`,
project_id: project.id,
organization_id: organization.id,
secret: await hashPassword(secret),
@@ -54,6 +62,7 @@ export default async function handler(
res.json({
clientId: client.id,
clientSecret: secret,
+ user,
});
} catch (error) {
handleError(res, error);
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
new file mode 100644
index 000000000..18568f6d7
--- /dev/null
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -0,0 +1,18 @@
+import { appRouter } from '@/server/api/root';
+import { getSession } from '@/server/auth';
+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
+
+const handler = (req: Request) =>
+ fetchRequestHandler({
+ endpoint: '/api/trpc',
+ req,
+ router: appRouter,
+ createContext: async () => {
+ const session = await getSession();
+ return {
+ session,
+ };
+ },
+ });
+
+export { handler as GET, handler as POST };
diff --git a/apps/web/src/app/auth.tsx b/apps/web/src/app/auth.tsx
new file mode 100644
index 000000000..d73c49093
--- /dev/null
+++ b/apps/web/src/app/auth.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { useState } from 'react';
+import { InputWithLabel } from '@/components/forms/InputWithLabel';
+import { Logo } from '@/components/Logo';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import { Widget, WidgetBody } from '@/components/Widget';
+import { zodResolver } from '@hookform/resolvers/zod';
+import { KeySquareIcon } from 'lucide-react';
+import { signIn } from 'next-auth/react';
+import Link from 'next/link';
+import { usePathname, useRouter } from 'next/navigation';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
+
+const validator = z.object({
+ email: z.string().email(),
+ password: z.string().min(6),
+});
+
+type IForm = z.infer<typeof validator>;
+export default function Auth() {
+ const form = useForm<IForm>({
+ resolver: zodResolver(validator),
+ });
+ const router = useRouter();
+ const pathname = usePathname();
+ const [state, setState] = useState<string | null>(null);
+ return (
+ <div className="flex items-center justify-center flex-col h-screen p-4">
+ <Widget className="max-w-md w-full mb-4">
+ <WidgetBody>
+ <div className="flex justify-center py-8">
+ <Logo />
+ </div>
+ <form
+ onSubmit={form.handleSubmit(async (values) => {
+ const res = await signIn('credentials', {
+ email: values.email,
+ password: values.password,
+ redirect: false,
+ }).catch(() => {
+ setState('Something went wrong. Please try again later');
+ });
+
+ if (res?.ok) {
+ router.refresh();
+ }
+
+ if (res?.status === 401) {
+ setState('Wrong email or password. Please try again');
+ }
+ })}
+ className="flex flex-col gap-4"
+ >
+ <InputWithLabel
+ label="Email"
+ placeholder="Your email"
+ error={form.formState.errors.email?.message}
+ {...form.register('email')}
+ />
+ <InputWithLabel
+ label="Password"
+ placeholder="...and your password"
+ error={form.formState.errors.password?.message}
+ {...form.register('password')}
+ />
+ {state !== null && (
+ <Alert variant="destructive">
+ <KeySquareIcon className="h-4 w-4" />
+ <AlertTitle>Failed</AlertTitle>
+ <AlertDescription>{state}</AlertDescription>
+ </Alert>
+ )}
+ <Button type="submit">Sign in</Button>
+ <Link href="/register" className="text-center text-sm">
+ No account?{' '}
+ <span className="font-medium text-blue-600">Sign up here!</span>
+ </Link>
+ </form>
+ </WidgetBody>
+ </Widget>
+ <p className="text-xs">Terms & conditions</p>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/cookie-provider.tsx b/apps/web/src/app/cookie-provider.tsx
new file mode 100644
index 000000000..06133d04c
--- /dev/null
+++ b/apps/web/src/app/cookie-provider.tsx
@@ -0,0 +1,24 @@
+import { createContext, useContext } from 'react';
+import type { RequestCookie } from 'next/dist/compiled/@edge-runtime/cookies';
+
+type ICookies = Record<string, string | null>;
+
+const context = createContext<ICookies>({});
+
+export const CookieProvider = ({
+ value,
+ children,
+}: {
+ children: React.ReactNode;
+ value: RequestCookie[];
+}) => {
+ const cookies = value.reduce((acc, cookie) => {
+ return {
+ ...acc,
+ [cookie.name]: cookie.value,
+ };
+ }, {} as ICookies);
+ return <context.Provider value={cookies}>{children}</context.Provider>;
+};
+
+export const useCookies = (): ICookies => useContext(context);
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
new file mode 100644
index 000000000..f0ef12ede
--- /dev/null
+++ b/apps/web/src/app/layout.tsx
@@ -0,0 +1,52 @@
+import { cn } from '@/utils/cn';
+import { Space_Grotesk } from 'next/font/google';
+
+import Providers from './providers';
+
+import '@/styles/globals.css';
+
+import { getSession } from '@/server/auth';
+import { cookies } from 'next/headers';
+import { redirect } from 'next/navigation';
+
+import Auth from './auth';
+
+// import { cookies } from 'next/headers';
+
+const font = Space_Grotesk({
+ subsets: ['latin'],
+ display: 'swap',
+ variable: '--text',
+});
+
+export const metadata = {};
+
+export const viewport = {
+ width: 'device-width',
+ initialScale: 1,
+ maximumScale: 1,
+ userScalable: 1,
+};
+
+export default async function RootLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const session = await getSession();
+
+ return (
+ <html lang="en" className="light">
+ <body
+ className={cn(
+ 'min-h-screen font-sans antialiased grainy bg-slate-50',
+ font.className
+ )}
+ >
+ <Providers cookies={cookies().getAll()} session={session}>
+ {session ? children : <Auth />}
+ </Providers>
+ </body>
+ </html>
+ );
+}
diff --git a/apps/web/src/app/providers.tsx b/apps/web/src/app/providers.tsx
new file mode 100644
index 000000000..b367014e0
--- /dev/null
+++ b/apps/web/src/app/providers.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import React, { useRef, useState } from 'react';
+import { api } from '@/app/_trpc/client';
+import { Toaster } from '@/components/ui/toaster';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { ModalProvider } from '@/modals';
+import type { AppStore } from '@/redux';
+import makeStore from '@/redux';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { httpBatchLink } from '@trpc/client';
+import type { Session } from 'next-auth';
+import { SessionProvider } from 'next-auth/react';
+import type { RequestCookie } from 'next/dist/compiled/@edge-runtime/cookies';
+import { Provider as ReduxProvider } from 'react-redux';
+import superjson from 'superjson';
+
+import { CookieProvider } from './cookie-provider';
+
+export default function Providers({
+ children,
+ session,
+ cookies,
+}: {
+ children: React.ReactNode;
+ session: Session | null;
+ cookies: RequestCookie[];
+}) {
+ const [queryClient] = useState(
+ () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ refetchOnMount: true,
+ refetchOnWindowFocus: false,
+ },
+ },
+ })
+ );
+ const [trpcClient] = useState(() =>
+ api.createClient({
+ transformer: superjson,
+ links: [
+ httpBatchLink({
+ url: 'http://localhost:3000/api/trpc',
+ }),
+ ],
+ })
+ );
+
+ const storeRef = useRef<AppStore>();
+ if (!storeRef.current) {
+ // Create the store instance the first time this renders
+ storeRef.current = makeStore();
+ }
+
+ return (
+ <SessionProvider session={session}>
+ <ReduxProvider store={storeRef.current}>
+ <api.Provider client={trpcClient} queryClient={queryClient}>
+ <QueryClientProvider client={queryClient}>
+ <TooltipProvider delayDuration={200}>
+ <CookieProvider value={cookies}>{children}</CookieProvider>
+ <Toaster />
+ <ModalProvider />
+ </TooltipProvider>
+ </QueryClientProvider>
+ </api.Provider>
+ </ReduxProvider>
+ </SessionProvider>
+ );
+}
diff --git a/apps/web/src/components/Card.tsx b/apps/web/src/components/Card.tsx
index f4ce40904..281856a12 100644
--- a/apps/web/src/components/Card.tsx
+++ b/apps/web/src/components/Card.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import {
DropdownMenu,
DropdownMenuContent,
@@ -17,7 +19,7 @@ export function Card({ children, hover, className }: CardProps) {
return (
<div
className={cn(
- 'border border-border rounded relative',
+ 'border border-border rounded relative bg-white',
hover && 'transition-all hover:shadow hover:border-black',
className
)}
diff --git a/apps/web/src/components/Content.tsx b/apps/web/src/components/Content.tsx
index 73dfe3701..2e7a736ea 100644
--- a/apps/web/src/components/Content.tsx
+++ b/apps/web/src/components/Content.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import { cn } from '@/utils/cn';
interface ContentHeaderProps {
diff --git a/apps/web/src/components/DataTable.tsx b/apps/web/src/components/DataTable.tsx
index 385dffd04..a4f244184 100644
--- a/apps/web/src/components/DataTable.tsx
+++ b/apps/web/src/components/DataTable.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import {
flexRender,
getCoreRowModel,
diff --git a/apps/web/src/components/Logo.tsx b/apps/web/src/components/Logo.tsx
new file mode 100644
index 000000000..08be41bdd
--- /dev/null
+++ b/apps/web/src/components/Logo.tsx
@@ -0,0 +1,8 @@
+export function Logo() {
+ return (
+ <div className="text-xl flex gap-2 items-center">
+ <img src="/logo.svg" className="w-8 rounded-lg" />
+ <span className="relative -top-0.5">openpanel</span>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/Pagination.tsx b/apps/web/src/components/Pagination.tsx
index a2fc8efe8..2193e95b6 100644
--- a/apps/web/src/components/Pagination.tsx
+++ b/apps/web/src/components/Pagination.tsx
@@ -12,6 +12,7 @@ export function usePagination(take = 100) {
take,
canPrev: skip > 0,
canNext: true,
+ page: skip / take + 1,
}),
[skip, setSkip, take]
);
@@ -21,7 +22,8 @@ export type PaginationProps = ReturnType<typeof usePagination>;
export function Pagination(props: PaginationProps) {
return (
- <div className="flex select-none items-center justify-end space-x-2 py-4">
+ <div className="flex select-none items-center justify-end gap-2">
+ <div className="font-medium text-xs">Page: {props.page}</div>
<Button
variant="outline"
size="sm"
diff --git a/apps/web/src/components/Syntax.tsx b/apps/web/src/components/Syntax.tsx
index 347df66bc..d12814a10 100644
--- a/apps/web/src/components/Syntax.tsx
+++ b/apps/web/src/components/Syntax.tsx
@@ -1,3 +1,5 @@
+'use client';
+
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';
diff --git a/apps/web/src/components/Widget.tsx b/apps/web/src/components/Widget.tsx
new file mode 100644
index 000000000..1e1deb5f6
--- /dev/null
+++ b/apps/web/src/components/Widget.tsx
@@ -0,0 +1,43 @@
+import { cn } from '@/utils/cn';
+
+interface WidgetHeadProps {
+ children: React.ReactNode;
+ className?: string;
+}
+export function WidgetHead({ children, className }: WidgetHeadProps) {
+ return (
+ <div
+ className={cn(
+ 'p-4 border-b border-border [&_.title]:font-medium',
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+interface WidgetBodyProps {
+ children: React.ReactNode;
+ className?: string;
+}
+export function WidgetBody({ children, className }: WidgetBodyProps) {
+ return <div className={cn('p-4', className)}>{children}</div>;
+}
+
+interface WidgetProps {
+ children: React.ReactNode;
+ className?: string;
+}
+export function Widget({ children, className }: WidgetProps) {
+ return (
+ <div
+ className={cn(
+ 'border border-border rounded-md bg-white self-start',
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/clients/ClientActions.tsx b/apps/web/src/components/clients/ClientActions.tsx
index 3198ec014..ba02ff466 100644
--- a/apps/web/src/components/clients/ClientActions.tsx
+++ b/apps/web/src/components/clients/ClientActions.tsx
@@ -1,9 +1,11 @@
-import { useRefetchActive } from '@/hooks/useRefetchActive';
+'use client';
+
+import { api } from '@/app/_trpc/client';
import { pushModal, showConfirm } from '@/modals';
import type { IClientWithProject } from '@/types';
-import { api } from '@/utils/api';
import { clipboard } from '@/utils/clipboard';
import { MoreHorizontal } from 'lucide-react';
+import { useRouter } from 'next/navigation';
import { Button } from '../ui/button';
import {
@@ -16,15 +18,16 @@ import {
} from '../ui/dropdown-menu';
import { toast } from '../ui/use-toast';
-export function ClientActions({ id }: IClientWithProject) {
- const refetch = useRefetchActive();
+export function ClientActions(client: IClientWithProject) {
+ const { id } = client;
+ const router = useRouter();
const deletion = api.client.remove.useMutation({
onSuccess() {
toast({
title: 'Success',
description: 'Client revoked, incoming requests will be rejected.',
});
- refetch();
+ router.refresh();
},
});
return (
@@ -42,7 +45,7 @@ export function ClientActions({ id }: IClientWithProject) {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
- pushModal('EditClient', { id });
+ pushModal('EditClient', client);
}}
>
Edit
diff --git a/apps/web/src/components/events/EventsTable.tsx b/apps/web/src/components/events/EventsTable.tsx
deleted file mode 100644
index c9b92209a..000000000
--- a/apps/web/src/components/events/EventsTable.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { useMemo } from 'react';
-import { DataTable } from '@/components/DataTable';
-import { Avatar, AvatarFallback } from '@/components/ui/avatar';
-import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import type { RouterOutputs } from '@/utils/api';
-import { formatDateTime } from '@/utils/date';
-import { toDots } from '@/utils/object';
-import { AvatarImage } from '@radix-ui/react-avatar';
-import { createColumnHelper } from '@tanstack/react-table';
-import Link from 'next/link';
-
-const columnHelper =
- createColumnHelper<RouterOutputs['event']['list'][number]>();
-
-interface EventsTableProps {
- data: RouterOutputs['event']['list'];
-}
-
-export function EventsTable({ data }: EventsTableProps) {
- const params = useOrganizationParams();
- const columns = useMemo(() => {
- return [
- columnHelper.accessor((row) => row.createdAt, {
- id: 'createdAt',
- header: () => 'Created At',
- cell(info) {
- return formatDateTime(info.getValue());
- },
- footer: () => 'Created At',
- }),
- columnHelper.accessor((row) => row.name, {
- id: 'event',
- header: () => 'Event',
- cell(info) {
- return <span className="font-medium">{info.getValue()}</span>;
- },
- footer: () => 'Created At',
- }),
- columnHelper.accessor((row) => row.profile, {
- id: 'profile',
- header: () => 'Profile',
- cell(info) {
- const profile = info.getValue();
- return (
- <Link
- shallow
- href={`/${params.organization}/${params.project}/profiles/${profile?.id}`}
- className="flex items-center gap-2"
- >
- <Avatar className="h-6 w-6">
- {profile?.avatar && <AvatarImage src={profile.avatar} />}
- <AvatarFallback className="text-xs">
- {profile?.first_name?.at(0)}
- </AvatarFallback>
- </Avatar>
- {`${profile?.first_name} ${profile?.last_name ?? ''}`}
- </Link>
- );
- },
- footer: () => 'Created At',
- }),
- columnHelper.accessor((row) => row.properties, {
- id: 'properties',
- header: () => 'Properties',
- cell(info) {
- const dots = toDots(info.getValue() as Record<string, any>);
- return (
- <Table className="mini">
- <TableBody>
- {Object.keys(dots).map((key) => {
- return (
- <TableRow key={key}>
- <TableCell className="font-medium">{key}</TableCell>
- <TableCell>
- {typeof dots[key] === 'boolean'
- ? dots[key]
- ? 'true'
- : 'false'
- : dots[key]}
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- );
- },
- footer: () => 'Created At',
- }),
- ];
- }, [params]);
-
- return <DataTable data={data} columns={columns} />;
-}
diff --git a/apps/web/src/components/events/ListProperties.tsx b/apps/web/src/components/events/ListProperties.tsx
new file mode 100644
index 000000000..d5020ba5e
--- /dev/null
+++ b/apps/web/src/components/events/ListProperties.tsx
@@ -0,0 +1,35 @@
+import { toDots } from '@/utils/object';
+
+import { Table, TableBody, TableCell, TableRow } from '../ui/table';
+
+interface ListPropertiesProps {
+ data: any;
+ className?: string;
+}
+
+export function ListProperties({
+ data,
+ className = 'mini',
+}: ListPropertiesProps) {
+ const dots = toDots(data);
+ return (
+ <Table className={className}>
+ <TableBody>
+ {Object.keys(dots).map((key) => {
+ return (
+ <TableRow key={key}>
+ <TableCell className="font-medium">{key}</TableCell>
+ <TableCell>
+ {typeof dots[key] === 'boolean'
+ ? dots[key]
+ ? 'true'
+ : 'false'
+ : dots[key]}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ );
+}
diff --git a/apps/web/src/components/forms/InputWithLabel.tsx b/apps/web/src/components/forms/InputWithLabel.tsx
index 47df69dfa..32fbbdb16 100644
--- a/apps/web/src/components/forms/InputWithLabel.tsx
+++ b/apps/web/src/components/forms/InputWithLabel.tsx
@@ -6,15 +6,23 @@ import { Label } from '../ui/label';
type InputWithLabelProps = InputProps & {
label: string;
+ error?: string | undefined;
};
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
({ label, className, ...props }, ref) => {
return (
<div className={className}>
- <Label htmlFor={label} className="block mb-2">
- {label}
- </Label>
+ <div className="block mb-2 flex justify-between">
+ <Label className="mb-0" htmlFor={label}>
+ {label}
+ </Label>
+ {props.error && (
+ <span className="text-sm text-destructive leading-none">
+ {props.error}
+ </span>
+ )}
+ </div>
<Input ref={ref} id={label} {...props} />
</div>
);
diff --git a/apps/web/src/components/general/ExpandableListItem.tsx b/apps/web/src/components/general/ExpandableListItem.tsx
new file mode 100644
index 000000000..5b676540d
--- /dev/null
+++ b/apps/web/src/components/general/ExpandableListItem.tsx
@@ -0,0 +1,54 @@
+import React, { useState } from 'react';
+import { cn } from '@/utils/cn';
+import { ChevronUp } from 'lucide-react';
+import AnimateHeight from 'react-animate-height';
+
+import { Button } from '../ui/button';
+
+interface ExpandableListItemProps {
+ children: React.ReactNode;
+ bullets: React.ReactNode[];
+ title: string;
+ image?: React.ReactNode;
+ initialOpen?: boolean;
+}
+export function ExpandableListItem({
+ title,
+ bullets,
+ image,
+ initialOpen = false,
+ children,
+}: ExpandableListItemProps) {
+ const [open, setOpen] = useState(initialOpen ?? false);
+ return (
+ <div className="bg-white shadow rounded-xl overflow-hidden">
+ <div className="p-3 sm:p-6 flex gap-4 items-start">
+ <div className="flex gap-1">{image}</div>
+ <div className="flex flex-col flex-1 gap-1 min-w-0">
+ <span className="text-lg font-medium leading-none mb-1">{title}</span>
+ <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-sm text-muted-foreground">
+ {bullets.map((bullet) => (
+ <span key={bullet}>{bullet}</span>
+ ))}
+ </div>
+ </div>
+ <Button
+ variant="secondary"
+ size="icon"
+ onClick={() => setOpen((p) => !p)}
+ >
+ <ChevronUp
+ size={20}
+ className={cn(
+ 'transition-transform',
+ open ? 'rotate-180' : 'rotate-0'
+ )}
+ />
+ </Button>
+ </div>
+ <AnimateHeight duration={200} height={open ? 'auto' : 0}>
+ <div className="border-t border-border">{children}</div>
+ </AnimateHeight>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layouts/MainLayout.tsx b/apps/web/src/components/layouts/MainLayout.tsx
deleted file mode 100644
index 49ed82e75..000000000
--- a/apps/web/src/components/layouts/MainLayout.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useState } from 'react';
-import { cn } from '@/utils/cn';
-import { MenuIcon } from 'lucide-react';
-import Link from 'next/link';
-
-import { Container } from '../Container';
-import { Breadcrumbs } from '../navbar/Breadcrumbs';
-import { NavbarMenu } from '../navbar/NavbarMenu';
-
-interface MainLayoutProps {
- children: React.ReactNode;
- className?: string;
-}
-
-export function MainLayout({ children, className }: MainLayoutProps) {
- const [visible, setVisible] = useState(false);
- 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 shallow href="/" className="text-3xl">
- mixan
- </Link>
- <div
- className={cn(
- 'flex items-center gap-8 z-50',
- visible === false && 'max-sm:hidden',
- visible === true &&
- 'max-sm:flex max-sm:flex-col max-sm:absolute max-sm:inset-0 max-sm:bg-white max-sm:justify-center max-sm:top-4 max-sm:shadow-lg'
- )}
- >
- <NavbarMenu />
- </div>
- <button
- className={cn(
- 'px-4 sm:hidden absolute z-50 top-9 right-4 transition-all',
- visible === true && 'rotate-90'
- )}
- onClick={() => {
- setVisible((p) => !p);
- }}
- >
- <MenuIcon />
- </button>
- </Container>
- </nav>
- <Breadcrumbs />
- <main className={cn(className, 'mb-8')}>{children}</main>
- </>
- );
-}
diff --git a/apps/web/src/components/layouts/SettingsLayout.tsx b/apps/web/src/components/layouts/SettingsLayout.tsx
deleted file mode 100644
index 7c495b6af..000000000
--- a/apps/web/src/components/layouts/SettingsLayout.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { cn } from '@/utils/cn';
-import Link from 'next/link';
-import { usePathname } from 'next/navigation';
-
-import { Container } from '../Container';
-import { PageTitle } from '../PageTitle';
-import { Sidebar, WithSidebar } from '../WithSidebar';
-import { MainLayout } from './MainLayout';
-
-interface 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
- shallow
- key={href}
- href={href}
- className={cn(
- 'p-4 py-3 leading-none rounded-lg transition-colors',
- pathname.startsWith(href)
- ? 'bg-slate-100'
- : 'hover:bg-slate-100'
- )}
- >
- {label}
- </Link>
- ))}
- </Sidebar>
- <div className={cn('flex flex-col', className)}>{children}</div>
- </WithSidebar>
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/components/navbar/Breadcrumbs.tsx b/apps/web/src/components/navbar/Breadcrumbs.tsx
index 88a67fcf4..983b1baf6 100644
--- a/apps/web/src/components/navbar/Breadcrumbs.tsx
+++ b/apps/web/src/components/navbar/Breadcrumbs.tsx
@@ -1,5 +1,5 @@
+import { api } from '@/app/_trpc/client';
import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { api } from '@/utils/api';
import { ChevronRight, HomeIcon } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
@@ -11,30 +11,30 @@ export function Breadcrumbs() {
const org = api.organization.get.useQuery(
{
- slug: params.organization,
+ id: params.organizationId,
},
{
- enabled: !!params.organization,
+ enabled: !!params.organizationId,
staleTime: Infinity,
}
);
const pro = api.project.get.useQuery(
{
- slug: params.project,
+ id: params.projectId,
},
{
- enabled: !!params.project,
+ enabled: !!params.projectId,
staleTime: Infinity,
}
);
const dashboard = api.dashboard.get.useQuery(
{
- slug: params.dashboard,
+ id: params.dashboardId,
},
{
- enabled: !!params.dashboard,
+ enabled: !!params.dashboardId,
staleTime: Infinity,
}
);
@@ -48,7 +48,7 @@ export function Breadcrumbs() {
{org.data && (
<>
<HomeIcon size={14} />
- <Link shallow href={`/${org.data.slug}`}>
+ <Link shallow href={`/${org.data.id}`}>
{org.data.name}
</Link>
</>
@@ -57,7 +57,7 @@ export function Breadcrumbs() {
{org.data && pro.data && (
<>
<ChevronRight size={10} />
- <Link shallow href={`/${org.data.slug}/${pro.data.slug}`}>
+ <Link shallow href={`/${org.data.id}/${pro.data.id}`}>
{pro.data.name}
</Link>
</>
@@ -68,7 +68,7 @@ export function Breadcrumbs() {
<ChevronRight size={10} />
<Link
shallow
- href={`/${org.data.slug}/${pro.data.slug}/${dashboard.data.slug}`}
+ href={`/${org.data.id}/${pro.data.id}/${dashboard.data.id}`}
>
{dashboard.data.name}
</Link>
diff --git a/apps/web/src/components/navbar/NavbarCreate.tsx b/apps/web/src/components/navbar/NavbarCreate.tsx
index ae1ca0c96..50a28d1ce 100644
--- a/apps/web/src/components/navbar/NavbarCreate.tsx
+++ b/apps/web/src/components/navbar/NavbarCreate.tsx
@@ -25,7 +25,7 @@ export function NavbarCreate() {
<DropdownMenuItem asChild>
<Link
shallow
- href={`/${params.organization}/${params.project}/reports`}
+ href={`/${params.organizationId}/${params.projectId}/reports`}
>
<LineChart className="mr-2 h-4 w-4" />
<span>Create a report</span>
diff --git a/apps/web/src/components/navbar/NavbarMenu.tsx b/apps/web/src/components/navbar/NavbarMenu.tsx
index 08760372e..374dad6e7 100644
--- a/apps/web/src/components/navbar/NavbarMenu.tsx
+++ b/apps/web/src/components/navbar/NavbarMenu.tsx
@@ -26,27 +26,27 @@ export function NavbarMenu() {
const params = useOrganizationParams();
return (
<div className={cn('flex gap-1 items-center text-sm', 'max-sm:flex-col')}>
- {params.project && (
- <Item href={`/${params.organization}/${params.project}`}>
+ {params.projectId && (
+ <Item href={`/${params.organizationId}/${params.projectId}`}>
Dashboards
</Item>
)}
- {params.project && (
- <Item href={`/${params.organization}/${params.project}/events`}>
+ {params.projectId && (
+ <Item href={`/${params.organizationId}/${params.projectId}/events`}>
Events
</Item>
)}
- {params.project && (
- <Item href={`/${params.organization}/${params.project}/profiles`}>
+ {params.projectId && (
+ <Item href={`/${params.organizationId}/${params.projectId}/profiles`}>
Profiles
</Item>
)}
- {params.project && (
+ {params.projectId && (
<Item
href={{
- pathname: `/${params.organization}/${params.project}/reports`,
+ pathname: `/${params.organizationId}/${params.projectId}/reports`,
query: strip({
- dashboard: params.dashboard,
+ dashboardId: params.dashboardId,
}),
}}
>
diff --git a/apps/web/src/components/navbar/NavbarUserDropdown.tsx b/apps/web/src/components/navbar/NavbarUserDropdown.tsx
index 323ef5df9..5ac5eb2c3 100644
--- a/apps/web/src/components/navbar/NavbarUserDropdown.tsx
+++ b/apps/web/src/components/navbar/NavbarUserDropdown.tsx
@@ -28,7 +28,7 @@ export function NavbarUserDropdown() {
<DropdownMenuGroup>
<DropdownMenuItem asChild className="cursor-pointer">
<Link
- href={`/${params.organization}/settings/organization`}
+ href={`/${params.organizationId}/settings/organization`}
shallow
>
<User className="mr-2 h-4 w-4" />
@@ -36,19 +36,19 @@ export function NavbarUserDropdown() {
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
- <Link href={`/${params.organization}/settings/projects`} shallow>
+ <Link href={`/${params.organizationId}/settings/projects`} shallow>
<User className="mr-2 h-4 w-4" />
Projects
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
- <Link href={`/${params.organization}/settings/clients`} shallow>
+ <Link href={`/${params.organizationId}/settings/clients`} shallow>
<User className="mr-2 h-4 w-4" />
Clients
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild className="cursor-pointer">
- <Link href={`/${params.organization}/settings/profile`} shallow>
+ <Link href={`/${params.organizationId}/settings/profile`} shallow>
<User className="mr-2 h-4 w-4" />
Profile
</Link>
diff --git a/apps/web/src/components/profiles/ProfileAvatar.tsx b/apps/web/src/components/profiles/ProfileAvatar.tsx
new file mode 100644
index 000000000..385d841e9
--- /dev/null
+++ b/apps/web/src/components/profiles/ProfileAvatar.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import type { IServiceProfile } from '@/server/services/profile.service';
+import { cn } from '@/utils/cn';
+import { AvatarImage } from '@radix-ui/react-avatar';
+import type { VariantProps } from 'class-variance-authority';
+import { cva } from 'class-variance-authority';
+
+import { Avatar, AvatarFallback } from '../ui/avatar';
+
+interface ProfileAvatarProps
+ extends VariantProps<typeof variants>,
+ Partial<Pick<IServiceProfile, 'avatar' | 'first_name'>> {
+ className?: string;
+}
+
+const variants = cva('', {
+ variants: {
+ size: {
+ default: 'h-12 w-12 rounded-xl [&>span]:rounded-xl',
+ sm: 'h-6 w-6 rounded [&>span]:rounded',
+ xs: 'h-4 w-4 rounded [&>span]:rounded',
+ },
+ },
+ defaultVariants: {
+ size: 'default',
+ },
+});
+
+export function ProfileAvatar({
+ avatar,
+ first_name,
+ className,
+ size,
+}: ProfileAvatarProps) {
+ return (
+ <Avatar className={cn(variants({ className, size }), className)}>
+ {avatar && <AvatarImage src={avatar} />}
+ <AvatarFallback
+ className={cn(
+ size === 'sm'
+ ? 'text-xs'
+ : size === 'xs'
+ ? 'text-[8px]'
+ : 'text-base',
+ 'bg-slate-200 text-slate-800'
+ )}
+ >
+ {first_name?.at(0) ?? '🫣'}
+ </AvatarFallback>
+ </Avatar>
+ );
+}
diff --git a/apps/web/src/components/projects/ProjectActions.tsx b/apps/web/src/components/projects/ProjectActions.tsx
index 99c78cedd..1b104d22b 100644
--- a/apps/web/src/components/projects/ProjectActions.tsx
+++ b/apps/web/src/components/projects/ProjectActions.tsx
@@ -1,9 +1,11 @@
-import { useRefetchActive } from '@/hooks/useRefetchActive';
+'use client';
+
+import { api } from '@/app/_trpc/client';
import { pushModal, showConfirm } from '@/modals';
import type { IProject } from '@/types';
-import { api } from '@/utils/api';
import { clipboard } from '@/utils/clipboard';
import { MoreHorizontal } from 'lucide-react';
+import { useRouter } from 'next/navigation';
import { Button } from '../ui/button';
import {
@@ -16,15 +18,16 @@ import {
} from '../ui/dropdown-menu';
import { toast } from '../ui/use-toast';
-export function ProjectActions({ id }: IProject) {
- const refetch = useRefetchActive();
+export function ProjectActions(project: IProject) {
+ const { id } = project;
+ const router = useRouter();
const deletion = api.project.remove.useMutation({
onSuccess() {
toast({
title: 'Success',
description: 'Project deleted successfully.',
});
- refetch();
+ router.refresh();
},
});
@@ -43,7 +46,7 @@ export function ProjectActions({ id }: IProject) {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
- pushModal('EditProject', { id });
+ pushModal('EditProject', project);
}}
>
Edit
diff --git a/apps/web/src/components/projects/table.tsx b/apps/web/src/components/projects/table.tsx
index abb4813d8..bff79da3c 100644
--- a/apps/web/src/components/projects/table.tsx
+++ b/apps/web/src/components/projects/table.tsx
@@ -1,3 +1,4 @@
+import { IServiceProject } from '@/server/services/project.service';
import { formatDate } from '@/utils/date';
import type { ColumnDef } from '@tanstack/react-table';
@@ -6,7 +7,6 @@ import type { Project as IProject } from '@mixan/db';
import { ProjectActions } from './ProjectActions';
export type Project = IProject;
-
export const columns: ColumnDef<Project>[] = [
{
accessorKey: 'name',
diff --git a/apps/web/src/components/report/ReportChartType.tsx b/apps/web/src/components/report/ReportChartType.tsx
index 2e3a632f9..c2c316fb4 100644
--- a/apps/web/src/components/report/ReportChartType.tsx
+++ b/apps/web/src/components/report/ReportChartType.tsx
@@ -1,23 +1,27 @@
import { useDispatch, useSelector } from '@/redux';
-import type { IChartType } from '@/types';
import { chartTypes } from '@/utils/constants';
+import { objectToZodEnums } from '@/utils/validation';
import { Combobox } from '../ui/combobox';
import { changeChartType } from './reportSlice';
-export function ReportChartType() {
+interface ReportChartTypeProps {
+ className?: string;
+}
+export function ReportChartType({ className }: ReportChartTypeProps) {
const dispatch = useDispatch();
const type = useSelector((state) => state.report.chartType);
return (
<Combobox
+ className={className}
placeholder="Chart type"
onChange={(value) => {
- dispatch(changeChartType(value as IChartType));
+ dispatch(changeChartType(value));
}}
value={type}
- items={Object.entries(chartTypes).map(([key, value]) => ({
- label: value,
+ items={objectToZodEnums(chartTypes).map((key) => ({
+ label: chartTypes[key],
value: key,
}))}
/>
diff --git a/apps/web/src/components/report/ReportInterval.tsx b/apps/web/src/components/report/ReportInterval.tsx
index 60eadff4d..fbfe8a2a8 100644
--- a/apps/web/src/components/report/ReportInterval.tsx
+++ b/apps/web/src/components/report/ReportInterval.tsx
@@ -1,21 +1,28 @@
import { useDispatch, useSelector } from '@/redux';
import type { IInterval } from '@/types';
-import { isMinuteIntervalEnabledByRange } from '@/utils/constants';
+import {
+ isHourIntervalEnabledByRange,
+ isMinuteIntervalEnabledByRange,
+} from '@/utils/constants';
import { Combobox } from '../ui/combobox';
import { changeInterval } from './reportSlice';
-export function ReportInterval() {
+interface ReportIntervalProps {
+ className?: string;
+}
+export function ReportInterval({ className }: ReportIntervalProps) {
const dispatch = useDispatch();
const interval = useSelector((state) => state.report.interval);
const range = useSelector((state) => state.report.range);
const chartType = useSelector((state) => state.report.chartType);
- if (chartType !== 'linear') {
+ if (chartType !== 'linear' && chartType !== 'histogram') {
return null;
}
return (
<Combobox
+ className={className}
placeholder="Interval"
onChange={(value) => {
dispatch(changeInterval(value as IInterval));
@@ -30,6 +37,7 @@ export function ReportInterval() {
{
value: 'hour',
label: 'Hour',
+ disabled: !isHourIntervalEnabledByRange(range),
},
{
value: 'day',
diff --git a/apps/web/src/components/report/ReportLineType.tsx b/apps/web/src/components/report/ReportLineType.tsx
new file mode 100644
index 000000000..fa74f2be9
--- /dev/null
+++ b/apps/web/src/components/report/ReportLineType.tsx
@@ -0,0 +1,34 @@
+import { useDispatch, useSelector } from '@/redux';
+import { lineTypes } from '@/utils/constants';
+import { objectToZodEnums } from '@/utils/validation';
+
+import { Combobox } from '../ui/combobox';
+import { changeLineType } from './reportSlice';
+
+interface ReportLineTypeProps {
+ className?: string;
+}
+export function ReportLineType({ className }: ReportLineTypeProps) {
+ const dispatch = useDispatch();
+ const chartType = useSelector((state) => state.report.chartType);
+ const type = useSelector((state) => state.report.lineType);
+
+ if (chartType != 'linear' && chartType != 'area') {
+ return null;
+ }
+
+ return (
+ <Combobox
+ className={className}
+ placeholder="Line type"
+ onChange={(value) => {
+ dispatch(changeLineType(value));
+ }}
+ value={type}
+ items={objectToZodEnums(lineTypes).map((key) => ({
+ label: lineTypes[key],
+ value: key,
+ }))}
+ />
+ );
+}
diff --git a/apps/web/src/components/report/ReportSaveButton.tsx b/apps/web/src/components/report/ReportSaveButton.tsx
index 03cdc067a..4a9b5b49c 100644
--- a/apps/web/src/components/report/ReportSaveButton.tsx
+++ b/apps/web/src/components/report/ReportSaveButton.tsx
@@ -1,15 +1,20 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
import { pushModal } from '@/modals';
import { useDispatch, useSelector } from '@/redux';
-import { api, handleError } from '@/utils/api';
import { SaveIcon } from 'lucide-react';
+import { useParams } from 'next/navigation';
-import { useReportId } from './hooks/useReportId';
import { resetDirty } from './reportSlice';
-export function ReportSaveButton() {
- const { reportId } = useReportId();
+interface ReportSaveButtonProps {
+ className?: string;
+}
+export function ReportSaveButton({ className }: ReportSaveButtonProps) {
+ const { reportId } = useParams();
const dispatch = useDispatch();
const update = api.report.update.useMutation({
onSuccess() {
@@ -26,11 +31,12 @@ export function ReportSaveButton() {
if (reportId) {
return (
<Button
+ className={className}
disabled={!report.dirty}
loading={update.isLoading}
onClick={() => {
update.mutate({
- reportId,
+ reportId: reportId as string,
report,
});
}}
@@ -42,6 +48,7 @@ export function ReportSaveButton() {
} else {
return (
<Button
+ className={className}
disabled={!report.dirty}
onClick={() => {
pushModal('SaveReport', {
diff --git a/apps/web/src/components/report/chart/ChartAnimation.tsx b/apps/web/src/components/report/chart/ChartAnimation.tsx
index 7d30102ff..d9d48c0b4 100644
--- a/apps/web/src/components/report/chart/ChartAnimation.tsx
+++ b/apps/web/src/components/report/chart/ChartAnimation.tsx
@@ -24,6 +24,9 @@ export const ChartAnimationContainer = (
) => (
<div
{...props}
- className={cn('border border-border rounded-md p-8', props.className)}
+ className={cn(
+ 'border border-border rounded-md p-8 bg-white',
+ props.className
+ )}
/>
);
diff --git a/apps/web/src/components/report/chart/LazyChart.tsx b/apps/web/src/components/report/chart/LazyChart.tsx
index 10eb95ddb..9a9a3066a 100644
--- a/apps/web/src/components/report/chart/LazyChart.tsx
+++ b/apps/web/src/components/report/chart/LazyChart.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import React, { useEffect, useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
diff --git a/apps/web/src/components/report/chart/ReportAreaChart.tsx b/apps/web/src/components/report/chart/ReportAreaChart.tsx
new file mode 100644
index 000000000..b6e64fc89
--- /dev/null
+++ b/apps/web/src/components/report/chart/ReportAreaChart.tsx
@@ -0,0 +1,104 @@
+import type { IChartData } from '@/app/_trpc/client';
+import { AutoSizer } from '@/components/AutoSizer';
+import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
+import { useRechartDataModel } from '@/hooks/useRechartDataModel';
+import { useVisibleSeries } from '@/hooks/useVisibleSeries';
+import type { IChartLineType, IInterval } from '@/types';
+import { cn } from '@/utils/cn';
+import { getChartColor } from '@/utils/theme';
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from 'recharts';
+
+import { getYAxisWidth } from './chart-utils';
+import { useChartContext } from './ChartProvider';
+import { ReportChartTooltip } from './ReportChartTooltip';
+import { ReportTable } from './ReportTable';
+
+interface ReportAreaChartProps {
+ data: IChartData;
+ interval: IInterval;
+ lineType: IChartLineType;
+}
+
+export function ReportAreaChart({
+ lineType,
+ interval,
+ data,
+}: ReportAreaChartProps) {
+ const { editMode } = useChartContext();
+ const { series, setVisibleSeries } = useVisibleSeries(data);
+ const formatDate = useFormatDateInterval(interval);
+ const rechartData = useRechartDataModel(data);
+
+ return (
+ <>
+ <div
+ className={cn(
+ 'max-sm:-mx-3',
+ editMode && 'border border-border bg-white rounded-md p-4'
+ )}
+ >
+ <AutoSizer disableHeight>
+ {({ width }) => (
+ <AreaChart
+ width={width}
+ height={Math.min(Math.max(width * 0.5, 250), 400)}
+ data={rechartData}
+ >
+ <Tooltip content={<ReportChartTooltip />} />
+ <XAxis
+ axisLine={false}
+ fontSize={12}
+ dataKey="date"
+ tickFormatter={(m: string) => formatDate(m)}
+ tickLine={false}
+ allowDuplicatedCategory={false}
+ />
+ <YAxis
+ width={getYAxisWidth(data.metrics.max)}
+ fontSize={12}
+ axisLine={false}
+ tickLine={false}
+ allowDecimals={false}
+ />
+
+ {series.map((serie) => {
+ return (
+ <Area
+ key={serie.name}
+ type={lineType}
+ isAnimationActive={false}
+ strokeWidth={0}
+ dataKey={`${serie.index}:count`}
+ stroke={getChartColor(serie.index)}
+ fill={getChartColor(serie.index)}
+ stackId={'1'}
+ fillOpacity={1}
+ />
+ );
+ })}
+ <CartesianGrid
+ strokeDasharray="3 3"
+ horizontal={true}
+ vertical={false}
+ />
+ </AreaChart>
+ )}
+ </AutoSizer>
+ </div>
+ {editMode && (
+ <ReportTable
+ data={data}
+ visibleSeries={series}
+ setVisibleSeries={setVisibleSeries}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/web/src/components/report/chart/ReportBarChart.tsx b/apps/web/src/components/report/chart/ReportBarChart.tsx
index 5581ea260..a433fd4e4 100644
--- a/apps/web/src/components/report/chart/ReportBarChart.tsx
+++ b/apps/web/src/components/report/chart/ReportBarChart.tsx
@@ -1,4 +1,5 @@
import { useMemo, useState } from 'react';
+import type { IChartData, RouterOutputs } from '@/app/_trpc/client';
import { ColorSquare } from '@/components/ColorSquare';
import {
Table,
@@ -8,8 +9,6 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/table';
-import type { IChartData } from '@/types';
-import type { RouterOutputs } from '@/utils/api';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
import {
@@ -36,6 +35,7 @@ export function ReportBarChart({ data }: ReportBarChartProps) {
const { editMode } = useChartContext();
const [ref, { width }] = useElementSize();
const [sorting, setSorting] = useState<SortingState>([]);
+ const maxCount = Math.max(...data.series.map((serie) => serie.metrics.sum));
const table = useReactTable({
data: useMemo(
() => (editMode ? data.series : data.series.slice(0, 20)),
@@ -57,7 +57,7 @@ export function ReportBarChart({ data }: ReportBarChartProps) {
footer: (info) => info.column.id,
size: width ? width * 0.3 : undefined,
}),
- columnHelper.accessor((row) => row.metrics.total, {
+ columnHelper.accessor((row) => row.metrics.sum, {
id: 'totalCount',
cell: (info) => (
<div className="text-right font-medium">{info.getValue()}</div>
@@ -67,15 +67,13 @@ export function ReportBarChart({ data }: ReportBarChartProps) {
size: width ? width * 0.1 : undefined,
enableSorting: true,
}),
- columnHelper.accessor((row) => row.metrics.total, {
+ columnHelper.accessor((row) => row.metrics.sum, {
id: 'graph',
cell: (info) => (
<div
className="shine h-4 rounded [.mini_&]:h-3"
style={{
- width:
- (info.getValue() / info.row.original.meta.highest) * 100 +
- '%',
+ width: (info.getValue() / maxCount) * 100 + '%',
background: getChartColor(info.row.index),
}}
/>
@@ -93,30 +91,10 @@ export function ReportBarChart({ data }: ReportBarChartProps) {
getCoreRowModel: getCoreRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
- // debugTable: true,
- // debugHeaders: true,
- // debugColumns: true,
});
+
return (
<div ref={ref}>
- {editMode && (
- <div className="mb-8 flex flex-wrap gap-4">
- {data.events.map((event) => {
- return (
- <div className="border border-border p-4" key={event.id}>
- <div className="flex items-center gap-2 text-lg font-medium">
- <ColorSquare>{event.id}</ColorSquare> {event.name}
- </div>
- <div className="mt-6 font-mono text-5xl font-light">
- {new Intl.NumberFormat('en-IN', {
- maximumSignificantDigits: 20,
- }).format(event.count)}
- </div>
- </div>
- );
- })}
- </div>
- )}
<div className="overflow-x-auto">
<Table
{...{
diff --git a/apps/web/src/components/report/chart/ReportLineChartTooltip.tsx b/apps/web/src/components/report/chart/ReportChartTooltip.tsx
similarity index 57%
rename from apps/web/src/components/report/chart/ReportLineChartTooltip.tsx
rename to apps/web/src/components/report/chart/ReportChartTooltip.tsx
index eda4b26d1..f37a95699 100644
--- a/apps/web/src/components/report/chart/ReportLineChartTooltip.tsx
+++ b/apps/web/src/components/report/chart/ReportChartTooltip.tsx
@@ -2,19 +2,19 @@ import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
import { useMappings } from '@/hooks/useMappings';
import { useSelector } from '@/redux';
import type { IToolTipProps } from '@/types';
-import { alphabetIds } from '@/utils/constants';
type ReportLineChartTooltipProps = IToolTipProps<{
- color: string;
value: number;
+ dataKey: string;
payload: {
date: Date;
count: number;
label: string;
+ color: string;
} & Record<string, any>;
}>;
-export function ReportLineChartTooltip({
+export function ReportChartTooltip({
active,
payload,
}: ReportLineChartTooltipProps) {
@@ -34,31 +34,32 @@ export function ReportLineChartTooltip({
const sorted = payload.slice(0).sort((a, b) => b.value - a.value);
const visible = sorted.slice(0, limit);
const hidden = sorted.slice(limit);
- const first = visible[0]!;
- const isBarChart = first.payload.count === undefined;
return (
<div className="flex flex-col gap-2 rounded-xl border bg-white p-3 text-sm shadow-xl">
- {formatDate(new Date(first.payload.date))}
{visible.map((item, index) => {
- const id = alphabetIds[index];
+ // If we have a <Cell /> component, payload can be nested
+ const payload = item.payload.payload ?? item.payload;
+ const data = item.dataKey.includes(':')
+ ? payload[`${item.dataKey.split(':')[0]}:payload`]
+ : payload;
+
return (
- <div key={item.payload.label} className="flex gap-2">
- <div
- className="w-[3px] rounded-full"
- style={{ background: item.color }}
- ></div>
- <div className="flex flex-col">
- <div className="min-w-0 max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap font-medium">
- {isBarChart
- ? item.payload[`${id}:label`]
- : getLabel(item.payload.label)}
- </div>
- <div>
- {isBarChart ? item.payload[`${id}:count`] : item.payload.count}
+ <>
+ {index === 0 && data.date ? formatDate(new Date(data.date)) : null}
+ <div key={item.payload.label} className="flex gap-2">
+ <div
+ className="w-[3px] rounded-full"
+ style={{ background: data.color }}
+ />
+ <div className="flex flex-col">
+ <div className="min-w-0 max-w-[200px] overflow-hidden text-ellipsis whitespace-nowrap font-medium">
+ {getLabel(data.label)}
+ </div>
+ <div>{data.count}</div>
</div>
</div>
- </div>
+ </>
);
})}
{hidden.length > 0 && (
diff --git a/apps/web/src/components/report/chart/ReportHistogramChart.tsx b/apps/web/src/components/report/chart/ReportHistogramChart.tsx
index 886ec3680..f85c7d55e 100644
--- a/apps/web/src/components/report/chart/ReportHistogramChart.tsx
+++ b/apps/web/src/components/report/chart/ReportHistogramChart.tsx
@@ -1,13 +1,16 @@
-import { useEffect, useRef, useState } from 'react';
+import type { IChartData } from '@/app/_trpc/client';
import { AutoSizer } from '@/components/AutoSizer';
import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
-import type { IChartData, IInterval } from '@/types';
-import { alphabetIds } from '@/utils/constants';
-import { getChartColor } from '@/utils/theme';
+import { useRechartDataModel } from '@/hooks/useRechartDataModel';
+import { useVisibleSeries } from '@/hooks/useVisibleSeries';
+import type { IInterval } from '@/types';
+import { cn } from '@/utils/cn';
+import { getChartColor, theme } from '@/utils/theme';
import { Bar, BarChart, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts';
+import { getYAxisWidth } from './chart-utils';
import { useChartContext } from './ChartProvider';
-import { ReportLineChartTooltip } from './ReportLineChartTooltip';
+import { ReportChartTooltip } from './ReportChartTooltip';
import { ReportTable } from './ReportTable';
interface ReportHistogramChartProps {
@@ -15,80 +18,61 @@ interface ReportHistogramChartProps {
interval: IInterval;
}
+function BarHover(props: any) {
+ const bg = theme?.colors?.slate?.['200'] as string;
+ return <rect {...props} rx="8" fill={bg} fill-opacity={0.5} />;
+}
+
export function ReportHistogramChart({
interval,
data,
}: ReportHistogramChartProps) {
const { editMode } = useChartContext();
- const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
const formatDate = useFormatDateInterval(interval);
+ const { series, setVisibleSeries } = useVisibleSeries(data);
- const ref = useRef(false);
- useEffect(() => {
- if (!ref.current && data) {
- const max = 20;
-
- setVisibleSeries(
- data?.series?.slice(0, max).map((serie) => serie.name) ?? []
- );
- // ref.current = true;
- }
- }, [data]);
-
- const rel = data.series[0]?.data.map(({ date }) => {
- return {
- date,
- ...data.series.reduce((acc, serie, idx) => {
- return {
- ...acc,
- ...serie.data.reduce(
- (acc2, item) => {
- const id = alphabetIds[idx];
- if (item.date === date) {
- acc2[`${id}:count`] = item.count;
- acc2[`${id}:label`] = item.label;
- }
- return acc2;
- },
- {} as Record<string, any>
- ),
- };
- }, {}),
- };
- });
+ const rechartData = useRechartDataModel(data);
return (
<>
- <div className="max-sm:-mx-3">
+ <div
+ className={cn(
+ 'max-sm:-mx-3',
+ editMode && 'border border-border bg-white rounded-md p-4'
+ )}
+ >
<AutoSizer disableHeight>
{({ width }) => (
<BarChart
width={width}
height={Math.min(Math.max(width * 0.5, 250), 400)}
- data={rel}
+ data={rechartData}
>
- <CartesianGrid strokeDasharray="3 3" />
- <Tooltip content={<ReportLineChartTooltip />} />
+ <CartesianGrid strokeDasharray="3 3" vertical={false} />
+ <Tooltip content={<ReportChartTooltip />} cursor={<BarHover />} />
<XAxis
fontSize={12}
dataKey="date"
tickFormatter={formatDate}
tickLine={false}
+ axisLine={false}
+ />
+ <YAxis
+ fontSize={12}
+ axisLine={false}
+ tickLine={false}
+ width={getYAxisWidth(data.metrics.max)}
/>
- {data.series.map((serie, index) => {
- const id = alphabetIds[index];
+ {series.map((serie) => {
return (
- <>
- <YAxis dataKey={`${id}:count`} fontSize={12}></YAxis>
- <Bar
- stackId={id}
- key={serie.name}
- isAnimationActive={false}
- name={serie.name}
- dataKey={`${id}:count`}
- fill={getChartColor(index)}
- />
- </>
+ <Bar
+ stackId={serie.index}
+ key={serie.name}
+ name={serie.name}
+ dataKey={`${serie.index}:count`}
+ fill={getChartColor(serie.index)}
+ radius={8}
+ />
);
})}
</BarChart>
@@ -98,7 +82,7 @@ export function ReportHistogramChart({
{editMode && (
<ReportTable
data={data}
- visibleSeries={visibleSeries}
+ visibleSeries={series}
setVisibleSeries={setVisibleSeries}
/>
)}
diff --git a/apps/web/src/components/report/chart/ReportLineChart.tsx b/apps/web/src/components/report/chart/ReportLineChart.tsx
index f0da61952..822cc84cf 100644
--- a/apps/web/src/components/report/chart/ReportLineChart.tsx
+++ b/apps/web/src/components/report/chart/ReportLineChart.tsx
@@ -1,7 +1,11 @@
import { useEffect, useRef, useState } from 'react';
+import type { IChartData } from '@/app/_trpc/client';
import { AutoSizer } from '@/components/AutoSizer';
import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
-import type { IChartData, IInterval } from '@/types';
+import { useRechartDataModel } from '@/hooks/useRechartDataModel';
+import { useVisibleSeries } from '@/hooks/useVisibleSeries';
+import type { IChartLineType, IInterval } from '@/types';
+import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
import {
CartesianGrid,
@@ -12,76 +16,76 @@ import {
YAxis,
} from 'recharts';
+import { getYAxisWidth } from './chart-utils';
import { useChartContext } from './ChartProvider';
-import { ReportLineChartTooltip } from './ReportLineChartTooltip';
+import { ReportChartTooltip } from './ReportChartTooltip';
import { ReportTable } from './ReportTable';
interface ReportLineChartProps {
data: IChartData;
interval: IInterval;
+ lineType: IChartLineType;
}
-export function ReportLineChart({ interval, data }: ReportLineChartProps) {
+export function ReportLineChart({
+ lineType,
+ interval,
+ data,
+}: ReportLineChartProps) {
const { editMode } = useChartContext();
- const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
const formatDate = useFormatDateInterval(interval);
-
- const ref = useRef(false);
- useEffect(() => {
- if (!ref.current && data) {
- const max = 20;
-
- setVisibleSeries(
- data?.series?.slice(0, max).map((serie) => serie.name) ?? []
- );
- // ref.current = true;
- }
- }, [data]);
+ const { series, setVisibleSeries } = useVisibleSeries(data);
+ const rechartData = useRechartDataModel(data);
return (
<>
- <div className="max-sm:-mx-3">
+ <div
+ className={cn(
+ 'max-sm:-mx-3',
+ editMode && 'border border-border bg-white rounded-md p-4'
+ )}
+ >
<AutoSizer disableHeight>
{({ width }) => (
<LineChart
width={width}
height={Math.min(Math.max(width * 0.5, 250), 400)}
+ data={rechartData}
>
- <YAxis dataKey={'count'} fontSize={12}></YAxis>
- <Tooltip content={<ReportLineChartTooltip />} />
- <CartesianGrid strokeDasharray="3 3" />
+ <CartesianGrid
+ strokeDasharray="3 3"
+ horizontal={true}
+ vertical={false}
+ />
+ <YAxis
+ width={getYAxisWidth(data.metrics.max)}
+ fontSize={12}
+ axisLine={false}
+ tickLine={false}
+ allowDecimals={false}
+ />
+ <Tooltip content={<ReportChartTooltip />} />
<XAxis
+ axisLine={false}
fontSize={12}
dataKey="date"
- tickFormatter={(m: string) => {
- return formatDate(m);
- }}
+ tickFormatter={(m: string) => formatDate(m)}
tickLine={false}
allowDuplicatedCategory={false}
/>
- {data?.series
- .filter((serie) => {
- return visibleSeries.includes(serie.name);
- })
- .map((serie) => {
- const realIndex = data?.series.findIndex(
- (item) => item.name === serie.name
- );
- const key = serie.name;
- const strokeColor = getChartColor(realIndex);
- return (
- <Line
- type="monotone"
- key={key}
- isAnimationActive={false}
- strokeWidth={2}
- dataKey="count"
- stroke={strokeColor}
- data={serie.data}
- name={serie.name}
- />
- );
- })}
+ {series.map((serie) => {
+ return (
+ <Line
+ type={lineType}
+ key={serie.name}
+ isAnimationActive={false}
+ strokeWidth={2}
+ dataKey={`${serie.index}:count`}
+ stroke={getChartColor(serie.index)}
+ name={serie.name}
+ />
+ );
+ })}
</LineChart>
)}
</AutoSizer>
@@ -89,7 +93,7 @@ export function ReportLineChart({ interval, data }: ReportLineChartProps) {
{editMode && (
<ReportTable
data={data}
- visibleSeries={visibleSeries}
+ visibleSeries={series}
setVisibleSeries={setVisibleSeries}
/>
)}
diff --git a/apps/web/src/components/report/chart/ReportMetricChart.tsx b/apps/web/src/components/report/chart/ReportMetricChart.tsx
new file mode 100644
index 000000000..571761b15
--- /dev/null
+++ b/apps/web/src/components/report/chart/ReportMetricChart.tsx
@@ -0,0 +1,79 @@
+import type { IChartData } from '@/app/_trpc/client';
+import { ColorSquare } from '@/components/ColorSquare';
+import { useVisibleSeries } from '@/hooks/useVisibleSeries';
+import { cn } from '@/utils/cn';
+import { theme } from '@/utils/theme';
+import AutoSizer from 'react-virtualized-auto-sizer';
+import { Area, AreaChart } from 'recharts';
+
+import { useChartContext } from './ChartProvider';
+
+interface ReportMetricChartProps {
+ data: IChartData;
+}
+
+export function ReportMetricChart({ data }: ReportMetricChartProps) {
+ const { editMode } = useChartContext();
+ const { series } = useVisibleSeries(data, editMode ? undefined : 2);
+ const color = theme?.colors['chart-0'];
+ return (
+ <div
+ className={cn(
+ 'grid grid-cols-1 gap-4',
+ editMode && 'md:grid-cols-2 lg:grid-cols-3'
+ )}
+ >
+ {series.map((serie) => {
+ return (
+ <div
+ className="relative border border-border p-4 rounded-md bg-white overflow-hidden"
+ key={serie.name}
+ >
+ <div className="absolute -top-1 -left-1 -right-1 -bottom-1 z-0 opacity-50">
+ <AutoSizer>
+ {({ width, height }) => (
+ <AreaChart
+ width={width}
+ height={height / 3}
+ data={serie.data}
+ style={{ marginTop: (height / 3) * 2 }}
+ >
+ <defs>
+ <linearGradient id="area" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={color} stopOpacity={0.3} />
+ <stop
+ offset="95%"
+ stopColor={color}
+ stopOpacity={0.1}
+ />
+ </linearGradient>
+ </defs>
+ <Area
+ dataKey="count"
+ type="monotone"
+ fill="url(#area)"
+ fillOpacity={1}
+ stroke={color}
+ strokeWidth={2}
+ />
+ </AreaChart>
+ )}
+ </AutoSizer>
+ </div>
+ <div className="relative">
+ <div className="flex items-center gap-2 text-lg font-medium">
+ <ColorSquare>{serie.event.id}</ColorSquare>
+ {serie.name ?? serie.event.displayName ?? serie.event.name}
+ </div>
+ <div className="mt-6 font-mono text-4xl font-light">
+ {new Intl.NumberFormat('en', {
+ maximumSignificantDigits: 20,
+ }).format(serie.metrics.sum)}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/report/chart/ReportPieChart.tsx b/apps/web/src/components/report/chart/ReportPieChart.tsx
new file mode 100644
index 000000000..d017016c4
--- /dev/null
+++ b/apps/web/src/components/report/chart/ReportPieChart.tsx
@@ -0,0 +1,81 @@
+import { useEffect, useRef, useState } from 'react';
+import type { IChartData } from '@/app/_trpc/client';
+import { AutoSizer } from '@/components/AutoSizer';
+import { useVisibleSeries } from '@/hooks/useVisibleSeries';
+import { cn } from '@/utils/cn';
+import { getChartColor } from '@/utils/theme';
+import { Cell, Pie, PieChart, Tooltip } from 'recharts';
+
+import { useChartContext } from './ChartProvider';
+import { ReportChartTooltip } from './ReportChartTooltip';
+import { ReportTable } from './ReportTable';
+
+interface ReportPieChartProps {
+ data: IChartData;
+}
+
+export function ReportPieChart({ data }: ReportPieChartProps) {
+ const { editMode } = useChartContext();
+ const { series, setVisibleSeries } = useVisibleSeries(data);
+
+ // Get max 10 series and than combine others into one
+ const pieData = series.map((serie) => {
+ return {
+ id: serie.name,
+ color: getChartColor(serie.index),
+ index: serie.index,
+ label: serie.name,
+ count: serie.metrics.sum,
+ };
+ });
+
+ return (
+ <>
+ <div
+ className={cn(
+ 'max-sm:-mx-3',
+ editMode && 'border border-border bg-white rounded-md p-4'
+ )}
+ >
+ <AutoSizer disableHeight>
+ {({ width }) => {
+ const height = Math.min(Math.max(width * 0.5, 250), 400);
+ return (
+ <PieChart
+ width={width}
+ height={Math.min(Math.max(width * 0.5, 250), 400)}
+ >
+ <Tooltip content={<ReportChartTooltip />} />
+ <Pie
+ dataKey={'count'}
+ data={pieData}
+ innerRadius={height / 4}
+ outerRadius={height / 2 - 20}
+ isAnimationActive={false}
+ >
+ {pieData.map((item) => {
+ return (
+ <Cell
+ key={item.id}
+ strokeWidth={2}
+ stroke={item.color}
+ fill={item.color}
+ />
+ );
+ })}
+ </Pie>
+ </PieChart>
+ );
+ }}
+ </AutoSizer>
+ </div>
+ {editMode && (
+ <ReportTable
+ data={data}
+ visibleSeries={series}
+ setVisibleSeries={setVisibleSeries}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/web/src/components/report/chart/ReportTable.tsx b/apps/web/src/components/report/chart/ReportTable.tsx
index cb33f9e24..7572498bd 100644
--- a/apps/web/src/components/report/chart/ReportTable.tsx
+++ b/apps/web/src/components/report/chart/ReportTable.tsx
@@ -1,15 +1,20 @@
import * as React from 'react';
+import type { IChartData } from '@/app/_trpc/client';
import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
import { useMappings } from '@/hooks/useMappings';
import { useSelector } from '@/redux';
-import type { IChartData } from '@/types';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
interface ReportTableProps {
data: IChartData;
- visibleSeries: string[];
+ visibleSeries: IChartData['series'];
setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;
}
@@ -40,31 +45,23 @@ export function ReportTable({
'bg-gray-50 text-emerald-600 font-medium border-r border-border';
return (
<>
- <div className="flex w-fit max-w-full rounded-md border border-border">
+ <div className="flex w-fit max-w-full rounded-md border border-border bg-white">
{/* Labels */}
<div className="border-r border-border">
<div className={cn(header, row, cell)}>Name</div>
- {/* <div
- className={cn(
- 'flex max-w-[200px] w-full min-w-full items-center gap-2',
- row,
- cell
- )}
- >
- <div className="font-medium min-w-0 overflow-scroll whitespace-nowrap scrollbar-hide">
- Summary
- </div>
- </div> */}
{data.series.map((serie, index) => {
- const checked = visibleSeries.includes(serie.name);
+ const checked = !!visibleSeries.find(
+ (item) => item.name === serie.name
+ );
return (
<div
key={serie.name}
className={cn(
- 'flex max-w-[200px] w-full min-w-full items-center gap-2',
+ 'flex max-w-[200px] lg:max-w-[400px] xl:max-w-[600px] w-full min-w-full items-center gap-2',
row,
- cell
+ // avoid using cell since its better on the right side
+ 'p-2'
)}
>
<Checkbox
@@ -81,12 +78,16 @@ export function ReportTable({
}
checked={checked}
/>
- <div
- title={getLabel(serie.name)}
- className="min-w-full overflow-scroll whitespace-nowrap scrollbar-hide"
- >
- {getLabel(serie.name)}
- </div>
+ <Tooltip delayDuration={200}>
+ <TooltipTrigger asChild>
+ <div className="min-w-0 overflow-hidden whitespace-nowrap text-ellipsis">
+ {getLabel(serie.name)}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{getLabel(serie.name)}</p>
+ </TooltipContent>
+ </Tooltip>
</div>
);
})}
@@ -113,7 +114,7 @@ export function ReportTable({
return (
<div className={cn('w-max', row)} key={serie.name}>
<div className={cn(header, value, cell, total)}>
- {serie.metrics.total}
+ {serie.metrics.sum}
</div>
<div className={cn(header, value, cell, total)}>
{serie.metrics.average}
@@ -130,14 +131,22 @@ export function ReportTable({
})}
</div>
</div>
- <div className="flex gap-2">
- <div>Total</div>
- <div>
- {data.series.reduce((acc, serie) => serie.metrics.total + acc, 0)}
+ <div className="flex gap-4">
+ <div className="flex gap-1">
+ <div>Total</div>
+ <div>{data.metrics.sum}</div>
+ </div>
+ <div className="flex gap-1">
+ <div>Average</div>
+ <div>{data.metrics.averge}</div>
+ </div>
+ <div className="flex gap-1">
+ <div>Min</div>
+ <div>{data.metrics.min}</div>
</div>
- <div>Average</div>
- <div>
- {data.series.reduce((acc, serie) => serie.metrics.average + acc, 0)}
+ <div className="flex gap-1">
+ <div>Max</div>
+ <div>{data.metrics.max}</div>
</div>
</div>
</>
diff --git a/apps/web/src/components/report/chart/chart-utils.ts b/apps/web/src/components/report/chart/chart-utils.ts
new file mode 100644
index 000000000..cce56acf1
--- /dev/null
+++ b/apps/web/src/components/report/chart/chart-utils.ts
@@ -0,0 +1,5 @@
+import { round } from '@/utils/math';
+
+export function getYAxisWidth(value: number) {
+ return round(value, 0).toString().length * 7.5 + 7.5;
+}
diff --git a/apps/web/src/components/report/chart/index.tsx b/apps/web/src/components/report/chart/index.tsx
index 31c5cef4b..4fef6605d 100644
--- a/apps/web/src/components/report/chart/index.tsx
+++ b/apps/web/src/components/report/chart/index.tsx
@@ -1,13 +1,18 @@
+'use client';
+
import { memo } from 'react';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
+import { api } from '@/app/_trpc/client';
+import { useAppParams } from '@/hooks/useAppParams';
import type { IChartInput } from '@/types';
-import { api } from '@/utils/api';
import { ChartAnimation, ChartAnimationContainer } from './ChartAnimation';
import { withChartProivder } from './ChartProvider';
+import { ReportAreaChart } from './ReportAreaChart';
import { ReportBarChart } from './ReportBarChart';
import { ReportHistogramChart } from './ReportHistogramChart';
import { ReportLineChart } from './ReportLineChart';
+import { ReportMetricChart } from './ReportMetricChart';
+import { ReportPieChart } from './ReportPieChart';
export type ReportChartProps = IChartInput;
@@ -19,8 +24,9 @@ export const Chart = memo(
chartType,
name,
range,
+ lineType,
}: ReportChartProps) {
- const params = useOrganizationParams();
+ const params = useAppParams();
const hasEmptyFilters = events.some((event) =>
event.filters.some((filter) => filter.value.length === 0)
);
@@ -29,13 +35,15 @@ export const Chart = memo(
{
interval,
chartType,
+ // dont send lineType since it does not need to be sent
+ lineType: 'monotone',
events,
breakdowns,
name,
range,
startDate: null,
endDate: null,
- projectSlug: params.project,
+ projectId: params.projectId,
},
{
keepPreviousData: false,
@@ -97,8 +105,32 @@ export const Chart = memo(
return <ReportBarChart data={chart.data} />;
}
+ if (chartType === 'metric') {
+ return <ReportMetricChart data={chart.data} />;
+ }
+
+ if (chartType === 'pie') {
+ return <ReportPieChart data={chart.data} />;
+ }
+
if (chartType === 'linear') {
- return <ReportLineChart interval={interval} data={chart.data} />;
+ return (
+ <ReportLineChart
+ lineType={lineType}
+ interval={interval}
+ data={chart.data}
+ />
+ );
+ }
+
+ if (chartType === 'area') {
+ return (
+ <ReportAreaChart
+ lineType={lineType}
+ interval={interval}
+ data={chart.data}
+ />
+ );
}
return (
diff --git a/apps/web/src/components/report/hooks/useReportId.ts b/apps/web/src/components/report/hooks/useReportId.ts
deleted file mode 100644
index 434e101cd..000000000
--- a/apps/web/src/components/report/hooks/useReportId.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { useQueryParams } from '@/hooks/useQueryParams';
-import { z } from 'zod';
-
-export const useReportId = () =>
- useQueryParams(
- z.object({
- reportId: z.string().optional(),
- })
- );
diff --git a/apps/web/src/components/report/reportSlice.ts b/apps/web/src/components/report/reportSlice.ts
index cd883e735..63cc802f7 100644
--- a/apps/web/src/components/report/reportSlice.ts
+++ b/apps/web/src/components/report/reportSlice.ts
@@ -2,25 +2,34 @@ import type {
IChartBreakdown,
IChartEvent,
IChartInput,
+ IChartLineType,
IChartRange,
IChartType,
IInterval,
} from '@/types';
-import { alphabetIds, isMinuteIntervalEnabledByRange } from '@/utils/constants';
+import {
+ alphabetIds,
+ getDefaultIntervalByRange,
+ isHourIntervalEnabledByRange,
+ isMinuteIntervalEnabledByRange,
+} from '@/utils/constants';
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
type InitialState = IChartInput & {
dirty: boolean;
+ ready: boolean;
startDate: string | null;
endDate: string | null;
};
// First approach: define the initial state using that type
const initialState: InitialState = {
+ ready: false,
dirty: false,
name: 'Untitled',
chartType: 'linear',
+ lineType: 'monotone',
interval: 'day',
breakdowns: [],
events: [],
@@ -42,12 +51,19 @@ export const reportSlice = createSlice({
reset() {
return initialState;
},
+ ready() {
+ return {
+ ...initialState,
+ ready: true,
+ };
+ },
setReport(state, action: PayloadAction<IChartInput>) {
return {
...action.payload,
startDate: null,
endDate: null,
dirty: false,
+ ready: true,
};
},
setName(state, action: PayloadAction<string>) {
@@ -132,6 +148,19 @@ export const reportSlice = createSlice({
) {
state.interval = 'hour';
}
+
+ if (
+ !isHourIntervalEnabledByRange(state.range) &&
+ state.interval === 'hour'
+ ) {
+ state.interval = 'day';
+ }
+ },
+
+ // Line type
+ changeLineType: (state, action: PayloadAction<IChartLineType>) => {
+ state.dirty = true;
+ state.lineType = action.payload;
},
// Date range
@@ -149,15 +178,7 @@ export const reportSlice = createSlice({
changeDateRanges: (state, action: PayloadAction<IChartRange>) => {
state.dirty = true;
state.range = action.payload;
- if (action.payload === '30min' || action.payload === '1h') {
- state.interval = 'minute';
- } else if (action.payload === 'today' || action.payload === '24h') {
- state.interval = 'hour';
- } else if (action.payload === '7d' || action.payload === '14d') {
- state.interval = 'day';
- } else {
- state.interval = 'month';
- }
+ state.interval = getDefaultIntervalByRange(action.payload);
},
},
});
@@ -165,6 +186,7 @@ export const reportSlice = createSlice({
// Action creators are generated for each case reducer function
export const {
reset,
+ ready,
setReport,
setName,
addEvent,
@@ -176,6 +198,7 @@ export const {
changeInterval,
changeDateRanges,
changeChartType,
+ changeLineType,
resetDirty,
} = reportSlice.actions;
diff --git a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
index 9c3275f02..9d0e77eac 100644
--- a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -1,20 +1,22 @@
+'use client';
+
+import { api } from '@/app/_trpc/client';
import { ColorSquare } from '@/components/ColorSquare';
import { Combobox } from '@/components/ui/combobox';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
import { useDispatch, useSelector } from '@/redux';
import type { IChartBreakdown } from '@/types';
-import { api } from '@/utils/api';
+import { useParams } from 'next/navigation';
import { addBreakdown, changeBreakdown, removeBreakdown } from '../reportSlice';
import { ReportBreakdownMore } from './ReportBreakdownMore';
import type { ReportEventMoreProps } from './ReportEventMore';
export function ReportBreakdowns() {
- const params = useOrganizationParams();
+ const params = useParams();
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
const dispatch = useDispatch();
const propertiesQuery = api.chart.properties.useQuery({
- projectSlug: params.project,
+ projectId: params.projectId as string,
});
const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({
value: item,
@@ -43,6 +45,8 @@ export function ReportBreakdowns() {
<div className="flex items-center gap-2 p-2 px-4">
<ColorSquare>{index}</ColorSquare>
<Combobox
+ className="flex-1"
+ searchable
value={item.name}
onChange={(value) => {
dispatch(
@@ -63,6 +67,7 @@ export function ReportBreakdowns() {
{selectedBreakdowns.length === 0 && (
<Combobox
+ searchable
value={''}
onChange={(value) => {
dispatch(
diff --git a/apps/web/src/components/report/sidebar/ReportEventFilters.tsx b/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
index 15c1bf73b..962eb6daa 100644
--- a/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
+++ b/apps/web/src/components/report/sidebar/ReportEventFilters.tsx
@@ -1,9 +1,9 @@
import type { Dispatch } from 'react';
+import { api } from '@/app/_trpc/client';
import { ColorSquare } from '@/components/ColorSquare';
import { Dropdown } from '@/components/Dropdown';
import { Button } from '@/components/ui/button';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
-import { ComboboxMulti } from '@/components/ui/combobox-multi';
import {
CommandDialog,
CommandEmpty,
@@ -15,16 +15,15 @@ import {
} from '@/components/ui/command';
import { RenderDots } from '@/components/ui/RenderDots';
import { useMappings } from '@/hooks/useMappings';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { useDispatch, useSelector } from '@/redux';
+import { useDispatch } from '@/redux';
import type {
IChartEvent,
IChartEventFilter,
IChartEventFilterValue,
} from '@/types';
-import { api } from '@/utils/api';
import { operators } from '@/utils/constants';
import { CreditCard, SlidersHorizontal, Trash } from 'lucide-react';
+import { useParams } from 'next/navigation';
import { changeEvent } from '../reportSlice';
@@ -39,12 +38,12 @@ export function ReportEventFilters({
isCreating,
setIsCreating,
}: ReportEventFiltersProps) {
- const params = useOrganizationParams();
+ const params = useParams();
const dispatch = useDispatch();
const propertiesQuery = api.chart.properties.useQuery(
{
event: event.name,
- projectSlug: params.project,
+ projectId: params.projectId as string,
},
{
enabled: !!event.name,
@@ -103,13 +102,13 @@ interface FilterProps {
}
function Filter({ filter, event }: FilterProps) {
- const params = useOrganizationParams();
+ const params = useParams<{ organizationId: string; projectId: string }>();
const getLabel = useMappings();
const dispatch = useDispatch();
const potentialValues = api.chart.values.useQuery({
event: event.name,
property: filter.name,
- projectSlug: params.project,
+ projectId: params?.projectId!,
});
const valuesCombobox =
@@ -196,8 +195,8 @@ function Filter({ filter, event }: FilterProps) {
</Dropdown>
<ComboboxAdvanced
items={valuesCombobox}
- selected={filter.value}
- setSelected={(setFn) => {
+ value={filter.value}
+ onChange={(setFn) => {
changeFilterValue(
typeof setFn === 'function' ? setFn(filter.value) : setFn
);
diff --git a/apps/web/src/components/report/sidebar/ReportEvents.tsx b/apps/web/src/components/report/sidebar/ReportEvents.tsx
index 9630ba78c..ebf46f06b 100644
--- a/apps/web/src/components/report/sidebar/ReportEvents.tsx
+++ b/apps/web/src/components/report/sidebar/ReportEvents.tsx
@@ -1,14 +1,16 @@
+'use client';
+
import { useState } from 'react';
+import { api } from '@/app/_trpc/client';
import { ColorSquare } from '@/components/ColorSquare';
import { Dropdown } from '@/components/Dropdown';
import { Combobox } from '@/components/ui/combobox';
import { Input } from '@/components/ui/input';
import { useDebounceFn } from '@/hooks/useDebounceFn';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
import { useDispatch, useSelector } from '@/redux';
import type { IChartEvent } from '@/types';
-import { api } from '@/utils/api';
import { Filter, GanttChart, Users } from 'lucide-react';
+import { useParams } from 'next/navigation';
import { addEvent, changeEvent, removeEvent } from '../reportSlice';
import { ReportEventFilters } from './ReportEventFilters';
@@ -19,9 +21,9 @@ export function ReportEvents() {
const [isCreating, setIsCreating] = useState(false);
const selectedEvents = useSelector((state) => state.report.events);
const dispatch = useDispatch();
- const params = useOrganizationParams();
+ const params = useParams();
const eventsQuery = api.chart.events.useQuery({
- projectSlug: params.project,
+ projectId: String(params.projectId),
});
const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({
value: item.name,
@@ -56,6 +58,8 @@ export function ReportEvents() {
<div className="flex items-center gap-2 p-2">
<ColorSquare>{event.id}</ColorSquare>
<Combobox
+ className="flex-1"
+ searchable
value={event.name}
onChange={(value) => {
dispatch(
diff --git a/apps/web/src/components/ui/RenderDots.tsx b/apps/web/src/components/ui/RenderDots.tsx
index 8542aec9e..267c42e7c 100644
--- a/apps/web/src/components/ui/RenderDots.tsx
+++ b/apps/web/src/components/ui/RenderDots.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import { cn } from '@/utils/cn';
import { Asterisk, ChevronRight } from 'lucide-react';
diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/web/src/components/ui/alert-dialog.tsx
index bc4751da8..463dc1e25 100644
--- a/apps/web/src/components/ui/alert-dialog.tsx
+++ b/apps/web/src/components/ui/alert-dialog.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/utils/cn';
diff --git a/apps/web/src/components/ui/alert.tsx b/apps/web/src/components/ui/alert.tsx
new file mode 100644
index 000000000..27093d2aa
--- /dev/null
+++ b/apps/web/src/components/ui/alert.tsx
@@ -0,0 +1,59 @@
+import * as React from 'react';
+import { cn } from '@/utils/cn';
+import { cva } from 'class-variance-authority';
+import type { VariantProps } from 'class-variance-authority';
+
+const alertVariants = cva(
+ 'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',
+ {
+ variants: {
+ variant: {
+ default: 'bg-background text-foreground',
+ destructive:
+ 'border-destructive text-destructive dark:border-destructive [&>svg]:text-destructive',
+ },
+ },
+ defaultVariants: {
+ variant: 'default',
+ },
+ }
+);
+
+const Alert = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
+>(({ className, variant, ...props }, ref) => (
+ <div
+ ref={ref}
+ role="alert"
+ className={cn(alertVariants({ variant }), className)}
+ {...props}
+ />
+));
+Alert.displayName = 'Alert';
+
+const AlertTitle = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLHeadingElement>
+>(({ className, ...props }, ref) => (
+ <h5
+ ref={ref}
+ className={cn('mb-1 font-medium leading-none tracking-tight', className)}
+ {...props}
+ />
+));
+AlertTitle.displayName = 'AlertTitle';
+
+const AlertDescription = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLParagraphElement>
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn('text-sm [&_p]:leading-relaxed', className)}
+ {...props}
+ />
+));
+AlertDescription.displayName = 'AlertDescription';
+
+export { Alert, AlertTitle, AlertDescription };
diff --git a/apps/web/src/components/ui/aspect-ratio.tsx b/apps/web/src/components/ui/aspect-ratio.tsx
index 5dfdf1e67..aaabffbc4 100644
--- a/apps/web/src/components/ui/aspect-ratio.tsx
+++ b/apps/web/src/components/ui/aspect-ratio.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio';
const AspectRatio = AspectRatioPrimitive.Root;
diff --git a/apps/web/src/components/ui/avatar.tsx b/apps/web/src/components/ui/avatar.tsx
index 24042045a..2817f1c69 100644
--- a/apps/web/src/components/ui/avatar.tsx
+++ b/apps/web/src/components/ui/avatar.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as AvatarPrimitive from '@radix-ui/react-avatar';
diff --git a/apps/web/src/components/ui/badge.tsx b/apps/web/src/components/ui/badge.tsx
index 79b75eefc..c8df0653d 100644
--- a/apps/web/src/components/ui/badge.tsx
+++ b/apps/web/src/components/ui/badge.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import { cva } from 'class-variance-authority';
diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx
index dad1731a6..5e4f5e59a 100644
--- a/apps/web/src/components/ui/button.tsx
+++ b/apps/web/src/components/ui/button.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import { Slot } from '@radix-ui/react-slot';
@@ -7,11 +9,12 @@ import type { LucideIcon } from 'lucide-react';
import { Loader2 } from 'lucide-react';
const buttonVariants = cva(
- 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
+ 'flex-shrink-0 inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
+ cta: 'bg-blue-600 text-primary-foreground hover:bg-blue-500',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline:
diff --git a/apps/web/src/components/ui/checkbox.tsx b/apps/web/src/components/ui/checkbox.tsx
index 0e908eb97..f5253de3b 100644
--- a/apps/web/src/components/ui/checkbox.tsx
+++ b/apps/web/src/components/ui/checkbox.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
diff --git a/apps/web/src/components/ui/combobox-advanced.tsx b/apps/web/src/components/ui/combobox-advanced.tsx
index c9684f785..8a6085803 100644
--- a/apps/web/src/components/ui/combobox-advanced.tsx
+++ b/apps/web/src/components/ui/combobox-advanced.tsx
@@ -1,6 +1,9 @@
+'use client';
+
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
import { Command, CommandGroup, CommandItem } from '@/components/ui/command';
+import { useOnClickOutside } from 'usehooks-ts';
import { Checkbox } from './checkbox';
import { Input } from './input';
@@ -9,23 +12,25 @@ type IValue = any;
type IItem = Record<'value' | 'label', IValue>;
interface ComboboxAdvancedProps {
- selected: IValue[];
- setSelected: React.Dispatch<React.SetStateAction<IValue[]>>;
+ value: IValue[];
+ onChange: React.Dispatch<React.SetStateAction<IValue[]>>;
items: IItem[];
placeholder: string;
}
export function ComboboxAdvanced({
items,
- selected,
- setSelected,
+ value,
+ onChange,
placeholder,
}: ComboboxAdvancedProps) {
const [open, setOpen] = React.useState(false);
const [inputValue, setInputValue] = React.useState('');
+ const ref = React.useRef<HTMLDivElement | null>(null);
+ useOnClickOutside(ref, () => setOpen(false));
const selectables = items
- .filter((item) => !selected.find((s) => s === item.value))
+ .filter((item) => !value.find((s) => s === item.value))
.filter(
(item) =>
(typeof item.label === 'string' &&
@@ -35,7 +40,7 @@ export function ComboboxAdvanced({
);
const renderItem = (item: IItem) => {
- const checked = !!selected.find((s) => s === item.value);
+ const checked = !!value.find((s) => s === item.value);
return (
<CommandItem
key={String(item.value)}
@@ -45,7 +50,7 @@ export function ComboboxAdvanced({
}}
onSelect={() => {
setInputValue('');
- setSelected((prev) => {
+ onChange((prev) => {
if (prev.includes(item.value)) {
return prev.filter((s) => s !== item.value);
}
@@ -66,15 +71,15 @@ export function ComboboxAdvanced({
};
return (
- <Command className="overflow-visible bg-white">
+ <Command className="overflow-visible bg-white" ref={ref}>
<button
type="button"
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"
onClick={() => setOpen((prev) => !prev)}
>
<div className="flex gap-1 flex-wrap">
- {selected.length === 0 && placeholder}
- {selected.slice(0, 2).map((value) => {
+ {value.length === 0 && placeholder}
+ {value.slice(0, 2).map((value) => {
const item = items.find((item) => item.value === value) ?? {
value,
label: value,
@@ -85,13 +90,13 @@ export function ComboboxAdvanced({
</Badge>
);
})}
- {selected.length > 2 && (
- <Badge variant="secondary">+{selected.length - 2} more</Badge>
+ {value.length > 2 && (
+ <Badge variant="secondary">+{value.length - 2} more</Badge>
)}
</div>
</button>
- <div className="relative mt-2">
- {open && (
+ {open && (
+ <div className="relative top-2">
<div className="max-h-80 min-w-[300px] absolute w-full z-10 top-0 rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in">
<CommandGroup className="max-h-80 overflow-auto">
<div className="p-1 mb-2">
@@ -102,13 +107,16 @@ export function ComboboxAdvanced({
/>
</div>
{inputValue === ''
- ? selected.map(renderUnknownItem)
- : renderUnknownItem(inputValue)}
+ ? value.map(renderUnknownItem)
+ : renderItem({
+ value: inputValue,
+ label: `Pick "${inputValue}"`,
+ })}
{selectables.map(renderItem)}
</CommandGroup>
</div>
- )}
- </div>
+ </div>
+ )}
</Command>
);
}
diff --git a/apps/web/src/components/ui/combobox-multi.tsx b/apps/web/src/components/ui/combobox-multi.tsx
index c6ddaadcf..34a132a95 100644
--- a/apps/web/src/components/ui/combobox-multi.tsx
+++ b/apps/web/src/components/ui/combobox-multi.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
import { Command, CommandGroup, CommandItem } from '@/components/ui/command';
diff --git a/apps/web/src/components/ui/combobox.tsx b/apps/web/src/components/ui/combobox.tsx
index 1c6fcf184..706d51a68 100644
--- a/apps/web/src/components/ui/combobox.tsx
+++ b/apps/web/src/components/ui/combobox.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { Button } from '@/components/ui/button';
import {
@@ -15,29 +17,31 @@ import {
import { cn } from '@/utils/cn';
import { Check, ChevronsUpDown } from 'lucide-react';
-import { ScrollArea } from './scroll-area';
-
-interface ComboboxProps {
+interface ComboboxProps<T> {
placeholder: string;
items: {
- value: string;
+ value: T;
label: string;
disabled?: boolean;
}[];
- value: string;
- onChange: (value: string) => void;
+ value: T | null | undefined;
+ onChange: (value: T) => void;
children?: React.ReactNode;
- onCreate?: (value: string) => void;
+ onCreate?: (value: T) => void;
+ className?: string;
+ searchable?: boolean;
}
-export function Combobox({
+export function Combobox<T extends string>({
placeholder,
items,
value,
onChange,
children,
onCreate,
-}: ComboboxProps) {
+ className,
+ searchable,
+}: ComboboxProps<T>) {
const [open, setOpen] = React.useState(false);
const [search, setSearch] = React.useState('');
function find(value: string) {
@@ -54,9 +58,9 @@ export function Combobox({
variant="outline"
role="combobox"
aria-expanded={open}
- className="w-full justify-between min-w-[150px]"
+ className={cn('justify-between min-w-[150px]', className)}
>
- <span className="overflow-hidden text-ellipsis">
+ <span className="overflow-hidden text-ellipsis whitespace-nowrap">
{value ? find(value)?.label ?? 'No match' : placeholder}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
@@ -65,11 +69,13 @@ export function Combobox({
</PopoverTrigger>
<PopoverContent className="w-full min-w-0 p-0" align="start">
<Command>
- <CommandInput
- placeholder="Search item..."
- value={search}
- onValueChange={setSearch}
- />
+ {searchable === true && (
+ <CommandInput
+ placeholder="Search item..."
+ value={search}
+ onValueChange={setSearch}
+ />
+ )}
{typeof onCreate === 'function' && search ? (
<CommandEmpty className="p-2">
<Button
@@ -85,7 +91,7 @@ export function Combobox({
) : (
<CommandEmpty>Nothing selected</CommandEmpty>
)}
- <div className="max-h-[300px] overflow-scroll">
+ <div className="max-h-[300px] overflow-y-auto over-x-hidden">
<CommandGroup>
{items.map((item) => (
<CommandItem
diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsx
index c143a853d..91b9f2af9 100644
--- a/apps/web/src/components/ui/command.tsx
+++ b/apps/web/src/components/ui/command.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { cn } from '@/utils/cn';
diff --git a/apps/web/src/components/ui/dialog.tsx b/apps/web/src/components/ui/dialog.tsx
index 0a5f0d354..fe85da543 100644
--- a/apps/web/src/components/ui/dialog.tsx
+++ b/apps/web/src/components/ui/dialog.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as DialogPrimitive from '@radix-ui/react-dialog';
diff --git a/apps/web/src/components/ui/dropdown-menu.tsx b/apps/web/src/components/ui/dropdown-menu.tsx
index a2cf187aa..842e461c8 100644
--- a/apps/web/src/components/ui/dropdown-menu.tsx
+++ b/apps/web/src/components/ui/dropdown-menu.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
diff --git a/apps/web/src/components/ui/input.tsx b/apps/web/src/components/ui/input.tsx
index 6e0b0a9cd..3a6d25536 100644
--- a/apps/web/src/components/ui/input.tsx
+++ b/apps/web/src/components/ui/input.tsx
@@ -1,16 +1,21 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
-export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
+export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {
+ error?: string | undefined;
+};
const Input = React.forwardRef<HTMLInputElement, InputProps>(
- ({ className, type, ...props }, ref) => {
+ ({ className, error, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 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,
+ !!error && 'border-destructive'
)}
ref={ref}
{...props}
diff --git a/apps/web/src/components/ui/label.tsx b/apps/web/src/components/ui/label.tsx
index eada103c0..198599168 100644
--- a/apps/web/src/components/ui/label.tsx
+++ b/apps/web/src/components/ui/label.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as LabelPrimitive from '@radix-ui/react-label';
diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx
index 4c0685727..b86795cd0 100644
--- a/apps/web/src/components/ui/popover.tsx
+++ b/apps/web/src/components/ui/popover.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as PopoverPrimitive from '@radix-ui/react-popover';
diff --git a/apps/web/src/components/ui/radio-group.tsx b/apps/web/src/components/ui/radio-group.tsx
index a29758587..fb251a995 100644
--- a/apps/web/src/components/ui/radio-group.tsx
+++ b/apps/web/src/components/ui/radio-group.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx
index f25a5f8c9..b2c7836c2 100644
--- a/apps/web/src/components/ui/scroll-area.tsx
+++ b/apps/web/src/components/ui/scroll-area.tsx
@@ -1,7 +1,8 @@
-import * as React from "react"
-import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
+'use client';
-import { cn } from "@/utils/cn"
+import * as React from 'react';
+import { cn } from '@/utils/cn';
+import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
@@ -9,7 +10,7 @@ const ScrollArea = React.forwardRef<
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
- className={cn("relative overflow-hidden", className)}
+ className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
@@ -18,34 +19,34 @@ const ScrollArea = React.forwardRef<
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
-))
-ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
+));
+ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
->(({ className, orientation = "vertical", ...props }, ref) => (
+>(({ className, orientation = 'vertical', ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
- "flex touch-none select-none transition-colors",
- orientation === "vertical" &&
- "h-full w-2.5 border-l border-l-transparent p-[1px]",
- orientation === "horizontal" &&
- "h-2.5 flex-col border-t border-t-transparent p-[1px]",
+ 'flex touch-none select-none transition-colors',
+ orientation === 'vertical' &&
+ 'h-full w-2.5 border-l border-l-transparent p-[1px]',
+ orientation === 'horizontal' &&
+ 'h-2.5 flex-col border-t border-t-transparent p-[1px]',
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
className={cn(
- "relative rounded-full bg-border",
- orientation === "vertical" && "flex-1"
+ 'relative rounded-full bg-border',
+ orientation === 'vertical' && 'flex-1'
)}
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
-))
-ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
+));
+ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
-export { ScrollArea, ScrollBar }
+export { ScrollArea, ScrollBar };
diff --git a/apps/web/src/components/ui/sheet.tsx b/apps/web/src/components/ui/sheet.tsx
index b2c7032eb..0e9cc931e 100644
--- a/apps/web/src/components/ui/sheet.tsx
+++ b/apps/web/src/components/ui/sheet.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as SheetPrimitive from '@radix-ui/react-dialog';
diff --git a/apps/web/src/components/ui/table.tsx b/apps/web/src/components/ui/table.tsx
index 4e67313f7..df94c8a61 100644
--- a/apps/web/src/components/ui/table.tsx
+++ b/apps/web/src/components/ui/table.tsx
@@ -1,11 +1,13 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
const Table = React.forwardRef<
HTMLTableElement,
- React.HTMLAttributes<HTMLTableElement>
->(({ className, ...props }, ref) => (
- <div className="border border-border rounded-md">
+ React.HTMLAttributes<HTMLTableElement> & { wrapper?: boolean }
+>(({ className, wrapper, ...props }, ref) => (
+ <div className={cn('border border-border rounded-md bg-white', className)}>
<div className="relative w-full overflow-auto ">
<table
ref={ref}
diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx
index 967cac45e..aa5ebf9f9 100644
--- a/apps/web/src/components/ui/toast.tsx
+++ b/apps/web/src/components/ui/toast.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as ToastPrimitives from '@radix-ui/react-toast';
diff --git a/apps/web/src/components/ui/toaster.tsx b/apps/web/src/components/ui/toaster.tsx
index 544056ecc..beb7f25cc 100644
--- a/apps/web/src/components/ui/toaster.tsx
+++ b/apps/web/src/components/ui/toaster.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import {
Toast,
ToastClose,
diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx
index f7ceae529..1849163fe 100644
--- a/apps/web/src/components/ui/tooltip.tsx
+++ b/apps/web/src/components/ui/tooltip.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import * as React from 'react';
import { cn } from '@/utils/cn';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
@@ -16,7 +18,7 @@ const TooltipContent = React.forwardRef<
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',
+ 'z-50 overflow-hidden rounded-md border bg-black px-3 py-1.5 text-sm text-popover 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}
diff --git a/apps/web/src/components/ui/use-toast.ts b/apps/web/src/components/ui/use-toast.ts
index 36d339c79..e6807d074 100644
--- a/apps/web/src/components/ui/use-toast.ts
+++ b/apps/web/src/components/ui/use-toast.ts
@@ -1,3 +1,5 @@
+'use client';
+
// Inspired by react-hot-toast library
import * as React from 'react';
import type { ToastActionElement, ToastProps } from '@/components/ui/toast';
@@ -134,7 +136,7 @@ function dispatch(action: Action) {
});
}
-type Toast = Omit<ToasterToast, 'id'>;
+export type Toast = Omit<ToasterToast, 'id'>;
function toast({ ...props }: Toast) {
const id = genId();
diff --git a/apps/web/src/components/user/ChangePassword.tsx b/apps/web/src/components/user/ChangePassword.tsx
index a2045cdbd..0230bcea8 100644
--- a/apps/web/src/components/user/ChangePassword.tsx
+++ b/apps/web/src/components/user/ChangePassword.tsx
@@ -1,8 +1,8 @@
+import { api, handleError } from '@/app/_trpc/client';
import { ContentHeader, ContentSection } from '@/components/Content';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { toast } from '@/components/ui/use-toast';
-import { api, handleError } from '@/utils/api';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
diff --git a/apps/web/src/hooks/useAppParams.ts b/apps/web/src/hooks/useAppParams.ts
new file mode 100644
index 000000000..805ac9d61
--- /dev/null
+++ b/apps/web/src/hooks/useAppParams.ts
@@ -0,0 +1,16 @@
+import { useParams } from 'next/navigation';
+
+// eslint-disable-next-line
+type AppParams = {
+ organizationId: string;
+ projectId: string;
+};
+
+export function useAppParams<T>() {
+ const params = useParams<T & AppParams>();
+ return {
+ ...(params ?? {}),
+ organizationId: params?.organizationId,
+ projectId: params?.projectId,
+ } as T & AppParams;
+}
diff --git a/apps/web/src/hooks/useEventNames.ts b/apps/web/src/hooks/useEventNames.ts
new file mode 100644
index 000000000..66f42e497
--- /dev/null
+++ b/apps/web/src/hooks/useEventNames.ts
@@ -0,0 +1,12 @@
+import { api } from '@/app/_trpc/client';
+
+export function useEventNames(projectId: string) {
+ const filterEventsQuery = api.chart.events.useQuery({
+ projectId: projectId,
+ });
+
+ return (filterEventsQuery.data ?? []).map((item) => ({
+ value: item.name,
+ label: item.name,
+ }));
+}
diff --git a/apps/web/src/hooks/useOrganizationParams.ts b/apps/web/src/hooks/useOrganizationParams.ts
deleted file mode 100644
index eaf5784e9..000000000
--- a/apps/web/src/hooks/useOrganizationParams.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { z } from 'zod';
-
-import { useQueryParams } from './useQueryParams';
-
-export function useOrganizationParams() {
- return useQueryParams(
- z.object({
- organization: z.string(),
- project: z.string(),
- dashboard: z.string(),
- profileId: z.string().optional(),
- })
- );
-}
diff --git a/apps/web/src/hooks/useRechartDataModel.ts b/apps/web/src/hooks/useRechartDataModel.ts
new file mode 100644
index 000000000..19177a58b
--- /dev/null
+++ b/apps/web/src/hooks/useRechartDataModel.ts
@@ -0,0 +1,34 @@
+import { useMemo } from 'react';
+import type { IChartData } from '@/app/_trpc/client';
+import { alphabetIds } from '@/utils/constants';
+import { getChartColor } from '@/utils/theme';
+
+export function useRechartDataModel(data: IChartData) {
+ return useMemo(() => {
+ return (
+ data.series[0]?.data.map(({ date }) => {
+ return {
+ date,
+ ...data.series.reduce((acc, serie, idx) => {
+ return {
+ ...acc,
+ ...serie.data.reduce(
+ (acc2, item) => {
+ if (item.date === date) {
+ acc2[`${idx}:count`] = item.count;
+ acc2[`${idx}:payload`] = {
+ ...item,
+ color: getChartColor(idx),
+ };
+ }
+ return acc2;
+ },
+ {} as Record<string, any>
+ ),
+ };
+ }, {}),
+ };
+ }) ?? []
+ );
+ }, [data]);
+}
diff --git a/apps/web/src/hooks/useSetCookie.ts b/apps/web/src/hooks/useSetCookie.ts
new file mode 100644
index 000000000..58097ecdf
--- /dev/null
+++ b/apps/web/src/hooks/useSetCookie.ts
@@ -0,0 +1,16 @@
+import { usePathname, useRouter } from 'next/navigation';
+
+export function useSetCookie() {
+ const router = useRouter();
+ const pathname = usePathname();
+ return (key: string, value: string, path?: string) => {
+ fetch(`/api/cookie?${key}=${value}`).then(() => {
+ if (path && path !== pathname) {
+ router.refresh();
+ router.replace(path);
+ } else {
+ router.refresh();
+ }
+ });
+ };
+}
diff --git a/apps/web/src/hooks/useVisibleSeries.ts b/apps/web/src/hooks/useVisibleSeries.ts
new file mode 100644
index 000000000..5d61bda6a
--- /dev/null
+++ b/apps/web/src/hooks/useVisibleSeries.ts
@@ -0,0 +1,28 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import type { IChartData } from '@/app/_trpc/client';
+
+export function useVisibleSeries(data: IChartData, limit?: number | undefined) {
+ const max = limit ?? 20;
+ const [visibleSeries, setVisibleSeries] = useState<string[]>([]);
+ const ref = useRef(false);
+ useEffect(() => {
+ if (!ref.current && data) {
+ setVisibleSeries(
+ data?.series?.slice(0, max).map((serie) => serie.name) ?? []
+ );
+ // ref.current = true;
+ }
+ }, [data, max]);
+
+ return useMemo(() => {
+ return {
+ series: data.series
+ .map((serie, index) => ({
+ ...serie,
+ index,
+ }))
+ .filter((serie) => visibleSeries.includes(serie.name)),
+ setVisibleSeries,
+ } as const;
+ }, [visibleSeries, data.series]);
+}
diff --git a/apps/web/src/modals/AddClient.tsx b/apps/web/src/modals/AddClient.tsx
index c4c62c03d..2de4a1dbe 100644
--- a/apps/web/src/modals/AddClient.tsx
+++ b/apps/web/src/modals/AddClient.tsx
@@ -1,25 +1,24 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
+import Syntax from '@/components/Syntax';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import { toast } from '@/components/ui/use-toast';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
import { clipboard } from '@/utils/clipboard';
import { zodResolver } from '@hookform/resolvers/zod';
import { Copy } from 'lucide-react';
-import dynamic from 'next/dynamic';
+import { useRouter } from 'next/navigation';
import { Controller, useForm, useWatch } from 'react-hook-form';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
-const Syntax = dynamic(import('@/components/Syntax'));
-
const validator = z.object({
name: z.string().min(1, 'Required'),
cors: z.string().min(1, 'Required'),
@@ -28,13 +27,16 @@ const validator = z.object({
});
type IForm = z.infer<typeof validator>;
+interface AddClientProps {
+ organizationId: string;
+}
-export default function CreateProject() {
- const params = useOrganizationParams();
- const refetch = useRefetchActive();
+export default function AddClient({ organizationId }: AddClientProps) {
+ const router = useRouter();
const query = api.project.list.useQuery({
- organizationSlug: params.organization,
+ organizationId,
});
+
const mutation = api.client.create.useMutation({
onError: handleError,
onSuccess() {
@@ -42,9 +44,10 @@ export default function CreateProject() {
title: 'Success',
description: 'Client created!',
});
- refetch();
+ router.refresh();
},
});
+
const { register, handleSubmit, formState, control } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
@@ -128,7 +131,7 @@ export default function CreateProject() {
onSubmit={handleSubmit((values) => {
mutation.mutate({
...values,
- organizationSlug: params.organization,
+ organizationId,
});
})}
>
diff --git a/apps/web/src/modals/AddDashboard.tsx b/apps/web/src/modals/AddDashboard.tsx
index f2cd7b2e1..03eac3d26 100644
--- a/apps/web/src/modals/AddDashboard.tsx
+++ b/apps/web/src/modals/AddDashboard.tsx
@@ -1,10 +1,12 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
@@ -12,8 +14,7 @@ import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
interface AddDashboardProps {
- organizationSlug: string;
- projectSlug: string;
+ projectId: string;
}
const validator = z.object({
@@ -22,11 +23,8 @@ const validator = z.object({
type IForm = z.infer<typeof validator>;
-export default function AddDashboard({
- // organizationSlug,
- projectSlug,
-}: AddDashboardProps) {
- const refetch = useRefetchActive();
+export default function AddDashboard({ projectId }: AddDashboardProps) {
+ const router = useRouter();
const { register, handleSubmit, formState } = useForm<IForm>({
resolver: zodResolver(validator),
@@ -38,7 +36,7 @@ export default function AddDashboard({
const mutation = api.dashboard.create.useMutation({
onError: handleError,
onSuccess() {
- refetch();
+ router.refresh();
toast({
title: 'Success',
description: 'Dashboard created.',
@@ -49,13 +47,13 @@ export default function AddDashboard({
return (
<ModalContent>
- <ModalHeader title="Edit client" />
+ <ModalHeader title="Add dashboard" />
<form
className="flex flex-col gap-4"
onSubmit={handleSubmit(({ name }) => {
mutation.mutate({
name,
- projectSlug,
+ projectId,
});
})}
>
diff --git a/apps/web/src/modals/AddProject.tsx b/apps/web/src/modals/AddProject.tsx
index 2bae26613..604edf93f 100644
--- a/apps/web/src/modals/AddProject.tsx
+++ b/apps/web/src/modals/AddProject.tsx
@@ -1,11 +1,12 @@
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
@@ -17,18 +18,19 @@ const validator = z.object({
});
type IForm = z.infer<typeof validator>;
-
-export default function AddProject() {
- const params = useOrganizationParams();
- const refetch = useRefetchActive();
+interface AddProjectProps {
+ organizationId: string;
+}
+export default function AddProject({ organizationId }: AddProjectProps) {
+ const router = useRouter();
const mutation = api.project.create.useMutation({
onError: handleError,
onSuccess() {
+ router.refresh();
toast({
title: 'Success',
description: 'Project created! Lets create a client for it 🤘',
});
- refetch();
popModal();
},
});
@@ -46,11 +48,17 @@ export default function AddProject() {
onSubmit={handleSubmit((values) => {
mutation.mutate({
...values,
- organizationSlug: params.organization,
+ organizationId,
});
})}
>
- <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <div className="flex flex-col gap-4">
+ <InputWithLabel
+ label="Name"
+ placeholder="Name"
+ {...register('name')}
+ />
+ </div>
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
diff --git a/apps/web/src/modals/Confirm.tsx b/apps/web/src/modals/Confirm.tsx
index d4c1a90d9..126d17bad 100644
--- a/apps/web/src/modals/Confirm.tsx
+++ b/apps/web/src/modals/Confirm.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import { ButtonContainer } from '@/components/ButtonContainer';
import { Button } from '@/components/ui/button';
diff --git a/apps/web/src/modals/EditClient.tsx b/apps/web/src/modals/EditClient.tsx
index 8a081ed43..2cac3767b 100644
--- a/apps/web/src/modals/EditClient.tsx
+++ b/apps/web/src/modals/EditClient.tsx
@@ -1,20 +1,20 @@
-import { useEffect } from 'react';
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
+import type { IClientWithProject } from '@/types';
import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
-interface EditClientProps {
- id: string;
-}
+type EditClientProps = IClientWithProject;
const validator = z.object({
id: z.string().min(1),
@@ -24,35 +24,29 @@ const validator = z.object({
type IForm = z.infer<typeof validator>;
-export default function EditClient({ id }: EditClientProps) {
- const refetch = useRefetchActive();
+export default function EditClient({ id, name, cors }: EditClientProps) {
+ const router = useRouter();
+ const { register, handleSubmit, reset, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ id,
+ name,
+ cors,
+ },
+ });
+
const mutation = api.client.update.useMutation({
onError: handleError,
onSuccess() {
+ reset();
toast({
title: 'Success',
description: 'Client updated.',
});
popModal();
- refetch();
+ router.refresh();
},
});
- const query = api.client.get.useQuery({ id });
- const data = query.data;
- const { register, handleSubmit, reset, formState } = useForm<IForm>({
- resolver: zodResolver(validator),
- defaultValues: {
- id: '',
- name: '',
- cors: '',
- },
- });
-
- useEffect(() => {
- if (data) {
- reset(data);
- }
- }, [data, reset]);
return (
<ModalContent>
@@ -67,11 +61,13 @@ export default function EditClient({ id }: EditClientProps) {
label="Name"
placeholder="Name"
{...register('name')}
+ defaultValue={name}
/>
<InputWithLabel
label="Cors"
placeholder="Cors"
{...register('cors')}
+ defaultValue={cors}
/>
</div>
<ButtonContainer>
diff --git a/apps/web/src/modals/EditDashboard.tsx b/apps/web/src/modals/EditDashboard.tsx
index dca3ac8ec..ee8862eea 100644
--- a/apps/web/src/modals/EditDashboard.tsx
+++ b/apps/web/src/modals/EditDashboard.tsx
@@ -1,20 +1,20 @@
-import { useEffect } from 'react';
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
+import type { IServiceDashboardWithProject } from '@/server/services/dashboard.service';
import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
-interface EditDashboardProps {
- id: string;
-}
+type EditDashboardProps = IServiceDashboardWithProject;
const validator = z.object({
id: z.string().min(1),
@@ -23,34 +23,28 @@ const validator = z.object({
type IForm = z.infer<typeof validator>;
-export default function EditDashboard({ id }: EditDashboardProps) {
- const refetch = useRefetchActive();
+export default function EditDashboard({ id, name }: EditDashboardProps) {
+ const router = useRouter();
+ const { register, handleSubmit, reset, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ id,
+ name,
+ },
+ });
+
const mutation = api.dashboard.update.useMutation({
onError: handleError,
onSuccess() {
+ reset();
toast({
title: 'Success',
description: 'Dashboard updated.',
});
popModal();
- refetch();
+ router.refresh();
},
});
- const query = api.dashboard.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>
@@ -60,7 +54,12 @@ export default function EditDashboard({ id }: EditDashboardProps) {
mutation.mutate(values);
})}
>
- <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <InputWithLabel
+ label="Name"
+ placeholder="Name"
+ {...register('name')}
+ defaultValue={name}
+ />
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
diff --git a/apps/web/src/modals/EditProject.tsx b/apps/web/src/modals/EditProject.tsx
index 7d8658f86..934875f2f 100644
--- a/apps/web/src/modals/EditProject.tsx
+++ b/apps/web/src/modals/EditProject.tsx
@@ -1,20 +1,20 @@
-import { useEffect } from 'react';
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { toast } from '@/components/ui/use-toast';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
+import type { IProject } from '@/types';
import { zodResolver } from '@hookform/resolvers/zod';
+import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
-interface EditProjectProps {
- id: string;
-}
+type EditProjectProps = IProject;
const validator = z.object({
id: z.string().min(1),
@@ -23,34 +23,28 @@ const validator = z.object({
type IForm = z.infer<typeof validator>;
-export default function EditProject({ id }: EditProjectProps) {
- const refetch = useRefetchActive();
+export default function EditProject({ id, name }: EditProjectProps) {
+ const router = useRouter();
+ const { register, handleSubmit, reset, formState } = useForm<IForm>({
+ resolver: zodResolver(validator),
+ defaultValues: {
+ id,
+ name,
+ },
+ });
+
const mutation = api.project.update.useMutation({
onError: handleError,
onSuccess() {
+ reset();
+ router.refresh();
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>
@@ -60,7 +54,12 @@ export default function EditProject({ id }: EditProjectProps) {
mutation.mutate(values);
})}
>
- <InputWithLabel label="Name" placeholder="Name" {...register('name')} />
+ <InputWithLabel
+ label="Name"
+ placeholder="Name"
+ {...register('name')}
+ defaultValue={name}
+ />
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel
diff --git a/apps/web/src/modals/EditReport.tsx b/apps/web/src/modals/EditReport.tsx
index c64755f55..bcbabab67 100644
--- a/apps/web/src/modals/EditReport.tsx
+++ b/apps/web/src/modals/EditReport.tsx
@@ -1,10 +1,8 @@
-import { useEffect } from 'react';
+'use client';
+
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
-import { toast } from '@/components/ui/use-toast';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
-import { api, handleError } from '@/utils/api';
import { zodResolver } from '@hookform/resolvers/zod';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
diff --git a/apps/web/src/modals/Modal/Container.tsx b/apps/web/src/modals/Modal/Container.tsx
index 61e1351b7..c943e52cf 100644
--- a/apps/web/src/modals/Modal/Container.tsx
+++ b/apps/web/src/modals/Modal/Container.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import { Button } from '@/components/ui/button';
import { X } from 'lucide-react';
@@ -17,16 +19,23 @@ export function ModalContent({ children }: ModalContentProps) {
interface ModalHeaderProps {
title: string | React.ReactNode;
+ onClose?: (() => void) | false;
}
-export function ModalHeader({ title }: ModalHeaderProps) {
+export function ModalHeader({ title, onClose }: ModalHeaderProps) {
return (
<div className="flex items-center justify-between mb-6">
<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>
+ {onClose !== false && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => (onClose ? onClose() : popModal())}
+ >
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </Button>
+ )}
</div>
);
}
diff --git a/apps/web/src/modals/SaveReport.tsx b/apps/web/src/modals/SaveReport.tsx
index 2327bc7e0..3e4b7f2fd 100644
--- a/apps/web/src/modals/SaveReport.tsx
+++ b/apps/web/src/modals/SaveReport.tsx
@@ -1,17 +1,15 @@
-import { useEffect } from 'react';
+'use client';
+
+import { api, handleError } from '@/app/_trpc/client';
import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import { toast } from '@/components/ui/use-toast';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { useRefetchActive } from '@/hooks/useRefetchActive';
import type { IChartInput } from '@/types';
-import { api, handleError } from '@/utils/api';
-import { strip } from '@/utils/object';
import { zodResolver } from '@hookform/resolvers/zod';
-import { useRouter } from 'next/router';
+import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { Controller, useForm } from 'react-hook-form';
import { z } from 'zod';
@@ -32,8 +30,12 @@ type IForm = z.infer<typeof validator>;
export default function SaveReport({ report }: SaveReportProps) {
const router = useRouter();
- const { organization, project, dashboard } = useOrganizationParams();
- const refetch = useRefetchActive();
+ const params = useParams();
+ const organizationId = params.organizationId as string;
+ const projectId = params.projectId as string;
+ const searchParams = useSearchParams();
+ const dashboardId = searchParams.get('dashboardId') ?? undefined;
+
const save = api.report.save.useMutation({
onError: handleError,
onSuccess(res) {
@@ -42,11 +44,11 @@ export default function SaveReport({ report }: SaveReportProps) {
description: 'Report saved.',
});
popModal();
- refetch();
- router.push({
- pathname: `/${organization}/${project}/reports/${res.id}`,
- query: strip({ dashboard }),
- });
+ router.push(
+ `/${organizationId}/${projectId}/reports/${
+ res.id
+ }?${searchParams.toString()}`
+ );
},
});
@@ -55,7 +57,7 @@ export default function SaveReport({ report }: SaveReportProps) {
resolver: zodResolver(validator),
defaultValues: {
name: report.name,
- dashboardId: '',
+ dashboardId,
},
});
@@ -72,7 +74,7 @@ export default function SaveReport({ report }: SaveReportProps) {
});
const dashboardQuery = api.dashboard.list.useQuery({
- projectSlug: project,
+ projectId,
});
const dashboards = (dashboardQuery.data ?? []).map((item) => ({
@@ -80,15 +82,6 @@ export default function SaveReport({ report }: SaveReportProps) {
label: item.name,
}));
- useEffect(() => {
- if (dashboard && dashboardQuery.data) {
- const match = dashboardQuery.data.find((item) => item.slug === dashboard);
- if (match) {
- setValue('dashboardId', match.id);
- }
- }
- }, [dashboard, dashboardQuery]);
-
return (
<ModalContent>
<ModalHeader title="Edit client" />
@@ -123,7 +116,7 @@ export default function SaveReport({ report }: SaveReportProps) {
placeholder="Select a dashboard"
onCreate={(value) => {
dashboardMutation.mutate({
- projectSlug: project,
+ projectId,
name: value,
});
}}
diff --git a/apps/web/src/modals/index.tsx b/apps/web/src/modals/index.tsx
index 3ac0fe488..3bd429edb 100644
--- a/apps/web/src/modals/index.tsx
+++ b/apps/web/src/modals/index.tsx
@@ -1,3 +1,5 @@
+'use client';
+
import { Suspense, useEffect, useRef, useState } from 'react';
import { Loader } from 'lucide-react';
import mitt from 'mitt';
@@ -7,7 +9,7 @@ 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">
+ <div className="fixed left-0 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>
);
@@ -65,11 +67,11 @@ interface StateItem {
interface ModalWrapperProps {
children: React.ReactNode;
- name: ModalRoutes;
- isOnTop: boolean;
+ name?: ModalRoutes;
+ isOnTop?: boolean;
}
-function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) {
+export function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) {
const ref = useRef<HTMLDivElement>(null);
useOnClickOutside(ref, (event) => {
@@ -79,7 +81,7 @@ function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) {
? !!target.closest('[data-radix-popper-content-wrapper]')
: false;
- if (isOnTop && !isPortal) {
+ if (isOnTop && !isPortal && name) {
emitter.emit('pop', {
name,
});
@@ -111,6 +113,8 @@ export function ModalProvider() {
useEffect(() => {
emitter.on('push', ({ name, props }) => {
+ console.log('hej?', name, props);
+
setState((p) => [
...p,
{
@@ -154,7 +158,7 @@ export function ModalProvider() {
return (
<>
{!!state.length && (
- <div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)]"></div>
+ <div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)] z-50"></div>
)}
{state.map((item, index) => {
const Modal = modals[item.name];
diff --git a/apps/web/src/pages/[organization]/[project]/[dashboard].tsx b/apps/web/src/pages/[organization]/[project]/[dashboard].tsx
deleted file mode 100644
index f70b5f58f..000000000
--- a/apps/web/src/pages/[organization]/[project]/[dashboard].tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import { useMemo, useState } from 'react';
-import { CardActions, CardActionsItem } from '@/components/Card';
-import { Container } from '@/components/Container';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { LazyChart } from '@/components/report/chart/LazyChart';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
-import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { db } from '@/server/db';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import type { IChartRange } from '@/types';
-import { api, handleError } from '@/utils/api';
-import { cn } from '@/utils/cn';
-import { timeRanges } from '@/utils/constants';
-import { ChevronRight, MoreHorizontal, Trash } from 'lucide-react';
-import Link from 'next/link';
-
-export const getServerSideProps = createServerSideProps(async (context) => {
- const projectSlug = context.params?.project as string;
- const dashboardSlug = context.params?.dashboard as string;
- try {
- await db.dashboard.findFirstOrThrow({
- select: {
- id: true,
- },
- where: {
- slug: dashboardSlug,
- project: {
- slug: projectSlug,
- },
- },
- });
- } catch (error) {
- return {
- notFound: true,
- };
- }
-});
-
-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 = useMemo(() => {
- return query.data?.reports ?? [];
- }, [query]);
-
- const deletion = api.report.delete.useMutation({
- onError: handleError,
- onSuccess() {
- query.refetch();
- },
- });
-
- const [range, setRange] = useState<null | IChartRange>(null);
-
- return (
- <MainLayout>
- <Container>
- <PageTitle>{dashboard?.name}</PageTitle>
-
- <RadioGroup className="mb-8 overflow-auto">
- {Object.values(timeRanges).map((key) => {
- return (
- <RadioGroupItem
- key={key}
- active={key === range}
- onClick={() => {
- setRange((p) => (p === key ? null : key));
- }}
- >
- {key}
- </RadioGroupItem>
- );
- })}
- </RadioGroup>
-
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
- {reports.map((report) => {
- const chartRange = timeRanges[report.range];
- return (
- <div
- className="rounded-md border border-border bg-white shadow"
- key={report.id}
- >
- <Link
- href={`/${params.organization}/${params.project}/reports/${report.id}?dashboard=${params.dashboard}`}
- className="flex border-b border-border p-4 leading-none [&_svg]:hover:opacity-100 items-center justify-between"
- shallow
- >
- <div>
- <div className="font-medium">{report.name}</div>
- {chartRange !== null && (
- <div className="mt-2 text-sm flex gap-2">
- <span className={range !== null ? 'line-through' : ''}>
- {chartRange}
- </span>
- {range !== null && <span>{range}</span>}
- </div>
- )}
- </div>
- <div className="flex items-center gap-4">
- <DropdownMenu>
- <DropdownMenuTrigger className="h-8 w-8 hover:border rounded justify-center items-center flex">
- <MoreHorizontal size={16} />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-[200px]">
- <DropdownMenuGroup>
- <DropdownMenuItem
- className="text-destructive"
- onClick={(event) => {
- event.stopPropagation();
- deletion.mutate({
- reportId: report.id,
- });
- }}
- >
- <Trash size={16} className="mr-2" />
- Delete
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <ChevronRight
- className="opacity-10 transition-opacity"
- size={16}
- />
- </div>
- </Link>
- <div
- className={cn(
- 'p-4 pl-2',
- report.chartType === 'bar' && 'overflow-auto max-h-[300px]'
- )}
- >
- <LazyChart
- {...report}
- range={range ?? report.range}
- editMode={false}
- />
- </div>
- </div>
- );
- })}
- </div>
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/[project]/events.tsx b/apps/web/src/pages/[organization]/[project]/events.tsx
deleted file mode 100644
index f73c3bb24..000000000
--- a/apps/web/src/pages/[organization]/[project]/events.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useMemo, useState } from 'react';
-import { Container } from '@/components/Container';
-import { EventsTable } from '@/components/events/EventsTable';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { Pagination, usePagination } from '@/components/Pagination';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { api } from '@/utils/api';
-
-export default function Events() {
- const pagination = usePagination();
- const params = useOrganizationParams();
- const [eventFilters, setEventFilters] = useState<string[]>([]);
- const eventsQuery = api.event.list.useQuery(
- {
- events: eventFilters,
- projectSlug: params.project,
- ...pagination,
- },
- {
- keepPreviousData: true,
- }
- );
- const events = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
-
- const filterEventsQuery = api.chart.events.useQuery({
- projectSlug: params.project,
- });
- const filterEvents = (filterEventsQuery.data ?? []).map((item) => ({
- value: item.name,
- label: item.name,
- }));
-
- return (
- <MainLayout>
- <Container>
- <PageTitle>Events</PageTitle>
-
- <div className="flex justify-between items-center">
- <div>
- <ComboboxAdvanced
- items={filterEvents}
- selected={eventFilters}
- setSelected={setEventFilters}
- placeholder="Filter by event"
- />
- </div>
- <Pagination {...pagination} />
- </div>
- <EventsTable data={events} />
- <Pagination {...pagination} />
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/[project]/index.tsx b/apps/web/src/pages/[organization]/[project]/index.tsx
deleted file mode 100644
index 7381b8292..000000000
--- a/apps/web/src/pages/[organization]/[project]/index.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { Card, CardActions, CardActionsItem } from '@/components/Card';
-import { Container } from '@/components/Container';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { pushModal } from '@/modals';
-import { db } from '@/server/db';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api, handleError } from '@/utils/api';
-import { Pencil, Plus, Trash } from 'lucide-react';
-import Link from 'next/link';
-
-export const getServerSideProps = createServerSideProps(async (context) => {
- const projectSlug = context.params?.project as string;
- try {
- await db.project.findFirstOrThrow({
- select: {
- id: true,
- },
- where: {
- slug: projectSlug,
- },
- });
- } catch (error) {
- return {
- notFound: true,
- };
- }
-});
-
-export default function Home() {
- const params = useOrganizationParams();
- const query = api.dashboard.list.useQuery(
- {
- projectSlug: params.project,
- },
- {
- enabled: Boolean(params.organization && params.project),
- }
- );
- const dashboards = query.data ?? [];
- const deletion = api.dashboard.delete.useMutation({
- onError: handleError,
- onSuccess() {
- query.refetch();
- },
- });
-
- return (
- <MainLayout>
- <Container>
- <PageTitle>Dashboards</PageTitle>
- <div className="grid sm:grid-cols-2 gap-4">
- {dashboards.map((item) => (
- <Card key={item.id} hover>
- <Link
- href={`/${params.organization}/${params.project}/${item.slug}`}
- className="block p-4 font-medium leading-none"
- shallow
- >
- {item.name}
- </Link>
-
- <CardActions>
- <CardActionsItem className="w-full" asChild>
- <button
- onClick={() => {
- pushModal('EditDashboard', {
- id: item.id,
- });
- }}
- >
- <Pencil size={16} />
- Edit
- </button>
- </CardActionsItem>
- <CardActionsItem className="text-destructive w-full" asChild>
- <button
- onClick={() => {
- deletion.mutate({
- id: item.id,
- });
- }}
- >
- <Trash size={16} />
- Delete
- </button>
- </CardActionsItem>
- </CardActions>
- </Card>
- ))}
- <Card hover className="border-dashed">
- <button
- className="flex items-center justify-between w-full p-4 font-medium leading-none"
- onClick={() => {
- pushModal('AddDashboard', {
- projectSlug: params.project,
- organizationSlug: params.organization,
- });
- }}
- >
- Create new dashboard
- <Plus size={16} />
- </button>
- </Card>
- </div>
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/[project]/profiles/[profileId].tsx b/apps/web/src/pages/[organization]/[project]/profiles/[profileId].tsx
deleted file mode 100644
index 090403f3f..000000000
--- a/apps/web/src/pages/[organization]/[project]/profiles/[profileId].tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useMemo, useState } from 'react';
-import { Container } from '@/components/Container';
-import { EventsTable } from '@/components/events/EventsTable';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { Pagination, usePagination } from '@/components/Pagination';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { useQueryParams } from '@/hooks/useQueryParams';
-import { api } from '@/utils/api';
-import { getProfileName } from '@/utils/getters';
-import { z } from 'zod';
-
-export default function ProfileId() {
- const pagination = usePagination();
- const params = useOrganizationParams();
- const { profileId } = useQueryParams(
- z.object({
- profileId: z.string(),
- })
- );
- const [eventFilters, setEventFilters] = useState<string[]>([]);
- const filterEventsQuery = api.chart.events.useQuery({
- projectSlug: params.project,
- });
- const filterEvents = (filterEventsQuery.data ?? []).map((item) => ({
- value: item.name,
- label: item.name,
- }));
- const profileQuery = api.profile.get.useQuery({
- id: profileId,
- });
- const eventsQuery = api.event.list.useQuery(
- {
- projectSlug: params.project,
- profileId,
- events: eventFilters,
- ...pagination,
- },
- {
- keepPreviousData: true,
- }
- );
- const profile = profileQuery.data ?? null;
- const events = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
-
- return (
- <MainLayout>
- <Container>
- <PageTitle>{getProfileName(profile)}</PageTitle>
- <pre>{JSON.stringify(profile?.properties, null, 2)}</pre>
- <div className="flex justify-between items-center">
- <div>
- <ComboboxAdvanced
- items={filterEvents}
- selected={eventFilters}
- setSelected={setEventFilters}
- placeholder="Filter by event"
- />
- </div>
- <Pagination {...pagination} />
- </div>
- <EventsTable data={events} />
- <Pagination {...pagination} />
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/[project]/profiles/index.tsx b/apps/web/src/pages/[organization]/[project]/profiles/index.tsx
deleted file mode 100644
index d4a1e86ab..000000000
--- a/apps/web/src/pages/[organization]/[project]/profiles/index.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { useMemo } from 'react';
-import { Container } from '@/components/Container';
-import { DataTable } from '@/components/DataTable';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { Pagination, usePagination } from '@/components/Pagination';
-import { Avatar, AvatarFallback } from '@/components/ui/avatar';
-import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { api } from '@/utils/api';
-import type { RouterOutputs } from '@/utils/api';
-import { formatDateTime } from '@/utils/date';
-import { toDots } from '@/utils/object';
-import { AvatarImage } from '@radix-ui/react-avatar';
-import { createColumnHelper } from '@tanstack/react-table';
-import Link from 'next/link';
-
-const columnHelper =
- createColumnHelper<RouterOutputs['profile']['list'][number]>();
-
-export default function Events() {
- const pagination = usePagination();
- const params = useOrganizationParams();
- const eventsQuery = api.profile.list.useQuery(
- {
- projectSlug: params.project,
- ...pagination,
- },
- {
- keepPreviousData: true,
- }
- );
- const profiles = useMemo(() => eventsQuery.data ?? [], [eventsQuery]);
- const columns = useMemo(() => {
- return [
- columnHelper.accessor((row) => row.createdAt, {
- id: 'createdAt',
- header: () => 'Created At',
- cell(info) {
- return formatDateTime(info.getValue());
- },
- }),
- columnHelper.accessor('first_name', {
- id: 'name',
- header: () => 'Name',
- cell(info) {
- const profile = info.row.original;
- return (
- <Link
- href={`/${params.organization}/${params.project}/profiles/${profile?.id}`}
- className="flex items-center gap-2"
- shallow
- >
- <Avatar className="h-6 w-6">
- {profile?.avatar && <AvatarImage src={profile.avatar} />}
- <AvatarFallback className="text-xs">
- {profile?.first_name?.at(0)}
- </AvatarFallback>
- </Avatar>
- <div className="flex flex-col">
- <div>
- {[profile?.first_name, profile?.last_name]
- .filter(Boolean)
- .join(' ')}
- </div>
- <div className="text-muted-foreground text-xs">
- {profile.external_id}
- </div>
- </div>
- </Link>
- );
- },
- }),
- columnHelper.accessor((row) => row.properties, {
- id: 'properties',
- header: () => 'Properties',
- cell(info) {
- const dots = toDots(info.getValue() as Record<string, any>);
- if (Object.keys(dots).length === 0) return 'No properties';
- return (
- <Table className="mini">
- <TableBody>
- {Object.keys(dots).map((key) => {
- return (
- <TableRow key={key}>
- <TableCell className="font-medium">{key}</TableCell>
- <TableCell>
- {typeof dots[key] === 'boolean'
- ? dots[key]
- ? 'true'
- : 'false'
- : dots[key]}
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- );
- },
- }),
- ];
- }, []);
- return (
- <MainLayout>
- <Container>
- <PageTitle>Profiles</PageTitle>
- <Pagination {...pagination} />
- <DataTable data={profiles} columns={columns}></DataTable>
- <Pagination {...pagination} />
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/[project]/reports/[reportId].tsx b/apps/web/src/pages/[organization]/[project]/reports/[reportId].tsx
deleted file mode 100644
index d1ed7acc2..000000000
--- a/apps/web/src/pages/[organization]/[project]/reports/[reportId].tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { createServerSideProps } from '@/server/getServerSideProps';
-
-export { default } from './index';
-
-export const getServerSideProps = createServerSideProps();
diff --git a/apps/web/src/pages/[organization]/[project]/reports/index.tsx b/apps/web/src/pages/[organization]/[project]/reports/index.tsx
deleted file mode 100644
index 37d7bc008..000000000
--- a/apps/web/src/pages/[organization]/[project]/reports/index.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useCallback, useEffect } from 'react';
-import { Container } from '@/components/Container';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { Chart } from '@/components/report/chart';
-import { useReportId } from '@/components/report/hooks/useReportId';
-import { ReportChartType } from '@/components/report/ReportChartType';
-import { ReportDateRange } from '@/components/report/ReportDateRange';
-import { ReportInterval } from '@/components/report/ReportInterval';
-import { ReportSaveButton } from '@/components/report/ReportSaveButton';
-import { reset, setName, setReport } from '@/components/report/reportSlice';
-import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar';
-import { Button } from '@/components/ui/button';
-import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
-import { popModal, pushModal } from '@/modals';
-import { useDispatch, useSelector } from '@/redux';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api } from '@/utils/api';
-import { Pencil } from 'lucide-react';
-
-export const getServerSideProps = createServerSideProps();
-
-export default function Page() {
- const { reportId } = useReportId();
- const dispatch = useDispatch();
- const report = useSelector((state) => state.report);
- const reportQuery = api.report.get.useQuery(
- { id: String(reportId) },
- {
- enabled: Boolean(reportId),
- }
- );
-
- // Set report if reportId exists
- useEffect(() => {
- if (reportId && reportQuery.data) {
- dispatch(setReport(reportQuery.data));
- }
-
- if (!reportId) {
- dispatch(reset());
- }
-
- // Reset report state before leaving
- return () => {
- dispatch(reset());
- };
- }, [reportId, reportQuery.data, dispatch]);
-
- return (
- <Sheet>
- <MainLayout>
- <Container>
- <PageTitle>
- <span className="flex items-center gap-4">
- {report.name}
- <Button
- variant={'outline'}
- onClick={() => {
- pushModal('EditReport', {
- form: {
- name: report.name,
- },
- onSubmit: (values) => {
- dispatch(setName(values.name));
- popModal('EditReport');
- },
- });
- }}
- >
- <Pencil size={16} />
- </Button>
- </span>
- </PageTitle>
- <div className="flex flex-col gap-4 mt-8">
- <div className="flex flex-col gap-4">
- <ReportDateRange />
- <div className="flex flex-col sm:flex-row gap-4 justify-between">
- <div className="flex gap-4">
- <ReportChartType />
- <ReportInterval />
- </div>
- <div className="flex gap-4">
- <SheetTrigger asChild>
- <Button size="default">Select events & filters</Button>
- </SheetTrigger>
- <ReportSaveButton />
- </div>
- </div>
- </div>
- <Chart {...report} editMode />
- </div>
- </Container>
- </MainLayout>
- <SheetContent className="!max-w-lg w-full">
- <ReportSidebar />
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/apps/web/src/pages/[organization]/index.tsx b/apps/web/src/pages/[organization]/index.tsx
deleted file mode 100644
index b015cc4ce..000000000
--- a/apps/web/src/pages/[organization]/index.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { Card } from '@/components/Card';
-import { Container } from '@/components/Container';
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { PageTitle } from '@/components/PageTitle';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api } from '@/utils/api';
-import Link from 'next/link';
-
-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>Projects</PageTitle>
- <div className="grid sm:grid-cols-2 gap-4">
- {projects.map((item) => (
- <Card key={item.id} hover>
- <Link
- href={`/${params.organization}/${item.slug}`}
- className="block p-4 font-medium leading-none"
- shallow
- >
- {item.name}
- </Link>
- </Card>
- ))}
- </div>
- </Container>
- </MainLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/settings/clients.tsx b/apps/web/src/pages/[organization]/settings/clients.tsx
deleted file mode 100644
index b62f621eb..000000000
--- a/apps/web/src/pages/[organization]/settings/clients.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { columns } from '@/components/clients/table';
-import { ContentHeader } from '@/components/Content';
-import { DataTable } from '@/components/DataTable';
-import { SettingsLayout } from '@/components/layouts/SettingsLayout';
-import { Button } from '@/components/ui/button';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { pushModal } from '@/modals';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api } from '@/utils/api';
-
-export const getServerSideProps = createServerSideProps();
-
-export default function Clients() {
- const params = useOrganizationParams();
- const query = api.client.list.useQuery({
- organizationSlug: params.organization,
- });
- const data = query.data ?? [];
- return (
- <SettingsLayout>
- <ContentHeader title="Clients" text="List of your clients">
- <Button onClick={() => pushModal('AddClient')}>Create</Button>
- </ContentHeader>
- <DataTable data={data} columns={columns} />
- </SettingsLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/settings/organization.tsx b/apps/web/src/pages/[organization]/settings/organization.tsx
deleted file mode 100644
index c0963cfe4..000000000
--- a/apps/web/src/pages/[organization]/settings/organization.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { useEffect } from 'react';
-import { ContentHeader, ContentSection } from '@/components/Content';
-import { InputError } from '@/components/forms/InputError';
-import { SettingsLayout } from '@/components/layouts/SettingsLayout';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { toast } from '@/components/ui/use-toast';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api, handleError } from '@/utils/api';
-import { useRouter } from 'next/router';
-import { useForm } from 'react-hook-form';
-import { z } from 'zod';
-
-export const getServerSideProps = createServerSideProps();
-
-const validator = z.object({
- id: z.string().min(2),
- name: z.string().min(2),
-});
-
-type IForm = z.infer<typeof validator>;
-
-export default function Organization() {
- const router = useRouter();
- const params = useOrganizationParams();
- const query = api.organization.get.useQuery({
- slug: params.organization,
- });
- const mutation = api.organization.update.useMutation({
- onSuccess(res) {
- toast({
- title: 'Organization updated',
- description: 'Your organization has been updated.',
- });
- query.refetch();
- router.replace(`/${res.slug}/settings/organization`);
- },
- onError: handleError,
- });
- const data = query.data;
-
- const { register, handleSubmit, reset, formState } = useForm<IForm>({
- defaultValues: {
- id: '',
- name: '',
- },
- });
-
- 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={[
- 'Notice. Changing name will result in a url change as well.',
- <InputError key="error" {...formState.errors.name} />,
- ]}
- >
- <Input {...register('name')} />
- </ContentSection>
- <ContentSection
- title="Invite user"
- text="Invite users to this organization. You can invite several users with (,)"
- >
- <Input disabled />
- </ContentSection>
- </form>
- </SettingsLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/settings/profile.tsx b/apps/web/src/pages/[organization]/settings/profile.tsx
deleted file mode 100644
index 854499b5d..000000000
--- a/apps/web/src/pages/[organization]/settings/profile.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { useEffect } from 'react';
-import { ContentHeader, ContentSection } from '@/components/Content';
-import { InputError } from '@/components/forms/InputError';
-import { SettingsLayout } from '@/components/layouts/SettingsLayout';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { toast } from '@/components/ui/use-toast';
-import { ChangePassword } from '@/components/user/ChangePassword';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api, handleError } from '@/utils/api';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useForm } from 'react-hook-form';
-import { z } from 'zod';
-
-export const getServerSideProps = createServerSideProps();
-
-const validator = z.object({
- name: z.string().min(2),
- email: z.string().email(),
-});
-
-type IForm = z.infer<typeof validator>;
-
-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<IForm>({
- resolver: zodResolver(validator),
- 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',
- <InputError key="error" {...formState.errors.name} />,
- ]}
- >
- <Input {...register('name')} />
- </ContentSection>
- <ContentSection
- title="Mail"
- text={[
- 'Your email address',
- <InputError key="error" {...formState.errors.email} />,
- ]}
- >
- <Input {...register('email')} />
- </ContentSection>
- </form>
-
- <div className="mt-8">
- <ChangePassword />
- </div>
- </SettingsLayout>
- );
-}
diff --git a/apps/web/src/pages/[organization]/settings/projects.tsx b/apps/web/src/pages/[organization]/settings/projects.tsx
deleted file mode 100644
index 75abde0aa..000000000
--- a/apps/web/src/pages/[organization]/settings/projects.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { ContentHeader } from '@/components/Content';
-import { DataTable } from '@/components/DataTable';
-import { SettingsLayout } from '@/components/layouts/SettingsLayout';
-import { columns } from '@/components/projects/table';
-import { Button } from '@/components/ui/button';
-import { useOrganizationParams } from '@/hooks/useOrganizationParams';
-import { pushModal } from '@/modals';
-import { createServerSideProps } from '@/server/getServerSideProps';
-import { api } from '@/utils/api';
-
-export const getServerSideProps = createServerSideProps();
-
-export default function Projects() {
- const params = useOrganizationParams();
- const query = api.project.list.useQuery({
- organizationSlug: params.organization,
- });
- const data = query.data ?? [];
- return (
- <SettingsLayout>
- <ContentHeader title="Projects" text="List of your projects">
- <Button onClick={() => pushModal('AddProject')}>Create</Button>
- </ContentHeader>
- <DataTable data={data} columns={columns} />
- </SettingsLayout>
- );
-}
diff --git a/apps/web/src/pages/_app.tsx b/apps/web/src/pages/_app.tsx
deleted file mode 100644
index 62741a5b0..000000000
--- a/apps/web/src/pages/_app.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { Suspense } from 'react';
-import { Toaster } from '@/components/ui/toaster';
-import store from '@/redux';
-import { api } from '@/utils/api';
-import type { Session } from 'next-auth';
-import { SessionProvider } from 'next-auth/react';
-import type { AppType } from 'next/app';
-import { Space_Grotesk } from 'next/font/google';
-import { Provider as ReduxProvider } from 'react-redux';
-
-import '@/styles/globals.css';
-
-import { TooltipProvider } from '@/components/ui/tooltip';
-import { ModalProvider } from '@/modals';
-
-const font = Space_Grotesk({
- subsets: ['latin'],
- display: 'swap',
- variable: '--text',
-});
-
-const MixanApp: AppType<{ session: Session | null }> = ({
- Component,
- pageProps: { session, ...pageProps },
-}) => {
- return (
- <div className={font.className}>
- <SessionProvider session={session}>
- <ReduxProvider store={store}>
- <Suspense fallback="Loading">
- <TooltipProvider delayDuration={200}>
- <Component {...pageProps} />
- </TooltipProvider>
- <Toaster />
- <ModalProvider />
- </Suspense>
- </ReduxProvider>
- </SessionProvider>
- </div>
- );
-};
-
-export default api.withTRPC(MixanApp);
diff --git a/apps/web/src/pages/api/auth/[...nextauth].ts b/apps/web/src/pages/api/auth/[...nextauth].ts
deleted file mode 100644
index 1e8a60d53..000000000
--- a/apps/web/src/pages/api/auth/[...nextauth].ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { authOptions } from '@/server/auth';
-import NextAuth from 'next-auth';
-
-export default NextAuth(authOptions);
diff --git a/apps/web/src/pages/api/trpc/[trpc].ts b/apps/web/src/pages/api/trpc/[trpc].ts
deleted file mode 100644
index f8dac78aa..000000000
--- a/apps/web/src/pages/api/trpc/[trpc].ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { env } from '@/env.mjs';
-import { appRouter } from '@/server/api/root';
-import { createTRPCContext } from '@/server/api/trpc';
-import { createNextApiHandler } from '@trpc/server/adapters/next';
-
-export const config = {
- api: {
- responseLimit: false,
- },
-};
-
-// export API handler
-export default createNextApiHandler({
- router: appRouter,
- createContext: createTRPCContext,
- onError:
- env.NODE_ENV === 'development'
- ? ({ path, error }) => {
- console.error(
- `❌ tRPC failed on ${path ?? '<no-path>'}: ${error.message}`
- );
- }
- : undefined,
-});
diff --git a/apps/web/src/pages/index.tsx b/apps/web/src/pages/index.tsx
deleted file mode 100644
index 3b6bc8121..000000000
--- a/apps/web/src/pages/index.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import { MainLayout } from '@/components/layouts/MainLayout';
-import { createServerSideProps } from '@/server/getServerSideProps';
-
-export const getServerSideProps = createServerSideProps();
-
-export default function Home() {
- return (
- <MainLayout>
- <div />
- </MainLayout>
- );
-}
diff --git a/apps/web/src/redux/index.ts b/apps/web/src/redux/index.ts
index e20c2610e..47aff75d7 100644
--- a/apps/web/src/redux/index.ts
+++ b/apps/web/src/redux/index.ts
@@ -6,16 +6,19 @@ import {
} from 'react-redux';
import type { TypedUseSelectorHook } from 'react-redux';
-const store = configureStore({
- reducer: {
- report: reportSlice,
- },
-});
+const makeStore = () =>
+ configureStore({
+ reducer: {
+ report: reportSlice,
+ },
+ });
-export type RootState = ReturnType<typeof store.getState>;
+export type AppStore = ReturnType<typeof makeStore>;
-export type AppDispatch = typeof store.dispatch;
+export type RootState = ReturnType<AppStore['getState']>;
+
+export type AppDispatch = AppStore['dispatch'];
export const useDispatch: () => AppDispatch = useBaseDispatch;
export const useSelector: TypedUseSelectorHook<RootState> = useBaseSelector;
-export default store;
+export default makeStore;
diff --git a/apps/web/src/server/api/routers/chart.ts b/apps/web/src/server/api/routers/chart.ts
index e30643a79..5e78218b1 100644
--- a/apps/web/src/server/api/routers/chart.ts
+++ b/apps/web/src/server/api/routers/chart.ts
@@ -4,29 +4,28 @@ import { getChartSql } from '@/server/chart-sql/getChartSql';
import { isJsonPath, selectJsonPath } from '@/server/chart-sql/helpers';
import { db } from '@/server/db';
import { getUniqueEvents } from '@/server/services/event.service';
-import { getProjectBySlug } from '@/server/services/project.service';
import type {
IChartEvent,
IChartRange,
IGetChartDataInput,
IInterval,
} from '@/types';
+import { alphabetIds } from '@/utils/constants';
import { getDaysOldDate } from '@/utils/date';
-import { average, isFloat, round, sum } from '@/utils/math';
+import { average, round, sum } from '@/utils/math';
import { toDots } from '@/utils/object';
import { zChartInputWithDates } from '@/utils/validation';
-import { last, pipe, sort, uniq } from 'ramda';
+import { pipe, sort, uniq } from 'ramda';
import { z } from 'zod';
export const chartRouter = createTRPCRouter({
events: protectedProcedure
- .input(z.object({ projectSlug: z.string() }))
- .query(async ({ input: { projectSlug } }) => {
- const project = await getProjectBySlug(projectSlug);
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input: { projectId } }) => {
const events = await cache.getOr(
- `events_${project.id}`,
+ `events_${projectId}`,
1000 * 60 * 60 * 24,
- () => getUniqueEvents({ projectId: project.id })
+ () => getUniqueEvents({ projectId: projectId })
);
return [
@@ -38,17 +37,16 @@ export const chartRouter = createTRPCRouter({
}),
properties: protectedProcedure
- .input(z.object({ event: z.string().optional(), projectSlug: z.string() }))
- .query(async ({ input: { projectSlug, event } }) => {
- const project = await getProjectBySlug(projectSlug);
+ .input(z.object({ event: z.string().optional(), projectId: z.string() }))
+ .query(async ({ input: { projectId, event } }) => {
const events = await cache.getOr(
- `events_${project.id}_${event ?? 'all'}`,
+ `events_${projectId}_${event ?? 'all'}`,
1000 * 60 * 60,
() =>
db.event.findMany({
take: 500,
where: {
- project_id: project.id,
+ project_id: projectId,
...(event
? {
name: event,
@@ -78,19 +76,16 @@ export const chartRouter = createTRPCRouter({
z.object({
event: z.string(),
property: z.string(),
- projectSlug: z.string(),
+ projectId: z.string(),
})
)
- .query(async ({ input: { event, property, projectSlug } }) => {
+ .query(async ({ input: { event, property, projectId } }) => {
const intervalInDays = 180;
- const project = await getProjectBySlug(projectSlug);
if (isJsonPath(property)) {
const events = await db.$queryRawUnsafe<{ value: string }[]>(
`SELECT ${selectJsonPath(
property
- )} AS value from events WHERE project_id = '${
- project.id
- }' AND name = '${event}' AND "createdAt" >= NOW() - INTERVAL '${intervalInDays} days'`
+ )} AS value from events WHERE project_id = '${projectId}' AND name = '${event}' AND "createdAt" >= NOW() - INTERVAL '${intervalInDays} days'`
);
return {
@@ -99,7 +94,7 @@ export const chartRouter = createTRPCRouter({
} else {
const events = await db.event.findMany({
where: {
- project_id: project.id,
+ project_id: projectId,
name: event,
[property]: {
not: null,
@@ -123,8 +118,8 @@ export const chartRouter = createTRPCRouter({
}),
chart: protectedProcedure
- .input(zChartInputWithDates.merge(z.object({ projectSlug: z.string() })))
- .query(async ({ input: { projectSlug, events, ...input } }) => {
+ .input(zChartInputWithDates.merge(z.object({ projectId: z.string() })))
+ .query(async ({ input: { projectId, events, ...input } }) => {
const { startDate, endDate } =
input.startDate && input.endDate
? {
@@ -132,18 +127,16 @@ export const chartRouter = createTRPCRouter({
endDate: input.endDate,
}
: getDatesFromRange(input.range);
- const project = await getProjectBySlug(projectSlug);
const series: Awaited<ReturnType<typeof getChartData>> = [];
for (const event of events) {
- series.push(
- ...(await getChartData({
- ...input,
- startDate,
- endDate,
- event,
- projectId: project.id,
- }))
- );
+ const result = await getChartData({
+ ...input,
+ startDate,
+ endDate,
+ event,
+ projectId: projectId,
+ });
+ series.push(...result);
}
const sorted = [...series].sort((a, b) => {
@@ -152,13 +145,18 @@ export const chartRouter = createTRPCRouter({
const sumB = b.data.reduce((acc, item) => acc + item.count, 0);
return sumB - sumA;
} else {
- return b.metrics.total - a.metrics.total;
+ return b.metrics.sum - a.metrics.sum;
}
});
- const meta = {
- highest: sorted[0]?.metrics.total ?? 0,
- lowest: last(sorted)?.metrics.total ?? 0,
+ const metrics = {
+ max: Math.max(...sorted.map((item) => item.metrics.max)),
+ min: Math.min(...sorted.map((item) => item.metrics.min)),
+ sum: sum(sorted.map((item) => item.metrics.sum, 0)),
+ averge: round(
+ average(sorted.map((item) => item.metrics.average, 0)),
+ 2
+ ),
};
return {
@@ -166,9 +164,9 @@ export const chartRouter = createTRPCRouter({
series.reduce(
(acc, item) => {
if (acc[item.event.id]) {
- acc[item.event.id] += item.metrics.total;
+ acc[item.event.id] += item.metrics.sum;
} else {
- acc[item.event.id] = item.metrics.total;
+ acc[item.event.id] = item.metrics.sum;
}
return acc;
},
@@ -180,8 +178,12 @@ export const chartRouter = createTRPCRouter({
})),
series: sorted.map((item) => ({
...item,
- meta,
+ metrics: {
+ ...item.metrics,
+ totalMetrics: metrics,
+ },
})),
+ metrics,
};
}),
});
@@ -282,36 +284,47 @@ async function getChartData(payload: IGetChartDataInput) {
);
return Object.keys(series).map((key) => {
- const legend = payload.breakdowns.length
- ? key
- : getEventLegend(payload.event);
- const data = series[key] ?? [];
+ // If we have breakdowns, we want to use the breakdown key as the legend
+ // But only if it successfully broke it down, otherwise we use the getEventLabel
+ const legend =
+ payload.breakdowns.length && !alphabetIds.includes(key as 'A')
+ ? key
+ : getEventLegend(payload.event);
+ const data =
+ payload.chartType === 'area' ||
+ payload.chartType === 'linear' ||
+ payload.chartType === 'histogram' ||
+ payload.chartType === 'metric'
+ ? fillEmptySpotsInTimeline(
+ series[key] ?? [],
+ payload.interval,
+ payload.startDate,
+ payload.endDate
+ ).map((item) => {
+ return {
+ label: legend,
+ count: round(item.count),
+ date: new Date(item.date).toISOString(),
+ };
+ })
+ : (series[key] ?? []).map((item) => ({
+ label: item.label,
+ count: round(item.count),
+ date: new Date(item.date).toISOString(),
+ }));
+
+ const counts = data.map((item) => item.count);
return {
name: legend,
- event: {
- id: payload.event.id,
- name: payload.event.name,
- },
+ event: payload.event,
metrics: {
- total: sum(data.map((item) => item.count)),
- average: round(average(data.map((item) => item.count))),
+ sum: sum(counts),
+ average: round(average(counts)),
+ max: Math.max(...counts),
+ min: Math.min(...counts),
},
- data:
- payload.chartType === 'linear' || payload.chartType === 'histogram'
- ? fillEmptySpotsInTimeline(
- data,
- payload.interval,
- payload.startDate,
- payload.endDate
- ).map((item) => {
- return {
- label: legend,
- count: round(item.count),
- date: new Date(item.date).toISOString(),
- };
- })
- : [],
+ data,
};
});
}
diff --git a/apps/web/src/server/api/routers/client.ts b/apps/web/src/server/api/routers/client.ts
index 786a7649d..69660333f 100644
--- a/apps/web/src/server/api/routers/client.ts
+++ b/apps/web/src/server/api/routers/client.ts
@@ -2,21 +2,19 @@ import { randomUUID } from 'crypto';
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
import { db } from '@/server/db';
import { hashPassword } from '@/server/services/hash.service';
-import { getOrganizationBySlug } from '@/server/services/organization.service';
import { z } from 'zod';
export const clientRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
- organizationSlug: z.string(),
+ organizationId: z.string(),
})
)
- .query(async ({ input }) => {
- const organization = await getOrganizationBySlug(input.organizationSlug);
+ .query(async ({ input: { organizationId } }) => {
return db.client.findMany({
where: {
- organization_id: organization.id,
+ organization_id: organizationId,
},
include: {
project: true,
@@ -60,16 +58,15 @@ export const clientRouter = createTRPCRouter({
z.object({
name: z.string(),
projectId: z.string(),
- organizationSlug: z.string(),
+ organizationId: z.string(),
withCors: z.boolean().default(true),
})
)
.mutation(async ({ input }) => {
- const organization = await getOrganizationBySlug(input.organizationSlug);
const secret = randomUUID();
const client = await db.client.create({
data: {
- organization_id: organization.id,
+ organization_id: input.organizationId,
project_id: input.projectId,
name: input.name,
secret: input.withCors ? null : await hashPassword(secret),
diff --git a/apps/web/src/server/api/routers/dashboard.ts b/apps/web/src/server/api/routers/dashboard.ts
index 616aba3c8..7ae5cdf7c 100644
--- a/apps/web/src/server/api/routers/dashboard.ts
+++ b/apps/web/src/server/api/routers/dashboard.ts
@@ -1,75 +1,72 @@
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
import { db } from '@/server/db';
-import { getDashboardBySlug } from '@/server/services/dashboard.service';
-import { getProjectBySlug } from '@/server/services/project.service';
-import { slug } from '@/utils/slug';
import { PrismaError } from 'prisma-error-enum';
import { z } from 'zod';
-import { Prisma } from '@mixan/db';
+import type { Prisma } from '@mixan/db';
export const dashboardRouter = createTRPCRouter({
get: protectedProcedure
- .input(
- z
- .object({
- slug: z.string(),
- })
- .or(z.object({ id: z.string() }))
- )
+ .input(z.object({ id: z.string() }))
.query(async ({ input }) => {
- if ('id' in input) {
- return db.dashboard.findUnique({
- where: {
- id: input.id,
- },
- });
- } else {
- return getDashboardBySlug(input.slug);
- }
+ return db.dashboard.findUnique({
+ where: {
+ id: input.id,
+ },
+ });
}),
list: protectedProcedure
.input(
z
.object({
- projectSlug: z.string(),
+ projectId: z.string(),
})
.or(
z.object({
- projectId: z.string(),
+ organizationId: z.string(),
})
)
)
.query(async ({ input }) => {
- let projectId = null;
if ('projectId' in input) {
- projectId = input.projectId;
+ return db.dashboard.findMany({
+ where: {
+ project_id: input.projectId,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ include: {
+ project: true,
+ },
+ });
} else {
- projectId = (await getProjectBySlug(input.projectSlug)).id;
+ return db.dashboard.findMany({
+ where: {
+ project: {
+ organization_id: input.organizationId,
+ },
+ },
+ include: {
+ project: true,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ });
}
-
- return db.dashboard.findMany({
- where: {
- project_id: projectId,
- },
- orderBy: {
- createdAt: 'desc',
- },
- });
}),
create: protectedProcedure
.input(
z.object({
name: z.string(),
- projectSlug: z.string(),
+ projectId: z.string(),
})
)
- .mutation(async ({ input: { projectSlug, name } }) => {
- const project = await getProjectBySlug(projectSlug);
+ .mutation(async ({ input: { projectId, name } }) => {
return db.dashboard.create({
data: {
- slug: slug(name),
- project_id: project.id,
+ project_id: projectId,
name,
},
});
@@ -95,17 +92,33 @@ export const dashboardRouter = createTRPCRouter({
.input(
z.object({
id: z.string(),
+ forceDelete: z.boolean().optional(),
})
)
- .mutation(async ({ input: { id } }) => {
+ .mutation(async ({ input: { id, forceDelete } }) => {
try {
+ if (forceDelete) {
+ await db.report.deleteMany({
+ where: {
+ dashboard_id: id,
+ },
+ });
+ }
+ await db.recentDashboards.deleteMany({
+ where: {
+ dashboard_id: id,
+ },
+ });
await db.dashboard.delete({
where: {
id,
},
});
- } catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ } catch (e) {
+ // Below does not work...
+ // error instanceof Prisma.PrismaClientKnownRequestError
+ if (typeof e === 'object' && e && 'code' in e) {
+ const error = e as Prisma.PrismaClientKnownRequestError;
switch (error.code) {
case PrismaError.ForeignConstraintViolation:
throw new Error(
diff --git a/apps/web/src/server/api/routers/event.ts b/apps/web/src/server/api/routers/event.ts
index ccef5100e..865926eef 100644
--- a/apps/web/src/server/api/routers/event.ts
+++ b/apps/web/src/server/api/routers/event.ts
@@ -2,29 +2,37 @@ import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
import { db } from '@/server/db';
import { z } from 'zod';
+import type { Event, Profile } from '@mixan/db';
+
+function transformEvent(
+ event: Event & {
+ profile: Profile;
+ }
+) {
+ return {
+ ...event,
+ properties: event.properties as Record<string, unknown>,
+ };
+}
+
export const eventRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
- projectSlug: z.string(),
+ projectId: z.string(),
take: z.number().default(100),
skip: z.number().default(0),
profileId: z.string().optional(),
events: z.array(z.string()).optional(),
})
)
- .query(
- async ({ input: { take, skip, projectSlug, profileId, events } }) => {
- const project = await db.project.findUniqueOrThrow({
- where: {
- slug: projectSlug,
- },
- });
- return db.event.findMany({
+ .query(async ({ input: { take, skip, projectId, profileId, events } }) => {
+ return db.event
+ .findMany({
take,
skip,
where: {
- project_id: project.id,
+ project_id: projectId,
profile_id: profileId,
...(events && events.length > 0
? {
@@ -40,7 +48,7 @@ export const eventRouter = createTRPCRouter({
include: {
profile: true,
},
- });
- }
- ),
+ })
+ .then((events) => events.map(transformEvent));
+ }),
});
diff --git a/apps/web/src/server/api/routers/organization.ts b/apps/web/src/server/api/routers/organization.ts
index f40f8295d..99a0cca16 100644
--- a/apps/web/src/server/api/routers/organization.ts
+++ b/apps/web/src/server/api/routers/organization.ts
@@ -1,10 +1,20 @@
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
import { db } from '@/server/db';
-import { getOrganizationBySlug } from '@/server/services/organization.service';
-import { slug } from '@/utils/slug';
+import { getOrganizationById } from '@/server/services/organization.service';
import { z } from 'zod';
export const organizationRouter = createTRPCRouter({
+ list: protectedProcedure.query(({ ctx }) => {
+ return db.organization.findMany({
+ where: {
+ users: {
+ some: {
+ id: ctx.session.user.id,
+ },
+ },
+ },
+ });
+ }),
first: protectedProcedure.query(({ ctx }) => {
return db.organization.findFirst({
where: {
@@ -19,11 +29,11 @@ export const organizationRouter = createTRPCRouter({
get: protectedProcedure
.input(
z.object({
- slug: z.string(),
+ id: z.string(),
})
)
.query(({ input }) => {
- return getOrganizationBySlug(input.slug);
+ return getOrganizationById(input.id);
}),
update: protectedProcedure
.input(
@@ -39,7 +49,6 @@ export const organizationRouter = createTRPCRouter({
},
data: {
name: input.name,
- slug: slug(input.name),
},
});
}),
diff --git a/apps/web/src/server/api/routers/profile.ts b/apps/web/src/server/api/routers/profile.ts
index a423665c3..fce67fd40 100644
--- a/apps/web/src/server/api/routers/profile.ts
+++ b/apps/web/src/server/api/routers/profile.ts
@@ -6,22 +6,42 @@ export const profileRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
- projectSlug: z.string(),
+ query: z.string().nullable(),
+ projectId: z.string(),
take: z.number().default(100),
skip: z.number().default(0),
})
)
- .query(async ({ input: { take, skip, projectSlug } }) => {
- const project = await db.project.findUniqueOrThrow({
- where: {
- slug: projectSlug,
- },
- });
+ .query(async ({ input: { take, skip, projectId, query } }) => {
return db.profile.findMany({
take,
skip,
where: {
- project_id: project.id,
+ project_id: projectId,
+ ...(query
+ ? {
+ OR: [
+ {
+ first_name: {
+ contains: query,
+ mode: 'insensitive',
+ },
+ },
+ {
+ last_name: {
+ contains: query,
+ mode: 'insensitive',
+ },
+ },
+ {
+ email: {
+ contains: query,
+ mode: 'insensitive',
+ },
+ },
+ ],
+ }
+ : {}),
},
orderBy: {
createdAt: 'desc',
diff --git a/apps/web/src/server/api/routers/project.ts b/apps/web/src/server/api/routers/project.ts
index 975a77fd9..5665842b5 100644
--- a/apps/web/src/server/api/routers/project.ts
+++ b/apps/web/src/server/api/routers/project.ts
@@ -1,40 +1,34 @@
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
-import { db } from '@/server/db';
-import { getOrganizationBySlug } from '@/server/services/organization.service';
-import { getProjectBySlug } from '@/server/services/project.service';
+import { db, getId } from '@/server/db';
+import { slug } from '@/utils/slug';
import { z } from 'zod';
export const projectRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
- organizationSlug: z.string(),
+ organizationId: z.string().nullable(),
})
)
- .query(async ({ input }) => {
- const organization = await getOrganizationBySlug(input.organizationSlug);
+ .query(async ({ input: { organizationId } }) => {
+ if (organizationId === null) return [];
+
return db.project.findMany({
where: {
- organization_id: organization.id,
+ organization_id: organizationId,
},
});
}),
get: protectedProcedure
.input(
- z
- .object({
- id: z.string(),
- })
- .or(z.object({ slug: z.string() }))
+ z.object({
+ id: z.string(),
+ })
)
- .query(({ input }) => {
- if ('slug' in input) {
- return getProjectBySlug(input.slug);
- }
-
+ .query(({ input: { id } }) => {
return db.project.findUniqueOrThrow({
where: {
- id: input.id,
+ id,
},
});
}),
@@ -58,15 +52,15 @@ export const projectRouter = createTRPCRouter({
create: protectedProcedure
.input(
z.object({
- name: z.string(),
- organizationSlug: z.string(),
+ name: z.string().min(1),
+ organizationId: z.string(),
})
)
.mutation(async ({ input }) => {
- const organization = await getOrganizationBySlug(input.organizationSlug);
return db.project.create({
data: {
- organization_id: organization.id,
+ id: await getId('project', input.name),
+ organization_id: input.organizationId,
name: input.name,
},
});
diff --git a/apps/web/src/server/api/routers/report.ts b/apps/web/src/server/api/routers/report.ts
index ba320337a..83a516cef 100644
--- a/apps/web/src/server/api/routers/report.ts
+++ b/apps/web/src/server/api/routers/report.ts
@@ -1,58 +1,9 @@
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
import { db } from '@/server/db';
-import { getDashboardBySlug } from '@/server/services/dashboard.service';
-import { getProjectBySlug } from '@/server/services/project.service';
-import type {
- IChartBreakdown,
- IChartEvent,
- IChartEventFilter,
- IChartInput,
- IChartRange,
-} from '@/types';
-import { alphabetIds, timeRanges } from '@/utils/constants';
+import { transformReport } from '@/server/services/reports.service';
import { zChartInput } from '@/utils/validation';
import { z } from 'zod';
-import type { Report as DbReport } from '@mixan/db';
-
-function transformFilter(
- filter: Partial<IChartEventFilter>,
- index: number
-): IChartEventFilter {
- return {
- id: filter.id ?? alphabetIds[index]!,
- name: filter.name ?? 'Unknown Filter',
- operator: filter.operator ?? 'is',
- value:
- typeof filter.value === 'string' ? [filter.value] : filter.value ?? [],
- };
-}
-
-function transformEvent(
- event: Partial<IChartEvent>,
- index: number
-): IChartEvent {
- return {
- segment: event.segment ?? 'event',
- filters: (event.filters ?? []).map(transformFilter),
- id: event.id ?? alphabetIds[index]!,
- name: event.name || 'unknown_event',
- displayName: event.displayName,
- };
-}
-
-function transformReport(report: DbReport): IChartInput & { id: string } {
- return {
- id: report.id,
- events: (report.events as IChartEvent[]).map(transformEvent),
- breakdowns: report.breakdowns as IChartBreakdown[],
- chartType: report.chart_type,
- interval: report.interval,
- name: report.name || 'Untitled',
- range: (report.range as IChartRange) ?? timeRanges['1m'],
- };
-}
-
export const reportRouter = createTRPCRouter({
get: protectedProcedure
.input(
@@ -72,22 +23,27 @@ export const reportRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
- projectSlug: z.string(),
- dashboardSlug: z.string(),
+ projectId: z.string(),
+ dashboardId: z.string(),
})
)
- .query(async ({ input: { projectSlug, dashboardSlug } }) => {
- const project = await getProjectBySlug(projectSlug);
- const dashboard = await getDashboardBySlug(dashboardSlug);
- const reports = await db.report.findMany({
- where: {
- project_id: project.id,
- dashboard_id: dashboard.id,
- },
- orderBy: {
- createdAt: 'desc',
- },
- });
+ .query(async ({ input: { projectId, dashboardId } }) => {
+ const [dashboard, reports] = await db.$transaction([
+ db.dashboard.findUniqueOrThrow({
+ where: {
+ id: dashboardId,
+ },
+ }),
+ db.report.findMany({
+ where: {
+ project_id: projectId,
+ dashboard_id: dashboardId,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ }),
+ ]);
return {
reports: reports.map(transformReport),
@@ -116,6 +72,7 @@ export const reportRouter = createTRPCRouter({
interval: report.interval,
breakdowns: report.breakdowns,
chart_type: report.chartType,
+ line_type: report.lineType,
range: report.range,
},
});
@@ -138,6 +95,7 @@ export const reportRouter = createTRPCRouter({
interval: report.interval,
breakdowns: report.breakdowns,
chart_type: report.chartType,
+ line_type: report.lineType,
range: report.range,
},
});
diff --git a/apps/web/src/server/api/routers/user.ts b/apps/web/src/server/api/routers/user.ts
index bacfd0c69..5fad162bb 100644
--- a/apps/web/src/server/api/routers/user.ts
+++ b/apps/web/src/server/api/routers/user.ts
@@ -56,4 +56,19 @@ export const userRouter = createTRPCRouter({
},
});
}),
+ invite: protectedProcedure
+ .input(
+ z.object({
+ email: z.string().email(),
+ organizationId: z.string(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ await db.invite.create({
+ data: {
+ organization_id: input.organizationId,
+ email: input.email,
+ },
+ });
+ }),
});
diff --git a/apps/web/src/server/api/trpc.ts b/apps/web/src/server/api/trpc.ts
index e7046f810..b59496537 100644
--- a/apps/web/src/server/api/trpc.ts
+++ b/apps/web/src/server/api/trpc.ts
@@ -7,8 +7,7 @@
* need to use are documented accordingly near the end.
*/
-import { getServerAuthSession } from '@/server/auth';
-import { db } from '@/server/db';
+import { getSession } from '@/server/auth';
import { initTRPC, TRPCError } from '@trpc/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import type { Session } from 'next-auth';
@@ -37,10 +36,9 @@ interface CreateContextOptions {
*
* @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
*/
-const createInnerTRPCContext = (opts: CreateContextOptions) => {
+export const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
- db,
};
};
@@ -51,9 +49,8 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
* @see https://trpc.io/docs/context
*/
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
- const { req, res } = opts;
// Get the session from the server using the getServerSession wrapper function
- const session = await getServerAuthSession({ req, res });
+ const session = await getSession();
return createInnerTRPCContext({
session,
diff --git a/apps/web/src/server/auth.ts b/apps/web/src/server/auth.ts
index d7b077390..9f2e13bdd 100644
--- a/apps/web/src/server/auth.ts
+++ b/apps/web/src/server/auth.ts
@@ -1,10 +1,7 @@
+import { cache } from 'react';
import { db } from '@/server/db';
import { verifyPassword } from '@/server/services/hash.service';
-import type {
- GetServerSidePropsContext,
- NextApiRequest,
- NextApiResponse,
-} from 'next';
+import type { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth';
import type { DefaultSession, NextAuthOptions } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
@@ -78,29 +75,12 @@ export const authOptions: NextAuthOptions = {
};
},
}),
- /**
- * ...add more providers here.
- *
- * Most other providers require a bit more work than the Discord provider. For example, the
- * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account
- * model. Refer to the NextAuth.js docs for the provider you want to use. Example:
- *
- * @see https://next-auth.js.org/providers/github
- */
],
};
-/**
- * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.
- *
- * @see https://next-auth.js.org/configuration/nextjs
- */
-export const getServerAuthSession = (ctx: {
- req: GetServerSidePropsContext['req'];
- res: GetServerSidePropsContext['res'];
-}) => {
- return getServerSession(ctx.req, ctx.res, authOptions);
-};
+export const getSession = cache(
+ async () => await getServerSession(authOptions)
+);
export async function validateSdkRequest(
req: NextApiRequest,
diff --git a/apps/web/src/server/db.ts b/apps/web/src/server/db.ts
index e765a404f..f56cc6ed0 100644
--- a/apps/web/src/server/db.ts
+++ b/apps/web/src/server/db.ts
@@ -1 +1,40 @@
+import { slug } from '@/utils/slug';
+
+import { db } from '@mixan/db';
+
export { db } from '@mixan/db';
+
+export async function getId(
+ tableName: 'project' | 'organization' | 'dashboard',
+ name: string
+) {
+ const newId = slug(name);
+ if (!db[tableName]) {
+ throw new Error('Table does not exists');
+ }
+
+ if (!('findUnique' in db[tableName])) {
+ throw new Error('findUnique does not exists');
+ }
+
+ // @ts-expect-error
+ const existingProject = await db[tableName]!.findUnique({
+ where: {
+ id: newId,
+ },
+ });
+
+ function random(str: string) {
+ const numbers = Math.floor(1000 + Math.random() * 9000);
+ if (str.match(/-\d{4}$/g)) {
+ return str.replace(/-\d{4}$/g, `-${numbers}`);
+ }
+ return `${str}-${numbers}`;
+ }
+
+ if (existingProject) {
+ return getId(tableName, random(name));
+ }
+
+ return newId;
+}
diff --git a/apps/web/src/server/getServerSideProps.ts b/apps/web/src/server/getServerSideProps.ts
deleted file mode 100644
index 002e9e945..000000000
--- a/apps/web/src/server/getServerSideProps.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type { GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
-
-import { getServerAuthSession } from './auth';
-import { db } from './db';
-
-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,
- },
- };
- }
-
- if (context.params?.organization) {
- const user = await db.user.findFirst({
- where: {
- id: session.user.id,
- organization: {
- slug: context.params.organization as string,
- },
- },
- });
-
- if (!user) {
- return {
- notFound: true,
- };
- }
- } else {
- const user = await db.user.findFirst({
- where: {
- id: session.user.id,
- },
- include: {
- organization: true,
- },
- });
-
- if (!user) {
- return {
- notFound: true,
- };
- }
-
- if (user.organization) {
- return {
- redirect: {
- destination: `/${user.organization.slug}`,
- permanent: false,
- },
- };
- }
- }
-
- const res = await (typeof cb === 'function'
- ? cb(context)
- : Promise.resolve({}));
- return {
- ...(res ?? {}),
- props: {
- session,
- ...(res?.props ?? {}),
- },
- };
- };
-}
diff --git a/apps/web/src/server/services/clients.service.ts b/apps/web/src/server/services/clients.service.ts
new file mode 100644
index 000000000..1a6111ef4
--- /dev/null
+++ b/apps/web/src/server/services/clients.service.ts
@@ -0,0 +1,12 @@
+import { db } from '@mixan/db';
+
+export function getClientsByOrganizationId(organizationId: string) {
+ return db.client.findMany({
+ where: {
+ organization_id: organizationId,
+ },
+ include: {
+ project: true,
+ },
+ });
+}
diff --git a/apps/web/src/server/services/dashboard.service.ts b/apps/web/src/server/services/dashboard.service.ts
index ad80ae531..acf59b541 100644
--- a/apps/web/src/server/services/dashboard.service.ts
+++ b/apps/web/src/server/services/dashboard.service.ts
@@ -1,9 +1,86 @@
+import { unstable_cache } from 'next/cache';
+
import { db } from '../db';
-export function getDashboardBySlug(slug: string) {
+export type IServiceRecentDashboards = Awaited<
+ ReturnType<typeof getRecentDashboardsByUserId>
+>;
+export type IServiceDashboard = Awaited<ReturnType<typeof getDashboardById>>;
+export type IServiceDashboardWithProject = Awaited<
+ ReturnType<typeof getDashboardsByProjectId>
+>[number];
+
+export function getDashboardById(id: string) {
return db.dashboard.findUniqueOrThrow({
where: {
- slug,
+ id,
+ },
+ });
+}
+
+export function getDashboardsByProjectId(projectId: string) {
+ return db.dashboard.findMany({
+ where: {
+ project_id: projectId,
+ },
+ include: {
+ project: true,
+ },
+ });
+}
+
+export async function getRecentDashboardsByUserId(userId: string) {
+ const tag = `recentDashboards_${userId}`;
+
+ return unstable_cache(
+ async (userId: string) => {
+ return db.recentDashboards.findMany({
+ where: {
+ user_id: userId,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ include: {
+ project: true,
+ dashboard: true,
+ },
+ take: 5,
+ });
+ },
+ tag.split('_'),
+ {
+ revalidate: 3600,
+ tags: [tag],
+ }
+ )(userId);
+}
+
+export async function createRecentDashboard({
+ organizationId,
+ projectId,
+ dashboardId,
+ userId,
+}: {
+ organizationId: string;
+ projectId: string;
+ dashboardId: string;
+ userId: string;
+}) {
+ await db.recentDashboards.deleteMany({
+ where: {
+ user_id: userId,
+ project_id: projectId,
+ dashboard_id: dashboardId,
+ organization_id: organizationId,
+ },
+ });
+ return db.recentDashboards.create({
+ data: {
+ user_id: userId,
+ organization_id: organizationId,
+ project_id: projectId,
+ dashboard_id: dashboardId,
},
});
}
diff --git a/apps/web/src/server/services/organization.service.ts b/apps/web/src/server/services/organization.service.ts
index fb75d404c..56d483aa8 100644
--- a/apps/web/src/server/services/organization.service.ts
+++ b/apps/web/src/server/services/organization.service.ts
@@ -1,9 +1,25 @@
import { db } from '../db';
-export function getOrganizationBySlug(slug: string) {
+export type IServiceOrganization = Awaited<
+ ReturnType<typeof getOrganizations>
+>[number];
+
+export function getOrganizations() {
+ return db.organization.findMany({
+ where: {
+ // users: {
+ // some: {
+ // id: '1',
+ // },
+ // }
+ },
+ });
+}
+
+export function getOrganizationById(id: string) {
return db.organization.findUniqueOrThrow({
where: {
- slug,
+ id,
},
});
}
diff --git a/apps/web/src/server/services/profile.service.ts b/apps/web/src/server/services/profile.service.ts
index abcc5dec1..1a640cbdf 100644
--- a/apps/web/src/server/services/profile.service.ts
+++ b/apps/web/src/server/services/profile.service.ts
@@ -1,6 +1,32 @@
import { db } from '@/server/db';
import { HttpError } from '@/server/exceptions';
+export type IServiceProfile = Awaited<ReturnType<typeof getProfileById>>;
+
+export function getProfileById(id: string) {
+ return db.profile.findUniqueOrThrow({
+ where: {
+ id,
+ },
+ });
+}
+
+export function getProfilesByExternalId(
+ externalId: string | null,
+ projectId: string
+) {
+ if (externalId === null) {
+ return [];
+ }
+
+ return db.profile.findMany({
+ where: {
+ external_id: externalId,
+ project_id: projectId,
+ },
+ });
+}
+
export function getProfile(id: string) {
return db.profile.findUniqueOrThrow({
where: {
diff --git a/apps/web/src/server/services/project.service.ts b/apps/web/src/server/services/project.service.ts
index 6777cf165..a0623162c 100644
--- a/apps/web/src/server/services/project.service.ts
+++ b/apps/web/src/server/services/project.service.ts
@@ -1,9 +1,44 @@
+import { unstable_cache } from 'next/cache';
+
import { db } from '../db';
-export function getProjectBySlug(slug: string) {
- return db.project.findUniqueOrThrow({
+export type IServiceProject = Awaited<ReturnType<typeof getProjectById>>;
+
+export function getProjectById(id: string) {
+ return db.project.findUnique({
+ where: {
+ id,
+ },
+ });
+}
+
+export function getProjectsByOrganizationId(organizationId: string) {
+ return db.project.findMany({
where: {
- slug,
+ organization_id: organizationId,
},
});
}
+
+export function getFirstProjectByOrganizationId(organizationId: string) {
+ const tag = `getFirstProjectByOrganizationId_${organizationId}`;
+ return unstable_cache(
+ async (organizationId: string) => {
+ return db.project.findFirst({
+ where: {
+ organization_id: organizationId,
+ },
+ orderBy: {
+ events: {
+ _count: 'desc',
+ },
+ },
+ });
+ },
+ tag.split('_'),
+ {
+ tags: [tag],
+ revalidate: 3600 * 24,
+ }
+ )(organizationId);
+}
diff --git a/apps/web/src/server/services/reports.service.ts b/apps/web/src/server/services/reports.service.ts
new file mode 100644
index 000000000..b7e624874
--- /dev/null
+++ b/apps/web/src/server/services/reports.service.ts
@@ -0,0 +1,75 @@
+import type {
+ IChartBreakdown,
+ IChartEvent,
+ IChartEventFilter,
+ IChartInput,
+ IChartLineType,
+ IChartRange,
+} from '@/types';
+import { alphabetIds, timeRanges } from '@/utils/constants';
+
+import { db } from '@mixan/db';
+import type { Report as DbReport } from '@mixan/db';
+
+export type IServiceReport = Awaited<ReturnType<typeof getReportById>>;
+
+export function transformFilter(
+ filter: Partial<IChartEventFilter>,
+ index: number
+): IChartEventFilter {
+ return {
+ id: filter.id ?? alphabetIds[index]!,
+ name: filter.name ?? 'Unknown Filter',
+ operator: filter.operator ?? 'is',
+ value:
+ typeof filter.value === 'string' ? [filter.value] : filter.value ?? [],
+ };
+}
+
+export function transformEvent(
+ event: Partial<IChartEvent>,
+ index: number
+): IChartEvent {
+ return {
+ segment: event.segment ?? 'event',
+ filters: (event.filters ?? []).map(transformFilter),
+ id: event.id ?? alphabetIds[index]!,
+ name: event.name || 'unknown_event',
+ displayName: event.displayName,
+ };
+}
+
+export function transformReport(
+ report: DbReport
+): IChartInput & { id: string } {
+ return {
+ id: report.id,
+ events: (report.events as IChartEvent[]).map(transformEvent),
+ breakdowns: report.breakdowns as IChartBreakdown[],
+ chartType: report.chart_type,
+ lineType: (report.line_type ?? 'kuk') as IChartLineType,
+ interval: report.interval,
+ name: report.name || 'Untitled',
+ range: (report.range as IChartRange) ?? timeRanges['1m'],
+ };
+}
+
+export function getReportsByDashboardId(dashboardId: string) {
+ return db.report
+ .findMany({
+ where: {
+ dashboard_id: dashboardId,
+ },
+ })
+ .then((reports) => reports.map(transformReport));
+}
+
+export function getReportById(id: string) {
+ return db.report
+ .findUniqueOrThrow({
+ where: {
+ id,
+ },
+ })
+ .then(transformReport);
+}
diff --git a/apps/web/src/server/services/user.service.ts b/apps/web/src/server/services/user.service.ts
new file mode 100644
index 000000000..5f379f3cf
--- /dev/null
+++ b/apps/web/src/server/services/user.service.ts
@@ -0,0 +1,20 @@
+import { db } from '@/server/db';
+
+export function getUserById(id: string) {
+ return db.user.findUniqueOrThrow({
+ where: {
+ id,
+ },
+ });
+}
+
+export type IServiceInvite = Awaited<
+ ReturnType<typeof getInvitesByOrganizationId>
+>[number];
+export function getInvitesByOrganizationId(organizationId: string) {
+ return db.invite.findMany({
+ where: {
+ organization_id: organizationId,
+ },
+ });
+}
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index 52e84e75a..9278d1a11 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -157,3 +157,10 @@
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
+
+/* Rechart */
+
+.recharts-wrapper .recharts-cartesian-grid-horizontal line:first-child,
+.recharts-wrapper .recharts-cartesian-grid-horizontal line:last-child {
+ stroke-opacity: 0;
+}
diff --git a/apps/web/src/types/index.ts b/apps/web/src/types/index.ts
index 9643aa64d..7b9fc7638 100644
--- a/apps/web/src/types/index.ts
+++ b/apps/web/src/types/index.ts
@@ -1,4 +1,3 @@
-import type { RouterOutputs } from '@/utils/api';
import type { timeRanges } from '@/utils/constants';
import type {
zChartBreakdown,
@@ -6,6 +5,7 @@ import type {
zChartInput,
zChartInputWithDates,
zChartType,
+ zLineType,
zTimeInterval,
} from '@/utils/validation';
import type { TooltipProps } from 'recharts';
@@ -27,7 +27,7 @@ export type IChartEventFilterValue =
export type IChartBreakdown = z.infer<typeof zChartBreakdown>;
export type IInterval = z.infer<typeof zTimeInterval>;
export type IChartType = z.infer<typeof zChartType>;
-export type IChartData = RouterOutputs['chart']['chart'];
+export type IChartLineType = z.infer<typeof zLineType>;
export type IChartRange = keyof typeof timeRanges;
export type IToolTipProps<T> = Omit<TooltipProps<number, string>, 'payload'> & {
payload?: T[];
diff --git a/apps/web/src/utils/api.ts b/apps/web/src/utils/api.ts
deleted file mode 100644
index 71af67e62..000000000
--- a/apps/web/src/utils/api.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which
- * contains the Next.js App-wrapper, as well as your type-safe React Query hooks.
- *
- * We also create a few inference helpers for input and output types.
- */
-import { toast } from '@/components/ui/use-toast';
-import type { AppRouter } from '@/server/api/root';
-import { httpLink, loggerLink } from '@trpc/client';
-import type { TRPCClientErrorBase } from '@trpc/client';
-import { createTRPCNext } from '@trpc/next';
-import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
-import superjson from 'superjson';
-
-const getBaseUrl = () => {
- if (typeof window !== 'undefined') return ''; // browser should use relative url
- if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url
- return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost
-};
-
-/** A set of type-safe react-query hooks for your tRPC API. */
-export const api = createTRPCNext<AppRouter>({
- config() {
- return {
- queryClientConfig: {
- defaultOptions: {
- queries: {
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- refetchOnMount: false,
- enabled: typeof window !== 'undefined',
- },
- },
- },
- /**
- * Transformer used for data de-serialization from the server.
- *
- * @see https://trpc.io/docs/data-transformers
- */
- transformer: superjson,
-
- /**
- * Links used to determine request flow from client to server.
- *
- * @see https://trpc.io/docs/links
- */
- links: [
- loggerLink({
- enabled: (opts) =>
- process.env.NODE_ENV === 'development' ||
- (opts.direction === 'down' && opts.result instanceof Error),
- }),
- httpLink({
- url: `${getBaseUrl()}/api/trpc`,
- }),
- ],
- };
- },
- /**
- * Whether tRPC should await queries when server rendering pages.
- *
- * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false
- */
- ssr: false,
-});
-
-/**
- * Inference helper for inputs.
- *
- * @example type HelloInput = RouterInputs['example']['hello']
- */
-export type RouterInputs = inferRouterInputs<AppRouter>;
-
-/**
- * Inference helper for outputs.
- *
- * @example type HelloOutput = RouterOutputs['example']['hello']
- */
-export type RouterOutputs = inferRouterOutputs<AppRouter>;
-
-export function handleError(error: TRPCClientErrorBase<any>) {
- toast({
- title: 'Error',
- description: error.message,
- });
-}
diff --git a/apps/web/src/utils/constants.ts b/apps/web/src/utils/constants.ts
index c2b1c78bd..af53bc0f2 100644
--- a/apps/web/src/utils/constants.ts
+++ b/apps/web/src/utils/constants.ts
@@ -14,6 +14,24 @@ export const chartTypes = {
area: 'Area',
};
+export const lineTypes = {
+ monotone: 'Monotone',
+ monotoneX: 'Monotone X',
+ monotoneY: 'Monotone Y',
+ linear: 'Linear',
+ natural: 'Natural',
+ basis: 'Basis',
+ step: 'Step',
+ stepBefore: 'Step before',
+ stepAfter: 'Step after',
+ basisClosed: 'Basis closed',
+ basisOpen: 'Basis open',
+ bumpX: 'Bump X',
+ bumpY: 'Bump Y',
+ bump: 'Bump',
+ linearClosed: 'Linear closed',
+};
+
export const intervals = {
minute: 'Minute',
day: 'Day',
@@ -50,3 +68,22 @@ export const timeRanges = {
export function isMinuteIntervalEnabledByRange(range: keyof typeof timeRanges) {
return range === '30min' || range === '1h';
}
+
+export function isHourIntervalEnabledByRange(range: keyof typeof timeRanges) {
+ return (
+ isMinuteIntervalEnabledByRange(range) ||
+ range === 'today' ||
+ range === '24h'
+ );
+}
+
+export function getDefaultIntervalByRange(range: keyof typeof timeRanges) {
+ if (range === '30min' || range === '1h') {
+ return 'minute';
+ } else if (range === 'today' || range === '24h') {
+ return 'hour';
+ } else if (range === '7d' || range === '14d' || range === '1m') {
+ return 'day';
+ }
+ return 'month';
+}
diff --git a/apps/web/src/utils/getters.ts b/apps/web/src/utils/getters.ts
index 98efbe63d..53d3e7841 100644
--- a/apps/web/src/utils/getters.ts
+++ b/apps/web/src/utils/getters.ts
@@ -1,6 +1,6 @@
import type { Profile } from '@mixan/db';
export function getProfileName(profile: Profile | undefined | null) {
- if (!profile) return '';
+ if (!profile) return 'No profile';
return [profile.first_name, profile.last_name].filter(Boolean).join(' ');
}
diff --git a/apps/web/src/utils/theme.ts b/apps/web/src/utils/theme.ts
index d67e187d6..6fccc0fae 100644
--- a/apps/web/src/utils/theme.ts
+++ b/apps/web/src/utils/theme.ts
@@ -4,7 +4,7 @@ import tailwinConfig from '../../tailwind.config';
export const resolvedTailwindConfig = resolveConfig(tailwinConfig);
-export const theme = resolvedTailwindConfig.theme;
+export const theme = resolvedTailwindConfig.theme as Record<string, any>;
export function getChartColor(index: number): string {
const colors = theme?.colors ?? {};
diff --git a/apps/web/src/utils/validation.ts b/apps/web/src/utils/validation.ts
index 2281a12e7..dcf8be804 100644
--- a/apps/web/src/utils/validation.ts
+++ b/apps/web/src/utils/validation.ts
@@ -1,8 +1,16 @@
import { z } from 'zod';
-import { chartTypes, intervals, operators, timeRanges } from './constants';
-
-function objectToZodEnums<K extends string>(obj: Record<K, any>): [K, ...K[]] {
+import {
+ chartTypes,
+ intervals,
+ lineTypes,
+ operators,
+ timeRanges,
+} from './constants';
+
+export function objectToZodEnums<K extends string>(
+ obj: Record<K, any>
+): [K, ...K[]] {
const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
return [firstKey!, ...otherKeys];
}
@@ -31,11 +39,14 @@ export const zChartBreakdowns = z.array(zChartBreakdown);
export const zChartType = z.enum(objectToZodEnums(chartTypes));
+export const zLineType = z.enum(objectToZodEnums(lineTypes));
+
export const zTimeInterval = z.enum(objectToZodEnums(intervals));
export const zChartInput = z.object({
name: z.string(),
chartType: zChartType,
+ lineType: zLineType,
interval: zTimeInterval,
events: zChartEvents,
breakdowns: zChartBreakdowns,
diff --git a/apps/web/tailwind.config.js b/apps/web/tailwind.config.js
index 931a5665b..fba135891 100644
--- a/apps/web/tailwind.config.js
+++ b/apps/web/tailwind.config.js
@@ -1,5 +1,5 @@
const colors = [
- '#7856ff',
+ '#2563EB',
'#ff7557',
'#7fe1d8',
'#f8bc3c',
@@ -11,6 +11,7 @@ const colors = [
'#febbb2',
'#cb80dc',
'#5cb7af',
+ '#7856ff',
];
/** @type {import('tailwindcss').Config} */
@@ -23,13 +24,6 @@ const config = {
'./src/**/*.{ts,tsx}',
],
theme: {
- container: {
- center: true,
- padding: '2rem',
- screens: {
- '2xl': '1400px',
- },
- },
extend: {
colors: {
border: 'hsl(var(--border))',
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index b62436fca..9d21e0446 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -3,15 +3,23 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
- "@/*": ["./src/*"]
+ "@/*": [
+ "./src/*"
+ ]
},
"plugins": [
{
"name": "next"
}
],
- "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
+ "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",
+ "strictNullChecks": true
},
- "include": [".", ".next/types/**/*.ts"],
- "exclude": ["node_modules"]
+ "include": [
+ ".",
+ ".next/types/**/*.ts"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
}
diff --git a/packages/db/prisma/migrations/20240113095542_remove_slug_2/migration.sql b/packages/db/prisma/migrations/20240113095542_remove_slug_2/migration.sql
new file mode 100644
index 000000000..dd3e14edb
--- /dev/null
+++ b/packages/db/prisma/migrations/20240113095542_remove_slug_2/migration.sql
@@ -0,0 +1,110 @@
+/*
+ Warnings:
+
+ - The primary key for the `dashboards` table will be changed. If it partially fails, the table could be left without primary key constraint.
+ - You are about to drop the column `slug` on the `dashboards` table. All the data in the column will be lost.
+ - The primary key for the `organizations` table will be changed. If it partially fails, the table could be left without primary key constraint.
+ - You are about to drop the column `slug` on the `organizations` table. All the data in the column will be lost.
+ - The primary key for the `projects` table will be changed. If it partially fails, the table could be left without primary key constraint.
+ - You are about to drop the column `slug` on the `projects` table. All the data in the column will be lost.
+
+*/
+-- DropForeignKey
+ALTER TABLE "clients" DROP CONSTRAINT "clients_organization_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "clients" DROP CONSTRAINT "clients_project_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "dashboards" DROP CONSTRAINT "dashboards_project_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "events" DROP CONSTRAINT "events_project_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "profiles" DROP CONSTRAINT "profiles_project_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "projects" DROP CONSTRAINT "projects_organization_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "reports" DROP CONSTRAINT "reports_dashboard_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "reports" DROP CONSTRAINT "reports_project_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "users" DROP CONSTRAINT "users_organization_id_fkey";
+
+-- DropIndex
+DROP INDEX "dashboards_slug_key";
+
+-- DropIndex
+DROP INDEX "organizations_slug_key";
+
+-- DropIndex
+DROP INDEX "projects_slug_key";
+
+-- AlterTable
+ALTER TABLE "clients" ALTER COLUMN "project_id" SET DATA TYPE TEXT,
+ALTER COLUMN "organization_id" SET DATA TYPE TEXT;
+
+-- AlterTable
+ALTER TABLE "dashboards" DROP CONSTRAINT "dashboards_pkey",
+DROP COLUMN "slug",
+ALTER COLUMN "id" SET DATA TYPE TEXT,
+ALTER COLUMN "project_id" SET DATA TYPE TEXT,
+ADD CONSTRAINT "dashboards_pkey" PRIMARY KEY ("id");
+
+-- AlterTable
+ALTER TABLE "events" ALTER COLUMN "project_id" SET DATA TYPE TEXT;
+
+-- AlterTable
+ALTER TABLE "organizations" DROP CONSTRAINT "organizations_pkey",
+DROP COLUMN "slug",
+ALTER COLUMN "id" SET DATA TYPE TEXT,
+ADD CONSTRAINT "organizations_pkey" PRIMARY KEY ("id");
+
+-- AlterTable
+ALTER TABLE "profiles" ALTER COLUMN "project_id" SET DATA TYPE TEXT;
+
+-- AlterTable
+ALTER TABLE "projects" DROP CONSTRAINT "projects_pkey",
+DROP COLUMN "slug",
+ALTER COLUMN "id" SET DATA TYPE TEXT,
+ALTER COLUMN "organization_id" SET DATA TYPE TEXT,
+ADD CONSTRAINT "projects_pkey" PRIMARY KEY ("id");
+
+-- AlterTable
+ALTER TABLE "reports" ALTER COLUMN "project_id" SET DATA TYPE TEXT,
+ALTER COLUMN "dashboard_id" SET DATA TYPE TEXT;
+
+-- AlterTable
+ALTER TABLE "users" ALTER COLUMN "organization_id" SET DATA TYPE TEXT;
+
+-- AddForeignKey
+ALTER TABLE "projects" ADD CONSTRAINT "projects_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "users" ADD CONSTRAINT "users_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "events" ADD CONSTRAINT "events_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "profiles" ADD CONSTRAINT "profiles_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "clients" ADD CONSTRAINT "clients_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "clients" ADD CONSTRAINT "clients_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "dashboards" ADD CONSTRAINT "dashboards_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "reports" ADD CONSTRAINT "reports_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "reports" ADD CONSTRAINT "reports_dashboard_id_fkey" FOREIGN KEY ("dashboard_id") REFERENCES "dashboards"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20240116100132_add_recent_dashboards/migration.sql b/packages/db/prisma/migrations/20240116100132_add_recent_dashboards/migration.sql
new file mode 100644
index 000000000..40975cd92
--- /dev/null
+++ b/packages/db/prisma/migrations/20240116100132_add_recent_dashboards/migration.sql
@@ -0,0 +1,15 @@
+-- CreateTable
+CREATE TABLE "recent_dashboards" (
+ "id" TEXT NOT NULL DEFAULT gen_random_uuid(),
+ "name" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+ "organization_id" TEXT NOT NULL,
+ "dashboard_id" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "userId" UUID NOT NULL,
+
+ CONSTRAINT "recent_dashboards_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "recent_dashboards" ADD CONSTRAINT "recent_dashboards_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20240116101051_fix_recent_dashboards/migration.sql b/packages/db/prisma/migrations/20240116101051_fix_recent_dashboards/migration.sql
new file mode 100644
index 000000000..5b4951164
--- /dev/null
+++ b/packages/db/prisma/migrations/20240116101051_fix_recent_dashboards/migration.sql
@@ -0,0 +1,18 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `userId` on the `recent_dashboards` table. All the data in the column will be lost.
+ - Changed the type of `user_id` on the `recent_dashboards` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
+
+*/
+-- DropForeignKey
+ALTER TABLE "recent_dashboards" DROP CONSTRAINT "recent_dashboards_userId_fkey";
+
+-- AlterTable
+ALTER TABLE "recent_dashboards" DROP COLUMN "userId",
+ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+DROP COLUMN "user_id",
+ADD COLUMN "user_id" UUID NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "recent_dashboards" ADD CONSTRAINT "recent_dashboards_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20240116101524_add_relations_to_recent/migration.sql b/packages/db/prisma/migrations/20240116101524_add_relations_to_recent/migration.sql
new file mode 100644
index 000000000..c2b1850a3
--- /dev/null
+++ b/packages/db/prisma/migrations/20240116101524_add_relations_to_recent/migration.sql
@@ -0,0 +1,5 @@
+-- AddForeignKey
+ALTER TABLE "recent_dashboards" ADD CONSTRAINT "recent_dashboards_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "recent_dashboards" ADD CONSTRAINT "recent_dashboards_dashboard_id_fkey" FOREIGN KEY ("dashboard_id") REFERENCES "dashboards"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20240116101723_remove_name_from_recent_dashboards/migration.sql b/packages/db/prisma/migrations/20240116101723_remove_name_from_recent_dashboards/migration.sql
new file mode 100644
index 000000000..db426f262
--- /dev/null
+++ b/packages/db/prisma/migrations/20240116101723_remove_name_from_recent_dashboards/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `name` on the `recent_dashboards` table. All the data in the column will be lost.
+
+*/
+-- AlterTable
+ALTER TABLE "recent_dashboards" DROP COLUMN "name";
diff --git a/packages/db/prisma/migrations/20240116183124_add_invite/migration.sql b/packages/db/prisma/migrations/20240116183124_add_invite/migration.sql
new file mode 100644
index 000000000..3a84e9524
--- /dev/null
+++ b/packages/db/prisma/migrations/20240116183124_add_invite/migration.sql
@@ -0,0 +1,14 @@
+-- CreateTable
+CREATE TABLE "invites" (
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
+ "email" TEXT NOT NULL,
+ "organization_id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "accepted" BOOLEAN NOT NULL DEFAULT false,
+
+ CONSTRAINT "invites_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "invites" ADD CONSTRAINT "invites_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/db/prisma/migrations/20240117210232_add_line_type/migration.sql b/packages/db/prisma/migrations/20240117210232_add_line_type/migration.sql
new file mode 100644
index 000000000..f137cd2d5
--- /dev/null
+++ b/packages/db/prisma/migrations/20240117210232_add_line_type/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "reports" ADD COLUMN "line_type" TEXT NOT NULL DEFAULT 'monotone';
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 4d298835a..045127ad8 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -11,33 +11,33 @@ datasource db {
}
model Organization {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()"))
name String
- slug String @unique @default(dbgenerated("gen_random_uuid()"))
projects Project[]
users User[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
clients Client[]
+ Invite Invite[]
@@map("organizations")
}
model Project {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()"))
name String
- slug String @unique @default(dbgenerated("gen_random_uuid()"))
- organization_id String @db.Uuid
+ organization_id String
organization Organization @relation(fields: [organization_id], references: [id])
events Event[]
profiles Profile[]
clients Client[]
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
- reports Report[]
- dashboards Dashboard[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ reports Report[]
+ dashboards Dashboard[]
+ RecentDashboards RecentDashboards[]
@@map("projects")
}
@@ -47,11 +47,12 @@ model User {
name String
email String
password String
- organization_id String @db.Uuid
+ organization_id String
organization Organization @relation(fields: [organization_id], references: [id])
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ RecentDashboards RecentDashboards[]
@@map("users")
}
@@ -60,7 +61,7 @@ model Event {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
properties Json
- project_id String @db.Uuid
+ project_id String
project Project @relation(fields: [project_id], references: [id])
profile_id String? @db.Uuid
@@ -80,7 +81,7 @@ model Profile {
email String?
avatar String?
properties Json
- project_id String @db.Uuid
+ project_id String
project Project @relation(fields: [project_id], references: [id])
events Event[]
@@ -103,9 +104,9 @@ model Client {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
secret String?
- project_id String @db.Uuid
+ project_id String
project Project @relation(fields: [project_id], references: [id])
- organization_id String @db.Uuid
+ organization_id String
organization Organization @relation(fields: [organization_id], references: [id])
cors String @default("*")
@@ -115,6 +116,20 @@ model Client {
@@map("clients")
}
+model RecentDashboards {
+ id String @id @default(dbgenerated("gen_random_uuid()"))
+ project_id String
+ project Project @relation(fields: [project_id], references: [id])
+ organization_id String
+ dashboard_id String
+ dashboard Dashboard @relation(fields: [dashboard_id], references: [id])
+ user_id String @db.Uuid
+ user User @relation(fields: [user_id], references: [id])
+ createdAt DateTime @default(now())
+
+ @@map("recent_dashboards")
+}
+
enum Interval {
hour
day
@@ -132,15 +147,15 @@ enum ChartType {
}
model Dashboard {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()"))
name String
- slug String @unique @default(dbgenerated("gen_random_uuid()"))
- project_id String @db.Uuid
+ project_id String
project Project @relation(fields: [project_id], references: [id])
reports Report[]
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ RecentDashboards RecentDashboards[]
@@map("dashboards")
}
@@ -151,12 +166,13 @@ model Report {
interval Interval
range String @default("1m")
chart_type ChartType
+ line_type String @default("monotone")
breakdowns Json
events Json
- project_id String @db.Uuid
+ project_id String
project Project @relation(fields: [project_id], references: [id])
- dashboard_id String @db.Uuid
+ dashboard_id String
dashboard Dashboard @relation(fields: [dashboard_id], references: [id])
createdAt DateTime @default(now())
@@ -164,3 +180,17 @@ model Report {
@@map("reports")
}
+
+model Invite {
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ email String
+ organization_id String
+ organization Organization @relation(fields: [organization_id], references: [id])
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ accepted Boolean @default(false)
+
+ @@map("invites")
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 753b9d69a..496e4bb29 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -155,7 +155,7 @@ importers:
version: 10.43.0(@trpc/[email protected])
'@trpc/next':
specifier: ^10.37.1
'@trpc/react-query':
specifier: ^10.37.1
@@ -174,6 +174,9 @@ importers:
cmdk:
specifier: ^0.2.0
+ hamburger-react:
+ specifier: ^2.5.0
+ version: 2.5.0([email protected])
lodash.debounce:
specifier: ^4.0.8
version: 4.0.8
@@ -187,11 +190,14 @@ importers:
specifier: ^3.0.1
version: 3.0.1
next:
- specifier: '13.4'
+ specifier: ~14.0.4
next-auth:
specifier: ^4.23.0
+ nuqs:
+ specifier: ^1.15.2
+ version: 1.15.2([email protected])
prisma-error-enum:
specifier: ^0.1.3
version: 0.1.3
@@ -204,6 +210,9 @@ importers:
react:
specifier: 18.2.0
version: 18.2.0
+ react-animate-height:
+ specifier: ^3.2.3
react-dom:
specifier: 18.2.0
version: 18.2.0([email protected])
@@ -539,8 +548,8 @@ importers:
tooling/eslint:
dependencies:
'@next/eslint-plugin-next':
- specifier: ^13.4.19
- version: 13.5.6
+ specifier: ^14.0.4
+ version: 14.0.4
'@types/eslint':
specifier: ^8.44.2
version: 8.44.6
@@ -550,6 +559,9 @@ importers:
'@typescript-eslint/parser':
specifier: ^6.6.0
+ eslint-config-next:
+ specifier: ^14.0.4
eslint-config-prettier:
specifier: ^9.0.0
version: 9.0.0([email protected])
@@ -558,7 +570,7 @@ importers:
version: 1.10.16([email protected])
eslint-plugin-import:
specifier: ^2.28.1
- version: 2.29.0(@typescript-eslint/[email protected])([email protected])
+ version: 2.29.0(@typescript-eslint/[email protected])([email protected])([email protected])
eslint-plugin-jsx-a11y:
specifier: ^6.7.1
version: 6.8.0([email protected])
@@ -1289,8 +1301,12 @@ packages:
resolution: {integrity: sha512-FsAT5x0jF2kkhNkKkukhsyYOrRqtSxrEhfliniIq0bwWbuXLgyt3Gv0Ml+b91XwjwArmuP7NxCiGd++GGKdNMQ==}
dev: false
- resolution: {integrity: sha512-ng7pU/DDsxPgT6ZPvuprxrkeew3XaRf4LAT4FabaEO/hAbvVx4P7wqnqdbTdDn1kgTvsI4tpIgT4Awn/m0bGbg==}
+ resolution: {integrity: sha512-irQnbMLbUNQpP1wcE5NstJtbuA/69kRfzBrpAD7Gsn8zm/CY6YQYc3HQBz8QPxwISG26tIm5afvvVbu508oBeQ==}
+ dev: false
+
+ resolution: {integrity: sha512-U3qMNHmEZoVmHA0j/57nRfi3AscXNvkOnxDmle/69Jz/G0o/gWjXTDdlgILZdrxQ0Lw/jv2mPW8PGy0EGIHXhQ==}
dependencies:
glob: 7.1.7
dev: false
@@ -1304,6 +1320,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-mF05E/5uPthWzyYDyptcwHptucf/jj09i2SXBPwNzbgBNc+XnwzrL0U6BmPjQeOL+FiB+iG1gwBeq7mlDjSRPg==}
+ engines: {node: '>= 10'}
+ cpu: [arm64]
+ os: [darwin]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-jyzO6wwYhx6F+7gD8ddZfuqO4TtpJdw3wyOduR4fxTUCm3aLw7YmHGYNjS0xRSYGAkLpBkH1E0RcelyId6lNsw==}
engines: {node: '>= 10'}
@@ -1313,6 +1338,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-IZQ3C7Bx0k2rYtrZZxKKiusMTM9WWcK5ajyhOZkYYTCc8xytmwSzR1skU7qLgVT/EY9xtXDG0WhY6fyujnI3rw==}
+ engines: {node: '>= 10'}
+ cpu: [x64]
+ os: [darwin]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-vdlnIlaAEh6H+G6HrKZB9c2zJKnpPVKnA6LBwjwT2BTjxI7e0Hx30+FoWCgi50e+YO49p6oPOtesP9mXDRiiUg==}
engines: {node: '>= 10'}
@@ -1322,6 +1356,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-VwwZKrBQo/MGb1VOrxJ6LrKvbpo7UbROuyMRvQKTFKhNaXjUmKTu7wxVkIuCARAfiI8JpaWAnKR+D6tzpCcM4w==}
+ engines: {node: '>= 10'}
+ cpu: [arm64]
+ os: [linux]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-aU0HkH2XPgxqrbNRBFb3si9Ahu/CpaR5RPmN2s9GiM9qJCiBBlZtRTiEca+DC+xRPyCThTtWYgxjWHgU7ZkyvA==}
engines: {node: '>= 10'}
@@ -1331,6 +1374,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-8QftwPEW37XxXoAwsn+nXlodKWHfpMaSvt81W43Wh8dv0gkheD+30ezWMcFGHLI71KiWmHK5PSQbTQGUiidvLQ==}
+ engines: {node: '>= 10'}
+ cpu: [arm64]
+ os: [linux]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-htwOEagMa/CXNykFFeAHHvMJeqZfNQEoQvHfsA4wgg5QqGNqD5soeCer4oGlCol6NGUxknrQO6VEustcv+Md+g==}
engines: {node: '>= 10'}
@@ -1340,6 +1392,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-/s/Pme3VKfZAfISlYVq2hzFS8AcAIOTnoKupc/j4WlvF6GQ0VouS2Q2KEgPuO1eMBwakWPB1aYFIA4VNVh667A==}
+ engines: {node: '>= 10'}
+ cpu: [x64]
+ os: [linux]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-4Gj4vvtbK1JH8ApWTT214b3GwUh9EKKQjY41hH/t+u55Knxi/0wesMzwQRhppK6Ddalhu0TEttbiJ+wRcoEj5Q==}
engines: {node: '>= 10'}
@@ -1349,6 +1410,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-m8z/6Fyal4L9Bnlxde5g2Mfa1Z7dasMQyhEhskDATpqr+Y0mjOBZcXQ7G5U+vgL22cI4T7MfvgtrM2jdopqWaw==}
+ engines: {node: '>= 10'}
+ cpu: [x64]
+ os: [linux]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-bUfDevQK4NsIAHXs3/JNgnvEY+LRyneDN788W2NYiRIIzmILjba7LaQTfihuFawZDhRtkYCv3JDC3B4TwnmRJw==}
engines: {node: '>= 10'}
@@ -1358,6 +1428,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-7Wv4PRiWIAWbm5XrGz3D8HUkCVDMMz9igffZG4NB1p4u1KoItwx9qjATHz88kwCEal/HXmbShucaslXCQXUM5w==}
+ engines: {node: '>= 10'}
+ cpu: [arm64]
+ os: [win32]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-Y5kikILFAr81LYIFaw6j/NrOtmiM4Sf3GtOc0pn50ez2GCkr+oejYuKGcwAwq3jiTKuzF6OF4iT2INPoxRycEA==}
engines: {node: '>= 10'}
@@ -1367,6 +1446,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-zLeNEAPULsl0phfGb4kdzF/cAVIfaC7hY+kt0/d+y9mzcZHsMS3hAS829WbJ31DkSlVKQeHEjZHIdhN+Pg7Gyg==}
+ engines: {node: '>= 10'}
+ cpu: [ia32]
+ os: [win32]
+ requiresBuild: true
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-YzA78jBDXMYiINdPdJJwGgPNT3YqBNNGhsthsDoWHL9p24tEJn9ViQf/ZqTbwSpX/RrkPupLfuuTH2sf73JBAw==}
engines: {node: '>= 10'}
@@ -1376,6 +1464,15 @@ packages:
dev: false
optional: true
+ resolution: {integrity: sha512-yEh2+R8qDlDCjxVpzOTEpBLQTEFAcP2A8fUFLaWNap9GitYKkKv1//y2S6XY6zsR4rCOPRpU7plYDR+az2n30A==}
+ engines: {node: '>= 10'}
+ cpu: [x64]
+ os: [win32]
+ requiresBuild: true
+ dev: false
+ optional: true
+
/@nodelib/[email protected]:
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -2414,12 +2511,22 @@ packages:
reselect: 4.1.8
dev: false
+ /@rushstack/[email protected]:
+ resolution: {integrity: sha512-Jh4t/593gxs0lJZ/z3NnasKlplXT2f+4y/LZYuaKZW5KAaiVFL/fThhs+17EbUd53jUVJ0QudYCBGbN/psvaqg==}
+ dev: false
+
resolution: {integrity: sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==}
dependencies:
tslib: 2.6.2
dev: false
+ resolution: {integrity: sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw==}
+ dependencies:
+ tslib: 2.6.2
+ dev: false
+
resolution: {integrity: sha512-3+SQt39OlmSaRLqYVFv8uRm1BpFepM5TIiMytRqO9cjH+wB77o6BIJdeyM5h5U4qLBMEzOJWCY4MBaU/rLwbYw==}
peerDependencies:
@@ -2494,7 +2601,7 @@ packages:
'@trpc/server': 10.43.0
dev: false
resolution: {integrity: sha512-yakRlkvf6+uc3igYZi8nPkppJ8jFaCyd/7kvSckgsdLC8ofM+N9rrBkfqdfS5Pd53awkK/MMK8js9v/vabKb6A==}
peerDependencies:
'@tanstack/react-query': ^4.18.0
@@ -2509,7 +2616,7 @@ packages:
'@trpc/client': 10.43.0(@trpc/[email protected])
'@trpc/react-query': 10.43.0(@tanstack/[email protected])(@trpc/[email protected])(@trpc/[email protected])([email protected])([email protected])
'@trpc/server': 10.43.0
react: 18.2.0
react-dom: 18.2.0([email protected])
react-ssr-prepass: 1.5.0([email protected])
@@ -3215,6 +3322,10 @@ packages:
resolution: {integrity: sha512-cPiMKZgqgkg5LY3/ntGeLFUpi6tzddBNS58A4tnTgQw1zON7u2sZMU7SzOeVH4tj20++9ggL+V6FDOFMTaFFYA==}
+ resolution: {integrity: sha512-rs2ZygrG1PNXMfmncM0B5H1hndY5ZCC9b5TkFaVNfZ+AUlyqcMyVIQtc3fsezi0NUCk5XZfDf9WS6WxMxnfdrg==}
+ dev: false
+
resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==}
engines: {node: '>=4'}
@@ -3652,6 +3763,14 @@ packages:
engines: {node: '>= 0.8'}
dev: false
+ resolution: {integrity: sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==}
+ engines: {node: '>=10.13.0'}
+ dependencies:
+ graceful-fs: 4.2.11
+ tapable: 2.2.1
+ dev: false
+
resolution: {integrity: sha512-eiiY8HQeYfYH2Con2berK+To6GrK2RxbPawDkGq4UiCQQfZHb6wX9qQqkbpPqaxQFcl8d9QzZqo0tGE0VcrdwA==}
engines: {node: '>= 0.4'}
@@ -3787,6 +3906,31 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-9/xbOHEQOmQtqvQ1UsTQZpnA7SlDMBtuKJ//S4JnoyK3oGLhILKXdBgu/UO7lQo/2xOykQULS1qQ6p2+EpHgAQ==}
+ peerDependencies:
+ eslint: ^7.23.0 || ^8.0.0
+ typescript: '>=3.3.1'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@next/eslint-plugin-next': 14.0.4
+ '@rushstack/eslint-patch': 1.7.0
+ '@typescript-eslint/parser': 6.9.1([email protected])([email protected])
+ eslint: 8.52.0
+ eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])
+ eslint-plugin-import: 2.29.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ eslint-plugin-jsx-a11y: 6.8.0([email protected])
+ eslint-plugin-react: 7.33.2([email protected])
+ eslint-plugin-react-hooks: 4.6.0([email protected])
+ typescript: 5.2.2
+ transitivePeerDependencies:
+ - eslint-import-resolver-webpack
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-IcJsTkJae2S35pRsRAwoCE+925rJJStOdkKnLVgtE+tEpqU0EVVM7OqrwxqgptKdX29NUwC82I5pXsGFIgSevw==}
hasBin: true
@@ -3815,7 +3959,30 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg==}
+ engines: {node: ^14.18.0 || >=16.0.0}
+ peerDependencies:
+ eslint: '*'
+ eslint-plugin-import: '*'
+ dependencies:
+ debug: 4.3.4
+ enhanced-resolve: 5.15.0
+ eslint: 8.52.0
+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])
+ eslint-plugin-import: 2.29.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ fast-glob: 3.3.1
+ get-tsconfig: 4.7.2
+ is-core-module: 2.13.1
+ is-glob: 4.0.3
+ transitivePeerDependencies:
+ - '@typescript-eslint/parser'
+ - eslint-import-resolver-node
+ - eslint-import-resolver-webpack
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-aWajIYfsqCKRDgUfjEXNN/JlrzauMuSEy5sbd7WXbtW3EH6A6MpwEh42c7qD+MqQo9QMJ6fWLAeIJynx0g6OAw==}
engines: {node: '>=4'}
peerDependencies:
@@ -3840,11 +4007,12 @@ packages:
debug: 3.2.7
eslint: 8.52.0
eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])
transitivePeerDependencies:
- supports-color
dev: false
resolution: {integrity: sha512-QPOO5NO6Odv5lpoTkddtutccQjysJuFxoPS7fAHO+9m9udNHvTCPSAMW9zGAYj8lAIdr40I8yPCdUYrncXtrwg==}
engines: {node: '>=4'}
peerDependencies:
@@ -3863,7 +4031,7 @@ packages:
doctrine: 2.1.0
eslint: 8.52.0
eslint-import-resolver-node: 0.3.9
- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])
hasown: 2.0.0
is-core-module: 2.13.1
is-glob: 4.0.3
@@ -4287,6 +4455,12 @@ packages:
get-intrinsic: 1.2.2
dev: false
+ resolution: {integrity: sha512-wuMsz4leaj5hbGgg4IvDU0bqJagpftG5l5cXIAvo8uZrqn0NJqwtfupTN00VnkQJPcIRrxYrm1Ue24btpCha2A==}
+ dependencies:
+ resolve-pkg-maps: 1.0.0
+ dev: false
+
resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
engines: {node: '>= 6'}
@@ -4387,6 +4561,14 @@ packages:
resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
+ resolution: {integrity: sha512-5GSXe+ucxTPJ0SkhIsPQ/PRDweZPIKya1lfahAuExx31SdheeUA4uOPfQIAirbKona8hvo79VDr5LJQzPXsdpw==}
+ peerDependencies:
+ react: ^16.8 || ^17 || ^18
+ dependencies:
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==}
dev: false
@@ -5124,7 +5306,7 @@ packages:
engines: {node: '>= 0.6'}
dev: false
resolution: {integrity: sha512-5DGffi+OpkbU62vPQIJ1z+hFnmow+ec5Qrn9m6eoglIO51m0DlrmLxBduZEwKAYDEg9k2joi1yelgmq1vqK3aQ==}
peerDependencies:
next: ^12.2.5 || ^13 || ^14
@@ -5139,7 +5321,7 @@ packages:
'@panva/hkdf': 1.1.1
cookie: 0.5.0
jose: 4.15.4
oauth: 0.9.15
openid-client: 5.6.1
preact: 10.18.1
@@ -5189,6 +5371,46 @@ packages:
- babel-plugin-macros
dev: false
+ resolution: {integrity: sha512-qbwypnM7327SadwFtxXnQdGiKpkuhaRLE2uq62/nRul9cj9KhQ5LhHmlziTNqUidZotw/Q1I9OjirBROdUJNgA==}
+ engines: {node: '>=18.17.0'}
+ hasBin: true
+ peerDependencies:
+ '@opentelemetry/api': ^1.1.0
+ react: ^18.2.0
+ react-dom: ^18.2.0
+ sass: ^1.3.0
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+ sass:
+ optional: true
+ dependencies:
+ '@next/env': 14.0.4
+ '@swc/helpers': 0.5.2
+ busboy: 1.6.0
+ caniuse-lite: 1.0.30001577
+ graceful-fs: 4.2.11
+ postcss: 8.4.31
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ styled-jsx: 5.1.1([email protected])
+ watchpack: 2.4.0
+ optionalDependencies:
+ '@next/swc-darwin-arm64': 14.0.4
+ '@next/swc-darwin-x64': 14.0.4
+ '@next/swc-linux-arm64-gnu': 14.0.4
+ '@next/swc-linux-arm64-musl': 14.0.4
+ '@next/swc-linux-x64-gnu': 14.0.4
+ '@next/swc-linux-x64-musl': 14.0.4
+ '@next/swc-win32-arm64-msvc': 14.0.4
+ '@next/swc-win32-ia32-msvc': 14.0.4
+ '@next/swc-win32-x64-msvc': 14.0.4
+ transitivePeerDependencies:
+ - '@babel/core'
+ - babel-plugin-macros
+ dev: false
+
resolution: {integrity: sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==}
dev: false
@@ -5252,6 +5474,15 @@ packages:
set-blocking: 2.0.0
dev: false
+ resolution: {integrity: sha512-fCFVp+835a1sZAP1FJwmaTchaumsDm6gzuYbdYSeurigz6D8+DAtiuKLeXvGGowqwtgmKj3lvV7sJ8oNuMat4Q==}
+ peerDependencies:
+ next: '>=13.4 <14.0.2 || ^14.0.3'
+ dependencies:
+ mitt: 3.0.1
+ dev: false
+
resolution: {integrity: sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==}
dev: false
@@ -5682,6 +5913,17 @@ packages:
unpipe: 1.0.0
dev: false
+ resolution: {integrity: sha512-R6DSvr7ud07oeCixScyvXWEMJY/Mt2+GyOWC1KMaRc69gOBw+SsCg4TJmrp4rKUM1hyd6p+YKw90brjPH93Y2A==}
+ engines: {node: '>= 12.0.0'}
+ peerDependencies:
+ react: '>=16.8.0'
+ react-dom: '>=16.8.0'
+ dependencies:
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==}
peerDependencies:
@@ -6045,6 +6287,10 @@ packages:
engines: {node: '>=8'}
dev: true
+ resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
+ dev: false
+
resolution: {integrity: sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==}
hasBin: true
@@ -6422,6 +6668,11 @@ packages:
transitivePeerDependencies:
- ts-node
+ resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==}
+ engines: {node: '>=6'}
+ dev: false
+
resolution: {integrity: sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==}
engines: {node: '>=10'}
diff --git a/tooling/eslint/nextjs.js b/tooling/eslint/nextjs.js
index 278d86600..22c8e3dd9 100644
--- a/tooling/eslint/nextjs.js
+++ b/tooling/eslint/nextjs.js
@@ -1,8 +1,8 @@
/** @type {import('eslint').Linter.Config} */
const config = {
- extends: ["plugin:@next/next/recommended"],
+ extends: ['next'],
rules: {
- "@next/next/no-html-link-for-pages": "off",
+ '@next/next/no-html-link-for-pages': 'off',
},
};
diff --git a/tooling/eslint/package.json b/tooling/eslint/package.json
index b027f735e..ef9c51a9e 100644
--- a/tooling/eslint/package.json
+++ b/tooling/eslint/package.json
@@ -15,10 +15,11 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "@next/eslint-plugin-next": "^13.4.19",
+ "@next/eslint-plugin-next": "^14.0.4",
"@types/eslint": "^8.44.2",
"@typescript-eslint/eslint-plugin": "^6.6.0",
"@typescript-eslint/parser": "^6.6.0",
+ "eslint-config-next": "^14.0.4",
"eslint-config-prettier": "^9.0.0",
"eslint-config-turbo": "^1.10.13",
"eslint-plugin-import": "^2.28.1",