Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api-service): Usage insights email #7346

Draft
wants to merge 34 commits into
base: next
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
9f7b9dc
feat: insights
scopsy Dec 4, 2024
5728669
feat: wip
scopsy Dec 4, 2024
6eb853e
fix: hello world
scopsy Dec 4, 2024
099fea9
fix: email
scopsy Dec 4, 2024
8fb84e3
fix: email style
scopsy Dec 4, 2024
60a85a3
fix: add marketing section
scopsy Dec 4, 2024
a49b625
fix: upload
scopsy Dec 4, 2024
d56c811
fix: logo
scopsy Dec 4, 2024
8a89c1b
Merge branch 'next' into insights-email
scopsy Dec 22, 2024
747dffd
fix: items
scopsy Dec 22, 2024
5ee4ad9
fix: workflows
scopsy Dec 22, 2024
6d7c867
fix: items
scopsy Dec 22, 2024
63ef939
fix: items
scopsy Dec 22, 2024
836c44f
fix: items
scopsy Dec 22, 2024
0dd5361
fix: refactor
scopsy Dec 22, 2024
9570eff
fix: review
scopsy Dec 22, 2024
2be2bf1
fix: items
scopsy Dec 22, 2024
5464b96
fix: items
scopsy Dec 22, 2024
2945749
fix: bugs
scopsy Dec 22, 2024
4c9bd12
fix: working state
scopsy Dec 22, 2024
3b4e5a9
feat: add controller
scopsy Dec 22, 2024
4a4f6bc
feat: add insights tester
scopsy Dec 22, 2024
88f0530
fix: mixpanel
scopsy Dec 22, 2024
510860a
fix: remove cache
scopsy Dec 22, 2024
efc2df7
fix: remove unused import
scopsy Dec 22, 2024
bd7e05f
fix: trigger
scopsy Dec 22, 2024
65c3d67
fix: empty state
scopsy Dec 22, 2024
9ea8c3c
fix: refactpr
scopsy Dec 22, 2024
69a10f8
fix: r emov unused
scopsy Dec 22, 2024
3173273
fix: validation
scopsy Dec 22, 2024
465427d
fix: remove pr info
scopsy Dec 22, 2024
2c39098
Merge branch 'next' into insights-email
scopsy Dec 22, 2024
ed1d443
Merge branch 'next' into insights-email
scopsy Dec 22, 2024
325762b
fix: import
scopsy Dec 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: email
  • Loading branch information
scopsy committed Dec 4, 2024
commit 099fea9072e76dfae820bfafeccf8c3990e83fd9
4 changes: 2 additions & 2 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ForwardReference } from '@nestjs/common/interfaces/modules/forward-refe
import { isClerkEnabled } from '@novu/shared';
import { SentryModule } from '@sentry/nestjs/setup';
import { ApiExcludeController } from '@nestjs/swagger';
import { usageLimitsWorkflow } from '@novu/notifications';
import { usageInsightsWorkflow, usageLimitsWorkflow } from '@novu/notifications';
import packageJson from '../package.json';
import { SharedModule } from './app/shared/shared.module';
import { UserModule } from './app/user/user.module';
Expand Down Expand Up @@ -167,7 +167,7 @@ modules.push(
process.env.NOVU_STRICT_AUTHENTICATION_ENABLED === 'true',
}),
controllerDecorators: [ApiExcludeController()],
workflows: [usageLimitsWorkflow],
workflows: [usageLimitsWorkflow, usageInsightsWorkflow],
})
);

Expand Down
1 change: 1 addition & 0 deletions libs/notifications/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './workflows/usage-limits/usage-limits.workflow';
export * from './workflows/usage-insights/usage-insights.workflow';
165 changes: 165 additions & 0 deletions libs/notifications/src/workflows/usage-insights/email.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import React from 'react';
import { Body, Container, Head, Heading, Html, Preview, Section, Tailwind, Text, Img } from '@react-email/components';
import { IUsageEmailData } from './types';

function MetricCard({
title,
current,
previous,
change,
}: {
title: string;
current: number;
previous: number;
change: number;
}) {
const isPositive = change > 0;
const changeColor = isPositive ? 'text-emerald-600' : 'text-rose-600';

const formatNumber = (num: number) => Math.floor(num).toLocaleString('en-US', { maximumFractionDigits: 0 });

return (
<div className="flex h-[88px] flex-col rounded-lg border border-gray-100 bg-gray-50/50 p-2">
<div className="flex items-start justify-between gap-2">
<Text className="mb-0 mt-0 min-h-[28px] text-xs font-medium leading-tight text-gray-600">{title}</Text>
<Text className={`whitespace-nowrap text-xs font-medium ${changeColor} mb-0 mt-0`}>
{isPositive ? '↑' : '↓'} {Math.abs(Math.floor(change))}%
</Text>
</div>
<div className="mt-auto">
<Text className="mb-0 mt-0 text-lg font-bold leading-none text-gray-900">{formatNumber(current)}</Text>
<Text className="mb-0 mt-0.5 text-[10px] leading-none text-gray-500">Previous: {formatNumber(previous)}</Text>
</div>
</div>
);
}

function SectionHeader({ title }: { title: string }) {
return (
<div className="mb-3">
<Heading className="text-base font-semibold text-gray-800">{title}</Heading>
</div>
);
}

function ChannelBreakdown({ channels }: { channels: IUsageEmailData['channelBreakdown'] }) {
return (
<Section className="mt-6">
<SectionHeader title="Channel Breakdown" />
<div className="grid grid-cols-3 gap-3">
{Object.entries(channels).map(([channel, metrics]) => (
<MetricCard
key={channel}
title={channel}
current={metrics.current}
previous={metrics.previous}
change={metrics.change}
/>
))}
</div>
</Section>
);
}

function InboxMetrics({ metrics }: { metrics: IUsageEmailData['inboxMetrics'] }) {
return (
<Section className="mt-6">
<SectionHeader title="Inbox Activity" />
<div className="grid grid-cols-3 gap-3">
<MetricCard
title="Sessions"
current={metrics.sessionInitialized.current}
previous={metrics.sessionInitialized.previous}
change={metrics.sessionInitialized.change}
/>
<MetricCard
title="Preference Updates"
current={metrics.updatePreferences.current}
previous={metrics.updatePreferences.previous}
change={metrics.updatePreferences.change}
/>
<MetricCard
title="Notifications Marked"
current={metrics.markNotification.current}
previous={metrics.markNotification.previous}
change={metrics.markNotification.change}
/>
<MetricCard
title="Actions Taken"
current={metrics.updateAction.current}
previous={metrics.updateAction.previous}
change={metrics.updateAction.change}
/>
</div>
</Section>
);
}

function WorkflowStats({ workflows }: { workflows: IUsageEmailData['workflowStats'] }) {
return (
<Section className="mt-6">
<SectionHeader title="Workflow Performance" />
<div className="grid grid-cols-3 gap-3">
{Object.entries(workflows).map(([name, metrics]) => (
<MetricCard
key={name}
title={name}
current={metrics.current}
previous={metrics.previous}
change={metrics.change}
/>
))}
</div>
</Section>
);
}

export default function UsageInsightsEmail(props: IUsageEmailData) {
return (
<Html>
<Head />
<Preview>
📊 Usage Insights for {props.organizationName} - {props.period.current}
</Preview>
<Tailwind>
<Body className="bg-gray-50 font-sans">
<Container className="mx-auto w-full">
<Section className="rounded-t-lg bg-indigo-600 px-6 py-8">
<Heading className="text-center text-2xl font-bold text-white">Novu Insights Report</Heading>
<Text className="text-center text-sm text-indigo-100">{props.organizationName}</Text>
</Section>

<Container className="rounded-b-lg bg-white px-6 py-6 shadow-sm">
<div className="mb-6 rounded-md border border-indigo-100/50 bg-indigo-50/50 p-3 text-center">
<Text className="text-xs font-medium text-indigo-900">
Reporting Period: {props.period.current}
<span className="mx-2">•</span>
Compared to: {props.period.previous}
</Text>
</div>

<Section className="mb-6">
<div className="rounded-lg border-2 border-indigo-100 bg-indigo-50/30 p-3">
<MetricCard
title="Total Subscriber Notifications"
current={props.subscriberNotifications.current}
previous={props.subscriberNotifications.previous}
change={props.subscriberNotifications.change}
/>
</div>
</Section>

<ChannelBreakdown channels={props.channelBreakdown} />
<InboxMetrics metrics={props.inboxMetrics} />
<WorkflowStats workflows={props.workflowStats} />

<Section className="mt-8 border-t border-gray-100 pt-6">
<Text className="text-center text-xs text-gray-400">Generated with ❤️ by Novu</Text>
</Section>
</Container>
</Container>
</Body>
</Tailwind>
</Html>
);
}
85 changes: 85 additions & 0 deletions libs/notifications/src/workflows/usage-insights/sample-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { IUsageEmailData } from './types';

export const sampleUsageData: IUsageEmailData = {
organizationName: 'dima test org 2',
period: {
current: '2024-01-01',
previous: '2023-01-01',
},
subscriberNotifications: {
current: 86,
previous: 161,
change: -46.58385093167702,
},
channelBreakdown: {
push: {
current: 4,
previous: 29,
change: -86.20689655172413,
},
trigger: {
current: 86,
previous: 161,
change: -46.58385093167702,
},
email: {
current: 86,
previous: 161,
change: -46.58385093167702,
},
},
inboxMetrics: {
sessionInitialized: {
current: 350009,
previous: 1110879,
change: -68.49260810583331,
},
updatePreferences: {
current: 0,
previous: 2,
change: -100,
},
markNotification: {
current: 74,
previous: 249,
change: -70.28112449799197,
},
updateAction: {
current: 0,
previous: 0,
change: 0,
},
},
workflowStats: {
'incorrect-password': {
current: 1,
previous: 1,
change: 0,
},
FILE_UPLOAD: {
current: 4,
previous: 29,
change: -86.20689655172413,
},
'User Welcome Email': {
current: 2,
previous: 3,
change: -33.33333333333333,
},
'Schedule Project': {
current: 68,
previous: 124,
change: -45.16129032258064,
},
'Client UserAccount verification': {
current: 1,
previous: 3,
change: -66.66666666666666,
},
'Account Verification': {
current: 10,
previous: 1,
change: 900,
},
},
};
34 changes: 34 additions & 0 deletions libs/notifications/src/workflows/usage-insights/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export interface IChannelMetrics {
current: number;
previous: number;
change: number;
}

export interface IInboxMetrics {
sessionInitialized: IChannelMetrics;
updatePreferences: IChannelMetrics;
markNotification: IChannelMetrics;
updateAction: IChannelMetrics;
}

export interface IWorkflowMetric {
current: number;
previous: number;
change: number;
}

export interface IUsageEmailData {
organizationName: string;
period: {
current: string;
previous: string;
};
subscriberNotifications: IChannelMetrics;
channelBreakdown: {
[channel: string]: IChannelMetrics;
};
inboxMetrics: IInboxMetrics;
workflowStats: {
[name: string]: IWorkflowMetric;
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { renderAsync } from '@react-email/components';
import { workflow } from '@novu/framework';
import { z } from 'zod';
import UsageInsightsEmail from './email';
import { IUsageEmailData } from './types';
import { sampleUsageData } from './sample-data';

async function renderUsageInsightsEmail(payload: IUsageEmailData, controls: any) {
const html = await renderAsync(UsageInsightsEmail(payload));

return html;
}

const channelMetricsSchema = z
.object({
current: z.number(),
previous: z.number(),
change: z.number(),
})
.required();

export const usageInsightsWorkflow = workflow(
'usage-insights',
async ({ step, payload }) => {
await step.email(
'email',
async (controls) => {
return {
subject: controls.subject,
body: await renderUsageInsightsEmail(payload as IUsageEmailData, controls),
};
},
{
controlSchema: z.object({
subject: z.string().default('Your Monthly Usage Insights'),
previewText: z.string().default('Here are your usage insights for {{payload.organizationName}}'),
}),
}
);
},
{
name: 'Usage Insights',
payloadSchema: z
.object({
organizationName: z.string().default(sampleUsageData.organizationName),
period: z
.object({
current: z.string().default(sampleUsageData.period.current),
previous: z.string().default(sampleUsageData.period.previous),
})
.required(),
subscriberNotifications: channelMetricsSchema.default(sampleUsageData.subscriberNotifications),
channelBreakdown: z
.object({
email: channelMetricsSchema.default(sampleUsageData.channelBreakdown.email),
sms: channelMetricsSchema.default(sampleUsageData.channelBreakdown.sms),
push: channelMetricsSchema.default(sampleUsageData.channelBreakdown.push),
})
.required(),
inboxMetrics: z
.object({
sessionInitialized: channelMetricsSchema.default(sampleUsageData.inboxMetrics.sessionInitialized),
updatePreferences: channelMetricsSchema.default(sampleUsageData.inboxMetrics.updatePreferences),
markNotification: channelMetricsSchema.default(sampleUsageData.inboxMetrics.markNotification),
updateAction: channelMetricsSchema.default(sampleUsageData.inboxMetrics.updateAction),
})
.required(),
workflowStats: z
.object({
'Welcome Flow': channelMetricsSchema.default(sampleUsageData.workflowStats['Welcome Flow']),
'Order Confirmation': channelMetricsSchema.default(sampleUsageData.workflowStats['Order Confirmation']),
'Password Reset': channelMetricsSchema.default(sampleUsageData.workflowStats['Password Reset']),
})
.required(),
})
.required(),
}
);
Loading