The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Backfill partner platforms from applications before sending webhooks
Kiran K344c074afe9f
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.tsindex 8adb746bd6..eaef44e56e 100644--- a/apps/web/lib/actions/partners/create-program-application.ts+++ b/apps/web/lib/actions/partners/create-program-application.ts@@ -13,13 +13,13 @@ import { autoApprovePartnerJob } from "@/lib/jobs/handlers/auto-approve-partner-import { autoRejectPartnerJob } from "@/lib/jobs/handlers/auto-reject-partner-job";import { programApplicationReminderJob } from "@/lib/jobs/handlers/program-application-reminder-job";import { getNetworkProfileChecklistProgress } from "@/lib/network/get-network-profile-checklist-progress";+import { backfillPartnerPlatforms } from "@/lib/partners/backfill-partner-platforms";import { evaluateApplicationRequirements } from "@/lib/partners/evaluate-application-requirements";import {formatApplicationFormData,formatWebsiteAndSocialsFields,} from "@/lib/partners/format-application-form-data";import { prisma } from "@/lib/prisma";-import { polyfillSocialMediaFields } from "@/lib/social-utils";import {ProgramApplicationFormData,ProgramApplicationFormDataWithValues,@@ -350,6 +350,12 @@ async function createApplicationAndEnrollment({},};+ const { platforms, socialFields } = await backfillPartnerPlatforms({+ partnerId: partner.id,+ platforms: partner.platforms,+ application,+ });+await Promise.allSettled([notifyProgramApplication({partner,@@ -392,7 +398,8 @@ async function createApplicationAndEnrollment({...webhookData,partner: {...webhookData.partner,- ...polyfillSocialMediaFields(partner.platforms),+ platforms,+ ...socialFields,},}),}),diff --git a/apps/web/lib/partners/backfill-partner-platforms.ts b/apps/web/lib/partners/backfill-partner-platforms.tsnew file mode 100644index 0000000000..68d60795d0--- /dev/null+++ b/apps/web/lib/partners/backfill-partner-platforms.ts@@ -0,0 +1,125 @@+import { prisma } from "@/lib/prisma";+import {+ buildSocialPlatformLookup,+ polyfillSocialMediaFields,+ sanitizeSocialHandle,+ sanitizeWebsite,+} from "@/lib/social-utils";+import {+ PartnerPlatform,+ PlatformType,+ ProgramApplication,+} from "@prisma/client";+import { formatWebsiteAndSocialsFields } from "./format-application-form-data";++type ApplicationPlatform = Pick<+ PartnerPlatform,+ "type" | "identifier" | "verifiedAt"+>;++// Merges the partner's profile platforms with the website/socials from the application,+// so webhook payloads and the platform backfill agree on what the partner has.+// Application values only fill in platforms the partner doesn't already have (the+// profile may be verified), and are marked unverified.+const mergeApplicationSocialPlatforms = ({+ platforms,+ application,+}: {+ platforms: ApplicationPlatform[];+ application: ProgramApplication;+}) => {+ const platformsLookup = buildSocialPlatformLookup(platforms);+ const formValues = formatWebsiteAndSocialsFields(application);++ const sanitize = (type: PlatformType, value: string | null | undefined) =>+ type === "website"+ ? sanitizeWebsite(value)+ : sanitizeSocialHandle(value, type);++ const missingPlatforms: ApplicationPlatform[] = Object.values(+ PlatformType,+ ).flatMap((type) => {+ if (platformsLookup[type]?.identifier) {+ return [];+ }++ const identifier =+ sanitize(type, formValues[type]) || sanitize(type, application[type]);++ if (!identifier) {+ return [];+ }++ return [+ {+ type,+ identifier,+ verifiedAt: null,+ },+ ];+ });++ const resolvedPlatforms = [...platforms, ...missingPlatforms];++ return {+ platforms: resolvedPlatforms,+ missingPlatforms,+ socialFields: polyfillSocialMediaFields(resolvedPlatforms),+ };+};++/**+ * Saves the website and social profiles from a program application that the+ * partner's profile doesn't have yet (e.g. they skipped them during onboarding).+ *+ * Existing profile platforms are never overwritten, since they may be verified.+ * New ones are sanitized and saved as unverified.+ *+ * Returns the partner's platforms as they are actually stored after the backfill,+ * along with the matching flat social fields (`website`, `youtube`, etc.). Re-reading+ * matters because `skipDuplicates` or a concurrent insert can keep a different+ * identifier than the application's. If the backfill fails, the error is logged and+ * the given `platforms` are returned unchanged, so callers can still send webhooks.+ */+export async function backfillPartnerPlatforms({+ partnerId,+ platforms,+ application,+}: {+ partnerId: string;+ platforms: PartnerPlatform[];+ application: ProgramApplication;+}) {+ const { missingPlatforms } = mergeApplicationSocialPlatforms({+ platforms,+ application,+ });++ let savedPlatforms = platforms;++ try {+ if (missingPlatforms.length > 0) {+ await prisma.partnerPlatform.createMany({+ skipDuplicates: true,+ data: missingPlatforms.map(({ type, identifier }) => ({+ partnerId,+ type,+ identifier,+ })),+ });++ savedPlatforms = await prisma.partnerPlatform.findMany({+ where: {+ partnerId,+ },+ });+ }+ } catch (error) {+ console.error("Failed to backfill partner platforms", error);+ }++ return {+ platforms: savedPlatforms,+ socialFields: polyfillSocialMediaFields(savedPlatforms),+ };+}diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.tsindex 73b906e726..f8bf5968a4 100644--- a/apps/web/lib/partners/complete-program-applications.ts+++ b/apps/web/lib/partners/complete-program-applications.ts@@ -1,6 +1,6 @@import { prisma } from "@/lib/prisma";import { pluck } from "@dub/utils";-import { PlatformType, Prisma } from "@prisma/client";+import { Prisma } from "@prisma/client";import { createId } from "../api/create-id";import { detectAndRecordFraudApplication } from "../api/fraud/detect-record-fraud-application";import { notifyProgramApplication } from "../api/partners/notify-program-application";@@ -8,15 +8,12 @@ import { queuePartnerSearchSync } from "../api/partners/queue-partner-search-synimport { markApplicationEventSubmitted } from "../application-events/update-application-event";import { autoApprovePartnerJob } from "../jobs/handlers/auto-approve-partner-job";import { autoRejectPartnerJob } from "../jobs/handlers/auto-reject-partner-job";-import {- buildSocialPlatformLookup,- polyfillSocialMediaFields,-} from "../social-utils";import { sendWorkspaceWebhook } from "../webhook/publish";import {partnerApplicationWebhookSchema,programApplicationWebhookSchema,} from "../zod/schemas/program-application";+import { backfillPartnerPlatforms } from "./backfill-partner-platforms";import { evaluateApplicationRequirements } from "./evaluate-application-requirements";import {formatApplicationFormData,@@ -164,6 +161,8 @@ export async function completeProgramApplications(userEmail: string) {workspaces.map((ws) => [ws.defaultProgramId, ws]),);+ let savedPlatforms = partner.platforms;+for (const programApplication of filteredProgramApplications) {const application = programApplication;const program = programApplication.program;@@ -172,38 +171,13 @@ export async function completeProgramApplications(userEmail: string) {programApplication.id,);- const socialPlatforms = buildSocialPlatformLookup(partner.platforms);-- const missingSocialFields = {- website:- application.website && !socialPlatforms.website?.identifier- ? application.website- : undefined,- youtube:- application.youtube && !socialPlatforms.youtube?.identifier- ? application.youtube- : undefined,- twitter:- application.twitter && !socialPlatforms.twitter?.identifier- ? application.twitter- : undefined,- linkedin:- application.linkedin && !socialPlatforms.linkedin?.identifier- ? application.linkedin- : undefined,- instagram:- application.instagram && !socialPlatforms.instagram?.identifier- ? application.instagram- : undefined,- tiktok:- application.tiktok && !socialPlatforms.tiktok?.identifier- ? application.tiktok- : undefined,- };+ const { platforms, socialFields } = await backfillPartnerPlatforms({+ partnerId: partner.id,+ platforms: savedPlatforms,+ application,+ });- const hasMissingSocialFields = Object.values(missingSocialFields).some(- (field) => field !== undefined,- );+ savedPlatforms = platforms;const applicationFormData = formatApplicationFormData(application).map(({ title, value }) => ({@@ -278,7 +252,8 @@ export async function completeProgramApplications(userEmail: string) {...webhookData,partner: {...webhookData.partner,- ...polyfillSocialMediaFields(partner.platforms),+ platforms,+ ...socialFields,},}),}),@@ -296,20 +271,6 @@ export async function completeProgramApplications(userEmail: string) {),]),- // if the application has any website or social fields but the partner doesn't have the corresponding one (maybe they forgot to add during onboarding)- // update the partner to use the website they applied with- hasMissingSocialFields &&- prisma.partnerPlatform.createMany({- data: Object.entries(missingSocialFields)- .filter(([, identifier]) => identifier !== undefined)- .map(([platform, identifier]) => ({- partnerId: partner.id,- type: platform as PlatformType,- identifier: identifier as string,- })),- skipDuplicates: true,- }),-// Detect and record fraud events for the partner when they apply to a programdetectAndRecordFraudApplication({context: {