The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
display the customer activity
Kiran Kaa4cc0d8112f
diff --git a/apps/web/app/api/customers/[id]/activities/route.ts b/apps/web/app/api/customers/[id]/activities/route.tsindex 95cd0c7375..4df4f3374b 100644--- a/apps/web/app/api/customers/[id]/activities/route.ts+++ b/apps/web/app/api/customers/[id]/activities/route.ts@@ -1,25 +1,14 @@import { getEvents } from "@/lib/analytics/get-events";import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";import { withWorkspace } from "@/lib/auth";-import {- customerActivitySchema,- CustomerSchema,-} from "@/lib/zod/schemas/customers";+import { CustomerActivity } from "@/lib/types";+import { customerActivityResponseSchema } from "@/lib/zod/schemas/customers";import { saleEventResponseSchema } from "@/lib/zod/schemas/sales";import { NextResponse } from "next/server";import { z } from "zod";-type CustomerActivity = z.infer<typeof customerActivitySchema>;type SaleEvent = z.infer<typeof saleEventResponseSchema>;-const responseSchema = z.object({- ltv: z.number(),- timeToLead: z.number(),- timeToSale: z.number(),- customer: CustomerSchema,- activities: z.array(customerActivitySchema),-});-// GET /api/customers/[id]/activities - get a customer's activityexport const GET = withWorkspace(async ({ workspace, params }) => {const { id: customerId } = params;@@ -43,7 +32,7 @@ export const GET = withWorkspace(async ({ workspace, params }) => {return {timestamp: new Date(event.timestamp),event: "sale",- event_name: event.eventName,+ event_name: "payment made", // event.eventNamemetadata: {amount: event.sale.amount,payment_processor: event.sale.paymentProcessor,@@ -92,7 +81,7 @@ export const GET = withWorkspace(async ({ workspace, params }) => {: 0;return NextResponse.json(- responseSchema.parse({+ customerActivityResponseSchema.parse({ltv,timeToLead,timeToSale,diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.tsindex 3d8c5a936a..e4f22cf445 100644--- a/apps/web/lib/analytics/get-events.ts+++ b/apps/web/lib/analytics/get-events.ts@@ -188,6 +188,8 @@ const getCustomersMap = async (customerIds: string[]) => {return customers.reduce((acc, customer) => {+ // TODO:+ // Can we do CustomerSchema.parse(customer) instead?acc[customer.id] = CustomerSchema.parse({id: customer.id,externalId: customer.externalId,@@ -196,6 +198,7 @@ const getCustomersMap = async (customerIds: string[]) => {avatar:customer.avatar ||`https://api.dicebear.com/9.x/notionists/png?seed=${customer.id}`,+ country: customer.country || "",createdAt: customer.createdAt,});return acc;diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex f513bf0edb..b0cce9c520 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -12,6 +12,8 @@ import {} from "@dub/prisma/client";import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";import {+ customerActivityResponseSchema,+ customerActivitySchema,CustomerSchema,trackCustomerResponseSchema,} from "./zod/schemas/customers";@@ -349,3 +351,9 @@ export type PayoutProps = z.infer<typeof PayoutSchema>;export type PayoutResponse = z.infer<typeof PayoutResponseSchema>;export type PartnerPayoutResponse = z.infer<typeof PartnerPayoutResponseSchema>;++export type CustomerActivity = z.infer<typeof customerActivitySchema>;++export type CustomerActivityResponse = z.infer<+ typeof customerActivityResponseSchema+>;diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex f18973ce34..90cc44adfe 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -26,20 +26,26 @@ export const createCustomerBodySchema = z.object({export const updateCustomerBodySchema = createCustomerBodySchema.partial();// customer object schema-export const CustomerSchema = z.object({- id: z.string().describe("The unique identifier of the customer in Dub."),- externalId: z- .string()- .describe("Unique identifier for the customer in the client's app."),- name: z.string().describe("Name of the customer."),- email: z.string().nullish().describe("Email of the customer."),- avatar: z.string().nullish().describe("Avatar URL of the customer."),- country: z- .string()- .nullish()- .describe("The 2-letter ISO 3166-1 country code of the customer."),- createdAt: z.date().describe("The date the customer was created."),-});+export const CustomerSchema = z+ .object({+ id: z.string().describe("The unique identifier of the customer in Dub."),+ externalId: z+ .string()+ .describe("Unique identifier for the customer in the client's app."),+ name: z.string().describe("Name of the customer."),+ email: z.string().nullish().describe("Email of the customer."),+ avatar: z.string().nullish().describe("Avatar URL of the customer."),+ country: z+ .string()+ .nullish()+ .describe("The 2-letter ISO 3166-1 country code of the customer."),+ createdAt: z.date().describe("The date the customer was created."),+ })+ .superRefine((data) => {+ if (!data.avatar) {+ data.avatar = `https://api.dicebear.com/9.x/notionists/png?seed=${data.id}`;+ }+ });export const trackCustomerRequestSchema = z.object({// Required@@ -110,3 +116,11 @@ export const customerActivitySchema = z.object({}),]),});++export const customerActivityResponseSchema = z.object({+ ltv: z.number(),+ timeToLead: z.number(),+ timeToSale: z.number(),+ customer: CustomerSchema,+ activities: z.array(customerActivitySchema),+});diff --git a/apps/web/ui/analytics/events/row-menu-button.tsx b/apps/web/ui/analytics/events/row-menu-button.tsxindex 7c3a77352d..952ed404e2 100644--- a/apps/web/ui/analytics/events/row-menu-button.tsx+++ b/apps/web/ui/analytics/events/row-menu-button.tsx@@ -1,3 +1,4 @@+import { useCustomerDetailsSheet } from "@/ui/partners/customer-details-sheet";import { Button, Icon, Popover, useCopyToClipboard } from "@dub/ui";import { Copy, Dots } from "@dub/ui/icons";import { cn } from "@dub/utils";@@ -11,60 +12,70 @@ export function RowMenuButton({ row }: { row: Row<EventDatum> }) {const [isOpen, setIsOpen] = useState(false);const [, copyToClipboard] = useCopyToClipboard();+ const { customerDetailsSheet, setIsOpen: setShowCustomerDetailsSheet } =+ useCustomerDetailsSheet({+ // @ts-expect-error+ customer: row.original.customer,+ });+return (- <Popover- openPopover={isOpen}- setOpenPopover={setIsOpen}- content={- <Command tabIndex={0} loop className="focus:outline-none">- <Command.List className="flex w-screen flex-col gap-1 p-1 text-sm sm:w-auto sm:min-w-[130px]">- {"eventId" in row.original && (+ <>+ {customerDetailsSheet}+ <Popover+ openPopover={isOpen}+ setOpenPopover={setIsOpen}+ content={+ <Command tabIndex={0} loop className="focus:outline-none">+ <Command.List className="flex w-screen flex-col gap-1 p-1 text-sm sm:w-auto sm:min-w-[130px]">+ {"eventId" in row.original && (+ <MenuItem+ icon={Copy}+ label="Copy event ID"+ onSelect={() => {+ if (!("eventId" in row.original)) return;+ const eventId = row.original.eventId as string;+ toast.promise(copyToClipboard(eventId), {+ success: "Copied to clipboard",+ });+ setIsOpen(false);+ }}+ />+ )}<MenuItemicon={Copy}- label="Copy event ID"+ label="Copy click ID"onSelect={() => {- if (!("eventId" in row.original)) return;- const eventId = row.original.eventId as string;- toast.promise(copyToClipboard(eventId), {+ const clickId = row.original.click_id as string;+ toast.promise(copyToClipboard(clickId), {success: "Copied to clipboard",});setIsOpen(false);}}/>- )}- <MenuItem- icon={Copy}- label="Copy click ID"- onSelect={() => {- const clickId = row.original.click_id as string;- toast.promise(copyToClipboard(clickId), {- success: "Copied to clipboard",- });- setIsOpen(false);- }}- />- {"customer" in row.original && (- <MenuItem- icon={Copy}- label="View customer"- onSelect={() => {- setIsOpen(false);- }}- />- )}- </Command.List>- </Command>- }- align="end"- >- <Button- type="button"- className="h-8 whitespace-nowrap px-2"- variant="outline"- icon={<Dots className="h-4 w-4 shrink-0" />}- />- </Popover>+ {"customer" in row.original && (+ <MenuItem+ icon={Copy}+ label="View activities"+ onSelect={() => {+ setShowCustomerDetailsSheet(true);+ setIsOpen(false);+ }}+ />+ )}+ </Command.List>+ </Command>+ }+ align="end"+ >+ <Button+ type="button"+ className="h-8 whitespace-nowrap px-2"+ variant="outline"+ icon={<Dots className="h-4 w-4 shrink-0" />}+ />+ </Popover>+ </>);}diff --git a/apps/web/ui/partners/customer-details-sheet.tsx b/apps/web/ui/partners/customer-details-sheet.tsxindex 415a003512..1d455011cb 100644--- a/apps/web/ui/partners/customer-details-sheet.tsx+++ b/apps/web/ui/partners/customer-details-sheet.tsx@@ -1,8 +1,35 @@import useWorkspace from "@/lib/swr/use-workspace";-import { Customer } from "@/lib/types";+import {+ Customer,+ CustomerActivity,+ CustomerActivityResponse,+} from "@/lib/types";import { X } from "@/ui/shared/icons";-import { Button, Sheet, useRouterStuff } from "@dub/ui";-import { Dispatch, SetStateAction } from "react";+import {+ Button,+ CursorRays,+ InvoiceDollar,+ LinesY,+ Sheet,+ useRouterStuff,+} from "@dub/ui";+import {+ COUNTRIES,+ currencyFormatter,+ DICEBEAR_AVATAR_URL,+ fetcher,+ getPrettyUrl,+} from "@dub/utils";+import { UserCheck } from "lucide-react";+import { Dispatch, SetStateAction, useState } from "react";+import useSWR from "swr";++// Fake link for now+const link = {+ domain: "dub.co",+ key: "123456",+ shortLink: "https://dub.co/123456",+};interface CustomerDetailsSheetProps {customer: Customer;@@ -13,7 +40,15 @@ function CustomerDetailsSheetContent({customer,setIsOpen,}: CustomerDetailsSheetProps) {- const { slug } = useWorkspace();+ const { id: workspaceId, slug } = useWorkspace();++ const { data: customerActivity, isLoading } =+ useSWR<CustomerActivityResponse>(+ `/api/customers/${customer.id}/activities?workspaceId=${workspaceId}`,+ fetcher,+ );++ console.log("activities", customerActivity);return (<>@@ -32,62 +67,71 @@ function CustomerDetailsSheetContent({</div><div className="p-6"><div className="flex items-start justify-between gap-6">- {/* <div className="flex flex-col">+ <div className="flex flex-col"><img- src={partner.image || `${DICEBEAR_AVATAR_URL}${partner.name}`}- alt={partner.name}+ src={+ customer.avatar || `${DICEBEAR_AVATAR_URL}${customer.name}`+ }+ alt={customer.name}className="size-12 rounded-full"/>- <div className="mt-4 flex items-start gap-2">+ <div className="mt-4 flex flex-col gap-1.5"><span className="text-lg font-semibold leading-tight text-neutral-900">- {partner.name}+ {customer.name}+ </span>+ <span className="text-sm text-neutral-500">+ {customer.email}</span>- {badge && (- <StatusBadge icon={null} variant={badge.variant}>- {badge.label}- </StatusBadge>+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <div className="flex min-w-[40%] shrink grow basis-1/2 flex-wrap items-center justify-end gap-2">+ {link && (+ <a+ href={`/${slug}/analytics?domain=${link.domain}&key=${link.key}`}+ target="_blank"+ className="group flex min-w-0 items-center gap-1.5 overflow-hidden rounded-full bg-neutral-100 px-2.5 py-1 text-xs text-neutral-700 transition-colors duration-100 hover:bg-neutral-200/70 active:bg-neutral-200"+ >+ <LinesY className="size-3.5" />+ <span className="truncate">+ {getPrettyUrl(link.shortLink)}+ </span>+ </a>)}</div>- </div> */}-- {/* <div className="flex min-w-[40%] shrink grow basis-1/2 flex-wrap items-center justify-end gap-2">- {partner.link && (- <a- href={`/${slug}/analytics?domain=${partner.link.domain}&key=${partner.link.key}`}- target="_blank"- className="group flex min-w-0 items-center gap-1.5 overflow-hidden rounded-full bg-neutral-100 px-2.5 py-1 text-xs text-neutral-700 transition-colors duration-100 hover:bg-neutral-200/70 active:bg-neutral-200"- >- <LinesY className="size-3.5" />- <span className="truncate">- {getPrettyUrl(partner.link.shortLink)}- </span>- </a>- )}- {partner.country && (- <div className="flex min-w-20 items-center gap-2 rounded-full bg-neutral-100 px-2.5 py-1 text-xs text-neutral-700">- <img- alt=""- src={`https://flag.vercel.app/m/${partner.country}.svg`}- className="h-3 w-4"- />- <span className="truncate">{COUNTRIES[partner.country]}</span>- </div>- )}- </div> */}+ <div>+ {customer.country && (+ <div className="flex min-w-20 items-center gap-2 rounded-full bg-neutral-100 px-2.5 py-1 text-xs text-neutral-700">+ <img+ alt=""+ src={`https://flag.vercel.app/m/${customer.country}.svg`}+ className="h-3 w-4"+ />+ <span className="truncate">+ {COUNTRIES[customer.country]}+ </span>+ </div>+ )}+ </div>+ </div></div>- <div className="mt-6 flex divide-x divide-neutral-200"></div>+ <div className="mt-6">+ {/* <div className="absolute ml-2 flex h-full flex-grow flex-col border-l border-neutral-200" /> */}+ <div className="flex flex-col gap-4">+ {customerActivity?.activities.map((activity, index) => (+ <Activity activity={activity} key={index} />+ ))}+ </div>+ </div></div></div>-- <div className="flex grow flex-col justify-end">- <div className="border-t border-neutral-200 p-5"></div>- </div></>);}-export function CustomerDetailsSheet({+function CustomerDetailsSheet({isOpen,...rest}: CustomerDetailsSheetProps & {@@ -99,9 +143,71 @@ export function CustomerDetailsSheet({<Sheetopen={isOpen}onOpenChange={rest.setIsOpen}- onClose={() => queryParams({ del: "partnerId", scroll: false })}+ onClose={() => queryParams({ del: "customerId", scroll: false })}><CustomerDetailsSheetContent {...rest} /></Sheet>);}+export function useCustomerDetailsSheet({+ customer,+}: Omit<CustomerDetailsSheetProps, "setIsOpen">) {+ const [isOpen, setIsOpen] = useState(false);++ return {+ customerDetailsSheet: (+ <CustomerDetailsSheet+ customer={customer}+ setIsOpen={setIsOpen}+ isOpen={isOpen}+ />+ ),+ setIsOpen,+ };+}++const activityIcons = {+ click: CursorRays,+ lead: UserCheck,+ sale: InvoiceDollar,+};++function Activity({ activity }: { activity: CustomerActivity }) {+ const timestamp = new Date(activity.timestamp);++ const month = timestamp.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ });++ const time = timestamp.toLocaleTimeString("en-US", {+ hour: "numeric",+ minute: "numeric",+ hour12: true,+ });++ const Icon = activityIcons[activity.event as keyof typeof activityIcons];++ return (+ <div className="flex items-center">+ <div className="mr-3 flex-shrink-0">+ <Icon className="size-4" />+ </div>+ <span className="flex-grow text-neutral-700">+ <span className="font-medium">+ {activity.metadata?.amount+ ? `${currencyFormatter(activity.metadata.amount / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })} `+ : null}+ </span>++ {activity.event_name}+ </span>+ <div className="text-sm text-neutral-500">+ {month} at {time}+ </div>+ </div>+ );+}