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.

partner-profile guardrails

Steven Tey867da4e2a218
diff --git a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts
deleted file mode 100644
index 06775cdcab..0000000000
--- a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { getCustomerEvents } from "@/lib/analytics/get-customer-events";
-import { DubApiError } from "@/lib/api/errors";
-import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
-import { withPartnerProfile } from "@/lib/auth/partner";
-import { customerActivityResponseSchema } from "@/lib/zod/schemas/customer-activity";
-import { prisma } from "@dub/prisma";
-import { NextResponse } from "next/server";
-
-// GET /api/partner-profile/programs/:programId/customers/:customerId/activity – Get a customer's activity by ID
-export const GET = withPartnerProfile(async ({ partner, params }) => {
- const { customerId, programId } = params;
-
- const { program, links } = await getProgramEnrollmentOrThrow({
- partnerId: partner.id,
- programId: programId,
- });
-
- const customer = await prisma.customer.findUnique({
- where: {
- id: customerId,
- },
- });
-
- if (!customer || customer?.projectId !== program.workspaceId) {
- throw new DubApiError({
- code: "not_found",
- message:
- "Customer not found. Make sure you're using the correct customer ID (e.g. `cus_3TagGjzRzmsFJdH8od2BNCsc`).",
- });
- }
-
- const events = await getCustomerEvents({
- customerId: customer.id,
- linkIds: links.map((link) => link.id),
- });
-
- // get the first partner link that this customer interacted with
- const firstLinkId = events[events.length - 1].link_id;
- const link = links.find((link) => link.id === firstLinkId);
-
- // Find the LTV of the customer
- // TODO: Calculate this from all events, not limited
- const ltv = events.reduce((acc, event) => {
- if (event.event === "sale" && event.saleAmount) {
- acc += Number(event.saleAmount);
- }
-
- return acc;
- }, 0);
-
- // Find the time to lead of the customer
- const timeToLead =
- customer.clickedAt && customer.createdAt
- ? customer.createdAt.getTime() - customer.clickedAt.getTime()
- : null;
-
- // Find the time to first sale of the customer
- // TODO: Calculate this from all events, not limited
- const firstSale = events.filter(({ event }) => event === "sale").pop();
-
- const timeToSale =
- firstSale && customer.createdAt
- ? new Date(firstSale.timestamp).getTime() - customer.createdAt.getTime()
- : null;
-
- return NextResponse.json(
- customerActivityResponseSchema.parse({
- ltv,
- timeToLead,
- timeToSale,
- events,
- link,
- }),
- );
-});
diff --git a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts
index 0419d6961a..0dfd98e3a4 100644
--- a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts
+++ b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts
@@ -1,3 +1,4 @@
+import { getCustomerEvents } from "@/lib/analytics/get-customer-events";
import { transformCustomer } from "@/lib/api/customers/transform-customer";
import { DubApiError } from "@/lib/api/errors";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
@@ -11,7 +12,7 @@ import { NextResponse } from "next/server";
export const GET = withPartnerProfile(async ({ partner, params }) => {
const { customerId, programId } = params;
- const { program } = await getProgramEnrollmentOrThrow({
+ const { program, links } = await getProgramEnrollmentOrThrow({
partnerId: partner.id,
programId: programId,
});
@@ -25,20 +26,64 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
if (!customer || customer?.projectId !== program.workspaceId) {
throw new DubApiError({
code: "not_found",
- message:
- "Customer not found. Make sure you're using the correct customer ID (e.g. `cus_3TagGjzRzmsFJdH8od2BNCsc`).",
+ message: "Customer is not part of this program.",
});
}
- customer.avatar = null;
- customer.email;
+ const events = await getCustomerEvents({
+ customerId: customer.id,
+ linkIds: links.map((link) => link.id),
+ });
+
+ if (events.length === 0) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Customer is not attributed to any links by this partner.",
+ });
+ }
+
+ // get the first partner link that this customer interacted with
+ const firstLinkId = events[events.length - 1].link_id;
+ const link = links.find((link) => link.id === firstLinkId);
+
+ // Find the LTV of the customer
+ // TODO: Calculate this from all events, not limited
+ const ltv = events.reduce((acc, event) => {
+ if (event.event === "sale" && event.saleAmount) {
+ acc += Number(event.saleAmount);
+ }
+
+ return acc;
+ }, 0);
+
+ // Find the time to lead of the customer
+ const timeToLead =
+ customer.clickedAt && customer.createdAt
+ ? customer.createdAt.getTime() - customer.clickedAt.getTime()
+ : null;
+
+ // Find the time to first sale of the customer
+ // TODO: Calculate this from all events, not limited
+ const firstSale = events.filter(({ event }) => event === "sale").pop();
+
+ const timeToSale =
+ firstSale && customer.createdAt
+ ? new Date(firstSale.timestamp).getTime() - customer.createdAt.getTime()
+ : null;
return NextResponse.json(
- PartnerProfileCustomerSchema.parse(
- transformCustomer({
+ PartnerProfileCustomerSchema.parse({
+ ...transformCustomer({
...customer,
email: customer.email || customer.name || generateRandomName(),
}),
- ),
+ activity: {
+ ltv,
+ timeToLead,
+ timeToSale,
+ events,
+ link,
+ },
+ }),
);
});
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx
index a03cea5f51..a4a3298efd 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx
@@ -3,9 +3,8 @@
import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/partners/constants";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import {
- CustomerActivityResponse,
- CustomerEnriched,
PartnerEarningsResponse,
+ PartnerProfileCustomerProps,
} from "@/lib/types";
import { CustomerActivityList } from "@/ui/customers/customer-activity-list";
import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";
@@ -25,23 +24,12 @@ export function ProgramCustomerPageClient() {
customerId: string;
}>();
- const {
- data: customer,
- isLoading,
- error,
- } = useSWR<CustomerEnriched>(
+ const { data: customer, isLoading } = useSWR<PartnerProfileCustomerProps>(
`/api/partner-profile/programs/${programSlug}/customers/${customerId}`,
fetcher,
);
- const { data: customerActivity, isLoading: isCustomerActivityLoading } =
- useSWR<CustomerActivityResponse>(
- customer &&
- `/api/partner-profile/programs/${programSlug}/customers/${customer.id}/activity`,
- fetcher,
- );
-
- if (!customer && !isLoading && !error) notFound();
+ if (!customer && !isLoading) notFound();
return (
<div className="mb-10 mt-2">
@@ -102,8 +90,8 @@ export function ProgramCustomerPageClient() {
Activity
</h2>
<CustomerActivityList
- activity={customerActivity}
- isLoading={!customer || isCustomerActivityLoading}
+ activity={customer?.activity}
+ isLoading={!customer}
/>
</section>
</div>
@@ -112,8 +100,8 @@ export function ProgramCustomerPageClient() {
<div className="-order-1 lg:order-1">
<CustomerDetailsColumn
customer={customer}
- customerActivity={customerActivity}
- isCustomerActivityLoading={!customer || isCustomerActivityLoading}
+ customerActivity={customer?.activity}
+ isCustomerActivityLoading={!customer}
/>
</div>
</div>
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 6a09e02526..2998c89997 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -2,6 +2,7 @@ import z from "@/lib/zod";
import { metaTagsSchema } from "@/lib/zod/schemas/metatags";
import {
PartnerEarningsSchema,
+ PartnerProfileCustomerSchema,
PartnerProfileLinkSchema,
} from "@/lib/zod/schemas/partner-profile";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
@@ -388,6 +389,10 @@ export type PartnerProps = z.infer<typeof PartnerSchema>;
export type ProgramPartnerLinkProps = z.infer<typeof ProgramPartnerLinkSchema>;
+export type PartnerProfileCustomerProps = z.infer<
+ typeof PartnerProfileCustomerSchema
+>;
+
export type PartnerProfileLinkProps = z.infer<typeof PartnerProfileLinkSchema>;
export type EnrolledPartnerProps = z.infer<
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index e0d2ead952..f073bc1766 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -8,6 +8,7 @@ import {
getCommissionsCountQuerySchema,
getCommissionsQuerySchema,
} from "./commissions";
+import { customerActivityResponseSchema } from "./customer-activity";
import { CustomerEnrichedSchema } from "./customers";
import { LinkSchema } from "./links";
@@ -80,10 +81,11 @@ export const PartnerProfileLinkSchema = LinkSchema.pick({
export const PartnerProfileCustomerSchema = CustomerEnrichedSchema.pick({
id: true,
- createdAt: true,
country: true,
+ createdAt: true,
}).extend({
email: z
.string()
.transform((email) => email.replace(/(?<=^.).+(?=.@)/, "****")),
+ activity: customerActivityResponseSchema,
});
diff --git a/apps/web/ui/customers/customer-details-column.tsx b/apps/web/ui/customers/customer-details-column.tsx
index 441eee885d..d44409c55f 100644
--- a/apps/web/ui/customers/customer-details-column.tsx
+++ b/apps/web/ui/customers/customer-details-column.tsx
@@ -18,7 +18,10 @@ export function CustomerDetailsColumn({
customerActivity,
isCustomerActivityLoading,
}: {
- customer?: CustomerProps;
+ customer?: Omit<CustomerProps, "name" | "externalId"> & {
+ name?: string;
+ externalId?: string;
+ };
customerActivity?: CustomerActivityResponse;
isCustomerActivityLoading: boolean;
}) {
@@ -129,7 +132,7 @@ export function CustomerDetailsColumn({
)}
</div>
- {customer && (customer?.externalId ?? null) !== null && (
+ {customer?.externalId && (
<div className="flex flex-col gap-2">
<DetailHeading>External ID</DetailHeading>
{
diff --git a/packages/tinybird/pipes/v2_customer_events.pipe b/packages/tinybird/pipes/v2_customer_events.pipe
index 4e706f5003..f23af53c4a 100644
--- a/packages/tinybird/pipes/v2_customer_events.pipe
+++ b/packages/tinybird/pipes/v2_customer_events.pipe
@@ -158,6 +158,7 @@ SQL >
SELECT *
FROM sale_events
)
- ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}
+ ORDER BY
+ timestamp DESC, CASE event WHEN 'click' THEN 1 WHEN 'lead' THEN 2 WHEN 'sale' THEN 3 END DESC