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.

Merge branch 'main' into partner-link-titles

Pedro Ladeira737dc016014f
diff --cc apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/route.ts
index c6837de199,66dde4fd6c..5d9fd25e5a
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/route.ts
@@@ -3,15 -3,15 +3,15 @@@ import { createLink, processLink } fro
import { validatePartnerLinkUrl } from "@/lib/api/links/validate-partner-link-url";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
- import { extractUtmParams } from "@/lib/api/utm/extract-utm-params";
+ import { applyGroupUtmToLink } from "@/lib/api/utm/apply-group-utm-to-link";
import { withPartnerProfile } from "@/lib/auth/partner";
import { prisma } from "@/lib/prisma";
+ import { getResolvedPartnerLinkRewards } from "@/lib/rewards/get-resolved-partner-link-rewards";
-import { PartnerProfileLinkSchema } from "@/lib/zod/schemas/partner-profile";
import {
- createPartnerLinkSchema,
- INACTIVE_ENROLLMENT_STATUSES,
-} from "@/lib/zod/schemas/partners";
+ createPartnerProfileLinkSchema,
+ PartnerProfileLinkSchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
- import { getUTMParamsFromURL } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
diff --cc apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx
index 27897eb6bc,c755d704c3..63c05ca03f
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page.tsx
@@@ -6,9 -6,11 +6,12 @@@ import
} from "@/lib/constants/partner-profile";
import usePartnerCustomers from "@/lib/swr/use-partner-customers";
import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
+import { usePartnerLinksDisplay } from "@/lib/swr/use-partner-links-display";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { CustomerRowItem } from "@/ui/customers/customer-row-item";
+ import { PartnerCustomersMenuPopover } from "@/ui/customers/partner-customers-menu-popover";
+ import { PageContent } from "@/ui/layout/page-content";
+ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { CountryFlag } from "@/ui/shared/country-flag";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
diff --cc apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-card.tsx
index 7ac2abac69,717e5c6f0f..7f458fca85
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-card.tsx
@@@ -70,7 -76,15 +77,16 @@@ const CHARTS =
export function PartnerLinkCard({ link }: { link: PartnerProfileLinkProps }) {
const { programEnrollment } = useProgramEnrollment();
const { displayOption } = usePartnerLinksContext();
+ const { displayProperties } = useContext(PartnerLinksDisplayContext);
+ const { showRewards, toggleRewards } = usePartnerLinkRewardsState();
+ const {
+ rewards,
+ discount,
+ primaryReward,
+ primaryText,
+ additionalCount,
+ hasIncentives,
+ } = usePartnerLinkRewards(link);
const partnerLink = constructPartnerLink({
group: programEnrollment?.group,
@@@ -78,12 -92,12 +94,47 @@@
});
const isDeactivated = programEnrollment?.status === "deactivated";
+ const isQueryLinkStructure =
+ programEnrollment?.group?.linkStructure === "query";
+ const showTitle =
+ displayProperties.includes("title") && Boolean(link.partnerLinkTitle);
+
++ const shortLink = (
++ <Tooltip
++ content={
++ <QueryLinkStructureHelpText
++ link={link}
++ className="px-3 py-2 first-letter:uppercase"
++ />
++ }
++ disabled={!isQueryLinkStructure || isDeactivated}
++ >
++ <a
++ href={isDeactivated ? undefined : partnerLink}
++ target="_blank"
++ rel="noopener noreferrer"
++ className={cn(
++ "truncate text-sm transition-colors",
++ showTitle
++ ? "text-neutral-500 hover:text-neutral-700 hover:underline hover:underline-offset-2"
++ : "font-semibold leading-6",
++ isDeactivated
++ ? "cursor-default text-neutral-400"
++ : !showTitle && "text-neutral-900 hover:text-black",
++ isQueryLinkStructure &&
++ !isDeactivated &&
++ "cursor-copy underline decoration-dotted underline-offset-2",
++ )}
++ onClick={isDeactivated ? (e) => e.preventDefault() : undefined}
++ >
++ {getPrettyUrl(partnerLink)}
++ </a>
++ </Tooltip>
++ );
+
const discountCodeSection = link.discountCode ? (
- <div className="hidden items-center gap-1.5 rounded-xl border border-neutral-200 py-1 pl-2 pr-1 sm:flex">
- <span className="text-sm leading-none text-neutral-500">
+ <div className="hidden h-8 items-center gap-1.5 rounded-lg border border-neutral-200 pl-2 pr-1.5 sm:flex">
+ <span className="text-xs font-medium leading-none tracking-tight text-neutral-500">
Discount code
</span>
<DiscountCodeBadge
@@@ -114,86 -129,70 +166,65 @@@
</div>
<div className="flex min-w-0 flex-col">
- <div className="flex flex-col">
+ <div className="flex flex-col gap-0.5">
<div className="flex items-center gap-1">
- <Tooltip
- content={
- <QueryLinkStructureHelpText
- link={link}
- className="px-3 py-2 first-letter:uppercase"
- />
- }
- disabled={!isQueryLinkStructure || isDeactivated}
- >
- <a
- href={isDeactivated ? undefined : partnerLink}
- target="_blank"
- rel="noopener noreferrer"
+ {showTitle ? (
+ <span
className={cn(
- "truncate text-sm font-semibold leading-6 transition-colors",
- isDeactivated
- ? "cursor-default text-neutral-400"
- : "text-neutral-900 hover:text-black",
- isQueryLinkStructure &&
- !isDeactivated &&
- "cursor-copy underline decoration-dotted underline-offset-2",
+ "truncate text-sm font-semibold leading-6",
- isDeactivated ? "text-neutral-400" : "text-neutral-700",
++ isDeactivated ? "text-neutral-400" : "text-neutral-900",
)}
- onClick={
- isDeactivated ? (e) => e.preventDefault() : undefined
- }
+ title={link.partnerLinkTitle ?? undefined}
>
- {getPrettyUrl(partnerLink)}
- </a>
- </Tooltip>
+ {link.partnerLinkTitle}
+ </span>
+ ) : (
- <a
- href={isDeactivated ? undefined : partnerLink}
- target="_blank"
- rel="noopener noreferrer"
- className={cn(
- "truncate text-sm font-semibold leading-6 transition-colors",
- isDeactivated
- ? "cursor-default text-neutral-400"
- : "text-neutral-700 hover:text-black",
- )}
- onClick={
- isDeactivated ? (e) => e.preventDefault() : undefined
- }
- >
- {getPrettyUrl(partnerLink)}
- </a>
++ shortLink
+ )}
{!isDeactivated && (
<CopyButton value={partnerLink} variant="neutral" />
)}
- {link.comments && <CommentsBadge comments={link.comments} />}
+ {link.partnerLinkComments && (
+ <CommentsBadge comments={link.partnerLinkComments} />
+ )}
</div>
- {/* The max width implementation here is a bit hacky, we should improve in the future */}
- <div className="flex max-w-[100px] items-center gap-1 py-0 pl-1 pr-1.5 sm:w-fit sm:max-w-[400px]">
- <ArrowTurnRight2 className="h-3 w-3 shrink-0 text-neutral-400" />
- {showTitle ? (
- <a
- href={isDeactivated ? undefined : partnerLink}
- target="_blank"
- rel="noopener noreferrer"
- className={cn(
- "truncate text-sm transition-colors",
- isDeactivated
- ? "cursor-default text-neutral-400"
- : "text-neutral-500 hover:text-neutral-700 hover:underline hover:underline-offset-2",
- )}
- title={getPrettyUrl(partnerLink)}
- onClick={
- isDeactivated ? (e) => e.preventDefault() : undefined
- }
- >
- {getPrettyUrl(partnerLink)}
- </a>
- ) : programEnrollment?.group?.linkStructure === "query" ? (
- <QueryLinkStructureHelpText
- link={link}
- className="mt-0.5"
- />
- ) : (
- <a
- href={isDeactivated ? undefined : link.url}
- target="_blank"
- rel="noopener noreferrer"
- className="cursor-alias truncate text-sm text-neutral-500 decoration-dotted transition-colors hover:text-neutral-700 hover:underline hover:underline-offset-2"
- title={getPrettyUrl(link.url)}
- onClick={
- isDeactivated ? (e) => e.preventDefault() : undefined
- }
- >
- {getPrettyUrl(link.url)}
- </a>
- )}
- </div>
++ {showTitle && (
++ <div className="flex max-w-[100px] items-center gap-1 py-0 pl-1 pr-1.5 sm:w-fit sm:max-w-[400px]">
++ <ArrowTurnRight2 className="h-3 w-3 shrink-0 text-neutral-400" />
++ {shortLink}
++ </div>
++ )}
++
+ {hasIncentives && primaryText ? (
+ <PartnerLinkRewardsSummary
+ primaryText={primaryText}
+ primaryReward={primaryReward}
+ additionalCount={additionalCount}
+ showRewards={showRewards}
+ onToggleRewards={toggleRewards}
+ />
+ ) : (
- /* The max width implementation here is a bit hacky, we should improve in the future */
- <div className="flex max-w-[100px] items-center gap-1 py-0 pl-1 pr-1.5 sm:w-fit sm:max-w-[400px]">
- <ArrowTurnRight2 className="h-3 w-3 shrink-0 text-neutral-400" />
- <a
- href={isDeactivated ? undefined : link.url}
- target="_blank"
- rel="noopener noreferrer"
- className="cursor-alias truncate text-sm text-neutral-500 decoration-dotted transition-colors hover:text-neutral-700 hover:underline hover:underline-offset-2"
- title={getPrettyUrl(link.url)}
- onClick={
- isDeactivated ? (e) => e.preventDefault() : undefined
- }
- >
- {getPrettyUrl(link.url)}
- </a>
- </div>
++ !showTitle && (
++ /* The max width implementation here is a bit hacky, we should improve in the future */
++ <div className="flex max-w-[100px] items-center gap-1 py-0 pl-1 pr-1.5 sm:w-fit sm:max-w-[400px]">
++ <ArrowTurnRight2 className="h-3 w-3 shrink-0 text-neutral-400" />
++ <a
++ href={isDeactivated ? undefined : link.url}
++ target="_blank"
++ rel="noopener noreferrer"
++ className="cursor-alias truncate text-sm text-neutral-500 decoration-dotted transition-colors hover:text-neutral-700 hover:underline hover:underline-offset-2"
++ title={getPrettyUrl(link.url)}
++ onClick={
++ isDeactivated ? (e) => e.preventDefault() : undefined
++ }
++ >
++ {getPrettyUrl(link.url)}
++ </a>
++ </div>
++ )
+ )}
</div>
</div>
</div>
diff --cc apps/web/lib/api/partner-profile/get-partner-earnings-count.ts
index 0000000000,6b47c6f24f..f4fd70f253
mode 000000,100644..100644
--- a/apps/web/lib/api/partner-profile/get-partner-earnings-count.ts
+++ b/apps/web/lib/api/partner-profile/get-partner-earnings-count.ts
@@@ -1,0 -1,184 +1,186 @@@
+ import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+ import { generateRandomName } from "@/lib/names";
+ import { prisma } from "@/lib/prisma";
+ import { getPartnerEarningsCountQuerySchema } from "@/lib/zod/schemas/partner-profile";
+ import { Prisma } from "@prisma/client";
+ import * as z from "zod/v4";
+ import { getEarningsProgramFilter } from "./get-earnings-program-id";
+ import { obfuscateCustomerEmail } from "./obfuscate-customer-email";
+
+ export async function getPartnerEarningsCount({
+ partnerId,
+ programId,
+ filters,
+ }: {
+ partnerId: string;
+ programId?: string; // if not provided, earnings across all programs (except the network program) are counted
+ filters: z.infer<typeof getPartnerEarningsCountQuerySchema>;
+ }) {
+ const {
+ groupBy,
+ type,
+ status,
+ linkId,
+ customerId,
+ payoutId,
+ interval,
+ start,
+ end,
+ timezone,
+ } = filters;
+
+ const { startDate, endDate } = getStartEndDates({
+ interval,
+ start,
+ end,
+ timezone,
+ });
+
+ const where: Prisma.CommissionWhereInput = {
+ earnings: {
+ not: 0,
+ },
+ programId: getEarningsProgramFilter(programId),
+ partnerId,
+ ...(payoutId && { payoutId }),
+ createdAt: {
+ gte: startDate,
+ lte: endDate,
+ },
+ };
+
+ if (!groupBy) {
+ const count = await prisma.commission.count({
+ where: {
+ ...where,
+ ...(type && { type }),
+ ...(status && { status }),
+ ...(linkId && { linkId }),
+ ...(customerId && { customerId }),
+ },
+ });
+
+ return { count };
+ }
+
+ const groupedWhere: Prisma.CommissionWhereInput = {
+ ...where,
+ ...(type && groupBy !== "type" && { type }),
+ ...(status && groupBy !== "status" && { status }),
+ ...(linkId && groupBy !== "linkId" && { linkId }),
+ ...(customerId && groupBy !== "customerId" && { customerId }),
+ };
+
+ if (groupBy === "customerId") {
+ // grouped by program too, since customer data sharing is set per program enrollment
+ const counts = await prisma.commission.groupBy({
+ by: ["customerId", "programId"],
+ where: groupedWhere,
+ _count: true,
+ orderBy: {
+ _count: {
+ customerId: "desc",
+ },
+ },
+ });
+
+ const [customers, programEnrollments] = await Promise.all([
+ prisma.customer.findMany({
+ where: {
+ id: {
+ in: counts
+ .map(({ customerId }) => customerId)
+ .filter((id): id is string => id !== null),
+ },
+ },
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ },
+ }),
+ prisma.programEnrollment.findMany({
+ where: {
+ partnerId,
+ programId: {
+ in: [...new Set(counts.map(({ programId }) => programId))],
+ },
+ },
+ select: {
+ programId: true,
+ customerDataSharingEnabledAt: true,
+ },
+ }),
+ ]);
+
+ const customersById = new Map(customers.map((c) => [c.id, c]));
+ const dataSharingByProgramId = new Map(
+ programEnrollments.map((p) => [
+ p.programId,
+ p.customerDataSharingEnabledAt,
+ ]),
+ );
+
+ return counts.map(({ customerId, programId, _count }) => {
+ const customer = customerId ? customersById.get(customerId) : undefined;
+ const customerDataSharingEnabledAt =
+ dataSharingByProgramId.get(programId);
+
+ return {
+ id: customerId,
+ email: customer?.email
+ ? customerDataSharingEnabledAt
+ ? customer.email
+ : obfuscateCustomerEmail(customer.email)
+ : customer?.name || generateRandomName(),
+ _count,
+ };
+ });
+ }
+
+ const counts = await prisma.commission.groupBy({
+ by: [groupBy],
+ where: groupedWhere,
+ _count: true,
+ orderBy: {
+ _count: {
+ [groupBy]: "desc",
+ },
+ },
+ });
+
+ if (groupBy === "linkId") {
+ const links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: counts
+ .map(({ linkId }) => linkId)
+ .filter((id): id is string => id !== null),
+ },
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
++ partnerLinkTitle: true,
+ },
+ });
+
+ const linksById = new Map(links.map((l) => [l.id, l]));
+
+ return counts.map(({ linkId, _count }) => {
+ const link = linkId ? linksById.get(linkId) : undefined;
+ return {
+ id: linkId,
+ domain: link?.domain,
+ key: link?.key,
+ url: link?.url,
++ partnerLinkTitle: link?.partnerLinkTitle,
+ _count,
+ };
+ });
+ }
+
+ return counts;
+ }
diff --cc apps/web/lib/zod/schemas/partner-profile.ts
index b17c155d94,5cac1bf92e..5a3cb0e44f
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@@ -26,8 -27,10 +27,10 @@@ import { DiscountSchema } from "./disco
import { LinkSchema } from "./links";
import { getPaginationQuerySchema } from "./misc";
import { payoutsQuerySchema } from "./payouts";
+ import { ProgramSchema } from "./programs";
+ import { RewardSchema } from "./rewards";
import { submittedLeadFormDataSchema } from "./submitted-lead-form";
-import { centsSchema } from "./utils";
+import { centsSchema, parseUrlSchema } from "./utils";
export const PartnerEarningsSchema = CommissionSchema.omit({
userId: true,
@@@ -87,32 -90,92 +94,118 @@@ export const getPartnerEarningsTimeseri
timezone: z.string().optional(),
});
+export const createPartnerProfileLinkSchema = z.object({
+ url: parseUrlSchema
+ .nullish()
+ .describe(
+ "The URL to shorten (if not provided, the program's default URL will be used).",
+ ),
+ key: z
+ .string()
+ .max(190)
+ .optional()
+ .describe(
+ "The short link slug. If not provided, a random 7-character slug will be generated.",
+ ),
+ partnerLinkTitle: z
+ .string()
+ .nullish()
+ .describe("The partner's private display title for the short link."),
+ partnerLinkComments: z
+ .string()
+ .nullish()
+ .describe("The partner's private comments for the short link."),
+});
+
+export const updatePartnerProfileLinkSchema =
+ createPartnerProfileLinkSchema.partial();
+
+ const programIdOrSlugSchema = z
+ .string()
+ .optional()
+ .describe(
+ "The ID or slug of the program to filter earnings by. If not provided, earnings across all programs are returned.",
+ );
+
+ const PartnerProfileEarningsProgramSchema = ProgramSchema.pick({
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ });
+
+ export const PartnerProfileEarningsSchema = PartnerEarningsSchema.extend({
+ program: PartnerProfileEarningsProgramSchema,
+ });
+
+ export const partnerProfileEarningsQuerySchema =
+ getPartnerEarningsQuerySchema.extend({
+ programIdOrSlug: programIdOrSlugSchema,
+ });
+
+ export const partnerProfileEarningsCountQuerySchema =
+ getPartnerEarningsCountQuerySchema.extend({
+ programIdOrSlug: programIdOrSlugSchema,
+ });
+
+ export const partnerProfileEarningsTimeseriesQuerySchema =
+ getPartnerEarningsTimeseriesSchema.extend({
+ programIdOrSlug: programIdOrSlugSchema,
+ groupBy: z
+ .enum(["type", "linkId", "programId"])
+ .optional()
+ .describe(
+ "The field to group the earnings by. If omitted, each period is the total earnings. Otherwise each period includes a `data` object with the earnings of each group.",
+ ),
+ });
+
+ export const partnerProfileEarningsAnalyticsQuerySchema =
+ partnerProfileEarningsCountQuerySchema
+ .pick({
+ programIdOrSlug: true,
+ type: true,
+ status: true,
+ interval: true,
+ start: true,
+ end: true,
+ timezone: true,
+ })
+ .extend({
+ groupBy: z
+ .enum(["programId", "linkId", "type"])
+ .describe(
+ "The field to sum earnings by. Returns the highest-earning programs, links, or commission types.",
+ ),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(100)
+ .default(10)
+ .describe("The number of groups to return, sorted by earnings."),
+ });
+
+ export const PartnerProfileTopProgramEarningsSchema =
+ PartnerProfileEarningsProgramSchema.extend({
+ earnings: z.number(),
+ });
+
+ export const PartnerProfileTopLinkEarningsSchema = LinkSchema.pick({
+ id: true,
+ domain: true,
+ key: true,
+ shortLink: true,
+ url: true,
+ }).extend({
+ program: PartnerProfileEarningsProgramSchema,
+ earnings: z.number(),
+ });
+
+ export const PartnerProfileTypeEarningsSchema = z.object({
+ type: z.enum(CommissionType),
+ earnings: z.number(),
+ });
+
export const PartnerProfileLinkSchema = LinkSchema.pick({
id: true,
domain: true,
@@@ -123,11 -186,14 +216,15 @@@
leads: true,
sales: true,
saleAmount: true,
- comments: true,
}).extend({
+ partnerLinkTitle: z.string().nullish().default(null),
+ partnerLinkComments: z.string().nullish().default(null),
createdAt: z.string().or(z.date()),
partnerGroupDefaultLinkId: z.string().nullish(),
+ clickReward: RewardSchema.nullable().default(null),
+ leadReward: RewardSchema.nullable().default(null),
+ saleReward: RewardSchema.nullable().default(null),
+ discount: DiscountSchema.nullable().default(null),
discountCode: z.string().nullable().default(null),
discountCodeDisabledAt: z.coerce.date().nullable().default(null),
});