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.

improve discoverability

Steven Teyb7c680bb1e91
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx
index af7bde0167..d3aa2eec05 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx
@@ -2,11 +2,20 @@
import { updatePartnerProfileAction } from "@/lib/actions/partners/update-partner-profile";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { PartnerProps } from "@/lib/types";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { useMergePartnerAccountsModal } from "@/ui/partners/merge-accounts/merge-partner-accounts-modal";
import { ThreeDots } from "@/ui/shared/icons";
-import { Button, Popover, Switch, Tooltip, Users2, UserSearch } from "@dub/ui";
+import {
+ Button,
+ Popover,
+ Switch,
+ Tooltip,
+ useOptimisticUpdate,
+ Users2,
+ UserSearch,
+} from "@dub/ui";
import { cn } from "@dub/utils/src";
import { useAction } from "next-safe-action/hooks";
import { useMemo, useState } from "react";
@@ -19,7 +28,6 @@ import { usePartnerDiscoveryRequirements } from "./use-partner-discovery-require
export function ProfileSettingsPageClient() {
const { partner } = usePartnerProfile();
-
const tasks = usePartnerDiscoveryRequirements();
const allTasksCompleted = useMemo(
@@ -60,7 +68,14 @@ function Controls({
}: {
showDiscoverableToggle: boolean;
}) {
- const { partner, mutate } = usePartnerProfile();
+ const { data: partner, update } = useOptimisticUpdate<PartnerProps>(
+ "/api/partner-profile",
+ {
+ loading: "Updating profile...",
+ success: "Profile updated",
+ error: "Failed to update profile",
+ },
+ );
const [isOpen, setIsOpen] = useState(false);
@@ -73,6 +88,23 @@ function Controls({
},
});
+ const handleDiscoverableUpdate = async ({
+ checked,
+ currentPartner,
+ }: {
+ checked: boolean;
+ currentPartner: PartnerProps;
+ }) => {
+ await executeAsync({
+ discoverable: checked,
+ });
+
+ return {
+ ...currentPartner,
+ discoverableAt: checked ? new Date() : null,
+ };
+ };
+
return (
<>
{showDiscoverableToggle && partner && (
@@ -99,29 +131,21 @@ function Controls({
<span className="text-sm font-medium">Discoverable</span>
<Switch
checked={!!partner.discoverableAt}
- fn={(checked) =>
- mutate(
- async () => {
- const result = await executeAsync({
- discoverable: checked,
- });
+ fn={(checked: boolean) => {
+ if (!partner) return;
- if (result?.serverError || result?.validationErrors)
- throw new Error("Failed to update profile");
-
- return {
- ...partner,
- discoverableAt: checked ? new Date() : null,
- };
- },
- {
- optimisticData: () => ({
- ...partner,
- discoverableAt: checked ? new Date() : null,
+ update(
+ () =>
+ handleDiscoverableUpdate({
+ checked,
+ currentPartner: partner,
}),
+ {
+ ...partner,
+ discoverableAt: checked ? new Date() : null,
},
- )
- }
+ );
+ }}
trackDimensions="radix-state-checked:bg-neutral-600 focus-visible:ring-black/20"
/>
</label>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx
index 24fa170ea6..0b8b37412f 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx
@@ -1,6 +1,4 @@
-import { PARTNER_DISCOVERY_MIN_COMMISSIONS } from "@/lib/partners/discoverability";
-import { ONLINE_PRESENCE_FIELDS } from "@/lib/partners/online-presence";
-import { PartnerProps, ProgramEnrollmentProps } from "@/lib/types";
+import { PartnerProps } from "@/lib/types";
import {
Button,
ChevronUp,
@@ -135,48 +133,3 @@ function ConditionalLink({
<div className={className}>{children}</div>
);
}
-
-export function getDiscoveryGuideTasks({
- partner,
- programEnrollments,
-}: {
- partner: PartnerProps;
- programEnrollments: ProgramEnrollmentProps[];
-}) {
- return [
- {
- label: "Add basic profile info",
- completed: true,
- },
- {
- label: "Verify your website or social account",
- href: "#sites",
- completed: ONLINE_PRESENCE_FIELDS.some(
- (field) => field.data(partner).verified,
- ),
- },
- {
- label: "Write your bio",
- href: "#about",
- completed: !!partner.description,
- },
- {
- label: "Select your industry interests",
- href: "#interests",
- completed: Boolean(partner.industryInterests?.length),
- },
- {
- label: "Choose your sales channels",
- href: "#channels",
- completed: Boolean(partner.salesChannels?.length),
- },
- {
- label: "Earn $100 in commissions",
- completed:
- programEnrollments.reduce(
- (acc, programEnrollment) => acc + programEnrollment.totalCommissions,
- 0,
- ) >= PARTNER_DISCOVERY_MIN_COMMISSIONS,
- },
- ];
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
index 9723bd16d7..28d8e9a81c 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
@@ -333,9 +333,7 @@ function PartnerCard({
id: "joinedAt",
icon: <UserPlus className="size-3.5 shrink-0" />,
text: partner
- ? partner.discoverableAt
- ? `Joined ${formatDate(partner.discoverableAt, { month: "short" })}`
- : null
+ ? `Joined ${formatDate(partner.createdAt, { month: "short" })}`
: undefined,
},
{
diff --git a/apps/web/lib/actions/partners/onboard-partner.ts b/apps/web/lib/actions/partners/onboard-partner.ts
index e1c3ee44a0..5d18c6498b 100644
--- a/apps/web/lib/actions/partners/onboard-partner.ts
+++ b/apps/web/lib/actions/partners/onboard-partner.ts
@@ -49,7 +49,6 @@ export const onboardPartnerAction = authUserActionClient
}),
...(description && { description }),
image: imageUrl,
- discoverableAt: new Date(),
users: {
connectOrCreate: {
where: {
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index d83f6edd5c..83b05e5351 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -77,10 +77,6 @@ export const updatePartnerProfileAction = authPartnerActionClient
let needsEmailVerification = false;
const emailChanged = newEmail !== undefined && partner.email !== newEmail;
- const discoverableChanged =
- discoverable !== undefined &&
- discoverable !== Boolean(partner.discoverableAt);
-
// Upload the new image
if (image) {
const path = `partners/${partner.id}/image_${nanoid(7)}`;
@@ -89,7 +85,7 @@ export const updatePartnerProfileAction = authPartnerActionClient
}
try {
- let updatedPartner = await prisma.partner.update({
+ const updatedPartner = await prisma.partner.update({
where: {
id: partner.id,
},
@@ -101,6 +97,11 @@ export const updatePartnerProfileAction = authPartnerActionClient
profileType,
companyName,
monthlyTraffic,
+ discoverableAt: discoverable
+ ? new Date()
+ : discoverable === false
+ ? null
+ : undefined,
...(industryInterests && {
industryInterests: {
@@ -129,28 +130,13 @@ export const updatePartnerProfileAction = authPartnerActionClient
},
}),
},
+ include: {
+ industryInterests: true,
+ salesChannels: true,
+ programs: true,
+ },
});
- // Update `discoverable` separately so we can check eligibility post-update
- if (discoverableChanged) {
- if (
- discoverable &&
- !(await isPartnerProfileEligibleForDiscovery({
- partnerId: partner.id,
- }))
- )
- throw new Error("Profile is not eligible for discovery");
-
- updatedPartner = await prisma.partner.update({
- where: {
- id: partner.id,
- },
- data: {
- discoverableAt: discoverable ? new Date() : null,
- },
- });
- }
-
// If the email is being changed, we need to verify the new email address
if (emailChanged) {
const partnerWithEmail = await prisma.partner.findUnique({
@@ -179,6 +165,49 @@ export const updatePartnerProfileAction = authPartnerActionClient
waitUntil(
Promise.allSettled([
(async () => {
+ // double check that the partner is still eligible for discovery
+ if (updatedPartner.discoverableAt) {
+ const partnerDiscoveryRequirements =
+ getPartnerDiscoveryRequirements({
+ partner: {
+ ...updatedPartner,
+ industryInterests: updatedPartner.industryInterests?.map(
+ (interest) => interest.industryInterest,
+ ),
+ salesChannels: updatedPartner.salesChannels?.map(
+ (channel) => channel.salesChannel,
+ ),
+ },
+ totalCommissions: updatedPartner.programs
+ .filter((program) => program.programId !== ACME_PROGRAM_ID)
+ .reduce(
+ (acc, program) => acc + program.totalCommissions,
+ 0,
+ ),
+ });
+
+ if (
+ !partnerDiscoveryRequirements.every(
+ (requirement) => requirement.completed,
+ )
+ ) {
+ console.log(
+ `Partner ${partner.id} is no longer eligible for discovery due to missing requirements: ${partnerDiscoveryRequirements
+ .filter((requirement) => !requirement.completed)
+ .map((requirement) => requirement.label)
+ .join(", ")}`,
+ );
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ discoverableAt: null,
+ },
+ });
+ }
+ }
+
const shouldExpireCache = !deepEqual(
{
name: partner.name,
@@ -194,33 +223,13 @@ export const updatePartnerProfileAction = authPartnerActionClient
return;
}
- qstash.publishJSON({
+ await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-partners`,
body: {
partnerId: partner.id,
},
});
})(),
-
- // Reset discoverable status if no longer eligible
- (async () => {
- if (
- !discoverableChanged &&
- updatedPartner.discoverableAt &&
- !(await isPartnerProfileEligibleForDiscovery({
- partnerId: partner.id,
- }))
- ) {
- await prisma.partner.update({
- where: {
- id: partner.id,
- },
- data: {
- discoverableAt: null,
- },
- });
- }
- })(),
]),
);
@@ -294,37 +303,3 @@ const deleteStripeAccountIfRequired = async ({
}
}
};
-
-async function isPartnerProfileEligibleForDiscovery({
- partnerId,
-}: {
- partnerId: string;
-}) {
- const partner = await prisma.partner.findUniqueOrThrow({
- where: {
- id: partnerId,
- },
- include: {
- industryInterests: true,
- salesChannels: true,
- programs: true,
- },
- });
-
- const requirements = getPartnerDiscoveryRequirements({
- partner: {
- ...partner,
- industryInterests: partner.industryInterests?.map(
- ({ industryInterest }) => industryInterest,
- ),
- salesChannels: partner.salesChannels?.map(
- ({ salesChannel }) => salesChannel,
- ),
- },
- totalCommissions: partner.programs
- .filter((program) => program.programId !== ACME_PROGRAM_ID)
- .reduce((acc, program) => acc + program.totalCommissions, 0),
- });
-
- return requirements.every(({ completed }) => completed);
-}
diff --git a/apps/web/lib/middleware/utils/get-default-partner.ts b/apps/web/lib/middleware/utils/get-default-partner.ts
index b47478125f..24b7dbedb3 100644
--- a/apps/web/lib/middleware/utils/get-default-partner.ts
+++ b/apps/web/lib/middleware/utils/get-default-partner.ts
@@ -1,6 +1,5 @@
import { UserProps } from "@/lib/types";
import { prismaEdge } from "@dub/prisma/edge";
-import { waitUntil } from "@vercel/functions";
export async function getDefaultPartnerId(user: UserProps) {
let defaultPartnerId = user?.defaultPartnerId;
@@ -61,16 +60,6 @@ export async function getDefaultPartnerId(user: UserProps) {
},
});
defaultPartnerId = partner.id;
- waitUntil(
- prismaEdge.partner.update({
- where: {
- id: partner.id,
- },
- data: {
- discoverableAt: new Date(),
- },
- }),
- );
}
}
}
diff --git a/apps/web/lib/partners/discoverability.ts b/apps/web/lib/partners/discoverability.ts
index 45bfcbc02a..96ba7f8a15 100644
--- a/apps/web/lib/partners/discoverability.ts
+++ b/apps/web/lib/partners/discoverability.ts
@@ -25,14 +25,14 @@ export function getPartnerDiscoveryRequirements({
completed: true,
},
{
- label: "Verify your website or social account",
+ label: "Connect your website or social account",
href: "#sites",
completed: ONLINE_PRESENCE_FIELDS.some(
- (field) => field.data(partner).verified,
+ (field) => field.data(partner).value, // TODO: update this to also check for "verified" in the future
),
},
{
- label: "Write your bio",
+ label: "Update your profile description",
href: "#about",
completed: !!partner.description,
},
diff --git a/apps/web/lib/zod/schemas/partner-network.ts b/apps/web/lib/zod/schemas/partner-network.ts
index baf45d10d4..6296e2feb8 100644
--- a/apps/web/lib/zod/schemas/partner-network.ts
+++ b/apps/web/lib/zod/schemas/partner-network.ts
@@ -91,7 +91,7 @@ export const NetworkPartnerSchema = PartnerSchema.pick({
profileType: true,
image: true,
description: true,
- discoverableAt: true,
+ createdAt: true,
monthlyTraffic: true,
industryInterests: true,
diff --git a/apps/web/scripts/migrations/backfill-discoverableat.ts b/apps/web/scripts/migrations/backfill-discoverableat.ts
index 80c7719c5d..51c5a29c88 100644
--- a/apps/web/scripts/migrations/backfill-discoverableat.ts
+++ b/apps/web/scripts/migrations/backfill-discoverableat.ts
@@ -1,16 +1,80 @@
import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { ACME_PROGRAM_ID } from "@dub/utils";
import "dotenv-flow/config";
async function main() {
- const partners = await prisma.partner.findMany({
- where: {
- discoverableAt: null,
- users: {
- some: {},
+ const where: Prisma.PartnerWhereInput = {
+ discoverableAt: null,
+ users: {
+ some: {},
+ },
+ industryInterests: {
+ some: {},
+ },
+ salesChannels: {
+ some: {},
+ },
+ programs: {
+ some: {
+ programId: {
+ not: ACME_PROGRAM_ID,
+ },
+ totalCommissions: {
+ gt: 0,
+ },
},
},
- take: 2000,
+ OR: [
+ {
+ website: {
+ not: null,
+ },
+ },
+ {
+ youtube: {
+ not: null,
+ },
+ },
+ {
+ twitter: {
+ not: null,
+ },
+ },
+ {
+ linkedin: {
+ not: null,
+ },
+ },
+ {
+ instagram: {
+ not: null,
+ },
+ },
+ {
+ tiktok: {
+ not: null,
+ },
+ },
+ ],
+ };
+ const partners = await prisma.partner.findMany({
+ where,
+ });
+ console.table(partners, [
+ "name",
+ "email",
+ "website",
+ "youtube",
+ "twitter",
+ "linkedin",
+ "instagram",
+ "tiktok",
+ ]);
+ const count = await prisma.partner.count({
+ where,
});
+ console.log(`Found ${count} partners to backfill`);
const res = await prisma.partner.updateMany({
where: {
diff --git a/apps/web/ui/partners/partner-info-cards.tsx b/apps/web/ui/partners/partner-info-cards.tsx
index 52b8ef4fe2..9f9fc25fec 100644
--- a/apps/web/ui/partners/partner-info-cards.tsx
+++ b/apps/web/ui/partners/partner-info-cards.tsx
@@ -144,7 +144,7 @@ export function PartnerInfoCards({
id: "joinedAt",
icon: <CalendarIcon className="size-3.5" />,
text: partner
- ? `Joined ${formatDate(partner.discoverableAt!)}`
+ ? `Joined ${formatDate(partner.createdAt!)}`
: undefined,
},
]