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: items
  • Loading branch information
scopsy committed Dec 22, 2024
commit 63ef9392b01b9afefa02ca7c7e8c5c65afab71d8
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
import { IsString } from 'class-validator';
import { EnvironmentCommand } from '@novu/application-generic';

export class UsageInsightsCommand extends EnvironmentCommand {
@IsString()
organizationId: string;
}
export class UsageInsightsCommand {}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
import { CommunityOrganizationRepository } from '@novu/dal';
import { InstrumentUsecase } from '@novu/application-generic';
import { InstrumentUsecase, FeatureFlagsService } from '@novu/application-generic';
import { FeatureFlagsKeysEnum } from '@novu/shared';
import axios from 'axios';
import { promises as fs } from 'fs';
import { join } from 'path';
Expand Down Expand Up @@ -106,7 +107,10 @@ export class UsageInsights {
private readonly INBOX_CACHE_FILE = join(process.cwd(), 'mixpanel-inbox-cache.json');
private readonly CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

constructor(private organizationRepository: CommunityOrganizationRepository) {
constructor(
private organizationRepository: CommunityOrganizationRepository,
private featureFlagsService: FeatureFlagsService
) {
Logger.debug('UsageInsights service initialized');
}

Expand Down Expand Up @@ -309,7 +313,10 @@ export class UsageInsights {
return orgMetrics;
}

private async logOrganizationMetrics(metrics: ICombinedMetrics, workflowStats: IMixpanelResponse['workflowStats']) {
private async sendOrganizationNotification(
metrics: ICombinedMetrics,
workflowStats: IMixpanelResponse['workflowStats']
) {
Logger.debug(`Processing metrics for organization: ${metrics.id}`);
try {
const organization = await this.organizationRepository.findById(metrics.id);
Expand All @@ -327,10 +334,22 @@ export class UsageInsights {

Logger.debug(`Enriched metrics for ${organization.name}:`, enrichedMetrics);

const isEnabled = await this.featureFlagsService.get(FeatureFlagsKeysEnum.IS_USAGE_INSIGHTS_ENABLED, false, {
environmentId: 'system',
organizationId: organization._id,
userId: 'system',
});

if (!isEnabled) {
Logger.log('Skipping notification delivery - usage insights disabled by feature flag', enrichedMetrics);

return;
}

await usageInsightsWorkflow.trigger({
to: {
subscriberId: '675fe9bcab6a05bb6dcb7dab_11',
email: 'dima@novu.co',
email: `dima+testing-${organization._id}@novu.co`,
},
payload: {
period: {
Expand Down Expand Up @@ -461,7 +480,7 @@ export class UsageInsights {
inboxStats.byOrganization[orgId] = defaultInboxMetrics;
}

await this.logOrganizationMetrics(metrics, workflowStats);
await this.sendOrganizationNotification(metrics, workflowStats);
}

Logger.debug('UsageInsights execution completed successfully');
Expand Down
27 changes: 14 additions & 13 deletions libs/notifications/src/workflows/usage-insights/email.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,20 @@ function MetricCard({
const formatNumber = (num: number) => Math.floor(num).toLocaleString('en-US', { maximumFractionDigits: 0 });

return (
<div className="h-[88px] rounded-lg border border-gray-100 bg-gray-50/50 p-2">
<div className="h-[75px] rounded-lg border border-gray-100 bg-gray-50/50 p-3">
<Row className="flex items-start justify-between gap-2">
<Column align="left" className="w-full">
<Text className="mb-0 mt-0 min-h-[28px] text-xs font-medium leading-tight text-gray-600">{title}</Text>
<Text className="mb-0 mt-0 min-h-[28px] text-xs font-medium capitalize leading-tight text-gray-600">
{title}
</Text>
</Column>
<Column align="right" className="w-full">
<Text className={`whitespace-nowrap text-xs font-medium ${changeColor} mb-0 mt-0`}>
<Text className={`whitespace-nowrap text-xs font-medium ${changeColor} mb-0 leading-[14px]`}>
{isPositive ? '↑' : '↓'} {Math.abs(Math.floor(change))}%
</Text>
</Column>
</Row>
<Row className="mt-[10px]">
<Row>
<Column align="left">
<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>
Expand All @@ -79,7 +81,7 @@ function ChannelBreakdown({ channels }: { channels: IUsageEmailData['channelBrea
<SectionHeader title="Channel Breakdown" />
<Row>
{Object.entries(channels).map(([channel, metrics]) => (
<Column key={channel} className="p-2 px-0">
<Column key={channel} className="p-2">
<MetricCard title={channel} current={metrics.current} previous={metrics.previous} change={metrics.change} />
</Column>
))}
Expand Down Expand Up @@ -134,12 +136,11 @@ function WorkflowStats({ workflows }: { workflows: IUsageEmailData['workflowStat
{topWorkflows?.map(([name, metrics], index) => {
const isPositive = metrics.change > 0;
const changeColor = isPositive ? 'text-emerald-600' : 'text-rose-600';
const isLast = index === topWorkflows.length - 1;

return (
<Row
key={index}
className={`flex items-center justify-between p-3 px-0 ${!isLast ? 'border-b border-gray-100' : ''}`}
className={`mb-2 flex items-center justify-between rounded-lg border border-gray-100 bg-gray-50/50 p-2`}
>
<Column align="left" className="w-full">
<Text className="mb-0.5 mt-0 text-sm font-medium text-gray-900">{name}</Text>
Expand Down Expand Up @@ -206,10 +207,10 @@ function MarketingSection({ config }: { config: IMarketingConfig }) {

export default function UsageInsightsEmail(props: IUsageEmailData & { marketingConfig: IMarketingConfig }) {
return (
<Html>
<Html className="bg-gray-50 font-sans">
<Head />
<Preview>
📊 Usage Insights for {props.organizationName} - {props.period.current}
📊 Usage Insights for {props.organizationName} - {formatDate(props.period.current)}
</Preview>
<Tailwind>
<Body className="bg-gray-50 font-sans">
Expand All @@ -221,13 +222,13 @@ export default function UsageInsightsEmail(props: IUsageEmailData & { marketingC
className="mx-auto my-[32px]"
/>
<Container className="mx-auto w-full max-w-[700px]">
<Section className="rounded-t-lg bg-indigo-600 px-6 py-8">
<Section className="rounded-t-lg bg-gray-900 px-6 py-8">
<Heading className="text-center text-2xl font-bold text-white">Usage Insights Report</Heading>
<Text className="text-center text-sm text-indigo-100">{props.organizationName}</Text>
</Section>

<div className="rounded-b-lg bg-white px-3 py-3 shadow-sm">
<div className="mb-6 rounded-md border border-indigo-100/50 bg-indigo-50/50 p-3 text-center">
<div className="mb-6 rounded-md border border-indigo-100/50 bg-indigo-50/50 p-2 text-center">
<Text className="text-xs font-medium text-indigo-900">
Reporting Period: {formatDate(props.period.current)}
<span className="mx-2">•</span>
Expand All @@ -236,9 +237,9 @@ export default function UsageInsightsEmail(props: IUsageEmailData & { marketingC
</div>

<Section className="mb-6">
<div className="rounded-lg border-2 border-indigo-100 bg-indigo-50/30 p-3">
<div className="rounded-lg border-2 border-indigo-100 bg-indigo-50/30">
<MetricCard
title="Total Subscriber Notifications"
title="Total Notification Triggers"
current={props.subscriberNotifications.current}
previous={props.subscriberNotifications.previous}
change={props.subscriberNotifications.change}
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/feature-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ export enum FeatureFlagsKeysEnum {
IS_NEW_DASHBOARD_ACTIVITY_FEED_ENABLED = 'IS_NEW_DASHBOARD_ACTIVITY_FEED_ENABLED',
IS_ND_INTEGRATION_STORE_ENABLED = 'IS_ND_INTEGRATION_STORE_ENABLED',
IS_ND_SMS_CHAT_PUSH_ENABLED = 'IS_ND_SMS_CHAT_PUSH_ENABLED',
IS_USAGE_INSIGHTS_ENABLED = 'IS_USAGE_INSIGHTS_ENABLED',
}
Loading