feature(dashboard): add integrations and notifications

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-10-02 22:12:05 +02:00
parent d920f6951c
commit f65a633403
94 changed files with 3692 additions and 127 deletions

View File

@@ -81,7 +81,7 @@ export function RealtimeLiveHistogram({
{staticArray.map((percent, i) => (
<div
key={i as number}
className="flex-1 animate-pulse rounded bg-def-200"
className="flex-1 animate-pulse rounded-sm bg-def-200"
style={{ height: `${percent}%` }}
/>
))}
@@ -101,7 +101,7 @@ export function RealtimeLiveHistogram({
<TooltipTrigger asChild>
<div
className={cn(
'flex-1 rounded transition-all ease-in-out hover:scale-110',
'flex-1 rounded-sm transition-all ease-in-out hover:scale-110',
minute.count === 0 ? 'bg-def-200' : 'bg-highlight',
)}
style={{

View File

@@ -0,0 +1,37 @@
import { ActiveIntegrations } from '@/components/integrations/active-integrations';
import { AllIntegrations } from '@/components/integrations/all-integrations';
import { PageTabs, PageTabsLink } from '@/components/page-tabs';
import { Padding } from '@/components/ui/padding';
import { parseAsStringEnum } from 'nuqs';
interface PageProps {
params: {
projectId: string;
};
searchParams: {
tab: string;
};
}
export default function Page({
params: { projectId },
searchParams,
}: PageProps) {
const tab = parseAsStringEnum(['installed', 'available'])
.withDefault('available')
.parseServerSide(searchParams.tab);
return (
<Padding>
<PageTabs className="mb-4">
<PageTabsLink href="?tab=available" isActive={tab === 'available'}>
Available
</PageTabsLink>
<PageTabsLink href="?tab=installed" isActive={tab === 'installed'}>
Installed
</PageTabsLink>
</PageTabs>
{tab === 'installed' && <ActiveIntegrations />}
{tab === 'available' && <AllIntegrations />}
</Padding>
);
}

View File

@@ -0,0 +1,40 @@
import { NotificationRules } from '@/components/notifications/notification-rules';
import { Notifications } from '@/components/notifications/notifications';
import { PageTabs, PageTabsLink } from '@/components/page-tabs';
import { Padding } from '@/components/ui/padding';
import { parseAsStringEnum } from 'nuqs';
interface PageProps {
params: {
projectId: string;
};
searchParams: {
tab: string;
};
}
export default function Page({
params: { projectId },
searchParams,
}: PageProps) {
const tab = parseAsStringEnum(['notifications', 'rules'])
.withDefault('notifications')
.parseServerSide(searchParams.tab);
return (
<Padding>
<PageTabs className="mb-4">
<PageTabsLink
href="?tab=notifications"
isActive={tab === 'notifications'}
>
Notifications
</PageTabsLink>
<PageTabsLink href="?tab=rules" isActive={tab === 'rules'}>
Rules
</PageTabsLink>
</PageTabs>
{tab === 'notifications' && <Notifications />}
{tab === 'rules' && <NotificationRules />}
</Padding>
);
}

View File

@@ -169,7 +169,7 @@ const Tracking = ({
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) =>
tag === '*' ? 'Allow domains' : tag
tag === '*' ? 'Allow all domains' : tag
}
onChange={(newValue) => {
field.onChange(

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -15,6 +15,7 @@ import { Provider as ReduxProvider } from 'react-redux';
import { Toaster } from 'sonner';
import superjson from 'superjson';
import { NotificationProvider } from '@/components/notifications/notification-provider';
import { OpenPanelComponent } from '@openpanel/nextjs';
function AllProviders({ children }: { children: React.ReactNode }) {
@@ -76,6 +77,7 @@ function AllProviders({ children }: { children: React.ReactNode }) {
<QueryClientProvider client={queryClient}>
<TooltipProvider delayDuration={200}>
{children}
<NotificationProvider />
<Toaster />
<ModalProvider />
</TooltipProvider>

View File

@@ -5,7 +5,7 @@ import type { LucideIcon } from 'lucide-react';
interface FullPageEmptyStateProps {
icon?: LucideIcon;
title: string;
children: React.ReactNode;
children?: React.ReactNode;
className?: string;
}

View File

@@ -0,0 +1,118 @@
'use client';
import { useAppParams } from '@/hooks/useAppParams';
import { pushModal, showConfirm } from '@/modals';
import { api } from '@/trpc/client';
import { useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { AnimatePresence, motion } from 'framer-motion';
import { BoxSelectIcon } from 'lucide-react';
import { useMemo } from 'react';
import { PingBadge } from '../ping';
import { Button } from '../ui/button';
import {
IntegrationCard,
IntegrationCardFooter,
IntegrationCardLogo,
IntegrationCardSkeleton,
} from './integration-card';
import { INTEGRATIONS } from './integrations';
export function ActiveIntegrations() {
const { organizationId } = useAppParams();
const query = api.integration.list.useQuery({
organizationId,
});
const client = useQueryClient();
const deletion = api.integration.delete.useMutation({
onSuccess() {
client.refetchQueries(
getQueryKey(api.integration.list, {
organizationId,
}),
);
},
});
const data = useMemo(() => {
return (query.data || [])
.map((item) => {
const integration = INTEGRATIONS.find(
(integration) => integration.type === item.config.type,
)!;
return {
...item,
integration,
};
})
.filter((item) => item.integration);
}, [query.data]);
const isLoading = query.isLoading;
return (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 auto-rows-auto">
{isLoading && (
<>
<IntegrationCardSkeleton />
<IntegrationCardSkeleton />
<IntegrationCardSkeleton />
</>
)}
{!isLoading && data.length === 0 && (
<IntegrationCard
icon={
<IntegrationCardLogo className="bg-def-200 text-foreground">
<BoxSelectIcon className="size-10" strokeWidth={1} />
</IntegrationCardLogo>
}
name="No integrations yet"
description="Integrations allow you to connect your systems to OpenPanel. You can add them in the available integrations section."
/>
)}
<AnimatePresence mode="popLayout">
{data.map((item) => {
return (
<motion.div key={item.id} layout="position">
<IntegrationCard {...item.integration} name={item.name}>
<IntegrationCardFooter className="row justify-between items-center">
<PingBadge>Connected</PingBadge>
<div className="row gap-2">
<Button
variant="ghost"
className="text-destructive"
onClick={() => {
showConfirm({
title: `Delete ${item.name}?`,
text: 'This action cannot be undone.',
onConfirm: () => {
deletion.mutate({
id: item.id,
});
},
});
}}
>
Delete
</Button>
<Button
variant="ghost"
onClick={() => {
pushModal('AddIntegration', {
id: item.id,
type: item.config.type,
});
}}
>
Edit
</Button>
</div>
</IntegrationCardFooter>
</IntegrationCard>
</motion.div>
);
})}
</AnimatePresence>
</div>
);
}

View File

@@ -0,0 +1,36 @@
'use client';
import { Button } from '@/components/ui/button';
import { pushModal } from '@/modals';
import { PlugIcon, WebhookIcon } from 'lucide-react';
import { IntegrationCard, IntegrationCardFooter } from './integration-card';
import { INTEGRATIONS } from './integrations';
export function AllIntegrations() {
return (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{INTEGRATIONS.map((integration) => (
<IntegrationCard
key={integration.name}
icon={integration.icon}
name={integration.name}
description={integration.description}
>
<IntegrationCardFooter className="row justify-end">
<Button
variant="outline"
onClick={() => {
pushModal('AddIntegration', {
type: integration.type,
});
}}
>
<PlugIcon className="size-4 mr-2" />
Connect
</Button>
</IntegrationCardFooter>
</IntegrationCard>
))}
</div>
);
}

View File

@@ -0,0 +1,91 @@
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { type RouterOutputs, api } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
import { sendTestDiscordNotification } from '@openpanel/integrations/src/discord';
import { zCreateDiscordIntegration } from '@openpanel/validation';
import { path, mergeDeepRight } from 'ramda';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
type IForm = z.infer<typeof zCreateDiscordIntegration>;
export function DiscordIntegrationForm({
defaultValues,
onSuccess,
}: {
defaultValues?: RouterOutputs['integration']['get'];
onSuccess: () => void;
}) {
const { organizationId } = useAppParams();
const form = useForm<IForm>({
defaultValues: mergeDeepRight(
{
id: defaultValues?.id,
organizationId,
config: {
type: 'discord' as const,
url: '',
headers: {},
},
},
defaultValues ?? {},
),
resolver: zodResolver(zCreateDiscordIntegration),
});
const mutation = api.integration.createOrUpdate.useMutation({
onSuccess,
onError() {
toast.error('Failed to create integration');
},
});
const handleSubmit = (values: IForm) => {
mutation.mutate(values);
};
const handleError = () => {
toast.error('Validation error');
};
const handleTest = async () => {
const webhookUrl = form.getValues('config.url');
if (!webhookUrl) {
return toast.error('Webhook URL is required');
}
const res = await sendTestDiscordNotification(webhookUrl);
if (res.ok) {
toast.success('Test notification sent');
} else {
toast.error('Failed to send test notification');
}
};
return (
<form
onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
>
<InputWithLabel
label="Name"
{...form.register('name')}
error={form.formState.errors.name?.message}
/>
<InputWithLabel
label="Discord Webhook URL"
{...form.register('config.url')}
error={path(['config', 'url', 'message'], form.formState.errors)}
/>
<div className="row gap-4">
<Button type="button" variant="outline" onClick={handleTest}>
Test connection
</Button>
<Button type="submit" className="flex-1">
Create
</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,85 @@
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import useWS from '@/hooks/useWS';
import { popModal } from '@/modals';
import { type RouterOutputs, api } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
import { zCreateSlackIntegration } from '@openpanel/validation';
import { useQueryClient } from '@tanstack/react-query';
import { useRef } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
type IForm = z.infer<typeof zCreateSlackIntegration>;
export function SlackIntegrationForm({
defaultValues,
onSuccess,
}: {
defaultValues?: RouterOutputs['integration']['get'];
onSuccess: () => void;
}) {
const popup = useRef<Window | null>(null);
const { organizationId } = useAppParams();
const client = useQueryClient();
useWS('/live/integrations/slack', (res) => {
if (popup.current) {
popup.current.close();
}
onSuccess();
});
const form = useForm<IForm>({
defaultValues: {
id: defaultValues?.id,
organizationId,
name: defaultValues?.name ?? '',
},
resolver: zodResolver(zCreateSlackIntegration),
});
const mutation = api.integration.createOrUpdateSlack.useMutation({
async onSuccess(res) {
const url = res.slackInstallUrl;
const width = 600;
const height = 800;
const left = window.screenX + (window.outerWidth - width) / 2;
const top = window.screenY + (window.outerHeight - height) / 2.5;
popup.current = window.open(
url,
'',
`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${top}, left=${left}`,
);
// The popup might have been blocked, so we redirect the user to the URL instead
if (!popup.current) {
window.location.href = url;
}
},
onError() {
toast.error('Failed to create integration');
},
});
const handleSubmit = (values: IForm) => {
mutation.mutate(values);
};
const handleError = () => {
toast.error('Validation error');
};
return (
<form
onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
>
<InputWithLabel
label="Name"
{...form.register('name')}
error={form.formState.errors.name?.message}
/>
<Button type="submit">Create</Button>
</form>
);
}

View File

@@ -0,0 +1,73 @@
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { popModal } from '@/modals';
import { type RouterOutputs, api } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
import { zCreateWebhookIntegration } from '@openpanel/validation';
import { useQueryClient } from '@tanstack/react-query';
import { path, mergeDeepRight } from 'ramda';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
type IForm = z.infer<typeof zCreateWebhookIntegration>;
export function WebhookIntegrationForm({
defaultValues,
onSuccess,
}: {
defaultValues?: RouterOutputs['integration']['get'];
onSuccess: () => void;
}) {
const { organizationId } = useAppParams();
const form = useForm<IForm>({
defaultValues: mergeDeepRight(
{
id: defaultValues?.id,
organizationId,
config: {
type: 'webhook' as const,
url: '',
headers: {},
},
},
defaultValues ?? {},
),
resolver: zodResolver(zCreateWebhookIntegration),
});
const client = useQueryClient();
const mutation = api.integration.createOrUpdate.useMutation({
onSuccess,
onError() {
toast.error('Failed to create integration');
},
});
const handleSubmit = (values: IForm) => {
mutation.mutate(values);
};
const handleError = () => {
toast.error('Validation error');
};
return (
<form
onSubmit={form.handleSubmit(handleSubmit, handleError)}
className="col gap-4"
>
<InputWithLabel
label="Name"
{...form.register('name')}
error={form.formState.errors.name?.message}
/>
<InputWithLabel
label="URL"
{...form.register('config.url')}
error={path(['config', 'url', 'message'], form.formState.errors)}
/>
<Button type="submit">Create</Button>
</form>
);
}

View File

@@ -0,0 +1,144 @@
import { Skeleton } from '@/components/skeleton';
import { cn } from '@/utils/cn';
export function IntegrationCardFooter({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className={cn('row p-4 border-t rounded-b', className)}>
{children}
</div>
);
}
export function IntegrationCardHeader({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className={cn('relative row p-4 border-b rounded-t', className)}>
{children}
</div>
);
}
export function IntegrationCardHeaderButtons({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div
className={cn(
'absolute right-4 top-0 bottom-0 row items-center gap-2',
className,
)}
>
{children}
</div>
);
}
export function IntegrationCardLogoImage({
src,
backgroundColor,
}: {
src: string;
backgroundColor: string;
}) {
return (
<IntegrationCardLogo
style={{
backgroundColor,
}}
>
<img src={src} alt="Integration Logo" />
</IntegrationCardLogo>
);
}
export function IntegrationCardLogo({
children,
className,
...props
}: {
children: React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn(
'size-14 rounded overflow-hidden shrink-0 center-center',
className,
)}
{...props}
>
{children}
</div>
);
}
export function IntegrationCard({
icon,
name,
description,
children,
}: {
icon: React.ReactNode;
name: string;
description: string;
children?: React.ReactNode;
}) {
return (
<div className="card self-start">
<IntegrationCardContent
icon={icon}
name={name}
description={description}
/>
{children}
</div>
);
}
export function IntegrationCardContent({
icon,
name,
description,
}: {
icon: React.ReactNode;
name: string;
description: string;
}) {
return (
<div className="row gap-4 p-4">
{icon}
<div className="col gap-1">
<h2 className="title">{name}</h2>
<p className="text-muted-foreground leading-tight">{description}</p>
</div>
</div>
);
}
export function IntegrationCardSkeleton() {
return (
<div className="card self-start">
<div className="row gap-4 p-4">
<Skeleton className="size-14 rounded shrink-0" />
<div className="col gap-1 flex-grow">
<Skeleton className="h-5 w-1/2 mb-2" />
<Skeleton className="h-3 w-full" />
<Skeleton className="h-3 w-3/4" />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,49 @@
import type { IIntegrationConfig } from '@openpanel/db';
import { WebhookIcon } from 'lucide-react';
import {
IntegrationCardLogo,
IntegrationCardLogoImage,
} from './integration-card';
export const INTEGRATIONS: {
type: IIntegrationConfig['type'];
name: string;
description: string;
icon: React.ReactNode;
}[] = [
{
type: 'slack',
name: 'Slack',
description:
'Connect your Slack workspace to get notified when new issues are created.',
icon: (
<IntegrationCardLogoImage
src="https://play-lh.googleusercontent.com/mzJpTCsTW_FuR6YqOPaLHrSEVCSJuXzCljdxnCKhVZMcu6EESZBQTCHxMh8slVtnKqo"
backgroundColor="#481449"
/>
),
},
{
type: 'discord',
name: 'Discord',
description:
'Connect your Discord server to get notified when new issues are created.',
icon: (
<IntegrationCardLogoImage
src="https://static.vecteezy.com/system/resources/previews/006/892/625/non_2x/discord-logo-icon-editorial-free-vector.jpg"
backgroundColor="#5864F2"
/>
),
},
{
type: 'webhook',
name: 'Webhook',
description:
'Create a webhook to take actions in your own systems when new events are created.',
icon: (
<IntegrationCardLogo className="bg-foreground text-background">
<WebhookIcon className="size-10" />
</IntegrationCardLogo>
),
},
];

View File

@@ -13,7 +13,13 @@ export function ProjectLink({
const { organizationSlug, projectId } = useAppParams();
if (typeof props.href === 'string') {
return (
<Link {...props} href={`/${organizationSlug}/${projectId}/${props.href}`}>
<Link
{...props}
href={`/${organizationSlug}/${projectId}/${props.href.replace(
/^\//,
'',
)}`}
>
{children}
</Link>
);

View File

@@ -0,0 +1,17 @@
import { useAppParams } from '@/hooks/useAppParams';
import useWS from '@/hooks/useWS';
import type { Notification } from '@openpanel/db';
import { BellIcon } from 'lucide-react';
import { toast } from 'sonner';
export function NotificationProvider() {
const { projectId } = useAppParams();
useWS<Notification>(`/live/notifications/${projectId}`, (notification) => {
toast(notification.title, {
description: notification.message,
icon: <BellIcon className="size-4" />,
});
});
return null;
}

View File

@@ -0,0 +1,74 @@
'use client';
import { useAppParams } from '@/hooks/useAppParams';
import { pushModal } from '@/modals';
import { api } from '@/trpc/client';
import { AnimatePresence, motion } from 'framer-motion';
import { BoxSelectIcon, PlusIcon } from 'lucide-react';
import { useMemo } from 'react';
import {
IntegrationCard,
IntegrationCardLogo,
IntegrationCardSkeleton,
} from '../integrations/integration-card';
import { Button } from '../ui/button';
import { RuleCard } from './rule-card';
export function NotificationRules() {
const { projectId } = useAppParams();
const query = api.notification.rules.useQuery({
projectId,
});
const data = useMemo(() => {
return query.data || [];
}, [query.data]);
const isLoading = query.isLoading;
return (
<div>
<div className="mb-2">
<Button
icon={PlusIcon}
variant="outline"
onClick={() =>
pushModal('AddNotificationRule', {
rule: undefined,
})
}
>
Add Rule
</Button>
</div>
<div className="col gap-4 w-full grid md:grid-cols-2">
{isLoading && (
<>
<IntegrationCardSkeleton />
<IntegrationCardSkeleton />
<IntegrationCardSkeleton />
</>
)}
{!isLoading && data.length === 0 && (
<IntegrationCard
icon={
<IntegrationCardLogo className="bg-def-200 text-foreground">
<BoxSelectIcon className="size-10" strokeWidth={1} />
</IntegrationCardLogo>
}
name="No integrations yet"
description="Integrations allow you to connect your systems to OpenPanel. You can add them in the available integrations section."
/>
)}
<AnimatePresence mode="popLayout">
{data.map((item) => {
return (
<motion.div key={item.id} layout="position">
<RuleCard rule={item} />
</motion.div>
);
})}
</AnimatePresence>
</div>
</div>
);
}

View File

@@ -0,0 +1,14 @@
'use client';
import { useAppParams } from '@/hooks/useAppParams';
import { api } from '@/trpc/client';
import { NotificationsTable } from './table';
export function Notifications() {
const { projectId } = useAppParams();
const query = api.notification.list.useQuery({
projectId,
});
return <NotificationsTable query={query} />;
}

View File

@@ -0,0 +1,131 @@
import { pushModal, showConfirm } from '@/modals';
import { type RouterOutputs, api } from '@/trpc/client';
import type { NotificationRule } from '@openpanel/db';
import type { IChartRange, IInterval } from '@openpanel/validation';
import { useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { AsteriskIcon, FilterIcon } from 'lucide-react';
import { Fragment } from 'react';
import { toast } from 'sonner';
import { ColorSquare } from '../color-square';
import {
IntegrationCardFooter,
IntegrationCardHeader,
} from '../integrations/integration-card';
import { PingBadge } from '../ping';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Tooltiper } from '../ui/tooltip';
function EventBadge({
event,
}: { event: NotificationRule['config']['events'][number] }) {
return (
<Tooltiper
disabled={!event.filters.length}
content={
<div className="col gap-2 font-mono">
{event.filters.map((filter) => (
<div key={filter.id}>
{filter.name} {filter.operator} {JSON.stringify(filter.value)}
</div>
))}
</div>
}
>
<Badge variant="outline" className="inline-flex">
{event.name}
{Boolean(event.filters.length) && (
<FilterIcon className="size-2 ml-1" />
)}
</Badge>
</Tooltiper>
);
}
export function RuleCard({
rule,
}: { rule: RouterOutputs['notification']['rules'][number] }) {
const client = useQueryClient();
const deletion = api.notification.deleteRule.useMutation({
onSuccess() {
toast.success('Rule deleted');
client.refetchQueries(getQueryKey(api.notification.rules));
},
});
const renderConfig = () => {
switch (rule.config.type) {
case 'events':
return (
<div className="row gap-2 items-baseline flex-wrap">
<div>Get notified when</div>
{rule.config.events.map((event) => (
<EventBadge key={event.id} event={event} />
))}
<div>occurs</div>
</div>
);
case 'funnel':
return (
<div className="col gap-4">
<div>Get notified when a session has completed this funnel</div>
<div className="col gap-2">
{rule.config.events.map((event, index) => (
<div
key={event.id}
className="row gap-2 items-center font-mono"
>
<ColorSquare>{index + 1}</ColorSquare>
<EventBadge key={event.id} event={event} />
</div>
))}
</div>
</div>
);
}
};
return (
<div className="card">
<IntegrationCardHeader>
<div className="title">{rule.name}</div>
</IntegrationCardHeader>
<div className="p-4 col gap-2">{renderConfig()}</div>
<IntegrationCardFooter className="row gap-2 justify-between items-center">
<div className="row gap-2 flex-wrap">
{rule.integrations.map((integration) => (
<PingBadge key={integration.id}>{integration.name}</PingBadge>
))}
</div>
<div className="row gap-2">
<Button
variant="ghost"
className="text-destructive"
onClick={() => {
showConfirm({
title: `Delete ${rule.name}?`,
text: 'This action cannot be undone.',
onConfirm: () => {
deletion.mutate({
id: rule.id,
});
},
});
}}
>
Delete
</Button>
<Button
variant="ghost"
onClick={() => {
pushModal('AddNotificationRule', {
rule,
});
}}
>
Edit
</Button>
</div>
</IntegrationCardFooter>
</div>
);
}

View File

@@ -0,0 +1,140 @@
import { useNumber } from '@/hooks/useNumerFormatter';
import { formatDateTime, formatTime } from '@/utils/date';
import type { ColumnDef } from '@tanstack/react-table';
import { isToday } from 'date-fns';
import { ProjectLink } from '@/components/links';
import { PingBadge } from '@/components/ping';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import type { RouterOutputs } from '@/trpc/client';
import type { INotificationPayload } from '@openpanel/db';
function getEventFromPayload(payload: INotificationPayload | null) {
if (payload?.type === 'event') {
return payload.event;
}
if (payload?.type === 'funnel') {
return payload.funnel[0] || null;
}
return null;
}
export function useColumns() {
const columns: ColumnDef<RouterOutputs['notification']['list'][number]>[] = [
{
accessorKey: 'title',
header: 'Title',
cell({ row }) {
const { title, isReadAt } = row.original;
return (
<div className="row gap-2 items-center">
{isReadAt === null && <PingBadge>Unread</PingBadge>}
<span className="max-w-md truncate font-medium">{title}</span>
</div>
);
},
},
{
accessorKey: 'message',
header: 'Message',
cell({ row }) {
const { message } = row.original;
return (
<div className="inline-flex min-w-full flex-none items-center gap-2">
{message}
</div>
);
},
},
{
accessorKey: 'country',
header: 'Country',
cell({ row }) {
const { payload } = row.original;
const event = getEventFromPayload(payload);
if (!event) {
return null;
}
return (
<div className="inline-flex min-w-full flex-none items-center gap-2">
<SerieIcon name={event.country} />
<span>{event.city}</span>
</div>
);
},
},
{
accessorKey: 'os',
header: 'OS',
cell({ row }) {
const { payload } = row.original;
const event = getEventFromPayload(payload);
if (!event) {
return null;
}
return (
<div className="flex min-w-full items-center gap-2">
<SerieIcon name={event.os} />
<span>{event.os}</span>
</div>
);
},
},
{
accessorKey: 'browser',
header: 'Browser',
cell({ row }) {
const { payload } = row.original;
const event = getEventFromPayload(payload);
if (!event) {
return null;
}
return (
<div className="inline-flex min-w-full flex-none items-center gap-2">
<SerieIcon name={event.browser} />
<span>{event.browser}</span>
</div>
);
},
},
{
accessorKey: 'profile',
header: 'Profile',
cell({ row }) {
const { payload } = row.original;
const event = getEventFromPayload(payload);
if (!event) {
return null;
}
return (
<ProjectLink
href={`/profiles/${event.profileId}`}
className="inline-flex min-w-full flex-none items-center gap-2"
>
{event.profileId}
</ProjectLink>
);
},
},
{
accessorKey: 'createdAt',
header: 'Created at',
cell({ row }) {
const date = row.original.createdAt;
const rule = row.original.integration?.notificationRules[0];
return (
<div className="col gap-1">
<div>{isToday(date) ? formatTime(date) : formatDateTime(date)}</div>
{rule && (
<div className="text-sm text-muted-foreground">
Rule: {rule.name}
</div>
)}
</div>
);
},
},
];
return columns;
}

View File

@@ -0,0 +1,64 @@
import { DataTable } from '@/components/data-table';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import { Pagination } from '@/components/pagination';
import { Button } from '@/components/ui/button';
import { TableSkeleton } from '@/components/ui/table';
import type { UseQueryResult } from '@tanstack/react-query';
import { GanttChartIcon } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';
import type { Notification } from '@openpanel/db';
import { useColumns } from './columns';
type Props =
| {
query: UseQueryResult<Notification[]>;
}
| {
query: UseQueryResult<Notification[]>;
cursor: number;
setCursor: Dispatch<SetStateAction<number>>;
};
export const NotificationsTable = ({ query, ...props }: Props) => {
const columns = useColumns();
const { data, isFetching, isLoading } = query;
if (isLoading) {
return <TableSkeleton cols={columns.length} />;
}
if (data?.length === 0) {
return (
<FullPageEmptyState title="No events here" icon={GanttChartIcon}>
<p>Could not find any events</p>
{'cursor' in props && props.cursor !== 0 && (
<Button
className="mt-8"
variant="outline"
onClick={() => props.setCursor((p) => p - 1)}
>
Go to previous page
</Button>
)}
</FullPageEmptyState>
);
}
return (
<>
<DataTable data={data ?? []} columns={columns} />
{'cursor' in props && (
<Pagination
className="mt-2"
setCursor={props.setCursor}
cursor={props.cursor}
count={Number.POSITIVE_INFINITY}
take={50}
loading={isFetching}
/>
)}
</>
);
};

View File

@@ -79,7 +79,7 @@ export function OverviewLiveHistogram({
{staticArray.map((percent, i) => (
<div
key={i as number}
className="flex-1 animate-pulse rounded-t bg-def-200"
className="flex-1 animate-pulse rounded-t-sm bg-def-200"
style={{ height: `${percent}%` }}
/>
))}
@@ -99,7 +99,7 @@ export function OverviewLiveHistogram({
<TooltipTrigger asChild>
<div
className={cn(
'flex-1 rounded-t transition-all ease-in-out hover:scale-110',
'flex-1 rounded-t-sm transition-all ease-in-out hover:scale-110',
minute.count === 0 ? 'bg-def-200' : 'bg-highlight',
)}
style={{

View File

@@ -0,0 +1,28 @@
import { cn } from '@/utils/cn';
import { Badge } from './ui/badge';
export function Ping({ className }: { className?: string }) {
return (
<div className="relative">
<div className={cn('size-2 bg-emerald-500 rounded-full', className)} />
<div
className={cn(
'size-2 bg-emerald-500 rounded-full absolute inset-0 animate-ping',
className,
)}
/>
</div>
);
}
export function PingBadge({
children,
className,
}: { children: React.ReactNode; className?: string }) {
return (
<Badge variant={'outline'} className={cn('flex gap-1', className)}>
<Ping />
{children}
</Badge>
);
}

View File

@@ -57,6 +57,14 @@ export default function SettingsToggle({ className }: Props) {
<DropdownMenuItem asChild>
<ProjectLink href="/settings/references">References</ProjectLink>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<ProjectLink href="/settings/notifications">
Notifications
</ProjectLink>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<ProjectLink href="/settings/integrations">Integrations</ProjectLink>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger className="flex w-full items-center justify-between">

View File

@@ -0,0 +1,5 @@
import { cn } from '@/utils/cn';
export function Skeleton({ className }: { className?: string }) {
return <div className={cn('animate-pulse rounded bg-def-200', className)} />;
}

View File

@@ -6,7 +6,7 @@ import type { VariantProps } from 'class-variance-authority';
import type * as React from 'react';
const badgeVariants = cva(
'inline-flex h-[20px] items-center rounded-full border px-2 text-sm font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
'inline-flex h-[20px] items-center rounded border px-2 text-sm font-mono transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
@@ -20,6 +20,7 @@ const badgeVariants = cva(
'border-transparent bg-emerald-500 text-emerald-100 hover:bg-emerald-500/80',
outline: 'text-foreground',
muted: 'bg-def-100 text-foreground',
foregroundish: 'bg-foregroundish text-foregroundish-foreground',
},
},
defaultVariants: {

View File

@@ -42,6 +42,7 @@ interface TooltiperProps {
side?: 'top' | 'right' | 'bottom' | 'left';
delayDuration?: number;
sideOffset?: number;
disabled?: boolean;
}
export function Tooltiper({
asChild,
@@ -52,7 +53,9 @@ export function Tooltiper({
side,
delayDuration = 0,
sideOffset = 10,
disabled = false,
}: TooltiperProps) {
if (disabled) return children;
return (
<Tooltip delayDuration={delayDuration}>
<TooltipTrigger asChild={asChild} className={className} onClick={onClick}>

View File

@@ -2,6 +2,7 @@ import { useParams } from 'next/navigation';
type AppParams = {
organizationSlug: string;
organizationId: string;
projectId: string;
};
@@ -10,6 +11,7 @@ export function useAppParams<T>() {
return {
...(params ?? {}),
organizationSlug: params?.organizationSlug,
organizationId: params?.organizationSlug,
projectId: params?.projectId,
} as T & AppParams;
}

View File

@@ -157,7 +157,9 @@ export default function AddClient(props: Props) {
error={form.formState.errors.cors?.message}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
renderTag={(tag) =>
tag === '*' ? 'Allow all domains' : tag
}
onChange={(newValue) => {
field.onChange(
newValue

View File

@@ -91,7 +91,7 @@ export default function EditClient({
error={formState.errors.cors?.message}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) => (tag === '*' ? 'Allow domains' : tag)}
renderTag={(tag) => (tag === '*' ? 'Allow all domains' : tag)}
onChange={(newValue) => {
field.onChange(
newValue

View File

@@ -0,0 +1,101 @@
'use client';
import { api } from '@/trpc/client';
import { DiscordIntegrationForm } from '@/components/integrations/forms/discord-integration';
import { SlackIntegrationForm } from '@/components/integrations/forms/slack-integration';
import { WebhookIntegrationForm } from '@/components/integrations/forms/webhook-integration';
import { IntegrationCardContent } from '@/components/integrations/integration-card';
import { INTEGRATIONS } from '@/components/integrations/integrations';
import { SheetContent } from '@/components/ui/sheet';
import type { IIntegrationConfig } from '@openpanel/validation';
import { useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { useQueryState } from 'nuqs';
import { toast } from 'sonner';
import { popModal } from '.';
import { ModalHeader } from './Modal/Container';
interface Props {
id?: string;
type: IIntegrationConfig['type'];
}
export default function AddIntegration(props: Props) {
const query = api.integration.get.useQuery(
{
id: props.id ?? '',
},
{
enabled: !!props.id,
},
);
const integration = INTEGRATIONS.find((i) => i.type === props.type);
const renderCard = () => {
if (!integration) {
return null;
}
return (
<div className="card bg-def-100">
<IntegrationCardContent {...integration} />
</div>
);
};
const [tab, setTab] = useQueryState('tab', {
shallow: false,
});
const client = useQueryClient();
const handleSuccess = () => {
toast.success('Integration created');
popModal();
client.refetchQueries([
getQueryKey(api.integration.list),
getQueryKey(api.integration.get, { id: props.id }),
]);
if (tab !== undefined) {
setTab('installed');
}
};
const renderForm = () => {
if (props.id && query.isLoading) {
return null;
}
switch (integration?.type) {
case 'webhook':
return (
<WebhookIntegrationForm
defaultValues={query.data}
onSuccess={handleSuccess}
/>
);
case 'discord':
return (
<DiscordIntegrationForm
defaultValues={query.data}
onSuccess={handleSuccess}
/>
);
case 'slack':
return (
<SlackIntegrationForm
defaultValues={query.data}
onSuccess={handleSuccess}
/>
);
default:
return null;
}
};
return (
<SheetContent className="[&>button.absolute]:hidden">
<ModalHeader title="Create an integration" />
{renderCard()}
{renderForm()}
</SheetContent>
);
}

View File

@@ -0,0 +1,308 @@
'use client';
import { type RouterOutputs, api } from '@/trpc/client';
import { SheetContent } from '@/components/ui/sheet';
import type { NotificationRule } from '@openpanel/db';
import { useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { toast } from 'sonner';
import { popModal } from '.';
import { ModalHeader } from './Modal/Container';
import { ColorSquare } from '@/components/color-square';
import { CheckboxItem } from '@/components/forms/checkbox-item';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
import { useAppParams } from '@/hooks/useAppParams';
import { useEventNames } from '@/hooks/useEventNames';
import { useEventProperties } from '@/hooks/useEventProperties';
import { zodResolver } from '@hookform/resolvers/zod';
import { shortId } from '@openpanel/common';
import {
IChartEvent,
type IChartRange,
type IInterval,
zCreateNotificationRule,
} from '@openpanel/validation';
import {
FilterIcon,
PlusIcon,
SaveIcon,
SmartphoneIcon,
TrashIcon,
} from 'lucide-react';
import {
Controller,
type SubmitHandler,
type UseFormReturn,
useFieldArray,
useForm,
useWatch,
} from 'react-hook-form';
import type { z } from 'zod';
interface Props {
rule?: RouterOutputs['notification']['rules'][number];
}
type IForm = z.infer<typeof zCreateNotificationRule>;
export default function AddNotificationRule({ rule }: Props) {
const client = useQueryClient();
const { organizationId, projectId } = useAppParams();
const form = useForm<IForm>({
resolver: zodResolver(zCreateNotificationRule),
defaultValues: {
id: rule?.id ?? '',
name: rule?.name ?? '',
sendToApp: rule?.sendToApp ?? false,
sendToEmail: rule?.sendToEmail ?? false,
integrations:
rule?.integrations.map((integration) => integration.id) ?? [],
projectId,
config: rule?.config ?? {
type: 'events',
events: [
{
name: '',
segment: 'event',
filters: [],
},
],
},
},
});
const mutation = api.notification.createOrUpdateRule.useMutation({
onSuccess() {
toast.success(
rule ? 'Notification rule updated' : 'Notification rule created',
);
client.refetchQueries(
getQueryKey(api.notification.rules, {
projectId,
}),
);
popModal();
},
});
const eventsArray = useFieldArray({
control: form.control,
name: 'config.events',
});
const onSubmit: SubmitHandler<IForm> = (data) => {
mutation.mutate(data);
};
const integrationsQuery = api.integration.list.useQuery({
organizationId,
});
const integrations = integrationsQuery.data ?? [];
return (
<SheetContent className="[&>button.absolute]:hidden">
<ModalHeader title={rule ? 'Edit rule' : 'Create rule'} />
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-4">
<InputWithLabel
label="Rule name"
placeholder="Eg. Sign ups on android"
error={form.formState.errors.name?.message}
{...form.register('name')}
/>
<WithLabel
label="Type"
// @ts-expect-error
error={form.formState.errors.config?.type.message}
>
<Controller
control={form.control}
name="config.type"
render={({ field }) => (
<Combobox
{...field}
className="w-full"
placeholder="Select type"
// @ts-expect-error
error={form.formState.errors.config?.type.message}
items={[
{
label: 'Events',
value: 'events',
},
{
label: 'Funnel',
value: 'funnel',
},
]}
/>
)}
/>
</WithLabel>
<WithLabel label="Events">
<div className="col gap-2">
{eventsArray.fields.map((field, index) => {
return (
<EventField
key={field.id}
form={form}
index={index}
remove={() => eventsArray.remove(index)}
/>
);
})}
<Button
className="self-start"
variant={'outline'}
icon={PlusIcon}
onClick={() =>
eventsArray.append({
name: '',
filters: [],
segment: 'event',
})
}
>
Add event
</Button>
</div>
</WithLabel>
<Controller
control={form.control}
name="integrations"
render={({ field }) => (
<WithLabel label="Integrations">
<ComboboxAdvanced
{...field}
value={field.value ?? []}
className="w-full"
placeholder="Pick integrations"
items={integrations.map((integration) => ({
label: integration.name,
value: integration.id,
}))}
/>
</WithLabel>
)}
/>
<Button type="submit" icon={SaveIcon}>
{rule ? 'Update' : 'Create'}
</Button>
</form>
</SheetContent>
);
}
const interval: IInterval = 'day';
const range: IChartRange = 'lastMonth';
function EventField({
form,
index,
remove,
}: {
form: UseFormReturn<IForm>;
index: number;
remove: () => void;
}) {
const { projectId } = useAppParams();
const eventNames = useEventNames({ projectId, interval, range });
const filtersArray = useFieldArray({
control: form.control,
name: `config.events.${index}.filters`,
});
const eventName = useWatch({
control: form.control,
name: `config.events.${index}.name`,
});
const properties = useEventProperties({ projectId, interval, range });
return (
<div className="border bg-def-100 rounded">
<div className="row gap-2 items-center p-2">
<ColorSquare>{index + 1}</ColorSquare>
<Controller
control={form.control}
name={`config.events.${index}.name`}
render={({ field }) => (
<Combobox
searchable
className="flex-1"
value={field.value}
placeholder="Select event"
onChange={field.onChange}
items={eventNames.map((item) => ({
label: item.name,
value: item.name,
}))}
/>
)}
/>
<Combobox
searchable
placeholder="Select a filter"
value=""
items={properties.map((item) => ({
label: item,
value: item,
}))}
onChange={(value) => {
filtersArray.append({
id: shortId(),
name: value,
operator: 'is',
value: [],
});
}}
>
<Button variant={'outline'} icon={FilterIcon} size={'icon'} />
</Combobox>
<Button
onClick={() => {
remove();
}}
variant={'outline'}
className="text-destructive"
icon={TrashIcon}
size={'icon'}
/>
</div>
{filtersArray.fields.map((filter, index) => {
return (
<div key={filter.id} className="p-2 border-t">
<PureFilterItem
eventName={eventName}
filter={filter}
range={range}
startDate={null}
endDate={null}
interval={interval}
onRemove={() => {
filtersArray.remove(index);
}}
onChangeValue={(value) => {
filtersArray.update(index, {
...filter,
value,
});
}}
onChangeOperator={(operator) => {
filtersArray.update(index, {
...filter,
operator,
});
}}
/>
</div>
);
})}
</div>
);
}

View File

@@ -74,6 +74,8 @@ const modals = {
Testimonial: dynamic(() => import('./Testimonial'), {
loading: Loading,
}),
AddIntegration: dynamic(() => import('./add-integration')),
AddNotificationRule: dynamic(() => import('./add-notification-rule')),
};
export const {

View File

@@ -13,6 +13,7 @@
--background: 0 0% 100%; /* #FFFFFF */
--foreground: 222.2 84% 4.9%; /* #0C162A */
--foregroundish: 226.49 3.06% 22.62%;
--card: 0 0% 100%; /* #FFFFFF */
--card-foreground: 222.2 84% 4.9%; /* #0C162A */
@@ -52,6 +53,7 @@
--background: 0 0% 12.02%; /* #1e1e1e */
--foreground: 0 0% 98%; /* #fafafa */
--foregroundish: 0 0% 79.23%;
--card: 0 0% 10%; /* #1a1a1a */
--card-foreground: 0 0% 98%; /* #fafafa */
@@ -108,25 +110,18 @@
@apply overflow-hidden text-ellipsis whitespace-nowrap;
}
.shine {
background-repeat: no-repeat;
background-position: -120px -120px, 0 0;
background-image: linear-gradient(
0 0,
rgba(255, 255, 255, 0.2) 0%,
rgba(255, 255, 255, 0.2) 37%,
rgba(255, 255, 255, 0.8) 45%,
rgba(255, 255, 255, 0) 50%
);
background-size: 250% 250%, 100% 100%;
transition: background-position 0s ease;
.heading {
@apply text-3xl font-semibold;
}
.shine:hover {
background-position: 0 0, 0 0;
transition-duration: 0.5s;
.title {
@apply text-lg font-semibold;
}
.subtitle {
@apply text-md font-medium;
}
.card {
@apply rounded-md border border-border bg-card;
}