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.

fix backfill script, improve UI

Steven Tey306afff0407f
diff --git a/apps/web/app/api/customers/[id]/activity/route.ts b/apps/web/app/api/customers/[id]/activity/route.ts
index af85a907e9..6d9abe0d95 100644
--- a/apps/web/app/api/customers/[id]/activity/route.ts
+++ b/apps/web/app/api/customers/[id]/activity/route.ts
@@ -4,6 +4,7 @@ import { withWorkspace } from "@/lib/auth";
import { CustomerActivity, SaleEvent } from "@/lib/types";
import { customerActivityResponseSchema } from "@/lib/zod/schemas/customers";
import { prisma } from "@dub/prisma";
+import { currencyFormatter, getPrettyUrl } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/customers/[id]/activity - get a customer's activity
@@ -43,10 +44,13 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
return {
timestamp: new Date(event.timestamp),
event: "sale",
- event_name: event.eventName,
+ eventName: event.eventName,
+ eventDetails: currencyFormatter(event.sale.amount / 100, {
+ maximumFractionDigits: 2,
+ }),
metadata: {
amount: event.sale.amount,
- payment_processor: event.sale.paymentProcessor,
+ paymentProcessor: event.sale.paymentProcessor,
},
};
});
@@ -55,7 +59,7 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
activity.push({
timestamp: customer.createdAt,
event: "lead",
- event_name: "Account created",
+ eventName: "Account created",
metadata: null,
});
@@ -63,7 +67,8 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
activity.push({
timestamp: customer.clickedAt!,
event: "click",
- event_name: "Link click",
+ eventName: "Link click",
+ eventDetails: link?.shortLink ? getPrettyUrl(link.shortLink) : null,
metadata: null,
});
@@ -90,6 +95,15 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
? new Date(firstSale.timestamp).getTime() - customer.createdAt.getTime()
: null;
+ console.log({
+ ltv,
+ timeToLead,
+ timeToSale,
+ customer,
+ activity,
+ link,
+ });
+
return NextResponse.json(
customerActivityResponseSchema.parse({
ltv,
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 58b6a6e6c2..2918d8fa03 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -98,11 +98,12 @@ export const customerEventsSchemaTB = z.object({
export const customerActivitySchema = z.object({
timestamp: z.date(),
event: z.enum(["click", "lead", "sale"]),
- event_name: z.string(),
+ eventName: z.string(),
+ eventDetails: z.string().nullish(),
metadata: z.union([
z.null(),
z.object({
- payment_processor: z.string(),
+ paymentProcessor: z.string(),
amount: z.number(),
}),
]),
diff --git a/apps/web/scripts/backfill-customers.ts b/apps/web/scripts/backfill-customers.ts
index 1f6ab64e1a..e0df1b9d2d 100644
--- a/apps/web/scripts/backfill-customers.ts
+++ b/apps/web/scripts/backfill-customers.ts
@@ -1,18 +1,38 @@
-import { getClickEvent, getLeadEvent } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
+import { tb } from "../lib/tinybird/client";
+import z from "../lib/zod";
-// Backfill new customer columns such as linkId, clickId, country
+export const getLeadEvents = tb.buildPipe({
+ pipe: "get_lead_events",
+ parameters: z.object({
+ customerIds: z.array(z.string()),
+ }),
+ data: z.any(),
+});
+
+export const getClickEvents = tb.buildPipe({
+ pipe: "get_click_events",
+ parameters: z.object({
+ clickIds: z.array(z.string()),
+ }),
+ data: z.any(),
+});
+// Backfill new customer columns such as linkId, clickId, country
async function main() {
const customers = await prisma.customer.findMany({
where: {
linkId: null,
+ projectId: "cl7pj5kq4006835rbjlt2ofka",
},
select: {
id: true,
},
- take: 10,
+ take: 2,
+ orderBy: {
+ createdAt: "desc",
+ },
});
if (customers.length === 0) {
@@ -21,24 +41,24 @@ async function main() {
}
// Find leads
- const leadResponse = await Promise.all(
- customers.map((customer) => getLeadEvent({ customerId: customer.id })),
- );
+ const customerIds = customers.map((customer) => customer.id);
- const leadEvents = leadResponse.map((event) =>
- event.data.length > 0 ? event.data[0] : undefined,
+ const leadEvents = await getLeadEvents({ customerIds }).then(
+ (res) => res.data,
);
// Find clicks
// We're fetching clicks, because leads doesn't have information about when click happened
- const clickResponse = await Promise.all(
- leadEvents.map((event) => getClickEvent({ clickId: event?.click_id! })),
- );
+ const clickIds = leadEvents
+ .map((event) => event.click_id)
+ .filter(Boolean) as string[];
- const clickEvents = clickResponse.map((event) =>
- event.data.length > 0 ? event.data[0] : undefined,
+ const clickEvents = await getClickEvents({ clickIds }).then(
+ (res) => res.data,
);
+ console.log({ leadEvents, clickEvents });
+
// Update customers
const result = await Promise.all(
customers.map(async (customer) => {
diff --git a/apps/web/ui/partners/customer-details-sheet.tsx b/apps/web/ui/partners/customer-details-sheet.tsx
index f4dae68e6d..f53c49bf40 100644
--- a/apps/web/ui/partners/customer-details-sheet.tsx
+++ b/apps/web/ui/partners/customer-details-sheet.tsx
@@ -6,18 +6,20 @@ import {
} from "@/lib/types";
import { X } from "@/ui/shared/icons";
import {
- ArrowRight,
Button,
CopyButton,
- CursorRays,
- FilterBars,
- Link4,
- MoneyBill2,
Sheet,
TabSelect,
Tooltip,
useRouterStuff,
} from "@dub/ui";
+import {
+ ArrowRight,
+ CursorRays,
+ Link4,
+ MoneyBill2,
+ UserCheck,
+} from "@dub/ui/icons";
import {
cn,
COUNTRIES,
@@ -25,9 +27,8 @@ import {
DICEBEAR_AVATAR_URL,
fetcher,
getPrettyUrl,
- timeAgo,
} from "@dub/utils";
-import { UserPlus2 } from "lucide-react";
+import { formatDistanceStrict } from "date-fns";
import Link from "next/link";
import { Dispatch, SetStateAction, useState } from "react";
import useSWR from "swr";
@@ -83,15 +84,14 @@ function CustomerDetailsSheetContent({
<div className="flex min-w-[40%] shrink grow basis-1/2 flex-col items-end justify-end gap-2">
{link ? (
<Link
- href={`/${slug}/events?domain=${link.domain}&key=${link.key}`}
+ href={`/${slug}/events?domain=${link.domain}&key=${link.key}&interval=all`}
target="_blank"
- className="group flex min-w-0 items-center gap-1 overflow-hidden rounded-full border border-neutral-200 bg-white px-1.5 py-0.5 text-xs text-neutral-700 group-hover:translate-x-0 group-hover:opacity-100"
+ className="flex min-w-0 items-center gap-1 overflow-hidden rounded-full border border-neutral-200 bg-white px-1.5 py-0.5 text-xs text-neutral-700 group-hover:translate-x-0 group-hover:opacity-100"
>
<Link4 className="size-3.5" />
<span className="truncate">
{getPrettyUrl(link.shortLink)}
</span>
- <FilterBars className="hidden size-3 transition-transform group-hover:block" />
</Link>
) : (
<div className="h-5 w-20 animate-pulse rounded-full bg-neutral-200" />
@@ -101,7 +101,7 @@ function CustomerDetailsSheetContent({
<Link
href={`/${slug}/events?country=${country}`}
target="_blank"
- className="group flex min-w-20 items-center gap-2 rounded-full border border-neutral-200 bg-white px-1.5 py-0.5 text-xs text-neutral-700 group-hover:translate-x-0 group-hover:opacity-100"
+ className="flex min-w-20 items-center gap-2 rounded-full border border-neutral-200 bg-white px-1.5 py-0.5 text-xs text-neutral-700 group-hover:translate-x-0 group-hover:opacity-100"
>
<img
alt=""
@@ -109,7 +109,6 @@ function CustomerDetailsSheetContent({
className="h-3 w-4 rounded-sm"
/>
<span className="truncate">{COUNTRIES[country]}</span>
- <FilterBars className="hidden size-3 transition-transform group-hover:block" />
</Link>
)}
</div>
@@ -149,23 +148,19 @@ function CustomerDetailsSheetContent({
{[
{
label: "Lead",
- value: customerActivity?.timeToLead
- ? timeAgo(
- new Date(Date.now() - customerActivity.timeToLead),
- )
+ value: customerActivity?.timeToLead // in milliseconds
+ ? formatDistanceStrict(0, customerActivity.timeToLead)
: "-",
description:
- "The time it took for this customer to convert into a lead.",
+ "The time it took for this customer to convert from last click to a signup.",
},
{
label: "Sale",
value: customerActivity?.timeToSale
- ? timeAgo(
- new Date(Date.now() - customerActivity.timeToSale),
- )
+ ? formatDistanceStrict(0, customerActivity.timeToSale)
: "-",
description:
- "The time it took for this customer to convert from a lead to a purchase.",
+ "The time it took for this customer to convert from signup to a purchase.",
className: "pl-6",
},
].map(({ label, value, description, className }, index) => (
@@ -226,7 +221,7 @@ function CustomerDetailsSheetContent({
</div>
<TabSelect
- className="mt-6"
+ className="mt-2"
options={[{ id: "activity", label: "Activity" }]}
selected={"activity"}
/>
@@ -258,7 +253,7 @@ function CustomerDetailsSheetContent({
const activityIcons = {
click: CursorRays,
- lead: UserPlus2,
+ lead: UserCheck,
sale: MoneyBill2,
};
@@ -293,16 +288,11 @@ function Activity({
)}
</div>
<span className="flex-grow text-sm text-neutral-700">
- {activity.event_name}
+ {activity.eventName}
- {activity.metadata?.amount && (
+ {activity.eventDetails && (
<span className="ml-1 font-medium text-neutral-700">
- (
- {currencyFormatter(activity.metadata.amount / 100, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })}
- )
+ ({activity.eventDetails})
</span>
)}
</span>