The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Support deleting partner link if no stats (#3345)
Steven Tey65cde14053f5
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.tsindex b596c32f55..410b8b0832 100644--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts@@ -1,5 +1,5 @@import { DubApiError, ErrorCodes } from "@/lib/api/errors";-import { processLink, updateLink } from "@/lib/api/links";+import { deleteLink, processLink, updateLink } from "@/lib/api/links";import { validatePartnerLinkUrl } from "@/lib/api/links/validate-partner-link-url";import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { parseRequestBody } from "@/lib/api/utils";@@ -154,3 +154,46 @@ export const PATCH = withPartnerProfile(return NextResponse.json(PartnerProfileLinkSchema.parse(partnerLink));},);++// DELETE /api/partner-profile/[programId]/links/[linkId] - delete a link for a partner+export const DELETE = withPartnerProfile(async ({ partner, params }) => {+ const { programId, linkId } = params;++ const { links, status } = await getProgramEnrollmentOrThrow({+ partnerId: partner.id,+ programId,+ include: {+ links: true,+ },+ });++ if (["banned", "deactivated"].includes(status)) {+ throw new DubApiError({+ code: "forbidden",+ message: "You are banned from this program.",+ });+ }++ const link = links.find((link) => link.id === linkId);++ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });+ }++ // Check if link has any clicks, leads, or sales+ if (link.clicks > 0 || link.leads > 0 || link.saleAmount > 0) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "You can only delete links with 0 clicks, 0 leads, and $0 in sales.",+ });+ }++ // Delete the link+ await deleteLink(link.id);++ return NextResponse.json({ id: link.id });+});diff --git a/apps/web/app/(ee)/api/partners/links/upsert/route.ts b/apps/web/app/(ee)/api/partners/links/upsert/route.tsindex 57640199b5..9493001a44 100644--- a/apps/web/app/(ee)/api/partners/links/upsert/route.ts+++ b/apps/web/app/(ee)/api/partners/links/upsert/route.ts@@ -41,7 +41,7 @@ export const PUT = withWorkspace(throw new DubApiError({code: "bad_request",message:- "You need to set a domain and url for this program before creating a partner.",+ "You need to set a domain and url for this program before upserting a partner link.",});}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-controls.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-controls.tsxindex c7e8a185b2..f501136c44 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-controls.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/links/partner-link-controls.tsx@@ -1,9 +1,10 @@import { PartnerProfileLinkProps } from "@/lib/types";+import { useDeletePartnerLinkModal } from "@/ui/modals/delete-partner-link-modal";import { usePartnerLinkModal } from "@/ui/modals/partner-link-modal";import { usePartnerLinkQRModal } from "@/ui/modals/partner-link-qr-modal";import { ThreeDots } from "@/ui/shared/icons";import { Button, PenWriting, Popover, useKeyboardShortcut } from "@dub/ui";-import { QRCode } from "@dub/ui/icons";+import { QRCode, Trash } from "@dub/ui/icons";import { CopyPlus } from "lucide-react";export function PartnerLinkControls({@@ -39,8 +40,19 @@ export function PartnerLinkControls({},});+ const canDelete =+ link.clicks === 0 && link.leads === 0 && link.saleAmount === 0;++ const { setShowDeletePartnerLinkModal, DeletePartnerLinkModal } =+ useDeletePartnerLinkModal({+ link,+ onSuccess: () => {+ setOpenPopover(false);+ },+ });+useKeyboardShortcut(- ["e", "q", "d"],+ ["e", "q", "d", "x"],(e) => {setOpenPopover(false);switch (e.key) {@@ -53,6 +65,11 @@ export function PartnerLinkControls({case "d":setShowDuplicateLinkModal(true);break;+ case "x":+ if (canDelete) {+ setShowDeletePartnerLinkModal(true);+ }+ break;}},{@@ -63,6 +80,7 @@ export function PartnerLinkControls({return (<div className="flex justify-end">+ <DeletePartnerLinkModal /><LinkQRModal /><PartnerLinkModal /><DuplicateLinkModal />@@ -103,6 +121,23 @@ export function PartnerLinkControls({shortcut="D"className="h-9 px-2 font-medium"/>+ <Button+ text="Delete"+ variant="danger-outline"+ onClick={() => {+ setOpenPopover(false);+ setShowDeletePartnerLinkModal(true);+ }}+ icon={<Trash className="size-4" />}+ shortcut="X"+ className="h-9 px-2 font-medium"+ disabled={!canDelete}+ disabledTooltip={+ !canDelete+ ? "You can only delete links with 0 clicks, 0 leads, and $0 in sales."+ : undefined+ }+ /></div></div>}diff --git a/apps/web/lib/openapi/partners/upsert-partner-link.ts b/apps/web/lib/openapi/partners/upsert-partner-link.tsindex 4864636029..1a170b47b4 100644--- a/apps/web/lib/openapi/partners/upsert-partner-link.ts+++ b/apps/web/lib/openapi/partners/upsert-partner-link.ts@@ -1,6 +1,6 @@import { openApiErrorResponses } from "@/lib/openapi/responses";import { LinkSchema } from "@/lib/zod/schemas/links";-import { createPartnerLinkSchema } from "@/lib/zod/schemas/partners";+import { upsertPartnerLinkSchema } from "@/lib/zod/schemas/partners";import { ZodOpenApiOperationObject } from "zod-openapi";export const upsertPartnerLink: ZodOpenApiOperationObject = {@@ -12,7 +12,7 @@ export const upsertPartnerLink: ZodOpenApiOperationObject = {requestBody: {content: {"application/json": {- schema: createPartnerLinkSchema,+ schema: upsertPartnerLinkSchema,},},},diff --git a/apps/web/ui/links/link-controls.tsx b/apps/web/ui/links/link-controls.tsxindex fe1f128d0a..c74b33f08b 100644--- a/apps/web/ui/links/link-controls.tsx+++ b/apps/web/ui/links/link-controls.tsx@@ -18,9 +18,10 @@ import {Copy,FolderBookmark,QRCode,+ Trash,} from "@dub/ui/icons";import { cn, isDubDomain, nanoid } from "@dub/utils";-import { CopyPlus, Delete, FolderInput } from "lucide-react";+import { CopyPlus, FolderInput } from "lucide-react";import { useParams, useRouter } from "next/navigation";import { useCallback } from "react";import { toast } from "sonner";@@ -336,7 +337,7 @@ export function LinkControls({setOpenPopover(false);setShowDeleteLinkModal(true);}}- icon={<Delete className="size-4" />}+ icon={<Trash className="size-4" />}shortcut="X"className="h-9 px-2 font-medium"disabled={isRootLink || isProgramLinkWithLeads}@@ -358,7 +359,7 @@ export function LinkControls({onClick={() => handleBanLink()}className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-red-600 transition-all duration-75 hover:bg-red-600 hover:text-white">- <IconMenu text="Ban" icon={<Delete className="size-4" />} />+ <IconMenu text="Ban" icon={<Trash className="size-4" />} /><kbd className="hidden rounded bg-red-100 px-2 py-0.5 text-xs font-light text-red-600 transition-all duration-75 group-hover:bg-red-500 group-hover:text-white sm:inline-block">B</kbd>diff --git a/apps/web/ui/modals/delete-partner-link-modal.tsx b/apps/web/ui/modals/delete-partner-link-modal.tsxnew file mode 100644index 0000000000..ee374673a1--- /dev/null+++ b/apps/web/ui/modals/delete-partner-link-modal.tsx@@ -0,0 +1,197 @@+import { constructPartnerLink } from "@/lib/partners/construct-partner-link";+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";+import { PartnerProfileLinkProps } from "@/lib/types";+import { SimpleLinkCard } from "@/ui/links/simple-link-card";+import { Button, Modal, useMediaQuery } from "@dub/ui";+import { getPrettyUrl } from "@dub/utils";+import { useParams } from "next/navigation";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { toast } from "sonner";+import { mutate } from "swr";++type DeletePartnerLinkModalProps = {+ showDeletePartnerLinkModal: boolean;+ setShowDeletePartnerLinkModal: Dispatch<SetStateAction<boolean>>;+ link: PartnerProfileLinkProps;+ onSuccess?: () => void;+};++function DeletePartnerLinkModal(props: DeletePartnerLinkModalProps) {+ return (+ <Modal+ showModal={props.showDeletePartnerLinkModal}+ setShowModal={props.setShowDeletePartnerLinkModal}+ >+ <DeletePartnerLinkModalInner {...props} />+ </Modal>+ );+}++function DeletePartnerLinkModalInner({+ setShowDeletePartnerLinkModal,+ link,+ onSuccess,+}: DeletePartnerLinkModalProps) {+ const { programSlug } = useParams();+ const { programEnrollment } = useProgramEnrollment();+ const { isMobile } = useMediaQuery();+ const [deleting, setDeleting] = useState(false);++ const partnerLink = constructPartnerLink({+ group: programEnrollment?.group,+ link,+ });++ const pattern = getPrettyUrl(partnerLink);++ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();+ if (!programEnrollment?.program.id) return;++ setDeleting(true);++ try {+ const response = await fetch(+ `/api/partner-profile/programs/${programEnrollment.program.id}/links/${link.id}`,+ {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ },+ );++ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error.message);+ }++ await mutate(`/api/partner-profile/programs/${programSlug}/links`);+ setShowDeletePartnerLinkModal(false);+ onSuccess?.();+ toast.success("Link deleted successfully!");+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to delete link. Please try again.",+ );+ } finally {+ setDeleting(false);+ }+ };++ return (+ <>+ <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">+ <h3 className="text-lg font-medium leading-none">Delete link</h3>+ </div>++ <div className="bg-neutral-50 p-4 sm:p-6">+ <p className="text-sm text-neutral-800">+ Are you sure you want to delete this link?+ </p>++ <p className="mt-4 text-sm font-medium text-neutral-800">+ Deleting this link will remove all of its analytics. This action+ cannot be undone – proceed with caution.+ </p>++ <div className="mt-4 rounded-2xl border border-neutral-200 p-2">+ <SimpleLinkCard+ link={{+ shortLink: partnerLink,+ url: link.url,+ }}+ />+ </div>+ </div>++ <form+ onSubmit={handleSubmit}+ className="flex flex-col bg-neutral-50 text-left"+ >+ <div className="px-4 sm:px-6">+ <label+ htmlFor="verification"+ className="block text-sm text-neutral-700"+ >+ To verify, type <span className="font-semibold">{pattern}</span>{" "}+ below+ </label>+ <div className="relative mt-1.5 rounded-md shadow-sm">+ <input+ type="text"+ name="verification"+ id="verification"+ pattern={pattern}+ required+ autoFocus={!isMobile}+ autoComplete="off"+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ />+ </div>+ </div>++ <div className="mt-8 flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">+ <Button+ onClick={() => setShowDeletePartnerLinkModal(false)}+ variant="secondary"+ text="Cancel"+ className="h-8 w-fit px-3"+ />+ <Button+ variant="danger"+ text="Delete link"+ loading={deleting}+ className="h-8 w-fit px-3"+ />+ </div>+ </form>+ </>+ );+}++export function useDeletePartnerLinkModal({+ link,+ onSuccess,+}: {+ link?: PartnerProfileLinkProps;+ onSuccess?: () => void;+}) {+ const [showDeletePartnerLinkModal, setShowDeletePartnerLinkModal] =+ useState(false);++ const linkRef = useRef(link);+ const onSuccessRef = useRef(onSuccess);++ useEffect(() => {+ linkRef.current = link;+ onSuccessRef.current = onSuccess;+ }, [link, onSuccess]);++ const DeletePartnerLinkModalCallback = useCallback(() => {+ return linkRef.current ? (+ <DeletePartnerLinkModal+ showDeletePartnerLinkModal={showDeletePartnerLinkModal}+ setShowDeletePartnerLinkModal={setShowDeletePartnerLinkModal}+ link={linkRef.current}+ onSuccess={onSuccessRef.current}+ />+ ) : null;+ }, [showDeletePartnerLinkModal, setShowDeletePartnerLinkModal]);++ return useMemo(+ () => ({+ setShowDeletePartnerLinkModal,+ DeletePartnerLinkModal: DeletePartnerLinkModalCallback,+ }),+ [setShowDeletePartnerLinkModal, DeletePartnerLinkModalCallback],+ );+}