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 Plain setup to sync customer's plans (#3281)

Steven Tey51f48655ee4e
diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/customers-data-request.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/customers-data-request.ts
index 5fba0eb521..03467033a1 100644
--- a/apps/web/app/(ee)/api/shopify/integration/webhook/customers-data-request.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/customers-data-request.ts
@@ -1,4 +1,4 @@
-import { createPlainThread } from "@/lib/plain";
+import { createPlainThread } from "@/lib/plain/create-plain-thread";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import { z } from "zod";
diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/customers-redact.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/customers-redact.ts
index 3ee966986f..7a7caba197 100644
--- a/apps/web/app/(ee)/api/shopify/integration/webhook/customers-redact.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/customers-redact.ts
@@ -1,5 +1,5 @@
import { generateRandomName } from "@/lib/names";
-import { createPlainThread } from "@/lib/plain";
+import { createPlainThread } from "@/lib/plain/create-plain-thread";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import { z } from "zod";
diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/shop-redact.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/shop-redact.ts
index cf8dd94f21..a6498d6642 100644
--- a/apps/web/app/(ee)/api/shopify/integration/webhook/shop-redact.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/shop-redact.ts
@@ -1,4 +1,4 @@
-import { createPlainThread } from "@/lib/plain";
+import { createPlainThread } from "@/lib/plain/create-plain-thread";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import { z } from "zod";
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
index f10905acfb..145d986d36 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
@@ -1,11 +1,13 @@
import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
import { tokenCache } from "@/lib/auth/token-cache";
+import { syncCustomerPlanToPlain } from "@/lib/plain/sync-customer-plan";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { WorkspaceProps } from "@/lib/types";
import { webhookCache } from "@/lib/webhook/cache";
import { prisma } from "@dub/prisma";
import { getPlanAndTierFromPriceId } from "@dub/utils";
import { NEW_BUSINESS_PRICE_IDS } from "@dub/utils/src";
+import { waitUntil } from "@vercel/functions";
export async function updateWorkspacePlan({
workspace,
@@ -46,7 +48,7 @@ export async function updateWorkspacePlan({
(workspace.payoutsLimit < newPlan.limits.payouts &&
NEW_BUSINESS_PRICE_IDS.includes(priceId))
) {
- await Promise.allSettled([
+ const [updatedWorkspace] = await Promise.allSettled([
prisma.project.update({
where: {
id: workspace.id,
@@ -67,6 +69,26 @@ export async function updateWorkspacePlan({
paymentFailedAt: null,
...(shouldDeleteFolders && { foldersUsage: 0 }),
},
+ include: {
+ users: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ take: 1,
+ },
+ },
}),
// expire tokens cache
@@ -140,6 +162,18 @@ export async function updateWorkspacePlan({
workspaceId: workspace.id,
});
}
+
+ if (
+ updatedWorkspace.status === "fulfilled" &&
+ updatedWorkspace.value.users.length
+ ) {
+ const workspaceOwner = updatedWorkspace.value.users[0].user;
+ waitUntil(
+ syncCustomerPlanToPlain({
+ customer: workspaceOwner,
+ }),
+ );
+ }
} else if (workspace.paymentFailedAt) {
await prisma.project.update({
where: {
diff --git a/apps/web/app/api/callback/plain/partner/route.ts b/apps/web/app/api/callback/plain/partner/route.ts
index 3e1428015d..9b049da0c6 100644
--- a/apps/web/app/api/callback/plain/partner/route.ts
+++ b/apps/web/app/api/callback/plain/partner/route.ts
@@ -1,4 +1,5 @@
-import { plain } from "@/lib/plain";
+import { plain } from "@/lib/plain/client";
+import { upsertPlainCustomer } from "@/lib/plain/upsert-plain-customer";
import { prisma } from "@dub/prisma";
import { COUNTRIES, currencyFormatter, formatDate } from "@dub/utils";
import { uiComponent } from "@team-plain/typescript-sdk";
@@ -32,7 +33,7 @@ export async function POST(req: NextRequest) {
},
});
- if (!user) {
+ if (!user || !user.email) {
return NextResponse.json({
cards: [
{
@@ -42,35 +43,18 @@ export async function POST(req: NextRequest) {
],
});
}
-
customer.externalId = user.id;
- const customerName = user.name || customer.email.split("@")[0];
-
- await plain.upsertCustomer({
- identifier: {
- emailAddress: customer.email,
- },
- onCreate: {
- fullName: customerName,
- shortName: customerName.split(" ")[0],
- email: {
- email: customer.email,
- isVerified: true,
- },
- externalId: user.id,
- },
- onUpdate: {
- externalId: {
- value: user.id,
- },
- },
+ await upsertPlainCustomer({
+ id: user.id,
+ name: user.name,
+ email: user.email,
});
}
const [plainCustomer, partnerProfile] = await Promise.all([
- plain.getCustomerByEmail({
- email: customer.email,
+ plain.getCustomerByExternalId({
+ externalId: customer.externalId,
}),
prisma.partner.findFirst({
where: {
diff --git a/apps/web/app/api/callback/plain/workspace/route.ts b/apps/web/app/api/callback/plain/workspace/route.ts
index 63cad032f6..128321f9d0 100644
--- a/apps/web/app/api/callback/plain/workspace/route.ts
+++ b/apps/web/app/api/callback/plain/workspace/route.ts
@@ -1,8 +1,10 @@
import { prefixWorkspaceId } from "@/lib/api/workspaces/workspace-id";
-import { plain } from "@/lib/plain";
+import { syncCustomerPlanToPlain } from "@/lib/plain/sync-customer-plan";
+import { upsertPlainCustomer } from "@/lib/plain/upsert-plain-customer";
import { prisma } from "@dub/prisma";
import { capitalize, formatDate } from "@dub/utils";
import { uiComponent } from "@team-plain/typescript-sdk";
+import { waitUntil } from "@vercel/functions";
import { NextRequest, NextResponse } from "next/server";
import {
plainCopySection,
@@ -33,7 +35,7 @@ export async function POST(req: NextRequest) {
},
});
- if (!user) {
+ if (!user || !user.email) {
return NextResponse.json({
cards: [
{
@@ -43,58 +45,42 @@ export async function POST(req: NextRequest) {
],
});
}
-
customer.externalId = user.id;
- const customerName = user.name || customer.email.split("@")[0];
-
- await plain.upsertCustomer({
- identifier: {
- emailAddress: customer.email,
- },
- onCreate: {
- fullName: customerName,
- shortName: customerName.split(" ")[0],
- email: {
- email: customer.email,
- isVerified: true,
- },
- externalId: user.id,
- },
- onUpdate: {
- externalId: {
- value: user.id,
- },
- },
+ await upsertPlainCustomer({
+ id: user.id,
+ name: user.name,
+ email: user.email,
});
}
- const [plainCustomer, topWorkspace] = await Promise.all([
- plain.getCustomerByEmail({
- email: customer.email,
+ waitUntil(
+ syncCustomerPlanToPlain({
+ customer,
}),
- prisma.project.findFirst({
- where: {
- users: {
- some: {
- userId: customer.externalId,
- },
+ );
+
+ const topWorkspace = await prisma.project.findFirst({
+ where: {
+ users: {
+ some: {
+ userId: customer.externalId,
},
},
- include: {
- _count: {
- select: {
- domains: true,
- users: true,
- },
+ },
+ include: {
+ _count: {
+ select: {
+ domains: true,
+ users: true,
},
},
- orderBy: {
- usageLimit: "desc",
- },
- take: 1,
- }),
- ]);
+ },
+ orderBy: {
+ usageLimit: "desc",
+ },
+ take: 1,
+ });
if (!topWorkspace) {
return NextResponse.json({
@@ -126,33 +112,6 @@ export async function POST(req: NextRequest) {
_count: { domains, users },
} = topWorkspace;
- const companyDomainName = customer.email && customer.email.split("@")[1];
-
- if (plainCustomer.data) {
- await Promise.allSettled([
- plain.addCustomerToCustomerGroups({
- customerId: plainCustomer.data.id,
- customerGroupIdentifiers: [
- {
- customerGroupKey: topWorkspace.plan.split(" ")[0],
- },
- ],
- }),
- ...(topWorkspace && companyDomainName
- ? [
- plain.updateCompanyTier({
- companyIdentifier: {
- companyDomainName,
- },
- tierIdentifier: {
- externalId: topWorkspace.plan.split(" ")[0],
- },
- }),
- ]
- : []),
- ]);
- }
-
return NextResponse.json({
cards: [
{
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page-client.tsx
index dac0878104..829886f1ce 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page-client.tsx
@@ -131,7 +131,8 @@ const InvoiceCard = ({
</div>
<div className="flex items-center">
{invoice.pdfUrl &&
- INVOICE_AVAILABLE_PAYOUT_STATUSES.includes(invoice.status ?? "") ? (
+ (!invoice.status ||
+ INVOICE_AVAILABLE_PAYOUT_STATUSES.includes(invoice.status)) ? (
<a
href={invoice.pdfUrl}
target="_blank"
@@ -263,7 +264,8 @@ const InvoiceCard = ({
<div className="flex items-center justify-end sm:col-span-1 sm:justify-end">
{invoice.pdfUrl &&
- INVOICE_AVAILABLE_PAYOUT_STATUSES.includes(invoice.status ?? "") ? (
+ (!invoice.status ||
+ INVOICE_AVAILABLE_PAYOUT_STATUSES.includes(invoice.status)) ? (
<a
href={invoice.pdfUrl}
target="_blank"
diff --git a/apps/web/lib/actions/submit-oauth-app-for-review.ts b/apps/web/lib/actions/submit-oauth-app-for-review.ts
index 9aada8a4ac..b43c181909 100644
--- a/apps/web/lib/actions/submit-oauth-app-for-review.ts
+++ b/apps/web/lib/actions/submit-oauth-app-for-review.ts
@@ -1,8 +1,8 @@
"use server";
-import { plain, upsertPlainCustomer } from "@/lib/plain";
import { prisma } from "@dub/prisma";
import { ComponentDividerSpacingSize } from "@team-plain/typescript-sdk";
+import { createPlainThread } from "../plain/create-plain-thread";
import { ratelimit } from "../upstash";
import z from "../zod";
import { authActionClient } from "./safe-action";
@@ -37,25 +37,8 @@ export const submitOAuthAppForReview = authActionClient
);
}
- let plainCustomerId: string | null = null;
-
- const plainCustomer = await plain.getCustomerByEmail({
- email: user.email,
- });
-
- if (plainCustomer.data) {
- plainCustomerId = plainCustomer.data.id;
- } else {
- const { data } = await upsertPlainCustomer(user);
- if (data) {
- plainCustomerId = data.customer.id;
- }
- }
-
- await plain.createThread({
- customerIdentifier: {
- customerId: plainCustomerId,
- },
+ await createPlainThread({
+ user,
title: `Integration Submission: ${integration.name}`,
components: [
{
diff --git a/apps/web/lib/is-generic-email.ts b/apps/web/lib/is-generic-email.ts
index 28997b0d86..2e6d2e9041 100644
--- a/apps/web/lib/is-generic-email.ts
+++ b/apps/web/lib/is-generic-email.ts
@@ -1,13 +1,19 @@
+export const GENERIC_EMAIL_DOMAINS = [
+ "gmail.com",
+ "yahoo.com",
+ "hotmail.com",
+ "outlook.com",
+ "icloud.com",
+ "aol.com",
+ "comcast.net",
+ "verizon.net",
+ "att.net",
+ "me.com",
+ "msn.com",
+ "live.com",
+ "protonmail.com",
+];
+
export const isGenericEmail = (email: string) => {
- return (
- email.endsWith("@gmail.com") ||
- email.endsWith("@yahoo.com") ||
- email.endsWith("@hotmail.com") ||
- email.endsWith("@outlook.com") ||
- email.endsWith("@icloud.com") ||
- email.endsWith("@aol.com") ||
- email.endsWith("@comcast.net") ||
- email.endsWith("@verizon.net") ||
- email.endsWith("@att.net")
- );
+ return GENERIC_EMAIL_DOMAINS.some((domain) => email.endsWith(`@${domain}`));
};
diff --git a/apps/web/lib/plain.ts b/apps/web/lib/plain.ts
deleted file mode 100644
index b38194fa75..0000000000
--- a/apps/web/lib/plain.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { CreateThreadInput, PlainClient } from "@team-plain/typescript-sdk";
-import { Session } from "./auth";
-
-export const plain = new PlainClient({
- apiKey: process.env.PLAIN_API_KEY as string,
-});
-
-type PlainUser = Pick<Session["user"], "id" | "name" | "email">;
-
-export const upsertPlainCustomer = async (user: PlainUser) => {
- const fullName = user.name ?? user.email;
- const shortName = user.name ?? user.email.split("@")[0];
-
- return await plain.upsertCustomer({
- identifier: {
- externalId: user.id,
- },
- onCreate: {
- fullName,
- shortName,
- email: {
- email: user.email,
- isVerified: true,
- },
- externalId: user.id,
- },
- onUpdate: {},
- });
-};
-
-export const createPlainThread = async ({
- user,
- ...rest
-}: {
- user: PlainUser;
-} & Omit<CreateThreadInput, "customerIdentifier">) => {
- let plainCustomerId: string | undefined;
- if (!user.email) {
- throw new Error("User email is required");
- }
-
- const plainCustomer = await plain.getCustomerByEmail({
- email: user.email,
- });
-
- if (plainCustomer.data) {
- plainCustomerId = plainCustomer.data.id;
- } else {
- const { data } = await upsertPlainCustomer({
- id: user.id,
- name: user.name,
- email: user.email,
- });
- if (data) {
- plainCustomerId = data.customer.id;
- }
- }
-
- const { data, error } = await plain.createThread({
- customerIdentifier: {
- customerId: plainCustomerId,
- },
- ...rest,
- });
-
- if (error) {
- throw new Error(`Failed to create thread: ${error.message}`);
- }
-
- return data;
-};
diff --git a/apps/web/lib/plain/client.ts b/apps/web/lib/plain/client.ts
new file mode 100644
index 0000000000..aea7f3d13f
--- /dev/null
+++ b/apps/web/lib/plain/client.ts
@@ -0,0 +1,11 @@
+import { PlainClient } from "@team-plain/typescript-sdk";
+
+export const plain = new PlainClient({
+ apiKey: process.env.PLAIN_API_KEY as string,
+});
+
+export type PlainUser = {
+ id: string;
+ name: string | null;
+ email: string | null;
+};
diff --git a/apps/web/lib/plain/create-plain-thread.ts b/apps/web/lib/plain/create-plain-thread.ts
new file mode 100644
index 0000000000..61e2842102
--- /dev/null
+++ b/apps/web/lib/plain/create-plain-thread.ts
@@ -0,0 +1,37 @@
+import { CreateThreadInput } from "@team-plain/typescript-sdk";
+import { plain, PlainUser } from "./client";
+import { upsertPlainCustomer } from "./upsert-plain-customer";
+
+export const createPlainThread = async ({
+ user,
+ ...rest
+}: {
+ user: PlainUser;
+} & Omit<CreateThreadInput, "customerIdentifier">) => {
+ if (!user.email) {
+ throw new Error("User email is required");
+ }
+
+ const { data: upsertResult } = await upsertPlainCustomer({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ });
+
+ if (!upsertResult) {
+ throw new Error("Failed to upsert plain customer");
+ }
+
+ const { data, error } = await plain.createThread({
+ customerIdentifier: {
+ customerId: upsertResult.customer.id,
+ },
+ ...rest,
+ });
+
+ if (error) {
+ throw new Error(`Failed to create thread: ${error.message}`);
+ }
+
+ return data;
+};
diff --git a/apps/web/lib/plain/sync-customer-plan.ts b/apps/web/lib/plain/sync-customer-plan.ts
new file mode 100644
index 0000000000..d8d205ffd7
--- /dev/null
+++ b/apps/web/lib/plain/sync-customer-plan.ts
@@ -0,0 +1,92 @@
+import { prisma } from "@dub/prisma";
+import { isGenericEmail } from "../is-generic-email";
+import { plain, PlainUser } from "./client";
+import { upsertPlainCustomer } from "./upsert-plain-customer";
+
+export const syncCustomerPlanToPlain = async ({
+ customer,
+}: {
+ customer: PlainUser;
+}) => {
+ if (!customer.email) {
+ console.log(
+ `Customer email is null for user ${customer.id}, skipping sync...`,
+ );
+ return;
+ }
+
+ await upsertPlainCustomer({
+ id: customer.id,
+ name: customer.name,
+ email: customer.email,
+ });
+
+ const plainCustomer = await plain.getCustomerByExternalId({
+ externalId: customer.id,
+ });
+
+ let companyDomainName: string | undefined;
+ if (!isGenericEmail(customer.email)) {
+ companyDomainName = customer.email.split("@")[1];
+ }
+
+ const topWorkspace = await prisma.project.findFirst({
+ where: {
+ users: {
+ some: companyDomainName
+ ? {
+ user: {
+ email: {
+ endsWith: `@${companyDomainName}`,
+ },
+ },
+ }
+ : {
+ userId: customer.id,
+ },
+ },
+ },
+ orderBy: {
+ usageLimit: "desc",
+ },
+ take: 1,
+ });
+
+ if (!topWorkspace) {
+ console.log(
+ `No workspace found for company domain ${companyDomainName}, skipping sync...`,
+ );
+ return;
+ }
+
+ if (plainCustomer.data) {
+ await Promise.allSettled([
+ plain.addCustomerToCustomerGroups({
+ customerId: plainCustomer.data.id,
+ customerGroupIdentifiers: [
+ {
+ customerGroupKey: "app.dub.co",
+ },
+ ],
+ }),
+ ...(companyDomainName
+ ? [
+ plain.updateCompanyTier({
+ companyIdentifier: {
+ companyDomainName,
+ },
+ tierIdentifier: {
+ externalId: topWorkspace.plan.split(" ")[0].toLowerCase(),
+ },
+ }),
+ ]
+ : []),
+ ]);
+
+ console.log(
+ `Synced customer ${customer.email}'s plan in Plain to ${topWorkspace.plan}`,
+ );
+ }
+
+ return plainCustomer;
+};
diff --git a/apps/web/lib/plain/upsert-plain-customer.ts b/apps/web/lib/plain/upsert-plain-customer.ts
new file mode 100644
index 0000000000..7246703f85
--- /dev/null
+++ b/apps/web/lib/plain/upsert-plain-customer.ts
@@ -0,0 +1,24 @@
+import { plain, PlainUser } from "./client";
+
+export const upsertPlainCustomer = async (
+ user: PlainUser & { email: string },
+) => {
+ const fullName = user.name || user.email;
+ const shortName = user.name || user.email.split("@")[0];
+
+ return await plain.upsertCustomer({
+ identifier: {
+ externalId: user.id,
+ },
+ onCreate: {
+ fullName,
+ shortName,
+ email: {
+ email: user.email,
+ isVerified: true,
+ },
+ externalId: user.id,
+ },
+ onUpdate: {},
+ });
+};
diff --git a/apps/web/scripts/migrations/backfill-plain-customers.ts b/apps/web/scripts/migrations/backfill-plain-customers.ts
new file mode 100644
index 0000000000..7ea06b8d40
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-plain-customers.ts
@@ -0,0 +1,53 @@
+import { GENERIC_EMAIL_DOMAINS } from "@/lib/is-generic-email";
+import { prisma } from "@dub/prisma";
+import { chunk } from "@dub/utils";
+import "dotenv-flow/config";
+import { syncCustomerPlanToPlain } from "../../lib/plain/sync-customer-plan";
+
+async function main() {
+ const users = await prisma.user.findMany({
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ where: {
+ NOT: GENERIC_EMAIL_DOMAINS.map((domain) => ({
+ email: {
+ endsWith: `@${domain}`,
+ },
+ })),
+ projects: {
+ some: {
+ project: {
+ plan: {
+ not: "free",
+ },
+ },
+ role: "owner",
+ },
+ },
+ },
+ take: 50,
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ const chunks = chunk(users, 50);
+ for (let i = 0; i < chunks.length; i++) {
+ const chunk = chunks[i];
+ await Promise.allSettled(
+ chunk.map((user) =>
+ syncCustomerPlanToPlain({
+ customer: user,
+ }),
+ ),
+ );
+ console.log(
+ `Backfilled ${chunk.length} users in batch ${i + 1} of ${chunks.length} (out of ${users.length} total users)`,
+ );
+ }
+}
+
+main();
diff --git a/apps/web/scripts/programs/3-import-customer-leads.ts b/apps/web/scripts/programs/3-import-customer-leads.ts
index 4bf28fd762..5e8170cedb 100644
--- a/apps/web/scripts/programs/3-import-customer-leads.ts
+++ b/apps/web/scripts/programs/3-import-customer-leads.ts
@@ -147,6 +147,10 @@ async function main() {
if (!clickData) {
return null;
}
+ const link = partnerLinks.find(
+ (link) =>
+ link.key.toLowerCase() === lead.partnerLinkKey.toLowerCase(),
+ )!;
return {
id: createId({ prefix: "cus_" }),
name: generateRandomName(),
@@ -154,9 +158,11 @@ async function main() {
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
stripeCustomerId: lead.stripeCustomerId,
- clickId: clickData.click_id,
- linkId: clickData.link_id,
+ linkId: link.id,
+ programId: link.programId,
+ partnerId: link.partnerId,
country: clickData.country,
+ clickId: clickData.click_id,
clickedAt: new Date(lead.timestamp).toISOString(),
createdAt: new Date(lead.timestamp).toISOString(),
};