The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Enhance partner profile member management by adding invite functionality and modals for inviting and revoking members.
Kiran K4c167ecc0429
diff --git a/apps/web/app/(ee)/api/partner-profile/invites/route.ts b/apps/web/app/(ee)/api/partner-profile/invites/route.tsindex 470a0b4464..648833e62f 100644--- a/apps/web/app/(ee)/api/partner-profile/invites/route.ts+++ b/apps/web/app/(ee)/api/partner-profile/invites/route.ts@@ -2,15 +2,16 @@ import { DubApiError } from "@/lib/api/errors";import { invitePartnerUser } from "@/lib/api/partners/invite-partner-user";import { parseRequestBody } from "@/lib/api/utils";import { withPartnerProfile } from "@/lib/auth/partner";+import {+ MAX_INVITES_PER_REQUEST,+ MAX_PARTNER_USERS,+} from "@/lib/partners/constants";import { invitePartnerMemberSchema } from "@/lib/zod/schemas/partner-profile";import { prisma } from "@dub/prisma";-import { isRejected } from "@dub/utils";+import { isRejected, pluralize } from "@dub/utils";import { NextResponse } from "next/server";import z from "zod";-const MAX_INVITES = 5;-const MAX_PARTNER_USERS = 25;-const removeInviteSchema = z.object({email: z.string().email(),});@@ -21,42 +22,58 @@ export const POST = withPartnerProfile(async ({ partner, req, session }) => {.array(invitePartnerMemberSchema).parse(await parseRequestBody(req));- if (invites.length > MAX_INVITES) {+ if (invites.length > MAX_INVITES_PER_REQUEST) {throw new DubApiError({code: "bad_request",message: "You can only invite up to 10 members at a time.",});}- const [invitesCount, partnerUsersCount, existingPartnerUsers] =- await Promise.all([- prisma.partnerInvite.count({- where: {- partnerId: partner.id,- },- }),+ const emails = Array.from(new Set([...invites.map(({ email }) => email)]));- prisma.partnerUser.count({- where: {- partnerId: partner.id,- },- }),+ const [+ invitesCount,+ partnerUsersCount,+ existingPartnerUsers,+ existingInvites,+ ] = await Promise.all([+ prisma.partnerInvite.count({+ where: {+ partnerId: partner.id,+ },+ }),- prisma.partnerUser.findMany({- where: {- partnerId: partner.id,- user: {- email: {- in: Array.from(new Set([...invites.map(({ email }) => email)])),- },+ prisma.partnerUser.count({+ where: {+ partnerId: partner.id,+ },+ }),++ prisma.partnerUser.findMany({+ where: {+ partnerId: partner.id,+ user: {+ email: {+ in: emails,},},- include: {- user: true,+ },+ include: {+ user: true,+ },+ }),++ prisma.partnerInvite.findMany({+ where: {+ partnerId: partner.id,+ email: {+ in: emails,},- }),- ]);+ },+ }),+ ]);+ // Check for users that already existconst existingPartnerUsersEmails = existingPartnerUsers.map(({ user }) => user?.email,);@@ -64,14 +81,24 @@ export const POST = withPartnerProfile(async ({ partner, req, session }) => {if (existingPartnerUsersEmails.length > 0) {throw new DubApiError({code: "bad_request",- message: `User ${existingPartnerUsersEmails.join(", ")} already exists in this partner profile.`,+ message: `${pluralize("User", existingPartnerUsersEmails.length)} ${existingPartnerUsersEmails.join(", ")} already ${pluralize("exists", existingPartnerUsersEmails.length, { plural: "exist" })} in this partner profile.`,+ });+ }++ // Check for pending invites+ const existingInviteEmails = existingInvites.map(({ email }) => email);++ if (existingInviteEmails.length > 0) {+ throw new DubApiError({+ code: "conflict",+ message: `${pluralize("User", existingInviteEmails.length)} ${existingInviteEmails.join(", ")} ${pluralize("has", existingInviteEmails.length, { plural: "have" })} already been invited to this partner profile.`,});}if (invitesCount + partnerUsersCount + invites.length > MAX_PARTNER_USERS) {throw new DubApiError({code: "exceeded_limit",- message: `You can only ${MAX_PARTNER_USERS} members in this partner profile.`,+ message: `You can only have ${MAX_PARTNER_USERS} members in this partner profile.`,});}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/members/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/members/page-client.tsxindex 36ef60b914..94f16da621 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/members/page-client.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/members/page-client.tsx@@ -6,7 +6,9 @@ import usePartnerProfileUsers, {import { PageContent } from "@/ui/layout/page-content";import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { useEditPartnerUserModal } from "@/ui/modals/edit-partner-user-modal";+import { useInvitePartnerMemberModal } from "@/ui/modals/invite-partner-member-modal";import { useRemovePartnerUserModal } from "@/ui/modals/remove-partner-user-modal";+import { useRevokePartnerInviteModal } from "@/ui/modals/revoke-partner-invite-modal";import { PartnerRole } from "@dub/prisma/client";import {Avatar,@@ -32,6 +34,9 @@ export function ProfileMembersPageClient() {const { data: session } = useSession();const { users, loading, error } = usePartnerProfileUsers();+ const { InvitePartnerMemberModal, setShowInvitePartnerMemberModal } =+ useInvitePartnerMemberModal();+const sortBy = searchParams.get("sortBy") || "name";const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";@@ -147,11 +152,23 @@ export function ProfileMembersPageClient() {});return (- <PageContent title="Members">- <PageWidthWrapper className="mb-20 flex flex-col gap-6">- <Table {...tableProps} table={table} />- </PageWidthWrapper>- </PageContent>+ <>+ <InvitePartnerMemberModal />+ <PageContent+ title="Members"+ controls={+ <Button+ text="Invite member"+ className="h-9 w-fit"+ onClick={() => setShowInvitePartnerMemberModal(true)}+ />+ }+ >+ <PageWidthWrapper className="mb-20 flex flex-col gap-6">+ <Table {...tableProps} table={table} />+ </PageWidthWrapper>+ </PageContent>+ </>);}@@ -160,18 +177,23 @@ function RowMenuButton({ row }: { row: Row<PartnerUserProps> }) {const { data: session } = useSession();const user = row.original;+ const isInvite = user.id === null;const { RemovePartnerUserModal, setShowRemovePartnerUserModal } =useRemovePartnerUserModal({user,});+ const { RevokePartnerInviteModal, setShowRevokePartnerInviteModal } =+ useRevokePartnerInviteModal({+ invite: user,+ });+const isCurrentUser = session?.user?.email === user.email;- const isInvite = user.id === null;return (<>- <RemovePartnerUserModal />+ {isInvite ? <RevokePartnerInviteModal /> : <RemovePartnerUserModal />}<PopoveropenPopover={isOpen}setOpenPopover={setIsOpen}@@ -190,7 +212,11 @@ function RowMenuButton({ row }: { row: Row<PartnerUserProps> }) {}variant="danger"onSelect={() => {- setShowRemovePartnerUserModal(true);+ if (isInvite) {+ setShowRevokePartnerInviteModal(true);+ } else {+ setShowRemovePartnerUserModal(true);+ }setIsOpen(false);}}/>diff --git a/apps/web/lib/partners/constants.ts b/apps/web/lib/partners/constants.tsindex f1fe2ca14b..da59b4c69b 100644--- a/apps/web/lib/partners/constants.ts+++ b/apps/web/lib/partners/constants.ts@@ -14,6 +14,9 @@ export const FAST_ACH_FEE_CENTS = 2500; // $25export const ALLOWED_MIN_WITHDRAWAL_AMOUNTS = [1000, 2500, 5000, 7500, 10000];export const ALLOWED_MIN_PAYOUT_AMOUNTS = [0, 2000, 5000, 10000];+export const MAX_INVITES_PER_REQUEST = 5;+export const MAX_PARTNER_USERS = 25;+// Direct debit payment types for Partner payoutexport const DIRECT_DEBIT_PAYMENT_TYPES_INFO: {type: Stripe.PaymentMethod.Type;diff --git a/apps/web/ui/modals/invite-partner-member-modal.tsx b/apps/web/ui/modals/invite-partner-member-modal.tsxnew file mode 100644index 0000000000..c13aa6446d--- /dev/null+++ b/apps/web/ui/modals/invite-partner-member-modal.tsx@@ -0,0 +1,187 @@+import { MAX_INVITES_PER_REQUEST } from "@/lib/partners/constants";+import usePartnerProfile from "@/lib/swr/use-partner-profile";+import { invitePartnerMemberSchema } from "@/lib/zod/schemas/partner-profile";+import { PartnerRole } from "@dub/prisma/client";+import { Button, Modal, useMediaQuery } from "@dub/ui";+import { Trash } from "@dub/ui/icons";+import { capitalize, pluralize } from "@dub/utils";+import { Plus } from "lucide-react";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { useFieldArray, useForm } from "react-hook-form";+import { toast } from "sonner";+import { mutate } from "swr";+import { z } from "zod";++type FormData = {+ invites: z.infer<typeof invitePartnerMemberSchema>[];+};++const partnerRoles: PartnerRole[] = ["owner", "member"];++function InvitePartnerMemberModal({+ showInvitePartnerMemberModal,+ setShowInvitePartnerMemberModal,+}: {+ showInvitePartnerMemberModal: boolean;+ setShowInvitePartnerMemberModal: Dispatch<SetStateAction<boolean>>;+}) {+ const { isMobile } = useMediaQuery();+ const { partner } = usePartnerProfile();+ const [isSubmitting, setIsSubmitting] = useState(false);++ const { control, register, handleSubmit } = useForm<FormData>({+ defaultValues: {+ invites: [{ email: "", role: "member" }],+ },+ });++ const { fields, append, remove } = useFieldArray({+ name: "invites",+ control,+ });++ const onSubmit = async (data: FormData) => {+ const invites = data.invites.filter(({ email }) => email.trim());+ setIsSubmitting(true);++ try {+ if (invites.length === 0) {+ throw new Error("Please enter at least one email address.");+ }++ const response = await fetch("/api/partner-profile/invites", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(invites),+ });++ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error.message);+ }++ await mutate("/api/partner-profile/users");+ toast.success(+ `${pluralize("Invitation", invites.length)} sent successfully!`,+ );+ setShowInvitePartnerMemberModal(false);+ } catch (error) {+ toast.error(error.message || "Failed to send invitations.");+ } finally {+ setIsSubmitting(false);+ }+ };++ return (+ <Modal+ showModal={showInvitePartnerMemberModal}+ setShowModal={setShowInvitePartnerMemberModal}+ className="max-w-md"+ >+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">+ <h3 className="text-lg font-medium">Invite Partner Members</h3>+ <p className="text-sm text-neutral-500">+ Invite team members to{" "}+ <span className="font-semibold text-black">{partner?.name}</span>.+ Invitations will be valid for 14 days.+ </p>+ </div>++ <form+ onSubmit={handleSubmit(onSubmit)}+ className="flex flex-col gap-6 bg-neutral-50 px-4 py-4 sm:px-6"+ >+ <div className="flex flex-col gap-2">+ <span className="text-sm font-medium text-neutral-700">+ {pluralize("Email", fields.length)}+ </span>++ {fields.map((field, index) => (+ <div key={field.id} className="flex items-end gap-2">+ <div className="flex-1">+ <div className="flex rounded-md shadow-sm">+ <input+ type="email"+ placeholder="[email protected]"+ autoFocus={index === 0 && !isMobile}+ autoComplete="off"+ className="flex-1 rounded-l-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ {...register(`invites.${index}.email`, {+ required: index === 0,+ })}+ />+ <select+ {...register(`invites.${index}.role`, {+ required: index === 0,+ })}+ defaultValue="member"+ className="rounded-r-md border border-l-0 border-neutral-300 bg-white pl-4 pr-8 text-neutral-600 focus:border-neutral-300 focus:outline-none focus:ring-0 sm:text-sm"+ >+ {partnerRoles.map((role) => (+ <option key={role} value={role}>+ {capitalize(role)}+ </option>+ ))}+ </select>+ </div>+ </div>+ {index > 0 && (+ <Button+ type="button"+ variant="outline"+ icon={<Trash className="size-4" />}+ className="h-10 w-10 shrink-0 p-0"+ onClick={() => remove(index)}+ />+ )}+ </div>+ ))}++ <Button+ type="button"+ className="h-9 w-fit"+ variant="secondary"+ icon={<Plus className="size-4" />}+ text="Add email"+ onClick={() => append({ email: "", role: "member" })}+ disabled={fields.length >= MAX_INVITES_PER_REQUEST}+ />+ </div>++ <Button+ type="submit"+ loading={isSubmitting}+ text={`Send ${pluralize("invite", fields.length)}`}+ />+ </form>+ </Modal>+ );+}++export function useInvitePartnerMemberModal() {+ const [showInvitePartnerMemberModal, setShowInvitePartnerMemberModal] =+ useState(false);++ const InvitePartnerMemberModalCallback = useCallback(() => {+ return (+ <InvitePartnerMemberModal+ showInvitePartnerMemberModal={showInvitePartnerMemberModal}+ setShowInvitePartnerMemberModal={setShowInvitePartnerMemberModal}+ />+ );+ }, [showInvitePartnerMemberModal, setShowInvitePartnerMemberModal]);++ return useMemo(+ () => ({+ setShowInvitePartnerMemberModal,+ InvitePartnerMemberModal: InvitePartnerMemberModalCallback,+ }),+ [setShowInvitePartnerMemberModal, InvitePartnerMemberModalCallback],+ );+}diff --git a/apps/web/ui/modals/remove-partner-user-modal.tsx b/apps/web/ui/modals/remove-partner-user-modal.tsxindex 3f47d579b3..7dd551d9f6 100644--- a/apps/web/ui/modals/remove-partner-user-modal.tsx+++ b/apps/web/ui/modals/remove-partner-user-modal.tsx@@ -1,8 +1,6 @@import usePartnerProfile from "@/lib/swr/use-partner-profile";import { PartnerUserProps } from "@/lib/swr/use-partner-profile-users";import { Avatar, Button, Modal, useMediaQuery } from "@dub/ui";-import { TriangleWarning } from "@dub/ui/icons";-import { timeAgo } from "@dub/utils";import { useSession } from "next-auth/react";import { useRouter } from "next/navigation";@@ -31,45 +29,40 @@ function RemovePartnerUserModal({const [removing, setRemoving] = useState(false);const { partner } = usePartnerProfile();- const isInvite = user.id === null;const self = session?.user?.email === user.email;const removePartnerUser = async () => {setRemoving(true);- try {- const url = isInvite- ? `/api/partner-profile/invites?email=${encodeURIComponent(user.email)}`- : `/api/partner-profile/users?userId=${user.id}`;-- const response = await fetch(url, {+ const response = await fetch(+ `/api/partner-profile/users?userId=${user.id}`,+ {method: "DELETE",headers: { "Content-Type": "application/json" },- });+ },+ );- if (response.ok) {- await mutate("/api/partner-profile/users");+ try {+ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error.message);+ }- if (self) {- // If user is removing themselves, redirect to home- router.push("/");- } else {- setShowRemovePartnerUserModal(false);- }+ await mutate("/api/partner-profile/users");- toast.success(- self- ? "You have left the partner profile!"- : isInvite- ? "Successfully revoked invitation!"- : "Successfully removed partner member!",- );+ if (self) {+ router.push("/");} else {- const { error } = await response.json();- toast.error(error.message);+ setShowRemovePartnerUserModal(false);}++ toast.success(+ self+ ? "You have left the partner profile!"+ : "Successfully removed partner member!",+ );} catch (error) {- toast.error("Failed to remove partner user");+ toast.error(error.message || "Failed to remove partner member.");} finally {setRemoving(false);}@@ -83,26 +76,16 @@ function RemovePartnerUserModal({><div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6"><h3 className="text-lg font-medium">- {isInvite- ? "Revoke Invitation"- : self- ? "Leave Partner Profile"- : "Remove Partner Member"}+ {self ? "Leave Partner Profile" : "Remove Partner Member"}</h3><p className="text-sm text-neutral-500">- {isInvite- ? "This will revoke "- : self- ? "You're about to leave "- : "This will remove "}+ {self ? "You're about to leave " : "This will remove "}<span className="font-semibold text-black">{self ? partner?.name : user.name || user.email}</span>- {isInvite- ? "'s invitation to join your partner profile. "- : self- ? ". You will lose all access to this partner profile. "- : " from your partner profile. "}+ {self+ ? ". You will lose all access to this partner profile. "+ : " from your partner profile. "}Are you sure you want to continue?</p></div>@@ -137,7 +120,8 @@ export function useRemovePartnerUserModal({}: {user: PartnerUserProps;}) {- const [showRemovePartnerUserModal, setShowRemovePartnerUserModal] = useState(false);+ const [showRemovePartnerUserModal, setShowRemovePartnerUserModal] =+ useState(false);const RemovePartnerUserModalCallback = useCallback(() => {return (diff --git a/apps/web/ui/modals/revoke-partner-invite-modal.tsx b/apps/web/ui/modals/revoke-partner-invite-modal.tsxnew file mode 100644index 0000000000..f9f4dfddc4--- /dev/null+++ b/apps/web/ui/modals/revoke-partner-invite-modal.tsx@@ -0,0 +1,121 @@+import { PartnerUserProps } from "@/lib/swr/use-partner-profile-users";+import { Avatar, Button, Modal, useMediaQuery } from "@dub/ui";++import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { toast } from "sonner";+import { mutate } from "swr";++function RevokePartnerInviteModal({+ showRevokePartnerInviteModal,+ setShowRevokePartnerInviteModal,+ invite,+}: {+ showRevokePartnerInviteModal: boolean;+ setShowRevokePartnerInviteModal: Dispatch<SetStateAction<boolean>>;+ invite: PartnerUserProps;+}) {+ const { isMobile } = useMediaQuery();+ const [revoking, setRevoking] = useState(false);++ const revokePartnerInvite = async () => {+ setRevoking(true);++ const response = await fetch(+ `/api/partner-profile/invites?email=${encodeURIComponent(invite.email)}`,+ {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ },+ );++ try {+ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error.message);+ }++ await mutate("/api/partner-profile/users");+ setShowRevokePartnerInviteModal(false);+ toast.success("Successfully revoked invitation!");+ } catch (error) {+ toast.error(error.message || "Failed to revoke invitation.");+ } finally {+ setRevoking(false);+ }+ };++ return (+ <Modal+ showModal={showRevokePartnerInviteModal}+ setShowModal={setShowRevokePartnerInviteModal}+ className="max-w-md"+ >+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">+ <h3 className="text-lg font-medium">Revoke Invitation</h3>+ <p className="text-sm text-neutral-500">+ This will revoke{" "}+ <span className="font-semibold text-black">+ {invite.name || invite.email}+ </span>+ 's invitation to join your partner profile. Are you sure you want to+ continue?+ </p>+ </div>++ <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-4 sm:px-6">+ <div className="relative flex items-center gap-2 space-x-3 rounded-md border border-neutral-300 bg-white px-4 py-2">+ <div className="flex items-center gap-2">+ <Avatar user={invite} className="size-10" />+ <div className="flex flex-col">+ <p className="text-sm font-medium text-neutral-900">+ {invite.name || invite.email}+ </p>+ <p className="text-xs text-neutral-500">{invite.email}</p>+ </div>+ </div>+ </div>++ <Button+ text="Revoke"+ variant="danger"+ autoFocus={!isMobile}+ loading={revoking}+ onClick={revokePartnerInvite}+ />+ </div>+ </Modal>+ );+}++export function useRevokePartnerInviteModal({+ invite,+}: {+ invite: PartnerUserProps;+}) {+ const [showRevokePartnerInviteModal, setShowRevokePartnerInviteModal] =+ useState(false);++ const RevokePartnerInviteModalCallback = useCallback(() => {+ return (+ <RevokePartnerInviteModal+ showRevokePartnerInviteModal={showRevokePartnerInviteModal}+ setShowRevokePartnerInviteModal={setShowRevokePartnerInviteModal}+ invite={invite}+ />+ );+ }, [showRevokePartnerInviteModal, setShowRevokePartnerInviteModal, invite]);++ return useMemo(+ () => ({+ setShowRevokePartnerInviteModal,+ RevokePartnerInviteModal: RevokePartnerInviteModalCallback,+ }),+ [setShowRevokePartnerInviteModal, RevokePartnerInviteModalCallback],+ );+}