Skip to content

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

fix(dashboard): improvements to notifications templates

Carl-Gerhard Lindesvärdc12eb808670d
diff --git a/apps/dashboard/src/app/(app)/[organizationSlug]/[projectId]/settings/integrations/page.tsx b/apps/dashboard/src/app/(app)/[organizationSlug]/[projectId]/settings/integrations/page.tsx
index 349ae84c5..538518473 100644
--- a/apps/dashboard/src/app/(app)/[organizationSlug]/[projectId]/settings/integrations/page.tsx
+++ b/apps/dashboard/src/app/(app)/[organizationSlug]/[projectId]/settings/integrations/page.tsx
@@ -21,17 +21,16 @@ export default function Page({
.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 className="col gap-8">
+ <div className="col gap-4">
+ <h2 className="text-3xl font-semibold">Your integrations</h2>
+ <ActiveIntegrations />
+ </div>
+
+ <div className="col gap-4">
+ <h2 className="text-3xl font-semibold">Available integrations</h2>
+ <AllIntegrations />
+ </div>
</Padding>
);
}
diff --git a/apps/dashboard/src/components/forms/input-with-label.tsx b/apps/dashboard/src/components/forms/input-with-label.tsx
index 937086dac..6e07fa618 100644
--- a/apps/dashboard/src/components/forms/input-with-label.tsx
+++ b/apps/dashboard/src/components/forms/input-with-label.tsx
@@ -10,7 +10,7 @@ type WithLabel = {
children: React.ReactNode;
label: string;
error?: string | undefined;
- info?: string;
+ info?: React.ReactNode;
className?: string;
};
type InputWithLabelProps = InputProps & Omit<WithLabel, 'children'>;
diff --git a/apps/dashboard/src/components/notifications/table/columns.tsx b/apps/dashboard/src/components/notifications/table/columns.tsx
index e4eae86a0..d9d783750 100644
--- a/apps/dashboard/src/components/notifications/table/columns.tsx
+++ b/apps/dashboard/src/components/notifications/table/columns.tsx
@@ -28,7 +28,7 @@ export function useColumns() {
const { title, isReadAt } = row.original;
return (
<div className="row gap-2 items-center">
- {isReadAt === null && <PingBadge>Unread</PingBadge>}
+ {/* {isReadAt === null && <PingBadge>Unread</PingBadge>} */}
<span className="max-w-md truncate font-medium">{title}</span>
</div>
);
@@ -46,6 +46,22 @@ export function useColumns() {
);
},
},
+ {
+ accessorKey: 'integration',
+ header: 'Integration',
+ cell({ row }) {
+ const integration = row.original.integration;
+ return <div>{integration?.name}</div>;
+ },
+ },
+ {
+ accessorKey: 'notificationRule',
+ header: 'Rule',
+ cell({ row }) {
+ const rule = row.original.notificationRule;
+ return <div>{rule?.name}</div>;
+ },
+ },
{
accessorKey: 'country',
header: 'Country',
@@ -121,16 +137,8 @@ export function useColumns() {
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>
+ <div>{isToday(date) ? formatTime(date) : formatDateTime(date)}</div>
);
},
},
diff --git a/apps/dashboard/src/components/ui/tooltip.tsx b/apps/dashboard/src/components/ui/tooltip.tsx
index b9865d43f..415754fca 100644
--- a/apps/dashboard/src/components/ui/tooltip.tsx
+++ b/apps/dashboard/src/components/ui/tooltip.tsx
@@ -62,7 +62,12 @@ export function Tooltiper({
if (disabled) return children;
return (
<Tooltip delayDuration={delayDuration}>
- <TooltipTrigger asChild={asChild} className={className} onClick={onClick}>
+ <TooltipTrigger
+ asChild={asChild}
+ className={className}
+ onClick={onClick}
+ type="button"
+ >
{children}
</TooltipTrigger>
<TooltipPortal>
diff --git a/apps/dashboard/src/modals/add-notification-rule.tsx b/apps/dashboard/src/modals/add-notification-rule.tsx
index e5c124feb..79adc7915 100644
--- a/apps/dashboard/src/modals/add-notification-rule.tsx
+++ b/apps/dashboard/src/modals/add-notification-rule.tsx
@@ -164,7 +164,48 @@ export default function AddNotificationRule({ rule }: Props) {
<WithLabel
label="Template"
- info="Customize your notification. Exisiting variables: $EVENT_NAME, $RULE_NAME"
+ info={
+ <div className="text-base leading-normal max-w-sm p-2 prose text-left text-white [&_code]:text-white">
+ <p>
+ Customize your notification message. You can grab any property
+ from your event.
+ </p>
+
+ <ul>
+ <li>
+ <code>{'{{name}}'}</code> - The name of the event
+ </li>
+ <li>
+ <code>{'{{rule_name}}'}</code> - The name of the rule
+ </li>
+ <li>
+ <code>{'{{properties.your.property}}'}</code> - Get the value
+ of a custom property
+ </li>
+ <li>
+ <div className="flex gap-x-2 flex-wrap">
+ And many more...
+ <code>profileId</code>
+ <code>createdAt</code>
+ <code>country</code>
+ <code>city</code>
+ <code>os</code>
+ <code>osVersion</code>
+ <code>browser</code>
+ <code>browserVersion</code>
+ <code>device</code>
+ <code>brand</code>
+ <code>model</code>
+ <code>path</code>
+ <code>origin</code>
+ <code>referrer</code>
+ <code>referrerName</code>
+ <code>referrerType</code>
+ </div>
+ </li>
+ </ul>
+ </div>
+ }
>
<Textarea
{...form.register('template')}
diff --git a/packages/db/prisma/migrations/20241229150840_add_rule_to_notification/migration.sql b/packages/db/prisma/migrations/20241229150840_add_rule_to_notification/migration.sql
new file mode 100644
index 000000000..70a98a07a
--- /dev/null
+++ b/packages/db/prisma/migrations/20241229150840_add_rule_to_notification/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "notifications" ADD COLUMN "notificationRuleId" UUID;
+
+-- AddForeignKey
+ALTER TABLE "notifications" ADD CONSTRAINT "notifications_notificationRuleId_fkey" FOREIGN KEY ("notificationRuleId") REFERENCES "notification_rules"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 294d66a19..6da411ff8 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -380,37 +380,40 @@ enum IntegrationType {
}
model NotificationRule {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- name String
- projectId String
- project Project @relation(fields: [projectId], references: [id])
- integrations Integration[]
- sendToApp Boolean @default(false)
- sendToEmail Boolean @default(false)
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ name String
+ projectId String
+ project Project @relation(fields: [projectId], references: [id])
+ integrations Integration[]
+ sendToApp Boolean @default(false)
+ sendToEmail Boolean @default(false)
/// [IPrismaNotificationRuleConfig]
- config Json
- template String?
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ config Json
+ template String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ notifications Notification[]
@@map("notification_rules")
}
model Notification {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- projectId String
- project Project @relation(fields: [projectId], references: [id])
- title String
- message String
- isReadAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
- sendToApp Boolean @default(false)
- sendToEmail Boolean @default(false)
- integration Integration? @relation(fields: [integrationId], references: [id])
- integrationId String? @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ projectId String
+ project Project @relation(fields: [projectId], references: [id])
+ title String
+ message String
+ isReadAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+ sendToApp Boolean @default(false)
+ sendToEmail Boolean @default(false)
+ integration Integration? @relation(fields: [integrationId], references: [id])
+ integrationId String? @db.Uuid
+ notificationRuleId String? @db.Uuid
+ notificationRule NotificationRule? @relation(fields: [notificationRuleId], references: [id])
/// [IPrismaNotificationPayload]
- payload Json?
+ payload Json?
@@map("notifications")
}
diff --git a/packages/db/src/services/notification.service.ts b/packages/db/src/services/notification.service.ts
index 908de6185..79f035ac5 100644
--- a/packages/db/src/services/notification.service.ts
+++ b/packages/db/src/services/notification.service.ts
@@ -17,7 +17,12 @@ import { getProjectByIdCached } from './project.service';
type ICreateNotification = Pick<
Notification,
- 'projectId' | 'title' | 'message' | 'integrationId' | 'payload'
+ | 'projectId'
+ | 'title'
+ | 'message'
+ | 'integrationId'
+ | 'payload'
+ | 'notificationRuleId'
>;
export type INotificationPayload =
@@ -118,6 +123,7 @@ export async function createNotification(notification: ICreateNotification) {
projectId: notification.projectId,
payload: notification.payload || Prisma.DbNull,
...getIntegration(notification.integrationId),
+ notificationRuleId: notification.notificationRuleId,
},
});
@@ -202,9 +208,23 @@ function notificationTemplateEvent({
rule: INotificationRuleCached;
}) {
if (!rule.template) return `You received a new "${payload.name}" event`;
- return rule.template
+ let template = rule.template
.replaceAll('$EVENT_NAME', payload.name)
- .replaceAll('$RULE_NAME', rule.name);
+ .replaceAll('$RULE_NAME', rule.name)
+ .replaceAll('{{rule_name}}', rule.name);
+
+ // Replace all {{xxx}} placeholders with their values
+ const placeholderMatches = template.match(/{{[^}]+}}/g) || [];
+ for (const match of placeholderMatches) {
+ const path = match.slice(2, -2); // Remove {{ and }}
+ const value = pathOr('', path.split('.'), payload);
+
+ if (value) {
+ template = template.replaceAll(match, JSON.stringify(value));
+ }
+ }
+
+ return template;
}
function notificationTemplateFunnel({
@@ -253,6 +273,7 @@ export async function checkNotificationRulesForEvent(
createNotification({
...notification,
integrationId: integration.id,
+ notificationRuleId: rule.id,
}),
);
@@ -261,6 +282,7 @@ export async function checkNotificationRulesForEvent(
createNotification({
...notification,
integrationId: APP_NOTIFICATION_INTEGRATION_ID,
+ notificationRuleId: rule.id,
}),
);
}
@@ -270,6 +292,7 @@ export async function checkNotificationRulesForEvent(
createNotification({
...notification,
integrationId: EMAIL_NOTIFICATION_INTEGRATION_ID,
+ notificationRuleId: rule.id,
}),
);
}
@@ -325,13 +348,18 @@ export async function checkNotificationRulesForSessionEnd(
// Generate notification promises
return [
...rule.integrations.map((integration) =>
- createNotification({ ...notification, integrationId: integration.id }),
+ createNotification({
+ ...notification,
+ integrationId: integration.id,
+ notificationRuleId: rule.id,
+ }),
),
...(rule.sendToApp
? [
createNotification({
...notification,
integrationId: APP_NOTIFICATION_INTEGRATION_ID,
+ notificationRuleId: rule.id,
}),
]
: []),
@@ -340,6 +368,7 @@ export async function checkNotificationRulesForSessionEnd(
createNotification({
...notification,
integrationId: EMAIL_NOTIFICATION_INTEGRATION_ID,
+ notificationRuleId: rule.id,
}),
]
: []),
diff --git a/packages/trpc/src/routers/notification.ts b/packages/trpc/src/routers/notification.ts
index 76fa53f67..feda96487 100644
--- a/packages/trpc/src/routers/notification.ts
+++ b/packages/trpc/src/routers/notification.ts
@@ -21,19 +21,19 @@ export const notificationRouter = createTRPCRouter({
return db.notification.findMany({
where: {
projectId: input.projectId,
- sendToApp: true,
},
orderBy: {
createdAt: 'desc',
},
include: {
integration: {
- include: {
- notificationRules: {
- select: {
- name: true,
- },
- },
+ select: {
+ name: true,
+ },
+ },
+ notificationRule: {
+ select: {
+ name: true,
},
},
},