Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add bulk csv link upload

Marc Seitzae24938a7833
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsx
index b0bb83ba..f94de291 100644
--- a/components/documents/document-header.tsx
+++ b/components/documents/document-header.tsx
@@ -14,6 +14,7 @@ import {
CloudDownloadIcon,
DownloadIcon,
FileDownIcon,
+ FileSpreadsheetIcon,
FolderIcon,
MoonIcon,
ServerIcon,
@@ -73,11 +74,13 @@ export default function DocumentHeader({
primaryVersion,
teamId,
actions,
+ onBulkImportLinks,
}: {
prismaDocument: DocumentWithVersion;
primaryVersion: DocumentVersion;
teamId: string;
actions?: React.ReactNode[];
+ onBulkImportLinks?: () => void;
}) {
const router = useRouter();
const teamInfo = useTeam();
@@ -728,6 +731,18 @@ export default function DocumentHeader({
</DropdownMenuItem>
)}
+ {onBulkImportLinks && (
+ <DropdownMenuItem
+ onClick={() => {
+ onBulkImportLinks();
+ setMenuOpen(false);
+ }}
+ >
+ <FileSpreadsheetIcon className="mr-2 h-4 w-4" />
+ Bulk import links from CSV
+ </DropdownMenuItem>
+ )}
+
{/* AI Agents - only show when team has AI enabled */}
{isAIEnabled &&
prismaDocument.type !== "notion" &&
diff --git a/components/links/bulk-import-modal.tsx b/components/links/bulk-import-modal.tsx
new file mode 100644
index 00000000..c30cb91c
--- /dev/null
+++ b/components/links/bulk-import-modal.tsx
@@ -0,0 +1,647 @@
+import { useCallback, useMemo, useRef, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ AlertCircleIcon,
+ CheckCircle2Icon,
+ CopyIcon,
+ DownloadIcon,
+ FileSpreadsheetIcon,
+ Loader2Icon,
+ UploadCloudIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+import { useAnalytics } from "@/lib/analytics";
+import useLimits from "@/lib/swr/use-limits";
+import { copyToClipboard } from "@/lib/utils";
+import { parseCsv, parseCsvBoolean, parseCsvList } from "@/lib/utils/csv-parse";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+const MAX_ROWS = 500;
+const MAX_FILE_SIZE_BYTES = 2 * 1024 * 1024; // 2 MB
+
+const TEMPLATE_HEADERS = [
+ "name",
+ "domain",
+ "slug",
+ "password",
+ "expiresAt",
+ "emailProtected",
+ "emailAuthenticated",
+ "allowDownload",
+ "enableNotification",
+ "enableScreenshotProtection",
+ "showBanner",
+ "allowList",
+ "denyList",
+ "presetId",
+] as const;
+
+const TEMPLATE_EXAMPLE_ROW = [
+ "Acme Corp",
+ "",
+ "",
+ "",
+ "2025-12-31T23:59:00Z",
+ "true",
+ "false",
+ "true",
+ "true",
+ "false",
+ "false",
+ "",
+ "",
+];
+
+type LinkPayload = {
+ name?: string;
+ domain?: string;
+ slug?: string;
+ password?: string;
+ expiresAt?: string;
+ emailProtected?: boolean;
+ emailAuthenticated?: boolean;
+ allowDownload?: boolean;
+ enableNotification?: boolean;
+ enableScreenshotProtection?: boolean;
+ showBanner?: boolean;
+ allowList?: string[];
+ denyList?: string[];
+ presetId?: string;
+};
+
+interface BulkResult {
+ row: number;
+ name?: string;
+ status: "success" | "error";
+ linkId?: string;
+ linkUrl?: string;
+ error?: string;
+}
+
+interface BulkResponse {
+ summary: { total: number; success: number; failed: number };
+ results: BulkResult[];
+}
+
+const BOOLEAN_FIELDS: Array<keyof LinkPayload> = [
+ "emailProtected",
+ "emailAuthenticated",
+ "allowDownload",
+ "enableNotification",
+ "enableScreenshotProtection",
+ "showBanner",
+];
+
+const LIST_FIELDS: Array<keyof LinkPayload> = ["allowList", "denyList"];
+const STRING_FIELDS: Array<keyof LinkPayload> = [
+ "name",
+ "domain",
+ "slug",
+ "password",
+ "expiresAt",
+ "presetId",
+];
+
+function buildTemplateCsv(): string {
+ const rows = [TEMPLATE_HEADERS.join(","), TEMPLATE_EXAMPLE_ROW.join(",")];
+ return rows.join("\n") + "\n";
+}
+
+function downloadTemplate() {
+ const blob = new Blob([buildTemplateCsv()], {
+ type: "text/csv;charset=utf-8;",
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.setAttribute("download", "papermark-bulk-links-template.csv");
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+function rowToPayload(row: Record<string, string>): LinkPayload {
+ const payload: LinkPayload = {};
+
+ for (const field of STRING_FIELDS) {
+ const raw = row[field];
+ if (raw && raw.trim().length > 0) {
+ (payload as any)[field] = raw.trim();
+ }
+ }
+
+ for (const field of BOOLEAN_FIELDS) {
+ const parsed = parseCsvBoolean(row[field]);
+ if (parsed !== undefined) {
+ (payload as any)[field] = parsed;
+ }
+ }
+
+ for (const field of LIST_FIELDS) {
+ const parsed = parseCsvList(row[field]);
+ if (parsed !== undefined) {
+ (payload as any)[field] = parsed;
+ }
+ }
+
+ return payload;
+}
+
+export function BulkImportLinksModal({
+ isOpen,
+ setIsOpen,
+ targetType,
+ targetId,
+ onImported,
+}: {
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+ targetType: "DOCUMENT" | "DATAROOM";
+ targetId: string;
+ onImported?: () => void;
+}) {
+ const { currentTeamId } = useTeam();
+ const { limits, canAddLinks } = useLimits();
+ const analytics = useAnalytics();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [fileName, setFileName] = useState<string | null>(null);
+ const [parsedRows, setParsedRows] = useState<LinkPayload[]>([]);
+ const [parseError, setParseError] = useState<string | null>(null);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [response, setResponse] = useState<BulkResponse | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+
+ const linkType = useMemo<"DOCUMENT_LINK" | "DATAROOM_LINK">(
+ () => (targetType === "DATAROOM" ? "DATAROOM_LINK" : "DOCUMENT_LINK"),
+ [targetType],
+ );
+ const endpointTargetType = targetType === "DATAROOM" ? "datarooms" : "documents";
+
+ const remainingLinks = useMemo<number | null>(() => {
+ const linkLimit = limits?.links;
+ if (
+ linkLimit === undefined ||
+ linkLimit === null ||
+ !Number.isFinite(linkLimit)
+ ) {
+ return null;
+ }
+ const used = limits?.usage?.links ?? 0;
+ return Math.max(0, (linkLimit as number) - used);
+ }, [limits]);
+
+ const exceedsLimit =
+ remainingLinks !== null && parsedRows.length > remainingLinks;
+
+ const reset = useCallback(() => {
+ setFileName(null);
+ setParsedRows([]);
+ setParseError(null);
+ setResponse(null);
+ if (fileInputRef.current) {
+ fileInputRef.current.value = "";
+ }
+ }, []);
+
+ const handleClose = useCallback(
+ (open: boolean) => {
+ if (!open) {
+ reset();
+ }
+ setIsOpen(open);
+ },
+ [reset, setIsOpen],
+ );
+
+ const handleFileSelected = useCallback(
+ async (file: File | undefined | null) => {
+ if (!file) return;
+ setParseError(null);
+ setResponse(null);
+
+ if (file.size > MAX_FILE_SIZE_BYTES) {
+ setParseError(
+ "CSV is larger than 2 MB. Please split into smaller files.",
+ );
+ return;
+ }
+
+ try {
+ const text = await file.text();
+ const { headers, rows } = parseCsv(text);
+
+ if (rows.length === 0) {
+ setParseError("CSV does not contain any data rows.");
+ setParsedRows([]);
+ return;
+ }
+
+ if (rows.length > MAX_ROWS) {
+ setParseError(
+ `CSV contains ${rows.length} rows. Maximum is ${MAX_ROWS}.`,
+ );
+ setParsedRows([]);
+ return;
+ }
+
+ const unknownHeaders = headers.filter(
+ (h) => h && !TEMPLATE_HEADERS.includes(h as any),
+ );
+ if (unknownHeaders.length > 0) {
+ // Surface as a soft warning – we still parse what we recognize.
+ toast.message(
+ `Ignoring unknown column${unknownHeaders.length > 1 ? "s" : ""}: ${unknownHeaders.join(", ")}`,
+ );
+ }
+
+ setParsedRows(rows.map(rowToPayload));
+ setFileName(file.name);
+ } catch (error) {
+ console.error(error);
+ setParseError(
+ error instanceof Error
+ ? error.message
+ : "Failed to read CSV. Please check the file format.",
+ );
+ }
+ },
+ [],
+ );
+
+ const handleDragOver = useCallback((event: React.DragEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = "copy";
+ }
+ setIsDragging(true);
+ }, []);
+
+ const handleDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsDragging(false);
+ }, []);
+
+ const handleDrop = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsDragging(false);
+
+ const file = event.dataTransfer?.files?.[0];
+ if (!file) return;
+
+ const isCsv =
+ file.type === "text/csv" ||
+ file.type === "application/vnd.ms-excel" ||
+ file.name.toLowerCase().endsWith(".csv");
+
+ if (!isCsv) {
+ setParseError("Please drop a CSV file.");
+ return;
+ }
+
+ void handleFileSelected(file);
+ },
+ [handleFileSelected],
+ );
+
+ const handleSubmit = useCallback(async () => {
+ if (!currentTeamId || parsedRows.length === 0 || !targetId) return;
+
+ setIsSubmitting(true);
+ try {
+ const res = await fetch(
+ `/api/teams/${currentTeamId}/${endpointTargetType}/${encodeURIComponent(
+ targetId,
+ )}/links/bulk`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ links: parsedRows,
+ }),
+ },
+ );
+
+ if (!res.ok) {
+ const payload = await res.json().catch(() => ({}));
+ toast.error(payload.error || "Failed to import links");
+ setIsSubmitting(false);
+ return;
+ }
+
+ const data: BulkResponse = await res.json();
+ setResponse(data);
+
+ analytics.capture("Links Bulk Imported", {
+ teamId: currentTeamId,
+ targetType,
+ targetId,
+ linkType,
+ attempted: data.summary.total,
+ imported: data.summary.success,
+ failed: data.summary.failed,
+ });
+
+ if (data.summary.success > 0) {
+ mutate(
+ `/api/teams/${currentTeamId}/${endpointTargetType}/${encodeURIComponent(
+ targetId,
+ )}/links`,
+ );
+ mutate(`/api/teams/${currentTeamId}/limits`);
+ onImported?.();
+ toast.success(
+ data.summary.failed === 0
+ ? `Created ${data.summary.success} links`
+ : `Created ${data.summary.success} of ${data.summary.total} links`,
+ );
+ } else {
+ toast.error("No links were created. See details below.");
+ }
+ } catch (error) {
+ console.error(error);
+ toast.error("Failed to import links");
+ } finally {
+ setIsSubmitting(false);
+ }
+ }, [
+ analytics,
+ currentTeamId,
+ linkType,
+ onImported,
+ endpointTargetType,
+ parsedRows,
+ targetId,
+ targetType,
+ ]);
+
+ const successCount = response?.summary.success ?? 0;
+ const failedCount = response?.summary.failed ?? 0;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={handleClose}>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>Bulk create links from CSV</DialogTitle>
+ <DialogDescription>
+ Upload a CSV to create multiple links at once for this{" "}
+ {targetType.toLowerCase()}. Each row creates one link and supports
+ the same options as the link settings.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/40 px-3 py-2 text-sm">
+ <div className="flex items-center gap-2">
+ <FileSpreadsheetIcon className="h-4 w-4 text-muted-foreground" />
+ <span className="text-muted-foreground">
+ Need a starting point?
+ </span>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={downloadTemplate}
+ >
+ <DownloadIcon className="mr-2 h-4 w-4" />
+ Download template
+ </Button>
+ </div>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".csv,text/csv,application/vnd.ms-excel"
+ className="hidden"
+ onChange={(event) => handleFileSelected(event.target.files?.[0])}
+ />
+
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ onDragEnter={handleDragOver}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ className={`flex flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors hover:border-foreground/40 hover:bg-muted/40 ${
+ isDragging ? "border-foreground/60 bg-muted/60" : "border-input"
+ }`}
+ >
+ <UploadCloudIcon className="h-6 w-6 text-muted-foreground" />
+ <div className="text-sm">
+ {fileName ? (
+ <>
+ <span className="font-medium">{fileName}</span>
+ <span className="ml-1 text-muted-foreground">
+ ({parsedRows.length} row{parsedRows.length === 1 ? "" : "s"}
+ )
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="font-medium text-foreground">
+ Click to choose a CSV
+ </span>
+ <span className="ml-1 text-muted-foreground">
+ or drag &amp; drop a file (max 2 MB, {MAX_ROWS} rows)
+ </span>
+ </>
+ )}
+ </div>
+ </button>
+
+ {parseError ? (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ <AlertCircleIcon className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>{parseError}</span>
+ </div>
+ ) : null}
+
+ {!response && !canAddLinks ? (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ <AlertCircleIcon className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>
+ You have reached your plan&apos;s link limit
+ {limits?.links ? ` of ${limits.links}` : ""}. Upgrade your plan
+ to create more links.
+ </span>
+ </div>
+ ) : !response && exceedsLimit && remainingLinks !== null ? (
+ <div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-700 dark:text-amber-400">
+ <AlertCircleIcon className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>
+ Your plan allows {limits?.links} link
+ {limits?.links === 1 ? "" : "s"} and you have{" "}
+ {remainingLinks === 0
+ ? "no remaining capacity"
+ : `${remainingLinks} remaining`}
+ . Only the first {remainingLinks} row
+ {remainingLinks === 1 ? "" : "s"} will be created — the rest
+ will be skipped. Upgrade your plan to create more links.
+ </span>
+ </div>
+ ) : null}
+
+ {response ? (
+ <ResultsList
+ results={response.results}
+ successCount={successCount}
+ failedCount={failedCount}
+ />
+ ) : parsedRows.length > 0 ? (
+ <PreviewList rows={parsedRows} />
+ ) : null}
+ </div>
+
+ <DialogFooter className="mt-2">
+ {response ? (
+ <Button type="button" onClick={() => handleClose(false)}>
+ Done
+ </Button>
+ ) : (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => handleClose(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSubmit}
+ disabled={
+ isSubmitting ||
+ parsedRows.length === 0 ||
+ !!parseError ||
+ !targetId ||
+ !canAddLinks
+ }
+ >
+ {isSubmitting ? (
+ <>
+ <Loader2Icon className="mr-2 h-4 w-4 animate-spin" />
+ Creating links…
+ </>
+ ) : (
+ `Create ${parsedRows.length || ""} link${
+ parsedRows.length === 1 ? "" : "s"
+ }`.trim()
+ )}
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function PreviewList({ rows }: { rows: LinkPayload[] }) {
+ return (
+ <div className="rounded-md border">
+ <div className="flex items-center justify-between border-b bg-muted/40 px-3 py-2 text-xs uppercase tracking-wide text-muted-foreground">
+ <span>Preview</span>
+ <span>
+ {rows.length} row{rows.length === 1 ? "" : "s"}
+ </span>
+ </div>
+ <div className="max-h-44 overflow-y-auto">
+ <ul className="divide-y text-sm">
+ {rows.map((row, idx) => (
+ <li key={idx} className="flex items-center gap-3 px-3 py-2">
+ <span className="w-8 shrink-0 text-xs text-muted-foreground">
+ #{idx + 1}
+ </span>
+ <span className="flex-1 truncate font-medium">
+ {row.name || "(unnamed link)"}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
+function ResultsList({
+ results,
+ successCount,
+ failedCount,
+}: {
+ results: BulkResult[];
+ successCount: number;
+ failedCount: number;
+}) {
+ return (
+ <div className="rounded-md border">
+ <div className="flex items-center justify-between border-b bg-muted/40 px-3 py-2 text-sm">
+ <span className="font-medium">Results</span>
+ <span className="text-xs text-muted-foreground">
+ <span className="text-emerald-600">{successCount} created</span>
+ {failedCount > 0 ? (
+ <>
+ <span className="mx-1">·</span>
+ <span className="text-destructive">{failedCount} failed</span>
+ </>
+ ) : null}
+ </span>
+ </div>
+ <div className="max-h-72 overflow-y-auto">
+ <ul className="divide-y text-sm">
+ {results.map((result) => (
+ <li
+ key={`${result.row}-${result.linkId ?? result.error ?? ""}`}
+ className="flex items-start gap-3 px-3 py-2"
+ >
+ <span className="w-6 shrink-0 pt-0.5 text-xs text-muted-foreground">
+ #{result.row}
+ </span>
+ {result.status === "success" ? (
+ <CheckCircle2Icon className="mt-0.5 h-4 w-4 shrink-0 text-emerald-600" />
+ ) : (
+ <AlertCircleIcon className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">
+ {result.name || `Link #${result.row}`}
+ </div>
+ {result.status === "success" && result.linkUrl ? (
+ <button
+ type="button"
+ onClick={() =>
+ copyToClipboard(result.linkUrl!, "Link copied")
+ }
+ className="group inline-flex max-w-full items-center gap-1 truncate text-xs text-muted-foreground hover:text-foreground"
+ >
+ <span className="truncate">{result.linkUrl}</span>
+ <CopyIcon className="h-3 w-3 opacity-60 group-hover:opacity-100" />
+ </button>
+ ) : (
+ <div className="text-xs text-destructive">{result.error}</div>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index 6fecd58a..25aae295 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -1,3 +1,4 @@
+import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -20,6 +21,7 @@ import {
EyeIcon,
EyeOffIcon,
FileSlidersIcon,
+ FileSpreadsheetIcon,
LinkIcon,
SendIcon,
Settings2Icon,
@@ -92,6 +94,14 @@ import { PermissionsSheet } from "./link-sheet/permissions-sheet";
import { TagColumn } from "./link-sheet/tags/tag-details";
import LinksVisitors from "./links-visitors";
+const BulkImportLinksModal = dynamic(
+ () =>
+ import("./bulk-import-modal").then((mod) => ({
+ default: mod.BulkImportLinksModal,
+ })),
+ { ssr: false },
+);
+
const isDocumentProcessing = (version?: DocumentVersion) => {
if (!version) return false;
return (
@@ -275,12 +285,14 @@ export default function LinksTable({
primaryVersion,
mutateDocument,
dataroomName,
+ onBulkImportOpen,
}: {
targetType: "DOCUMENT" | "DATAROOM";
links?: LinkWithViews[];
primaryVersion?: DocumentVersion;
mutateDocument?: () => void;
dataroomName?: string;
+ onBulkImportOpen?: () => void;
}) {
const [tags, _] = useQueryState<string[]>("tags", {
parse: (value: string) => value.split(",").filter(Boolean),
@@ -342,6 +354,7 @@ export default function LinksTable({
const [isLoading, setIsLoading] = useState<boolean>(false);
const [loadingLinks, setLoadingLinks] = useState<Set<string>>(new Set());
const [isLinkSheetVisible, setIsLinkSheetVisible] = useState<boolean>(false);
+ const [isBulkImportOpen, setIsBulkImportOpen] = useState<boolean>(false);
const [selectedLink, setSelectedLink] = useState<DEFAULT_LINK_TYPE>(
DEFAULT_LINK_PROPS(`${targetType}_LINK`, groupId),
);
@@ -377,6 +390,15 @@ export default function LinksTable({
const dataroomDisplayName = dataroomName ?? "this dataroom";
+ const openBulkImport = useCallback(() => {
+ if (onBulkImportOpen) {
+ onBulkImportOpen();
+ return;
+ }
+
+ setIsBulkImportOpen(true);
+ }, [onBulkImportOpen]);
+
const handleCopyToClipboard = (linkString: string) => {
copyToClipboard(`${linkString}`, "Link copied to clipboard.");
};
@@ -717,9 +739,30 @@ export default function LinksTable({
);
} else {
return (
- <Button onClick={() => setIsLinkSheetVisible(true)}>
- Create link to share
- </Button>
+ <div className="flex items-center gap-2">
+ <Button onClick={() => setIsLinkSheetVisible(true)}>
+ Create link to share
+ </Button>
+ {targetId ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ aria-label="More link actions"
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={openBulkImport}>
+ <FileSpreadsheetIcon className="mr-2 h-4 w-4" />
+ Bulk import from CSV
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </div>
);
}
};
@@ -1353,6 +1396,15 @@ export default function LinksTable({
/>
)}
+ {!onBulkImportOpen && targetId ? (
+ <BulkImportLinksModal
+ isOpen={isBulkImportOpen}
+ setIsOpen={setIsBulkImportOpen}
+ targetType={targetType}
+ targetId={targetId}
+ />
+ ) : null}
+
<DeleteLinkModal />
</div>
</>
diff --git a/lib/api/links/bulk-import.ts b/lib/api/links/bulk-import.ts
new file mode 100644
index 00000000..8d855636
--- /dev/null
+++ b/lib/api/links/bulk-import.ts
@@ -0,0 +1,437 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";
+import { checkRateLimit, rateLimiters } from "@/ee/features/security";
+import { getLimits } from "@/ee/limits/server";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { LinkPreset } from "@prisma/client";
+import { put } from "@vercel/blob";
+import { waitUntil } from "@vercel/functions";
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import {
+ convertDataUrlToBuffer,
+ generateEncrpytedPassword,
+ isDataUrl,
+} from "@/lib/utils";
+import { sendLinkCreatedWebhook } from "@/lib/webhook/triggers/link-created";
+
+export const bulkImportConfig = {
+ // Allow background work to flush after the response.
+ supportsResponseStreaming: true,
+ maxDuration: 120,
+};
+
+// Reused from `pages/api/webhooks/services/[...path]/index.ts` so the CSV
+// importer accepts the same option set users already configure through the
+// incoming-webhooks API.
+const LinkSchema = z
+ .object({
+ name: z.string().optional(),
+ domain: z.string().optional(),
+ slug: z.string().optional(),
+ password: z.string().optional(),
+ expiresAt: z.string().optional(), // ISO-8601 date string
+ emailProtected: z.boolean().optional(),
+ emailAuthenticated: z.boolean().optional(),
+ allowDownload: z.boolean().optional(),
+ enableNotification: z.boolean().optional(),
+ enableScreenshotProtection: z.boolean().optional(),
+ showBanner: z.boolean().optional(),
+ allowList: z.array(z.string()).optional(),
+ denyList: z.array(z.string()).optional(),
+ presetId: z.string().optional(),
+ })
+ .strict();
+
+const RequestBodySchema = z
+ .object({
+ links: z.array(LinkSchema).min(1).max(500),
+ })
+ .strict();
+
+type LinkInput = z.infer<typeof LinkSchema>;
+
+interface BulkResult {
+ row: number; // 1-based row number in the CSV (header excluded)
+ name?: string;
+ status: "success" | "error";
+ linkId?: string;
+ linkUrl?: string;
+ error?: string;
+}
+
+interface CachedPreset {
+ preset: LinkPreset | null;
+ metaImage: string | null;
+ metaFavicon: string | null;
+}
+
+interface BulkImportContext {
+ teamId: string;
+ targetId: string;
+ linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";
+}
+
+export async function handleBulkLinkImport(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ { teamId, targetId, linkType }: BulkImportContext,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: { userId_teamId: { userId, teamId } },
+ select: { teamId: true },
+ });
+ if (!teamAccess) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ // Rate limit bulk imports per team to prevent abuse. Keyed by teamId so
+ // multiple users on the same team share the budget and a single user
+ // cannot bypass it by switching IPs.
+ const rateLimitResult = await checkRateLimit(
+ rateLimiters.bulkLinkImport,
+ `team:${teamId}`,
+ );
+ if (!rateLimitResult.success) {
+ return res.status(429).json({
+ error:
+ "Too many bulk link imports. Please wait before importing again.",
+ remaining: rateLimitResult.remaining,
+ });
+ }
+
+ const teamIsPaused = await isTeamPausedById(teamId);
+ if (teamIsPaused) {
+ return res.status(403).json({
+ error: "Team is currently paused. New link creation is not available.",
+ });
+ }
+
+ const validation = RequestBodySchema.safeParse(req.body);
+ if (!validation.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: validation.error.format(),
+ });
+ }
+
+ const { links } = validation.data;
+
+ // Lock the import to the resource encoded in the route. This prevents callers
+ // from re-targeting rows to other documents or datarooms by bypassing the UI.
+ if (linkType === "DOCUMENT_LINK") {
+ const document = await prisma.document.findUnique({
+ where: { id: targetId, teamId },
+ select: { id: true },
+ });
+ if (!document) {
+ return res.status(404).json({ error: "Document not found" });
+ }
+ } else {
+ const dataroom = await prisma.dataroom.findUnique({
+ where: { id: targetId, teamId },
+ select: { id: true, isFrozen: true },
+ });
+ if (!dataroom) {
+ return res.status(404).json({ error: "Dataroom not found" });
+ }
+ if (dataroom.isFrozen) {
+ return res.status(403).json({
+ error: "This data room is frozen. Cannot create new links.",
+ });
+ }
+ }
+
+ // Enforce the team's plan link limit. We compute remaining capacity once
+ // up front, then track creations locally so a single CSV cannot exceed
+ // the cap (rows beyond the cap are returned as per-row errors).
+ const limits = await getLimits({ teamId, userId });
+ const linkLimit = limits?.links;
+ const currentLinkCount = limits?.usage?.links ?? 0;
+ const isUnlimited =
+ linkLimit === undefined || linkLimit === null || !Number.isFinite(linkLimit);
+ const remainingCapacity = isUnlimited
+ ? Number.POSITIVE_INFINITY
+ : Math.max(0, (linkLimit as number) - currentLinkCount);
+
+ if (remainingCapacity === 0) {
+ return res.status(403).json({
+ error: `You have reached your plan's link limit of ${linkLimit}. Upgrade your plan to create more links.`,
+ });
+ }
+
+ // Pre-resolve presets and domains once per request to avoid duplicate
+ // lookups across rows.
+ const presetCache = new Map<string, CachedPreset>();
+ const domainCache = new Map<string, { id: string } | null>();
+
+ const results: BulkResult[] = [];
+ let createdCount = 0;
+
+ for (let i = 0; i < links.length; i++) {
+ const row = links[i];
+ const rowNumber = i + 1;
+
+ if (createdCount >= remainingCapacity) {
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error: `Link limit reached. Your plan allows ${linkLimit} link${
+ linkLimit === 1 ? "" : "s"
+ }. Upgrade your plan to create more links.`,
+ });
+ continue;
+ }
+
+ try {
+ // Validate domain + slug pairing when provided.
+ let domainId: string | null = null;
+ if (row.domain && row.slug) {
+ const domainCacheKey = `${teamId}:${row.domain}`;
+ let domain = domainCache.get(domainCacheKey);
+ if (domain === undefined) {
+ domain = await prisma.domain.findUnique({
+ where: { slug: row.domain, teamId },
+ select: { id: true },
+ });
+ domainCache.set(domainCacheKey, domain);
+ }
+ if (!domain) {
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error: "Domain not found or not associated with this team",
+ });
+ continue;
+ }
+ domainId = domain.id;
+
+ const existingLink = await prisma.link.findUnique({
+ where: {
+ domainSlug_slug: { slug: row.slug, domainSlug: row.domain },
+ },
+ select: { id: true },
+ });
+ if (existingLink) {
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error: "The link with this domain and slug already exists",
+ });
+ continue;
+ }
+ } else if (row.domain || row.slug) {
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error: "Both 'domain' and 'slug' must be provided together",
+ });
+ continue;
+ }
+
+ // Resolve preset (cached).
+ let preset: LinkPreset | null = null;
+ let metaImage: string | null = null;
+ let metaFavicon: string | null = null;
+ if (row.presetId) {
+ const cachedPreset = presetCache.get(row.presetId);
+ if (cachedPreset) {
+ preset = cachedPreset.preset;
+ metaImage = cachedPreset.metaImage;
+ metaFavicon = cachedPreset.metaFavicon;
+ } else {
+ preset = await prisma.linkPreset.findUnique({
+ where: { pId: row.presetId, teamId },
+ });
+
+ if (preset?.enableCustomMetaTag) {
+ if (preset.metaImage && isDataUrl(preset.metaImage)) {
+ const { buffer, filename } = convertDataUrlToBuffer(
+ preset.metaImage,
+ );
+ const blob = await put(filename, buffer, {
+ access: "public",
+ addRandomSuffix: true,
+ });
+ metaImage = blob.url;
+ }
+ if (preset.metaFavicon && isDataUrl(preset.metaFavicon)) {
+ const { buffer, filename } = convertDataUrlToBuffer(
+ preset.metaFavicon,
+ );
+ const blob = await put(filename, buffer, {
+ access: "public",
+ addRandomSuffix: true,
+ });
+ metaFavicon = blob.url;
+ }
+ }
+
+ presetCache.set(row.presetId, {
+ preset,
+ metaImage,
+ metaFavicon,
+ });
+ }
+
+ if (!preset) {
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error: "Link preset not found or not associated with this team",
+ });
+ continue;
+ }
+ }
+
+ const newLink = await createLinkFromRow({
+ row,
+ teamId,
+ userId,
+ targetId,
+ linkType,
+ domainId,
+ preset,
+ metaImage,
+ metaFavicon,
+ });
+
+ createdCount++;
+
+ results.push({
+ row: rowNumber,
+ name: row.name ?? newLink.name ?? undefined,
+ status: "success",
+ linkId: newLink.id,
+ linkUrl:
+ newLink.domainSlug && newLink.slug
+ ? `https://${newLink.domainSlug}/${newLink.slug}`
+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${newLink.id}`,
+ });
+
+ waitUntil(
+ sendLinkCreatedWebhook({
+ teamId,
+ data: {
+ link_id: newLink.id,
+ document_id: linkType === "DOCUMENT_LINK" ? targetId : null,
+ dataroom_id: linkType === "DATAROOM_LINK" ? targetId : null,
+ },
+ }),
+ );
+ } catch (error) {
+ console.error(`Bulk link import row ${rowNumber} failed:`, error);
+ results.push({
+ row: rowNumber,
+ name: row.name,
+ status: "error",
+ error:
+ error instanceof Error
+ ? error.message
+ : "Unexpected error while creating link",
+ });
+ }
+ }
+
+ const summary = {
+ total: results.length,
+ success: results.filter((result) => result.status === "success").length,
+ failed: results.filter((result) => result.status === "error").length,
+ };
+
+ return res.status(200).json({ summary, results });
+}
+
+async function createLinkFromRow({
+ row,
+ teamId,
+ userId,
+ targetId,
+ linkType,
+ domainId,
+ preset,
+ metaImage,
+ metaFavicon,
+}: {
+ row: LinkInput;
+ teamId: string;
+ userId: string;
+ targetId: string;
+ linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";
+ domainId: string | null;
+ preset: LinkPreset | null;
+ metaImage: string | null;
+ metaFavicon: string | null;
+}) {
+ const hashedPassword = row.password
+ ? await generateEncrpytedPassword(row.password)
+ : preset?.password
+ ? await generateEncrpytedPassword(preset.password)
+ : null;
+
+ const expiresAtDate = row.expiresAt
+ ? new Date(row.expiresAt)
+ : preset?.expiresAt
+ ? new Date(preset.expiresAt)
+ : null;
+
+ if (expiresAtDate && Number.isNaN(expiresAtDate.getTime())) {
+ throw new Error(
+ `Invalid expiresAt date: '${row.expiresAt}'. Use ISO-8601 (e.g. 2025-12-31T23:59:00Z).`,
+ );
+ }
+
+ return prisma.link.create({
+ data: {
+ documentId: linkType === "DOCUMENT_LINK" ? targetId : null,
+ dataroomId: linkType === "DATAROOM_LINK" ? targetId : null,
+ linkType,
+ teamId,
+ ownerId: userId,
+ name: row.name ?? null,
+ password: hashedPassword,
+ domainId,
+ domainSlug: row.domain || null,
+ slug: row.slug || null,
+ expiresAt: expiresAtDate,
+ emailProtected: row.emailProtected ?? preset?.emailProtected ?? false,
+ emailAuthenticated:
+ row.emailAuthenticated ?? preset?.emailAuthenticated ?? false,
+ allowDownload: row.allowDownload ?? preset?.allowDownload,
+ enableNotification:
+ row.enableNotification ?? preset?.enableNotification ?? false,
+ enableScreenshotProtection: row.enableScreenshotProtection,
+ showBanner: row.showBanner ?? preset?.showBanner ?? false,
+ allowList: row.allowList ?? preset?.allowList,
+ denyList: row.denyList ?? preset?.denyList,
+ ...(preset?.enableCustomMetaTag && {
+ enableCustomMetatag: preset.enableCustomMetaTag,
+ metaTitle: preset.metaTitle,
+ metaDescription: preset.metaDescription,
+ metaImage,
+ metaFavicon,
+ }),
+ },
+ });
+}
diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.ts
index 856e84d2..43d7892d 100644
--- a/lib/api/links/link-data.ts
+++ b/lib/api/links/link-data.ts
@@ -285,7 +285,7 @@ export async function fetchDataroomLinkData({
},
});
- if (!linkData?.dataroom) {
+ if (!linkData?.dataroom || linkData.dataroom.teamId !== teamId) {
throw new Error("Dataroom not found");
}
@@ -437,7 +437,7 @@ export async function fetchDataroomDocumentLinkData({
},
});
- if (!linkData?.dataroom) {
+ if (!linkData?.dataroom || linkData.dataroom.teamId !== teamId) {
throw new Error("Dataroom not found");
}
@@ -518,7 +518,7 @@ export async function fetchDocumentLinkData({
},
});
- if (!linkData?.document) {
+ if (!linkData?.document || linkData.document.teamId !== teamId) {
throw new Error("Document not found");
}
diff --git a/lib/utils/csv-parse.ts b/lib/utils/csv-parse.ts
new file mode 100644
index 00000000..696d8b03
--- /dev/null
+++ b/lib/utils/csv-parse.ts
@@ -0,0 +1,128 @@
+/**
+ * Lightweight RFC4180-compliant CSV parser used for bulk import flows.
+ * Keeps the bundle slim by avoiding a third-party dependency.
+ */
+export type CsvRow = Record<string, string>;
+
+export interface ParsedCsv {
+ headers: string[];
+ rows: CsvRow[];
+}
+
+/**
+ * Parses CSV text into a list of header keys and trimmed row records. Handles
+ * quoted values, escaped quotes (""), CR/LF line endings, and a trailing
+ * newline. Empty rows are skipped.
+ */
+export function parseCsv(text: string): ParsedCsv {
+ // Strip BOM if present – Excel exports often include it.
+ if (text.charCodeAt(0) === 0xfeff) {
+ text = text.slice(1);
+ }
+
+ const records: string[][] = [];
+ let field = "";
+ let row: string[] = [];
+ let inQuotes = false;
+
+ for (let i = 0; i < text.length; i++) {
+ const char = text[i];
+
+ if (inQuotes) {
+ if (char === '"') {
+ if (text[i + 1] === '"') {
+ field += '"';
+ i++;
+ } else {
+ inQuotes = false;
+ }
+ } else {
+ field += char;
+ }
+ continue;
+ }
+
+ if (char === '"') {
+ inQuotes = true;
+ continue;
+ }
+
+ if (char === ",") {
+ row.push(field);
+ field = "";
+ continue;
+ }
+
+ if (char === "\n" || char === "\r") {
+ // Handle CRLF: skip the LF that may follow a CR
+ if (char === "\r" && text[i + 1] === "\n") {
+ i++;
+ }
+ row.push(field);
+ field = "";
+ records.push(row);
+ row = [];
+ continue;
+ }
+
+ field += char;
+ }
+
+ // Flush any remaining field/row from a file with no trailing newline.
+ if (field.length > 0 || row.length > 0) {
+ row.push(field);
+ records.push(row);
+ }
+
+ if (records.length === 0) {
+ return { headers: [], rows: [] };
+ }
+
+ const headers = records[0].map((h) => h.trim());
+ const rows: CsvRow[] = [];
+
+ for (let r = 1; r < records.length; r++) {
+ const cols = records[r];
+ // Skip blank lines (a single empty cell).
+ const isEmpty =
+ cols.length === 0 || (cols.length === 1 && cols[0].trim() === "");
+ if (isEmpty) continue;
+
+ const record: CsvRow = {};
+ for (let c = 0; c < headers.length; c++) {
+ const value = (cols[c] ?? "").trim();
+ record[headers[c]] = value;
+ }
+ rows.push(record);
+ }
+
+ return { headers, rows };
+}
+
+/**
+ * Coerces common "boolean-ish" strings produced by spreadsheet exports.
+ * Returns undefined when the value is empty/whitespace, allowing the caller
+ * to distinguish "not provided" from "false".
+ */
+export function parseCsvBoolean(value: string | undefined): boolean | undefined {
+ if (value === undefined) return undefined;
+ const v = value.trim().toLowerCase();
+ if (v === "") return undefined;
+ if (["true", "yes", "y", "1", "on"].includes(v)) return true;
+ if (["false", "no", "n", "0", "off"].includes(v)) return false;
+ return undefined;
+}
+
+/**
+ * Parses a delimited list inside a single CSV cell. Supports semicolons,
+ * pipes, and newlines so users can paste pre-formatted lists.
+ */
+export function parseCsvList(value: string | undefined): string[] | undefined {
+ if (value === undefined) return undefined;
+ const trimmed = value.trim();
+ if (trimmed === "") return undefined;
+ return trimmed
+ .split(/[;|\n]+/)
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0);
+}
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index ce758863..4f613b62 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -231,8 +231,8 @@ export default async function handle(
...linkDomainData
} = req.body;
- const dataroomLink = linkType === "DATAROOM_LINK";
- const documentLink = linkType === "DOCUMENT_LINK";
+ let resolvedLinkType: "DOCUMENT_LINK" | "DATAROOM_LINK" | null = null;
+ let resolvedTargetId: string | null = null;
try {
const existingLink = await prisma.link.findUnique({
@@ -267,25 +267,108 @@ export default async function handle(
});
}
- // If the PUT retargets the link (different targetId or linkType),
- // ensure the destination dataroom is not frozen.
- if (dataroomLink && targetId) {
- const existingTargetId =
- existingLink.linkType === "DATAROOM_LINK"
- ? existingLink.dataroomId
- : existingLink.documentId;
- const isRetargeting =
- existingLink.linkType !== linkType || existingTargetId !== targetId;
-
- if (isRetargeting) {
- const destinationDataroom = await prisma.dataroom.findUnique({
- where: { id: targetId, teamId },
- select: { isFrozen: true },
+ resolvedLinkType = linkType ?? existingLink.linkType;
+
+ if (
+ resolvedLinkType !== "DOCUMENT_LINK" &&
+ resolvedLinkType !== "DATAROOM_LINK"
+ ) {
+ return res.status(400).json({ error: "Invalid link type." });
+ }
+
+ resolvedTargetId =
+ targetId ??
+ (resolvedLinkType === "DATAROOM_LINK"
+ ? existingLink.dataroomId
+ : existingLink.documentId);
+
+ if (!resolvedTargetId) {
+ return res.status(400).json({
+ error: "A target document or data room is required.",
+ });
+ }
+
+ if (resolvedLinkType === "DOCUMENT_LINK") {
+ const destinationDocument = await prisma.document.findUnique({
+ where: { id: resolvedTargetId, teamId },
+ select: { id: true },
+ });
+ if (!destinationDocument) {
+ return res.status(400).json({
+ error: "Invalid document.",
+ });
+ }
+ } else {
+ const destinationDataroom = await prisma.dataroom.findUnique({
+ where: { id: resolvedTargetId, teamId },
+ select: { isFrozen: true },
+ });
+ if (!destinationDataroom) {
+ return res.status(400).json({
+ error: "Invalid data room.",
+ });
+ }
+ if (destinationDataroom.isFrozen) {
+ return res.status(403).json({
+ error:
+ "This data room is frozen. You cannot modify links for a frozen data room.",
+ });
+ }
+ }
+
+ // ViewerGroup (groupId) and PermissionGroup (permissionGroupId) are
+ // both scoped to a specific dataroom. Whenever the request carries
+ // either binding, ensure it actually belongs to the resolved target
+ // dataroom — this also covers the case where the target changes but
+ // the client forgets to clear/replace a stale group reference.
+ const incomingGroupId =
+ typeof req.body.groupId === "string" && req.body.groupId.length > 0
+ ? req.body.groupId
+ : null;
+ const incomingPermissionGroupId =
+ typeof req.body.permissionGroupId === "string" &&
+ req.body.permissionGroupId.length > 0
+ ? req.body.permissionGroupId
+ : null;
+
+ if (incomingGroupId || incomingPermissionGroupId) {
+ if (resolvedLinkType !== "DATAROOM_LINK") {
+ return res.status(400).json({
+ error:
+ "Visitor groups and permission groups can only be assigned to dataroom links.",
});
- if (destinationDataroom?.isFrozen) {
- return res.status(403).json({
+ }
+
+ if (incomingGroupId) {
+ const viewerGroup = await prisma.viewerGroup.findFirst({
+ where: {
+ id: incomingGroupId,
+ teamId,
+ dataroomId: resolvedTargetId,
+ },
+ select: { id: true },
+ });
+ if (!viewerGroup) {
+ return res.status(400).json({
error:
- "This data room is frozen. You cannot modify links for a frozen data room.",
+ "The selected visitor group does not belong to this data room.",
+ });
+ }
+ }
+
+ if (incomingPermissionGroupId) {
+ const permissionGroup = await prisma.permissionGroup.findFirst({
+ where: {
+ id: incomingPermissionGroupId,
+ teamId,
+ dataroomId: resolvedTargetId,
+ },
+ select: { id: true },
+ });
+ if (!permissionGroup) {
+ return res.status(400).json({
+ error:
+ "The selected permission group does not belong to this data room.",
});
}
}
@@ -297,6 +380,15 @@ export default async function handle(
});
}
+ if (!resolvedLinkType || !resolvedTargetId) {
+ return res.status(400).json({
+ error: "A target document or data room is required.",
+ });
+ }
+
+ const dataroomLink = resolvedLinkType === "DATAROOM_LINK";
+ const documentLink = resolvedLinkType === "DOCUMENT_LINK";
+
const hashedPassword =
password && password.length > 0
? await generateEncrpytedPassword(password)
@@ -317,11 +409,14 @@ export default async function handle(
domainObj = await prisma.domain.findUnique({
where: {
slug: domain,
+ teamId,
},
});
if (!domainObj) {
- return res.status(400).json({ error: "Domain not found." });
+ return res.status(400).json({
+ error: "Domain not found or not associated with this team.",
+ });
}
const currentLink = await prisma.link.findUnique({
@@ -415,7 +510,7 @@ export default async function handle(
}
if (normalizedIds.length > 0) {
- if (!dataroomLink || !targetId) {
+ if (!dataroomLink || !resolvedTargetId) {
return res.status(400).json({
error: "Upload folders can only be assigned to dataroom links.",
});
@@ -424,7 +519,7 @@ export default async function handle(
const validFolders = await prisma.dataroomFolder.findMany({
where: {
id: { in: normalizedIds },
- dataroomId: targetId,
+ dataroomId: resolvedTargetId,
},
select: { id: true, name: true, path: true },
});
@@ -448,8 +543,9 @@ export default async function handle(
const link = await tx.link.update({
where: { id, teamId },
data: {
- documentId: documentLink ? targetId : null,
- dataroomId: dataroomLink ? targetId : null,
+ documentId: documentLink ? resolvedTargetId : null,
+ dataroomId: dataroomLink ? resolvedTargetId : null,
+ linkType: resolvedLinkType,
password: hashedPassword,
name: linkData.name || null,
emailProtected:
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 5ef3f675..752ed1ea 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -102,6 +102,30 @@ export default async function handler(
});
}
+ if (!targetId) {
+ return res.status(400).json({
+ error: "A target document or data room is required.",
+ });
+ }
+
+ if (!documentLink && !dataroomLink) {
+ return res.status(400).json({
+ error: "Invalid link type.",
+ });
+ }
+
+ if (documentLink) {
+ const document = await prisma.document.findUnique({
+ where: { id: targetId, teamId },
+ select: { id: true },
+ });
+ if (!document) {
+ return res.status(400).json({
+ error: "Invalid document.",
+ });
+ }
+ }
+
if (dataroomLink && targetId) {
const dataroom = await prisma.dataroom.findUnique({
where: { id: targetId, teamId },
@@ -140,11 +164,14 @@ export default async function handler(
domainObj = await prisma.domain.findUnique({
where: {
slug: domain,
+ teamId,
},
});
if (!domainObj) {
- return res.status(400).json({ error: "Domain not found." });
+ return res.status(400).json({
+ error: "Domain not found or not associated with this team.",
+ });
}
const existingLink = await prisma.link.findUnique({
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/links/bulk.ts b/pages/api/teams/[teamId]/datarooms/[id]/links/bulk.ts
new file mode 100644
index 00000000..f6f134bd
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/links/bulk.ts
@@ -0,0 +1,21 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import {
+ bulkImportConfig,
+ handleBulkLinkImport,
+} from "@/lib/api/links/bulk-import";
+
+export const config = bulkImportConfig;
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const { teamId, id } = req.query as { teamId: string; id: string };
+
+ return handleBulkLinkImport(req, res, {
+ teamId,
+ targetId: id,
+ linkType: "DATAROOM_LINK",
+ });
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/links/bulk.ts b/pages/api/teams/[teamId]/documents/[id]/links/bulk.ts
new file mode 100644
index 00000000..f92445f0
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/links/bulk.ts
@@ -0,0 +1,21 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import {
+ bulkImportConfig,
+ handleBulkLinkImport,
+} from "@/lib/api/links/bulk-import";
+
+export const config = bulkImportConfig;
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const { teamId, id } = req.query as { teamId: string; id: string };
+
+ return handleBulkLinkImport(req, res, {
+ teamId,
+ targetId: id,
+ linkType: "DOCUMENT_LINK",
+ });
+}
diff --git a/pages/api/teams/[teamId]/links/bulk.ts b/pages/api/teams/[teamId]/links/bulk.ts
new file mode 100644
index 00000000..e6cbf30d
--- /dev/null
+++ b/pages/api/teams/[teamId]/links/bulk.ts
@@ -0,0 +1,16 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ return res.status(410).json({
+ error:
+ "Bulk link imports must use the resource-scoped document or dataroom endpoint.",
+ });
+}
diff --git a/pages/datarooms/[id]/permissions/index.tsx b/pages/datarooms/[id]/permissions/index.tsx
index 45895028..03fc38c1 100644
--- a/pages/datarooms/[id]/permissions/index.tsx
+++ b/pages/datarooms/[id]/permissions/index.tsx
@@ -1,7 +1,14 @@
+import dynamic from "next/dynamic";
import { useState } from "react";
import { InviteViewersModal } from "@/ee/features/dataroom-invitations/components/invite-viewers-modal";
-import { CircleHelpIcon, PlusIcon, SendIcon } from "lucide-react";
+import {
+ CircleHelpIcon,
+ FileSpreadsheetIcon,
+ MoreHorizontalIcon,
+ PlusIcon,
+ SendIcon,
+} from "lucide-react";
import { usePlan } from "@/lib/swr/use-billing";
import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";
@@ -11,8 +18,22 @@ import { DataroomLinkSheet } from "@/components/links/link-sheet/dataroom-link-s
import LinksTable from "@/components/links/links-table";
import { TabMenu } from "@/components/tab-menu";
import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { BadgeTooltip } from "@/components/ui/tooltip";
+const BulkImportLinksModal = dynamic(
+ () =>
+ import("@/components/links/bulk-import-modal").then((mod) => ({
+ default: mod.BulkImportLinksModal,
+ })),
+ { ssr: false },
+);
+
export default function DataroomLinksPage() {
const { dataroom } = useDataroom();
const { links } = useDataroomLinks();
@@ -20,6 +41,7 @@ export default function DataroomLinksPage() {
const canInviteViewers = isDataroomsPlus;
const [isLinkSheetOpen, setIsLinkSheetOpen] = useState(false);
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false);
+ const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
if (!dataroom) {
return <div>Loading...</div>;
@@ -59,6 +81,23 @@ export default function DataroomLinksPage() {
<PlusIcon className="h-4 w-4" />
Create link
</Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ aria-label="More link actions"
+ >
+ <MoreHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setIsBulkImportOpen(true)}>
+ <FileSpreadsheetIcon className="mr-2 h-4 w-4" />
+ Bulk import from CSV
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
</div>
@@ -84,6 +123,7 @@ export default function DataroomLinksPage() {
links={links}
targetType={"DATAROOM"}
dataroomName={dataroom.name}
+ onBulkImportOpen={() => setIsBulkImportOpen(true)}
/>
</div>
@@ -95,6 +135,13 @@ export default function DataroomLinksPage() {
linkTargetId={dataroom.id}
/>
+ <BulkImportLinksModal
+ isOpen={isBulkImportOpen}
+ setIsOpen={setIsBulkImportOpen}
+ targetType="DATAROOM"
+ targetId={dataroom.id}
+ />
+
{!canInviteViewers && (
<InviteViewersModal
open={isInviteModalOpen}
diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsx
index b308c7aa..686633d3 100644
--- a/pages/documents/[id]/index.tsx
+++ b/pages/documents/[id]/index.tsx
@@ -63,6 +63,14 @@ const VisitorsTable = dynamic(
},
);
+const BulkImportLinksModal = dynamic(
+ () =>
+ import("@/components/links/bulk-import-modal").then((mod) => ({
+ default: mod.BulkImportLinksModal,
+ })),
+ { ssr: false },
+);
+
export default function DocumentPage() {
const {
data: overview,
@@ -82,6 +90,7 @@ export default function DocumentPage() {
const teamId = teamInfo?.currentTeam?.id;
const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);
+ const [isBulkImportOpen, setIsBulkImportOpen] = useState<boolean>(false);
// Mutate function that updates both overview and links
const mutateDocument = () => {
@@ -107,12 +116,14 @@ export default function DocumentPage() {
);
} else {
return (
- <Button
- className="flex h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm"
- onClick={() => setIsLinkSheetOpen(true)}
- >
- Create Link
- </Button>
+ <div className="flex items-center gap-2">
+ <Button
+ className="flex h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm"
+ onClick={() => setIsLinkSheetOpen(true)}
+ >
+ Create Link
+ </Button>
+ </div>
);
}
};
@@ -150,6 +161,7 @@ export default function DocumentPage() {
primaryVersion={primaryVersion}
prismaDocument={prismaDocument}
teamId={teamId}
+ onBulkImportLinks={() => setIsBulkImportOpen(true)}
actions={[
<NotionAccessibilityIndicator
key={"notion-status"}
@@ -219,6 +231,7 @@ export default function DocumentPage() {
targetType={"DOCUMENT"}
primaryVersion={primaryVersion}
mutateDocument={mutateDocument}
+ onBulkImportOpen={() => setIsBulkImportOpen(true)}
/>
{/* Visitors - Always show */}
@@ -235,6 +248,14 @@ export default function DocumentPage() {
setIsOpen={setIsLinkSheetOpen}
existingLinks={links}
/>
+
+ <BulkImportLinksModal
+ isOpen={isBulkImportOpen}
+ setIsOpen={setIsBulkImportOpen}
+ targetType="DOCUMENT"
+ targetId={prismaDocument.id}
+ onImported={mutateDocument}
+ />
</main>
</AppLayout>
);