The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
plainCallbackSchema, fix sidebar layout when UpgradeBanner is shown
Steven Teyc4614d97e569
diff --git a/apps/web/app/api/callback/plain/partner/route.ts b/apps/web/app/api/callback/plain/partner/route.tsindex 9b049da0c6..40469b1dae 100644--- a/apps/web/app/api/callback/plain/partner/route.ts+++ b/apps/web/app/api/callback/plain/partner/route.ts@@ -5,6 +5,7 @@ import { COUNTRIES, currencyFormatter, formatDate } from "@dub/utils";import { uiComponent } from "@team-plain/typescript-sdk";import { NextRequest, NextResponse } from "next/server";import {+ plainCallbackSchema,plainCopySection,plainDivider,plainEmptyContainer,@@ -19,11 +20,7 @@ export async function POST(req: NextRequest) {return new Response("Unauthorized", { status: 401 });}- let { cardKeys, customer } = await req.json();-- if (!cardKeys || !customer) {- return new Response("Invalid payload", { status: 400 });- }+ let { customer } = plainCallbackSchema.parse(await req.json());// if there's no externalId yet, try to find the user by email and set itif (!customer.externalId) {@@ -52,42 +49,37 @@ export async function POST(req: NextRequest) {});}- const [plainCustomer, partnerProfile] = await Promise.all([- plain.getCustomerByExternalId({- externalId: customer.externalId,- }),- prisma.partner.findFirst({- where: {- users: {- some: {- userId: customer.externalId,- },+ const partnerProfile = await prisma.partner.findFirst({+ where: {+ users: {+ some: {+ userId: customer.externalId,},},- include: {- programs: {- select: {- program: {- select: {- name: true,- },+ },+ include: {+ programs: {+ select: {+ program: {+ select: {+ name: true,},- createdAt: true,- totalCommissions: true,},- where: {- totalCommissions: {- gt: 0,- },- },- orderBy: {- totalCommissions: "desc",+ createdAt: true,+ totalCommissions: true,+ },+ where: {+ totalCommissions: {+ gt: 0,},- take: 5,},+ orderBy: {+ totalCommissions: "desc",+ },+ take: 5,},- }),- ]);+ },+ });if (!partnerProfile) {return NextResponse.json({@@ -110,16 +102,14 @@ export async function POST(req: NextRequest) {payoutsEnabledAt,} = partnerProfile;- if (plainCustomer.data) {- await plain.addCustomerToCustomerGroups({- customerId: plainCustomer.data.id,- customerGroupIdentifiers: [- {- customerGroupKey: "partners.dub.co",- },- ],- });- }+ await plain.addCustomerToCustomerGroups({+ customerId: customer.id,+ customerGroupIdentifiers: [+ {+ customerGroupKey: "partners.dub.co",+ },+ ],+ });return NextResponse.json({cards: [diff --git a/apps/web/app/api/callback/plain/utils.ts b/apps/web/app/api/callback/plain/utils.tsindex f74904c8f3..78c7e68556 100644--- a/apps/web/app/api/callback/plain/utils.ts+++ b/apps/web/app/api/callback/plain/utils.ts@@ -1,5 +1,14 @@import { nFormatter } from "@dub/utils";import { uiComponent } from "@team-plain/typescript-sdk";+import { z } from "zod";++export const plainCallbackSchema = z.object({+ customer: z.object({+ id: z.string(),+ email: z.string().email(),+ externalId: z.string().nullish(),+ }),+});export const plainDivider = uiComponent.divider({spacingSize: "M",diff --git a/apps/web/app/api/callback/plain/workspace/route.ts b/apps/web/app/api/callback/plain/workspace/route.tsindex a48ed9fcab..4161e03f32 100644--- a/apps/web/app/api/callback/plain/workspace/route.ts+++ b/apps/web/app/api/callback/plain/workspace/route.ts@@ -7,6 +7,7 @@ import { uiComponent } from "@team-plain/typescript-sdk";import { waitUntil } from "@vercel/functions";import { NextRequest, NextResponse } from "next/server";import {+ plainCallbackSchema,plainCopySection,plainDivider,plainEmptyContainer,@@ -21,41 +22,36 @@ export async function POST(req: NextRequest) {return new Response("Unauthorized", { status: 401 });}- let { cardKeys, customer } = await req.json();+ let { customer } = plainCallbackSchema.parse(await req.json());- if (!cardKeys || !customer) {- return new Response("Invalid payload", { status: 400 });- }+ const user = await prisma.user.findUnique({+ where: customer.externalId+ ? { id: customer.externalId }+ : { email: customer.email },+ });- // 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 || !user.email) {+ return NextResponse.json({+ cards: [+ {+ key: "workspace",+ components: [plainEmptyContainer("No user found.")],+ },+ ],});+ }- if (!user || !user.email) {- return NextResponse.json({- cards: [- {- key: "workspace",- components: [plainEmptyContainer("No user found.")],- },- ],- });- }+ if (!customer.externalId) {customer.externalId = user.id;-await upsertPlainCustomer({id: user.id,name: user.name,email: user.email,});-- waitUntil(syncUserPlanToPlain(user));}+ waitUntil(syncUserPlanToPlain(user));+const topWorkspace = await prisma.project.findFirst({where: {users: {diff --git a/apps/web/lib/plain/sync-user-plan.ts b/apps/web/lib/plain/sync-user-plan.tsindex e09a3a283d..794afe2969 100644--- a/apps/web/lib/plain/sync-user-plan.ts+++ b/apps/web/lib/plain/sync-user-plan.ts@@ -9,15 +9,19 @@ export const syncUserPlanToPlain = async (user: PlainUser) => {return;}- await upsertPlainCustomer({+ const { data } = await upsertPlainCustomer({id: user.id,name: user.name,email: user.email,});- const plainCustomer = await plain.getCustomerByExternalId({- externalId: user.id,- });+ if (!data) {+ console.log(+ `Failed to upsert plain customer for user ${user.id}, skipping sync...`,+ );+ return;+ }+ const plainCustomer = data.customer;let companyDomainName: string | undefined;if (!isGenericEmail(user.email)) {@@ -52,34 +56,39 @@ export const syncUserPlanToPlain = async (user: PlainUser) => {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(),- },- }),- ]- : []),- ]);+ await Promise.allSettled([+ plain.addCustomerToCustomerGroups({+ customerId: plainCustomer.id,+ customerGroupIdentifiers: [+ {+ customerGroupKey: "app.dub.co",+ },+ ],+ }),+ ...(companyDomainName+ ? [+ plain.updateCompanyTier({+ companyIdentifier: {+ companyDomainName,+ },+ tierIdentifier: {+ externalId: topWorkspace.plan.split(" ")[0].toLowerCase(),+ },+ }),+ ]+ : []),+ ]);- console.log(- `Synced user ${user.id}'s plan in Plain to ${topWorkspace.plan}`,- );- }+ await plain.addCustomerToCustomerGroups({+ customerId: plainCustomer.id,+ customerGroupIdentifiers: [+ {+ customerGroupKey: "app.dub.co",+ },+ ],+ });++ console.log(`Synced user ${user.id}'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.tsindex 7246703f85..5a74692fb9 100644--- a/apps/web/lib/plain/upsert-plain-customer.ts+++ b/apps/web/lib/plain/upsert-plain-customer.ts@@ -19,6 +19,17 @@ export const upsertPlainCustomer = async (},externalId: user.id,},- onUpdate: {},+ onUpdate: {+ fullName: {+ value: fullName,+ },+ shortName: {+ value: shortName,+ },+ email: {+ email: user.email,+ isVerified: true,+ },+ },});};diff --git a/apps/web/lib/swr/use-workspace.ts b/apps/web/lib/swr/use-workspace.tsindex 657bec8959..8006749ac5 100644--- a/apps/web/lib/swr/use-workspace.ts+++ b/apps/web/lib/swr/use-workspace.ts@@ -35,11 +35,16 @@ export default function useWorkspace({isOwner: workspace?.users && workspace.users[0].role === "owner",exceededClicks: workspace && workspace.usage >= workspace.usageLimit,exceededLinks: workspace && workspace.linksUsage >= workspace.linksLimit,+ exceededPayouts:+ workspace?.payoutsLimit &&+ workspace.payoutsUsage >= workspace.payoutsLimit+ ? true+ : false,exceededAI: workspace && workspace.aiUsage >= workspace.aiLimit,exceededDomains:workspace?.domains && workspace.domains.length >= workspace.domainsLimit,isMegaWorkspace:- workspace && workspace.totalLinks > MEGA_WORKSPACE_LINKS_LIMIT,+ workspace && workspace.totalLinks >= MEGA_WORKSPACE_LINKS_LIMIT,error,defaultFolderId: workspace?.users && workspace.users[0].defaultFolderId,mutate,diff --git a/apps/web/ui/layout/main-nav.tsx b/apps/web/ui/layout/main-nav.tsxindex d3eaa561a1..fd8eedeca4 100644--- a/apps/web/ui/layout/main-nav.tsx+++ b/apps/web/ui/layout/main-nav.tsx@@ -13,6 +13,7 @@ import {useEffect,useState,} from "react";+import { useUpgradeBannerVisible } from "./upgrade-banner";type SideNavContext = {isOpen: boolean;@@ -41,6 +42,7 @@ export function MainNav({const { isMobile } = useMediaQuery();const [isOpen, setIsOpen] = useState(false);+ const isUpgradeBannerVisible = useUpgradeBannerVisible();// Prevent body scroll when side nav is openuseEffect(() => {@@ -57,10 +59,13 @@ export function MainNav({{/* Side nav backdrop */}<divclassName={cn(- "fixed left-0 top-0 z-50 h-dvh w-screen transition-[background-color,backdrop-filter] md:sticky md:z-auto md:w-full md:bg-transparent",+ "fixed left-0 z-50 w-screen transition-[background-color,backdrop-filter] md:sticky md:z-auto md:w-full md:bg-transparent",isOpen? "bg-black/20 backdrop-blur-sm": "bg-transparent max-md:pointer-events-none",+ isUpgradeBannerVisible+ ? "top-12 h-[calc(100dvh-48px)]"+ : "top-0 h-dvh",)}onClick={(e) => {if (e.target === e.currentTarget) {@@ -79,7 +84,12 @@ export function MainNav({<Sidebar toolContent={toolContent} newsContent={newsContent} /></div></div>- <div className="h-screen bg-neutral-200 pb-[var(--page-bottom-margin)] pt-[var(--page-top-margin)] [--page-bottom-margin:0px] [--page-top-margin:0px] md:pb-2 md:pr-2 md:[--page-bottom-margin:0.5rem] md:[--page-top-margin:0.5rem]">+ <div+ className={cn(+ "bg-neutral-200 pb-[var(--page-bottom-margin)] pt-[var(--page-top-margin)] [--page-bottom-margin:0px] [--page-top-margin:0px] md:pb-2 md:pr-2 md:[--page-bottom-margin:0.5rem] md:[--page-top-margin:0.5rem]",+ isUpgradeBannerVisible ? "mt-12 h-[calc(100vh-48px)]" : "h-screen",+ )}+ ><div className="relative h-full overflow-y-auto bg-neutral-100 pt-px md:rounded-xl md:bg-white"><SideNavContext.Provider value={{ isOpen, setIsOpen }}>{children}diff --git a/apps/web/ui/layout/upgrade-banner.tsx b/apps/web/ui/layout/upgrade-banner.tsxindex 6d89ea62b7..43fee7149c 100644--- a/apps/web/ui/layout/upgrade-banner.tsx+++ b/apps/web/ui/layout/upgrade-banner.tsx@@ -5,41 +5,30 @@ import { Crown } from "@dub/ui";import { cn } from "@dub/utils";import { motion } from "motion/react";import Link from "next/link";-import { useMemo } from "react";+import ManageSubscriptionButton from "../workspaces/manage-subscription-button";++export function useUpgradeBannerVisible() {+ const { exceededClicks, exceededLinks, exceededPayouts, paymentFailedAt } =+ useWorkspace();++ const needsUpgrade = exceededClicks || exceededLinks || exceededPayouts;+ return needsUpgrade || !!paymentFailedAt;+}export function UpgradeBanner() {- const {- slug,- plan,- usage,- usageLimit,- linksUsage,- linksLimit,- payoutsUsage,- payoutsLimit,- paymentFailedAt,- } = useWorkspace();+ const { slug, exceededClicks, exceededLinks, exceededPayouts } =+ useWorkspace();- const needsUpgrade = useMemo(- () =>- [- [usage, usageLimit],- [linksUsage, linksLimit],- [payoutsUsage, payoutsLimit],- ].some(- ([usage, limit]) =>- usage !== undefined && limit !== undefined && usage > limit,- ),- [usage, usageLimit, linksUsage, linksLimit, payoutsUsage, payoutsLimit],- );+ const needsUpgrade = exceededClicks || exceededLinks || exceededPayouts;- if (!needsUpgrade && !paymentFailedAt) return null;+ const isVisible = useUpgradeBannerVisible();+ if (!isVisible) return null;return (<motion.div- initial={{ height: 0 }}- animate={{ height: "48px" }}- className="text-content-inverted bg-bg-inverted flex h-12 items-center justify-center overflow-hidden px-6"+ initial={{ transform: "translateY(-100%)" }}+ animate={{ transform: "translateY(0)" }}+ className="text-content-inverted bg-bg-inverted fixed left-0 right-0 top-0 z-50 flex h-12 items-center justify-center overflow-hidden px-6">{needsUpgrade && <Crown className="mr-2 size-4 shrink-0" />}<p className="text-sm">@@ -47,7 +36,9 @@ export function UpgradeBanner() {<>You’ve hit the{" "}<Link href={`/${slug}/settings/billing`} className="underline">- monthly usage limit+ monthly{" "}+ {exceededClicks ? "events" : exceededLinks ? "links" : "payouts"}{" "}+ limit</Link><span className="xs:inline hidden"> on your current plan</span><span className="hidden md:inline">@@ -61,19 +52,23 @@ export function UpgradeBanner() {</>)}</p>- <Link- href={- needsUpgrade- ? `/${slug}/settings/billing/upgrade`- : `/${slug}/settings/billing`- }- className={cn(- "bg-bg-default text-content-emphasis border-border-subtle ml-4 flex h-7 items-center justify-center rounded-lg border px-2.5 text-sm font-medium",- "hover:bg-bg-subtle transition-colors duration-150",- )}- >- {needsUpgrade ? "Upgrade" : "Update Payment Method"}- </Link>+ {needsUpgrade ? (+ <Link+ href={`/${slug}/settings/billing/upgrade`}+ className={cn(+ "bg-bg-default text-content-emphasis border-border-subtle ml-4 flex h-7 items-center justify-center rounded-lg border px-2.5 text-sm font-medium",+ "hover:bg-bg-subtle transition-colors duration-150",+ )}+ >+ Upgrade+ </Link>+ ) : (+ <ManageSubscriptionButton+ text="Update Payment Method"+ variant="secondary"+ className="ml-4 h-7 w-fit px-2.5 text-sm font-medium"+ />+ )}</motion.div>);}diff --git a/apps/web/ui/workspaces/manage-subscription-button.tsx b/apps/web/ui/workspaces/manage-subscription-button.tsxindex c2c99ccc21..eec87a63e8 100644--- a/apps/web/ui/workspaces/manage-subscription-button.tsx+++ b/apps/web/ui/workspaces/manage-subscription-button.tsx@@ -17,7 +17,7 @@ export default function ManageSubscriptionButton(props: ButtonProps) {{...props}text={props.text || "Manage Subscription"}variant={props.variant || "secondary"}- className={cn(props.className, "h-9")}+ className={cn("h-9", props.className)}onClick={() => {setClicked(true);fetch(`/api/workspaces/${workspaceId}/billing/manage`, {