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.

Add Plain callback API route

Steven Tey501e86dde35d
diff --git a/apps/web/app/api/callback/plain/route.ts b/apps/web/app/api/callback/plain/route.ts
new file mode 100644
index 0000000000..6518095e33
--- /dev/null
+++ b/apps/web/app/api/callback/plain/route.ts
@@ -0,0 +1,264 @@
+import { plain } from "@/lib/plain";
+import prisma from "@/lib/prisma";
+import { capitalize, formatDate } from "@dub/utils";
+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 userName = user.name || customer.email.split("@")[0];
+
+ await plain.upsertCustomer({
+ identifier: {
+ emailAddress: customer.email,
+ },
+ onCreate: {
+ fullName: userName,
+ shortName: userName.split(" ")[0],
+ email: {
+ email: customer.email,
+ isVerified: true,
+ },
+ externalId: user.id,
+ },
+ onUpdate: {
+ externalId: {
+ value: user.id,
+ },
+ },
+ });
+ }
+
+ const [topWorkspace, plainCustomer] = await Promise.all([
+ prisma.project.findFirst({
+ where: {
+ users: {
+ some: {
+ userId: customer.externalId,
+ },
+ },
+ },
+ include: {
+ _count: {
+ select: {
+ links: true,
+ domains: true,
+ tags: true,
+ users: true,
+ },
+ },
+ },
+ orderBy: {
+ usageLimit: "desc",
+ },
+ take: 1,
+ }),
+ plain.getCustomerByEmail({
+ email: customer.email,
+ }),
+ ]);
+
+ if (!topWorkspace) {
+ return NextResponse.json({
+ cards: [
+ {
+ key: "workspace",
+ components: [
+ plainEmptyContainer("User does not belong to any workspace."),
+ ],
+ },
+ ],
+ });
+ }
+
+ const {
+ name,
+ slug,
+ plan,
+ usage,
+ usageLimit,
+ linksUsage,
+ linksLimit,
+ domainsLimit,
+ tagsLimit,
+ usersLimit,
+ _count: { links, domains, tags, users },
+ } = topWorkspace;
+
+ if (plainCustomer.data) {
+ await plain.addCustomerToCustomerGroups({
+ customerId: plainCustomer.data.id,
+ customerGroupIdentifiers: [
+ {
+ customerGroupKey: plan.split(" ")[0],
+ },
+ ],
+ });
+ }
+
+ return NextResponse.json({
+ cards: [
+ {
+ key: "workspace",
+ components: [
+ ...plainCopySection({
+ label: "Workspace Name",
+ value: name,
+ }),
+ plainSpacer,
+ ...plainCopySection({
+ label: "Workspace Slug",
+ value: slug,
+ }),
+ plainDivider,
+ {
+ componentRow: {
+ rowMainContent: [
+ {
+ componentText: {
+ text: "Plan",
+ },
+ },
+ ],
+ rowAsideContent: [
+ {
+ componentBadge: {
+ badgeLabel: capitalize(plan),
+ badgeColor:
+ plan === "enterprise"
+ ? "RED"
+ : plan.startsWith("business")
+ ? "GREEN"
+ : plan === "pro"
+ ? "BLUE"
+ : "GREY",
+ },
+ },
+ ],
+ },
+ },
+ plainSpacer,
+ {
+ componentRow: {
+ rowMainContent: [
+ {
+ componentText: {
+ text: "Customer since",
+ },
+ },
+ ],
+ rowAsideContent: [
+ {
+ componentText: {
+ text: formatDate(topWorkspace.createdAt),
+ },
+ },
+ ],
+ },
+ },
+ plainDivider,
+ plainUsageSection({
+ usage,
+ usageLimit,
+ label: "Clicks",
+ sublabel: "This billing period",
+ color: "GREEN",
+ }),
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ plainUsageSection({
+ usage: linksUsage,
+ usageLimit: linksLimit,
+ label: "Links",
+ sublabel: "This billing period",
+ color: "YELLOW",
+ }),
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ plainUsageSection({
+ usage: links,
+ label: "Total Links",
+ color: "YELLOW",
+ }),
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ plainUsageSection({
+ usage: domains,
+ usageLimit: domainsLimit,
+ label: "Total Domains",
+ color: "BLUE",
+ }),
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ plainUsageSection({
+ usage: tags,
+ usageLimit: tagsLimit,
+ label: "Total Tags",
+ color: "RED",
+ }),
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ plainUsageSection({
+ usage: users,
+ usageLimit: usersLimit,
+ label: "Total Users",
+ color: "GREY",
+ }),
+ ],
+ },
+ ],
+ });
+}
diff --git a/apps/web/app/api/callback/plain/utils.ts b/apps/web/app/api/callback/plain/utils.ts
new file mode 100644
index 0000000000..84564850f5
--- /dev/null
+++ b/apps/web/app/api/callback/plain/utils.ts
@@ -0,0 +1,145 @@
+import { nFormatter } from "@dub/utils";
+
+export const plainDivider = {
+ componentDivider: {
+ dividerSpacingSize: "M",
+ },
+};
+
+export const plainEmptyContainer = (text: string) => ({
+ componentContainer: {
+ containerContent: [
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ {
+ componentPlainText: {
+ text: "No user found.",
+ size: "S",
+ },
+ },
+ {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+ },
+ ],
+ },
+});
+
+export const plainSpacer = {
+ componentSpacer: {
+ spacerSize: "M",
+ },
+};
+
+export const plainTextSection = ({
+ label,
+ value,
+}: {
+ label: string;
+ value: string;
+}) => ({
+ componentRow: {
+ rowMainContent: [
+ {
+ componentText: {
+ textSize: "M",
+ textColor: "MUTED",
+ text: label,
+ },
+ },
+ ],
+ rowAsideContent: [
+ {
+ componentText: {
+ textSize: "M",
+ textColor: "NORMAL",
+ text: value,
+ },
+ },
+ ],
+ },
+});
+
+export const plainCopySection = ({
+ label,
+ value,
+}: {
+ label: string;
+ value: string;
+}) => [
+ {
+ componentText: {
+ text: label,
+ textSize: "S",
+ textColor: "MUTED",
+ },
+ },
+ {
+ componentRow: {
+ rowMainContent: [
+ {
+ componentText: {
+ text: value,
+ },
+ },
+ ],
+ rowAsideContent: [
+ {
+ componentCopyButton: {
+ copyButtonTooltipLabel: `Copy ${label}`,
+ copyButtonValue: value,
+ },
+ },
+ ],
+ },
+ },
+];
+
+export const plainUsageSection = ({
+ usage,
+ usageLimit,
+ label,
+ sublabel,
+ color,
+}: {
+ usage: number;
+ usageLimit?: number;
+ label: string;
+ sublabel?: string;
+ color: "GREY" | "GREEN" | "YELLOW" | "RED" | "BLUE";
+}) => ({
+ componentRow: {
+ rowMainContent: [
+ {
+ componentText: {
+ textSize: "M",
+ textColor: "NORMAL",
+ text: label,
+ },
+ },
+ ...(sublabel
+ ? [
+ {
+ componentText: {
+ textSize: "S",
+ textColor: "MUTED",
+ text: sublabel,
+ },
+ },
+ ]
+ : []),
+ ],
+ rowAsideContent: [
+ {
+ componentBadge: {
+ badgeLabel: `${nFormatter(usage, { full: true })}${usageLimit ? ` of ${nFormatter(usageLimit, { full: true })}` : ""}`,
+ badgeColor: color,
+ },
+ },
+ ],
+ },
+});
diff --git a/apps/web/lib/plain.ts b/apps/web/lib/plain.ts
new file mode 100644
index 0000000000..ab30d9df17
--- /dev/null
+++ b/apps/web/lib/plain.ts
@@ -0,0 +1,5 @@
+import { PlainClient } from "@team-plain/typescript-sdk";
+
+export const plain = new PlainClient({
+ apiKey: process.env.PLAIN_API_KEY as string,
+});
diff --git a/apps/web/package.json b/apps/web/package.json
index bd43e710fb..5d94516358 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -24,6 +24,7 @@
"@splinetool/react-spline": "^2.2.6",
"@splinetool/runtime": "^1.0.87",
"@stripe/stripe-js": "^1.44.1",
+ "@team-plain/typescript-sdk": "^3.9.0",
"@upstash/qstash": "^2.3.0",
"@upstash/ratelimit": "^0.3.6",
"@upstash/redis": "^1.25.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3beb32fb94..1ca31034f1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -73,6 +73,9 @@ importers:
'@stripe/stripe-js':
specifier: ^1.44.1
version: 1.44.1
+ '@team-plain/typescript-sdk':
+ specifier: ^3.9.0
+ version: 3.9.0
'@upstash/qstash':
specifier: ^2.3.0
version: 2.3.0
@@ -3282,6 +3285,14 @@ packages:
- supports-color
dev: false
+ /@graphql-typed-document-node/[email protected]([email protected]):
+ resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==}
+ peerDependencies:
+ graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
+ dependencies:
+ graphql: 16.8.1
+ dev: false
+
resolution: {integrity: sha512-iouYNlPxRAwZ2XboDT+OfRKHuaKHiqjB5VFYZ0NFrHkbEF+AV3muIUY9olQsp8uxU4VvRCMiRk9ftzFDGb61aw==}
engines: {node: ^8.13.0 || >=10.10.0}
@@ -6805,6 +6816,16 @@ packages:
tailwindcss: 3.3.3
dev: false
+ /@team-plain/[email protected]:
+ resolution: {integrity: sha512-fS22kpwPuKzXpIHs+tK+974Wx/+CPs3+vmxW1kldmuXGWZ1p8V4PdYC0R8AC0uiG9f48VX4gq6x1Uw2isPpM+w==}
+ dependencies:
+ '@graphql-typed-document-node/core': 3.2.0([email protected])
+ ajv: 8.12.0
+ ajv-formats: 2.1.1([email protected])
+ graphql: 16.8.1
+ zod: 3.22.4
+ dev: false
+
/@tediousjs/[email protected]:
resolution: {integrity: sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ==}
dev: false
@@ -7594,6 +7615,17 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
+ peerDependencies:
+ ajv: ^8.0.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+ dependencies:
+ ajv: 8.12.0
+ dev: false
+
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
peerDependencies:
@@ -7610,6 +7642,15 @@ packages:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
+ resolution: {integrity: sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==}
+ dependencies:
+ fast-deep-equal: 3.1.3
+ json-schema-traverse: 1.0.0
+ require-from-string: 2.0.2
+ uri-js: 4.4.1
+ dev: false
+
resolution: {integrity: sha512-hCv9AqTQ8ycjpSd3upOJd7vFwW1JaoYQ7tpham03GJ1ca8/65rqn0RpaWpItOAd6ylW9wAw6luXYPJIyPFVOww==}
dev: false
@@ -10066,6 +10107,11 @@ packages:
resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
+ resolution: {integrity: sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==}
+ engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
+ dev: false
+
resolution: {integrity: sha512-KcFVtoP1CVFtQu0aSk3AyAt2og66PFhZAlkUOuWKwzMLoulHXG5W5wE5xAnHb+yl3/wEFoqGW7/cDGMU8igDZQ==}
engines: {node: '>=14.0.0'}
@@ -10851,6 +10897,10 @@ packages:
resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}
+ resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+ dev: false
+
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
@@ -13055,7 +13105,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
+ prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
dev: true
@@ -13850,6 +13900,11 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
+ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
+ engines: {node: '>=0.10.0'}
+ dev: false
+
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
dev: false