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.

upgrade plain SDK

Steven Tey694a44286e14
diff --git a/apps/web/app/api/callback/plain/partner/route.ts b/apps/web/app/api/callback/plain/partner/route.ts
new file mode 100644
index 0000000000..1c26fb813d
--- /dev/null
+++ b/apps/web/app/api/callback/plain/partner/route.ts
@@ -0,0 +1,230 @@
+import { plain } from "@/lib/plain";
+import { prisma } from "@dub/prisma";
+import { currencyFormatter, formatDate } from "@dub/utils";
+import { uiComponent } from "@team-plain/typescript-sdk";
+import { NextRequest, NextResponse } from "next/server";
+import {
+ plainCopySection,
+ plainDivider,
+ plainEmptyContainer,
+ plainSpacer,
+ plainUsageSection,
+} from "../utils";
+
+export async function POST(req: NextRequest) {
+ // authenticate webhook X-Plain-Webhook-Secret
+ const token = req.headers.get("X-Plain-Webhook-Secret");
+ if (token !== process.env.PLAIN_WEBHOOK_SECRET) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ let { cardKeys, customer } = await req.json();
+
+ if (!cardKeys || !customer) {
+ return new Response("Invalid payload", { status: 400 });
+ }
+
+ // if there's no externalId yet, try to find the user by email and set it
+ if (!customer.externalId) {
+ const user = await prisma.user.findUnique({
+ where: {
+ email: customer.email,
+ },
+ });
+
+ if (!user) {
+ return NextResponse.json({
+ cards: [
+ {
+ key: "workspace",
+ components: [plainEmptyContainer("No user found.")],
+ },
+ ],
+ });
+ }
+
+ 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,
+ },
+ },
+ });
+ }
+
+ const [plainCustomer, partnerProfile] = await Promise.all([
+ plain.getCustomerByEmail({
+ email: customer.email,
+ }),
+ prisma.partner.findFirst({
+ where: {
+ users: {
+ some: {
+ userId: customer.externalId,
+ },
+ },
+ },
+ include: {
+ programs: {
+ select: {
+ program: {
+ select: {
+ name: true,
+ },
+ },
+ createdAt: true,
+ totalCommissions: true,
+ },
+ where: {
+ totalCommissions: {
+ gt: 0,
+ },
+ },
+ orderBy: {
+ totalCommissions: "desc",
+ },
+ take: 5,
+ },
+ },
+ }),
+ ]);
+
+ if (!partnerProfile) {
+ return NextResponse.json({});
+ }
+
+ const {
+ id,
+ name,
+ email,
+ country,
+ stripeConnectId,
+ paypalEmail,
+ payoutsEnabledAt,
+ } = partnerProfile;
+
+ if (plainCustomer.data) {
+ await plain.addCustomerToCustomerGroups({
+ customerId: plainCustomer.data.id,
+ customerGroupIdentifiers: [
+ {
+ customerGroupKey: "partners.dub.co",
+ },
+ ],
+ });
+ }
+
+ return NextResponse.json({
+ cards: [
+ {
+ key: "partner",
+ components: [
+ ...plainCopySection({
+ label: "Partner ID",
+ value: id,
+ }),
+ plainSpacer,
+ ...plainCopySection({
+ label: "Partner Name",
+ value: name,
+ }),
+ ...(email
+ ? [
+ plainSpacer,
+ ...plainCopySection({
+ label: "Partner Email",
+ value: email,
+ }),
+ ]
+ : []),
+ plainSpacer,
+ ...plainCopySection({
+ label: "Partner Country",
+ value: country ?? "Unknown",
+ }),
+ ...(stripeConnectId
+ ? [
+ plainSpacer,
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: "Stripe Express Account",
+ size: "M",
+ color: "NORMAL",
+ }),
+ uiComponent.text({
+ text: stripeConnectId,
+ size: "S",
+ color: "MUTED",
+ }),
+ ],
+ asideContent: [
+ uiComponent.linkButton({
+ url: `https://dashboard.stripe.com/connect/accounts/${stripeConnectId}`,
+ label: "View in Stripe",
+ }),
+ ],
+ }),
+ ]
+ : []),
+ ...(paypalEmail
+ ? plainCopySection({
+ label: "Paypal Email",
+ value: paypalEmail,
+ })
+ : []),
+ plainSpacer,
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: "Payouts Enabled",
+ }),
+ ],
+ asideContent: [
+ uiComponent.badge({
+ label: payoutsEnabledAt ? "Yes" : "No",
+ color: payoutsEnabledAt ? "GREEN" : "RED",
+ }),
+ ],
+ }),
+ ...(partnerProfile.programs.length > 0
+ ? [
+ plainDivider,
+ ...partnerProfile.programs.flatMap(
+ ({ program, createdAt, totalCommissions }) => [
+ plainUsageSection({
+ usage: currencyFormatter(totalCommissions / 100, {
+ maximumFractionDigits: 2,
+ }),
+ label: program.name,
+ sublabel: `Partner since ${formatDate(createdAt)}`,
+ color: "GREEN",
+ }),
+ uiComponent.spacer({
+ size: "M",
+ }),
+ ],
+ ),
+ ]
+ : []),
+ ],
+ },
+ ],
+ });
+}
diff --git a/apps/web/app/api/callback/plain/utils.ts b/apps/web/app/api/callback/plain/utils.ts
index 40cb220ceb..8425977236 100644
--- a/apps/web/app/api/callback/plain/utils.ts
+++ b/apps/web/app/api/callback/plain/utils.ts
@@ -1,39 +1,28 @@
import { nFormatter } from "@dub/utils";
+import { uiComponent } from "@team-plain/typescript-sdk";
-export const plainDivider = {
- componentDivider: {
- dividerSpacingSize: "M",
- },
-};
-
-export const plainEmptyContainer = (text: string) => ({
- componentContainer: {
- containerContent: [
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
- {
- componentPlainText: {
- text,
- size: "S",
- },
- },
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
- ],
- },
+export const plainDivider = uiComponent.divider({
+ spacingSize: "M",
+});
+export const plainSpacer = uiComponent.spacer({
+ size: "S",
});
-export const plainSpacer = {
- componentSpacer: {
- spacerSize: "M",
- },
-};
+export const plainEmptyContainer = (text: string) =>
+ uiComponent.container({
+ content: [
+ uiComponent.spacer({
+ size: "M",
+ }),
+ uiComponent.plainText({
+ text,
+ size: "S",
+ }),
+ uiComponent.spacer({
+ size: "M",
+ }),
+ ],
+ });
export const plainTextSection = ({
label,
@@ -41,28 +30,23 @@ export const plainTextSection = ({
}: {
label: string;
value: string;
-}) => ({
- componentRow: {
- rowMainContent: [
- {
- componentText: {
- textSize: "M",
- textColor: "MUTED",
- text: label,
- },
- },
+}) =>
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: label,
+ size: "M",
+ color: "MUTED",
+ }),
],
- rowAsideContent: [
- {
- componentText: {
- textSize: "M",
- textColor: "NORMAL",
- text: value,
- },
- },
+ asideContent: [
+ uiComponent.text({
+ text: value,
+ size: "M",
+ color: "NORMAL",
+ }),
],
- },
-});
+ });
export const plainCopySection = ({
label,
@@ -71,32 +55,24 @@ export const plainCopySection = ({
label: string;
value: string;
}) => [
- {
- componentText: {
- text: label,
- textSize: "S",
- textColor: "MUTED",
- },
- },
- {
- componentRow: {
- rowMainContent: [
- {
- componentText: {
- text: value,
- },
- },
- ],
- rowAsideContent: [
- {
- componentCopyButton: {
- copyButtonTooltipLabel: `Copy ${label}`,
- copyButtonValue: value,
- },
- },
- ],
- },
- },
+ uiComponent.text({
+ text: label,
+ size: "S",
+ color: "MUTED",
+ }),
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: value,
+ }),
+ ],
+ asideContent: [
+ uiComponent.copyButton({
+ tooltip: `Copy ${label}`,
+ value: value,
+ }),
+ ],
+ }),
];
export const plainUsageSection = ({
@@ -106,40 +82,36 @@ export const plainUsageSection = ({
sublabel,
color,
}: {
- usage: number;
+ usage: number | string;
usageLimit?: number;
label: string;
sublabel?: string;
color: "GREY" | "GREEN" | "YELLOW" | "RED" | "BLUE";
-}) => ({
- componentRow: {
- rowMainContent: [
- {
- componentText: {
- textSize: "M",
- textColor: "NORMAL",
- text: label,
- },
- },
+}) =>
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: label,
+ size: "M",
+ color: "NORMAL",
+ }),
...(sublabel
? [
- {
- componentText: {
- textSize: "S",
- textColor: "MUTED",
- text: sublabel,
- },
- },
+ uiComponent.text({
+ text: sublabel,
+ size: "S",
+ color: "MUTED",
+ }),
]
: []),
],
- rowAsideContent: [
- {
- componentBadge: {
- badgeLabel: `${nFormatter(usage, { full: true })}${usageLimit ? ` of ${nFormatter(usageLimit, { full: true })}` : ""}`,
- badgeColor: color,
- },
- },
+ asideContent: [
+ uiComponent.badge({
+ label:
+ typeof usage === "number"
+ ? `${nFormatter(usage, { full: true })}${usageLimit ? ` of ${nFormatter(usageLimit, { full: true })}` : ""}`
+ : usage,
+ color: color,
+ }),
],
- },
-});
+ });
diff --git a/apps/web/app/api/callback/plain/route.ts b/apps/web/app/api/callback/plain/workspace/route.ts
similarity index 70%
rename from apps/web/app/api/callback/plain/route.ts
rename to apps/web/app/api/callback/plain/workspace/route.ts
index 2594b81a30..760fd19001 100644
--- a/apps/web/app/api/callback/plain/route.ts
+++ b/apps/web/app/api/callback/plain/workspace/route.ts
@@ -2,6 +2,7 @@ import { prefixWorkspaceId } from "@/lib/api/workspace-id";
import { plain } from "@/lib/plain";
import { prisma } from "@dub/prisma";
import { capitalize, formatDate } from "@dub/utils";
+import { uiComponent } from "@team-plain/typescript-sdk";
import { NextRequest, NextResponse } from "next/server";
import {
plainCopySection,
@@ -9,7 +10,7 @@ import {
plainEmptyContainer,
plainSpacer,
plainUsageSection,
-} from "./utils";
+} from "../utils";
export async function POST(req: NextRequest) {
// authenticate webhook X-Plain-Webhook-Secret
@@ -45,15 +46,15 @@ export async function POST(req: NextRequest) {
customer.externalId = user.id;
- const userName = user.name || customer.email.split("@")[0];
+ const customerName = user.name || customer.email.split("@")[0];
await plain.upsertCustomer({
identifier: {
emailAddress: customer.email,
},
onCreate: {
- fullName: userName,
- shortName: userName.split(" ")[0],
+ fullName: customerName,
+ shortName: customerName.split(" ")[0],
email: {
email: customer.email,
isVerified: true,
@@ -68,7 +69,10 @@ export async function POST(req: NextRequest) {
});
}
- const [topWorkspace, plainCustomer] = await Promise.all([
+ const [plainCustomer, topWorkspace] = await Promise.all([
+ plain.getCustomerByEmail({
+ email: customer.email,
+ }),
prisma.project.findFirst({
where: {
users: {
@@ -90,9 +94,6 @@ export async function POST(req: NextRequest) {
},
take: 1,
}),
- plain.getCustomerByEmail({
- email: customer.email,
- }),
]);
if (!topWorkspace) {
@@ -113,6 +114,7 @@ export async function POST(req: NextRequest) {
name,
slug,
plan,
+ stripeId,
usage,
usageLimit,
totalClicks,
@@ -120,20 +122,35 @@ export async function POST(req: NextRequest) {
linksLimit,
totalLinks,
domainsLimit,
- tagsLimit,
usersLimit,
_count: { domains, users },
} = topWorkspace;
+ const companyDomainName = customer.email && customer.email.split("@")[1];
+
if (plainCustomer.data) {
- await plain.addCustomerToCustomerGroups({
- customerId: plainCustomer.data.id,
- customerGroupIdentifiers: [
- {
- customerGroupKey: plan.split(" ")[0],
- },
- ],
- });
+ 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({
@@ -145,6 +162,7 @@ export async function POST(req: NextRequest) {
label: "Workspace ID",
value: prefixWorkspaceId(id),
}),
+ plainSpacer,
...plainCopySection({
label: "Workspace Name",
value: name,
@@ -154,7 +172,7 @@ export async function POST(req: NextRequest) {
label: "Workspace Slug",
value: slug,
}),
- plainDivider,
+ plainSpacer,
{
componentRow: {
rowMainContent: [
@@ -183,7 +201,36 @@ export async function POST(req: NextRequest) {
],
},
},
- plainSpacer,
+ ...(stripeId
+ ? [
+ uiComponent.spacer({
+ size: "M",
+ }),
+ uiComponent.row({
+ mainContent: [
+ uiComponent.text({
+ text: "Stripe Customer",
+ size: "M",
+ color: "NORMAL",
+ }),
+ uiComponent.text({
+ text: stripeId,
+ size: "S",
+ color: "MUTED",
+ }),
+ ],
+ asideContent: [
+ uiComponent.linkButton({
+ url: `https://dashboard.stripe.com/customers/${stripeId}`,
+ label: "View in Stripe",
+ }),
+ ],
+ }),
+ ]
+ : []),
+ uiComponent.spacer({
+ size: "M",
+ }),
{
componentRow: {
rowMainContent: [
@@ -210,11 +257,9 @@ export async function POST(req: NextRequest) {
sublabel: "This billing period",
color: "GREEN",
}),
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
+ uiComponent.spacer({
+ size: "M",
+ }),
plainUsageSection({
usage: linksUsage,
usageLimit: linksLimit,
@@ -222,42 +267,34 @@ export async function POST(req: NextRequest) {
sublabel: "This billing period",
color: "YELLOW",
}),
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
+ uiComponent.spacer({
+ size: "M",
+ }),
plainUsageSection({
usage: totalClicks,
label: "Total Clicks",
color: "GREEN",
}),
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
+ uiComponent.spacer({
+ size: "M",
+ }),
plainUsageSection({
usage: totalLinks,
label: "Total Links",
color: "YELLOW",
}),
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
+ uiComponent.spacer({
+ size: "M",
+ }),
plainUsageSection({
usage: domains,
usageLimit: domainsLimit,
label: "Total Domains",
color: "BLUE",
}),
- {
- componentSpacer: {
- spacerSize: "M",
- },
- },
+ uiComponent.spacer({
+ size: "M",
+ }),
plainUsageSection({
usage: users,
usageLimit: usersLimit,
diff --git a/apps/web/package.json b/apps/web/package.json
index e0e2ed1d8d..fb4de6e6ef 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -41,7 +41,7 @@
"@splinetool/runtime": "^1.2.8",
"@stripe/stripe-js": "^7.3.1",
"@tanstack/react-table": "^8.17.3",
- "@team-plain/typescript-sdk": "^5.8.0",
+ "@team-plain/typescript-sdk": "^5.9.0",
"@types/base-x": "^3.0.10",
"@types/bcryptjs": "^2.4.6",
"@types/buffer-crc32": "0.2.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 95e9a04cbc..28739ccff3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -113,8 +113,8 @@ importers:
specifier: ^8.17.3
'@team-plain/typescript-sdk':
- specifier: ^5.8.0
- version: 5.8.0
+ specifier: ^5.9.0
+ version: 5.9.0
'@types/base-x':
specifier: ^3.0.10
version: 3.0.10
@@ -5050,8 +5050,8 @@ packages:
resolution: {integrity: sha512-mPBodDGVL+fl6d90wUREepHa/7lhsghg2A3vFpakEhrhtbIlgNAZiMr7ccTgak5qbHqF14Fwy+W1yFWQt+WmYQ==}
engines: {node: '>=12'}
- '@team-plain/[email protected]':
- resolution: {integrity: sha512-qgDGX96yDsdTo5+Yh8R+rhtInmAm90w17607B2Ugik8Ij0H1wocjjp8xtMxHruSmms5ani43Y5xRxVFPSxYVeg==}
+ '@team-plain/[email protected]':
+ resolution: {integrity: sha512-AHSXyt1kDt74m9YKZBCRCd6cQjB8QjUNr9cehtR2QHzZ/8yXJPzawPJDqOQ3ms5KvwuYrBx2qT3e6C/zrQ5UtA==}
'@tediousjs/[email protected]':
resolution: {integrity: sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ==}
@@ -17332,7 +17332,7 @@ snapshots:
'@tanstack/[email protected]': {}
- '@team-plain/[email protected]':
+ '@team-plain/[email protected]':
dependencies:
'@graphql-typed-document-node/core': 3.2.0([email protected])
ajv: 8.12.0