Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

wip metrics

Kiran K4ea7e8c35c26
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-metrics.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-metrics.tsx
new file mode 100644
index 0000000000..6a1bfa4f69
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-metrics.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { CircleCheck, CircleWarning, EnvelopeArrowRight } from "@dub/ui";
+
+interface CampaignMetricsProps {
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+export function CampaignMetrics({ isOpen, onClose }: CampaignMetricsProps) {
+ // Placeholder data - will be replaced with real data later
+ const metrics = [
+ {
+ icon: CircleCheck,
+ label: "Delivered",
+ percentage: "95.91%",
+ count: "8,700",
+ },
+ {
+ icon: CircleWarning,
+ label: "Bounced",
+ percentage: "4.09%",
+ count: "370",
+ },
+ {
+ icon: EnvelopeArrowRight,
+ label: "Opened",
+ percentage: "35.64%",
+ count: "3,200",
+ },
+ ];
+
+ return (
+ <div>
+ <div className="border-border-subtle flex h-12 items-center justify-between border-b px-6 sm:h-16">
+ <h2 className="text-lg font-semibold text-gray-900">Metrics</h2>
+ </div>
+
+ <div className="bg-neutral-50 p-6">
+ <div className="flex flex-col gap-6 divide-y divide-neutral-200 rounded-lg border border-neutral-200">
+ {metrics.map((metric) => (
+ <div key={metric.label} className="flex w-full flex-col">
+ <div className="flex items-center gap-1.5 p-3">
+ <metric.icon className="size-3.5 text-gray-500" />
+ <div className="text-xs font-medium text-gray-500">
+ {metric.label}
+ </div>
+ </div>
+
+ <div className="flex justify-between">
+ <span>{metric.percentage}</span>
+ <span>{metric.count}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+{
+ /* <div className="text-2xl font-normal text-gray-600">
+{metric.count}
+</div> */
+}
+
+{
+ /* <div className="flex">
+<div className="text-sm text-gray-500">{metric.label}</div>
+<div className="text-2xl font-semibold text-gray-900">
+ {metric.percentage}
+</div>
+</div> */
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/page-client.tsx
index 41de90e9e8..b735237d1a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/page-client.tsx
@@ -7,6 +7,7 @@ import { useState } from "react";
import useCampaign from "../use-campaign";
import { CampaignEditor } from "./campaign-editor";
import { CampaignEditorSkeleton } from "./campaign-editor-skeleton";
+import { CampaignMetrics } from "./campaign-metrics";
export function ProgramCampaignPageClient() {
const { campaign, error, loading } = useCampaign();
@@ -38,7 +39,7 @@ export function ProgramCampaignPageClient() {
/>
</div>
- {/* Right panel - Empty for now */}
+ {/* Right panel - Metrics */}
<div
className={cn(
"absolute right-0 top-0 h-full min-h-0 w-0 overflow-hidden bg-white shadow-lg transition-[width]",
@@ -47,7 +48,10 @@ export function ProgramCampaignPageClient() {
)}
>
<div className="border-border-subtle flex size-full min-h-0 w-full flex-col border-l sm:w-[360px]">
- {/* Content will go here */}
+ <CampaignMetrics
+ isOpen={isRightPanelOpen}
+ onClose={() => setIsRightPanelOpen(false)}
+ />
</div>
</div>
</div>
diff --git a/apps/web/lib/api/campaigns/get-campaign-events.ts b/apps/web/lib/api/campaigns/get-campaign-events.ts
index 6d8c7378e4..6d38e2820c 100644
--- a/apps/web/lib/api/campaigns/get-campaign-events.ts
+++ b/apps/web/lib/api/campaigns/get-campaign-events.ts
@@ -9,7 +9,7 @@ interface GetCampaignEventsParams
campaignId: string;
}
-const schema = z.object({
+const campaignEventSchema = z.object({
partner: EnrolledPartnerSchema.pick({
id: true,
name: true,
@@ -20,7 +20,10 @@ const schema = z.object({
name: true,
color: true,
}),
- date: z.date(),
+ createdAt: z.date(),
+ openedAt: z.date().nullable(),
+ bouncedAt: z.date().nullable(),
+ deliveredAt: z.date().nullable(),
});
export const getCampaignEvents = async (params: GetCampaignEventsParams) => {
@@ -32,24 +35,44 @@ export const getCampaignEvents = async (params: GetCampaignEventsParams) => {
...(status === "opened" && { openedAt: { not: null } }),
...(status === "bounced" && { bouncedAt: { not: null } }),
},
- include: {
+ select: {
+ createdAt: true,
+ openedAt: true,
+ bouncedAt: true,
+ deliveredAt: true,
partner: {
- include: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
programs: {
- include: {
- partnerGroup: true
- }
- }
- }
- }
+ select: {
+ partnerGroup: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ },
},
skip: (page - 1) * pageSize,
take: pageSize,
});
- console.log(results)
-
- return results;
+ const events = results.map((result) => {
+ return {
+ partner: result.partner,
+ group: result.partner?.programs[0]?.partnerGroup,
+ createdAt: result.createdAt,
+ openedAt: result.openedAt,
+ bouncedAt: result.bouncedAt,
+ deliveredAt: result.deliveredAt,
+ };
+ });
- // return schema.parse(results);
+ return z.array(campaignEventSchema).parse(events);
};
diff --git a/apps/web/lib/api/campaigns/get-campaign-summary.ts b/apps/web/lib/api/campaigns/get-campaign-summary.ts
index 0777e164a1..ca3d3b792a 100644
--- a/apps/web/lib/api/campaigns/get-campaign-summary.ts
+++ b/apps/web/lib/api/campaigns/get-campaign-summary.ts
@@ -1,7 +1,7 @@
import { prisma } from "@dub/prisma";
import { z } from "zod";
-const schema = z.object({
+const campaignSummarySchema = z.object({
sent: z.coerce.number(),
delivered: z.coerce.number(),
opened: z.coerce.number(),
@@ -9,7 +9,9 @@ const schema = z.object({
});
export const getCampaignSummary = async (campaignId: string) => {
- const [queryResult] = await prisma.$queryRaw<z.infer<typeof schema>[]>`
+ const [queryResult] = await prisma.$queryRaw<
+ z.infer<typeof campaignSummarySchema>[]
+ >`
SELECT
COUNT(*) AS sent,
SUM(CASE WHEN deliveredAt IS NOT NULL THEN 1 ELSE 0 END) AS delivered,
@@ -19,5 +21,5 @@ export const getCampaignSummary = async (campaignId: string) => {
WHERE campaignId = ${campaignId}
`;
- return schema.parse(queryResult);
+ return campaignSummarySchema.parse(queryResult);
};
diff --git a/apps/web/scripts/seed-notification-email.ts b/apps/web/scripts/seed-notification-email.ts
new file mode 100644
index 0000000000..4f89fa9899
--- /dev/null
+++ b/apps/web/scripts/seed-notification-email.ts
@@ -0,0 +1,176 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import { NotificationEmailType } from "@dub/prisma/client";
+import "dotenv-flow/config";
+
+// Configuration
+const CAMPAIGN_ID = "cmp_1K6N08X99G94EQVC7884V0AAS"; // Replace with actual campaign ID
+const TOTAL_EMAILS = 100;
+
+// Email status distribution
+const STATUS_DISTRIBUTION = {
+ delivered: 60, // 60% delivered
+ opened: 25, // 25% opened (also delivered)
+ bounced: 10, // 10% bounced
+ pending: 5, // 5% pending (not delivered yet)
+};
+
+async function main() {
+ console.log(`Creating ${TOTAL_EMAILS} notification emails for campaign ${CAMPAIGN_ID}...`);
+
+ // Verify campaign exists
+ const campaign = await prisma.campaign.findUnique({
+ where: { id: CAMPAIGN_ID },
+ select: { id: true, name: true, programId: true }
+ });
+
+ if (!campaign) {
+ console.error(`Campaign with ID ${CAMPAIGN_ID} not found. Please provide a valid campaign ID.`);
+ process.exit(1);
+ }
+
+ console.log(`Found campaign: ${campaign.name} (${campaign.id})`);
+
+ // Generate notification emails with different statuses
+ const notificationEmails = generateNotificationEmails(campaign.id, campaign.programId);
+
+ // Create emails in batches
+ const batchSize = 20;
+ let created = 0;
+
+ for (let i = 0; i < notificationEmails.length; i += batchSize) {
+ const batch = notificationEmails.slice(i, i + batchSize);
+
+ await prisma.notificationEmail.createMany({
+ data: batch,
+ skipDuplicates: true,
+ });
+
+ created += batch.length;
+ console.log(`Created ${created}/${TOTAL_EMAILS} notification emails...`);
+ }
+
+ console.log(`✅ Successfully created ${created} notification emails for campaign ${CAMPAIGN_ID}`);
+
+ // Print summary
+ const summary = await getEmailStatusSummary(CAMPAIGN_ID);
+ console.log("\n📊 Email Status Summary:");
+ Object.entries(summary).forEach(([status, count]) => {
+ console.log(` ${status}: ${count}`);
+ });
+}
+
+function generateNotificationEmails(campaignId: string, programId: string) {
+ const emails: any[] = [];
+ let emailCount = 0;
+
+ // Generate emails based on status distribution
+ Object.entries(STATUS_DISTRIBUTION).forEach(([status, count]) => {
+ const statusCount = Math.floor((count / 100) * TOTAL_EMAILS);
+
+ for (let i = 0; i < statusCount && emailCount < TOTAL_EMAILS; i++) {
+ const email = createNotificationEmail(campaignId, programId, status as EmailStatus);
+ emails.push(email);
+ emailCount++;
+ }
+ });
+
+ // Fill remaining slots if needed
+ while (emailCount < TOTAL_EMAILS) {
+ const status = getRandomStatus();
+ const email = createNotificationEmail(campaignId, programId, status);
+ emails.push(email);
+ emailCount++;
+ }
+
+ return emails;
+}
+
+function createNotificationEmail(campaignId: string, programId: string, status: EmailStatus) {
+ const now = new Date();
+ const emailId = createId({ prefix: "em_" });
+
+ const baseEmail = {
+ id: createId({ prefix: "em_" }),
+ emailId,
+ type: NotificationEmailType.Campaign,
+ campaignId,
+ programId,
+ recipientUserId: createId({ prefix: "user_" }),
+ createdAt: new Date(now.getTime() - Math.random() * 7 * 24 * 60 * 60 * 1000), // Random date in last 7 days
+ };
+
+ switch (status) {
+ case "pending":
+ return baseEmail;
+
+ case "delivered":
+ return {
+ ...baseEmail,
+ deliveredAt: new Date(baseEmail.createdAt.getTime() + Math.random() * 60 * 60 * 1000), // Delivered within 1 hour
+ };
+
+ case "opened":
+ const deliveredAt = new Date(baseEmail.createdAt.getTime() + Math.random() * 60 * 60 * 1000);
+ return {
+ ...baseEmail,
+ deliveredAt,
+ openedAt: new Date(deliveredAt.getTime() + Math.random() * 24 * 60 * 60 * 1000), // Opened within 24 hours of delivery
+ };
+
+ case "bounced":
+ return {
+ ...baseEmail,
+ bouncedAt: new Date(baseEmail.createdAt.getTime() + Math.random() * 2 * 60 * 60 * 1000), // Bounced within 2 hours
+ };
+
+ default:
+ return baseEmail;
+ }
+}
+
+async function getEmailStatusSummary(campaignId: string) {
+ const emails = await prisma.notificationEmail.findMany({
+ where: { campaignId },
+ select: {
+ deliveredAt: true,
+ openedAt: true,
+ bouncedAt: true,
+ },
+ });
+
+ const summary = {
+ pending: 0,
+ delivered: 0,
+ opened: 0,
+ bounced: 0,
+ };
+
+ emails.forEach(email => {
+ if (email.bouncedAt) {
+ summary.bounced++;
+ } else if (email.openedAt) {
+ summary.opened++;
+ } else if (email.deliveredAt) {
+ summary.delivered++;
+ } else {
+ summary.pending++;
+ }
+ });
+
+ return summary;
+}
+
+function getRandomStatus(): EmailStatus {
+ const statuses: EmailStatus[] = ["pending", "delivered", "opened", "bounced"];
+ return statuses[Math.floor(Math.random() * statuses.length)];
+}
+
+type EmailStatus = "pending" | "delivered" | "opened" | "bounced";
+
+// Run the script
+main()
+ .catch((error) => {
+ console.error("❌ Error seeding notification emails:", error);
+ process.exit(1);
+ });