Files
zeekayandHanzo Dev f77d5010d8 ee: delete the relocated upstream commercial code and its paywall
Papermark dual-licenses: AGPL-3.0 for the tree, a separate commercial
licence for ee/. We hold the first and not the second, so none of the
second may live here.

ee/ was already absent from main, but it was never deleted. 98f0da7fa
("ci: amd64-only build") renamed 150 files out of ee/ byte-identical
into features/, lib/billing/legacy/ (ee/stripe), lib/billing/limits/
(ee/limits), and flattened app/(ee)/ into app/ — putting commercially
licensed code under our AGPL root LICENSE. A rename is not a deletion.
Every path that commit moved is now gone, edited-since or not.

Deleted, with their routes and UI entry points: features/ai and
app/api/ai, features/workflows and app/api/{workflows,workflow-entry},
features/conversations and the Q&A/FAQ surface, features/security/sso
with app/api/auth/saml + app/api/scim + lib/jackson.ts (we use Hanzo
IAM OIDC natively), features/dataroom-invitations, features/templates,
features/access-notifications, features/conversions, features/
permissions. Five of these were gated by lib/featureFlags, which reads
@vercel/edge-config and returns false for every flag when EDGE_CONFIG
is unset — every non-Vercel deployment we run. Those flags are gone too.

Deleted the commercial gating outright rather than reimplementing it:
lib/billing/legacy (ee/stripe) and lib/billing/limits (ee/limits), the
upgrade modals and banners, UpgradeButton, FeaturePreview, PlanBadge,
the trial and blocking modals, /settings/upgrade, /settings/billing and
the billing checkout/seat/pause/cancel API. usePlan() no longer returns
capability booleans — the plan tag describes provisioning, it is not a
permission — and useLimits() is gone with every quota check it fed.
Subscription pause went the same way. Also dropped the npm dependencies
that existed only for the removed features (@boxyhq/saml-jackson, the
@ai-sdk packages, openai, streamdown, use-stick-to-bottom,
@trigger.dev/python) and the Jackson-specific next.config webpack shims.

Rewritten as original Hanzo code where a capability was load-bearing:
- lib/utils/get-file-size-limits.ts — one UPLOAD_LIMITS set plus
  getFileSizeLimit(contentType), env-overridable. Operational limits,
  not commercial ones, so the tus and browser-upload paths still refuse
  oversized files without consulting a plan matrix.
- components/links/link-sheet/permissions-sheet.tsx — a flat, depth
  annotated item list with view/download switches over the same
  /permission-groups API. Two states, not three. ItemPermission now has
  a single definition in lib/types.ts.
- app/api/links/[id]/upload/route.ts — visitor uploads, built around one
  authorize() helper shared by GET and POST, and a notification debounce
  keyed per (link, viewer) instead of listing and cancelling runs.

There is now exactly one link sheet: the ee DataroomLinkSheet duplicated
the AGPL LinkSheet, which already handled DATAROOM_LINK. Replaced
upstream's Omit<LinkType, "WORKFLOW_LINK"> — Omit on a string union
yields an object type and never narrowed anything — with a real union.

Verified: the S3/tus upload+download harness passes 13/13 against MinIO
after the deletions, and tsc goes from 257 pre-existing errors on
origin/main to 192 with zero files worse than baseline.

Reasoning recorded in LLM.md. LICENSE untouched.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-03 20:19:21 -07:00

876 lines
28 KiB
TypeScript

import { useRouter } from "next/router";
import { FormEvent, useEffect, useState } from "react";
import { useTeam } from "@/context/team-context";
import { DefaultPermissionStrategy } from "@prisma/client";
import { parsePageId } from "notion-utils";
import { toast } from "sonner";
import { mutate } from "swr";
import { z } from "zod";
import { useAnalytics } from "@/lib/analytics";
import {
DocumentData,
createDocument,
createNewDocumentVersion,
} from "@/lib/documents/create-document";
import { putFile } from "@/lib/files/put-file";
import { useDataroomPermissions } from "@/lib/hooks/use-dataroom-permissions";
import { getNotionPageIdFromSlug } from "@/lib/notion/utils";
import { usePlan } from "@/lib/swr/use-billing";
import { useDataroom } from "@/lib/swr/use-dataroom";
import { getSupportedContentType } from "@/lib/utils/get-content-type";
import { SetUnifiedPermissionsModal } from "@/components/datarooms/groups/set-unified-permissions-modal";
import DocumentUpload from "@/components/document-upload";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
interface DataroomDocument {
id: string;
documentId: string;
dataroomId: string;
}
export function AddDocumentModal({
newVersion,
children,
isDataroom,
dataroomId,
setAddDocumentModalOpen,
openModal,
}: {
newVersion?: boolean;
children: React.ReactNode;
isDataroom?: boolean;
openModal?: boolean;
dataroomId?: string;
setAddDocumentModalOpen?: (isOpen: boolean) => void;
}) {
const router = useRouter();
const analytics = useAnalytics();
const [uploading, setUploading] = useState<boolean>(false);
const [isOpen, setIsOpen] = useState<boolean | undefined>(undefined);
const [currentFile, setCurrentFile] = useState<File | null>(null);
const [notionLink, setNotionLink] = useState<string | null>(null);
const [webLink, setWebLink] = useState<string | null>(null);
const [uploadMode, setUploadMode] = useState<"file" | "link">("file");
const [showGroupPermissions, setShowGroupPermissions] = useState(false);
const [uploadedFiles, setUploadedFiles] = useState<
{
documentId: string;
dataroomDocumentId: string;
fileName: string;
}[]
>([]);
const teamInfo = useTeam();
const { plan } = usePlan();
const { dataroom } = useDataroom();
const teamId = teamInfo?.currentTeam?.id as string;
const { applyPermissions } = useDataroomPermissions();
useEffect(() => {
if (openModal) setIsOpen(openModal);
}, [openModal]);
/** current folder name */
const currentFolderPath = router.query.name as string[] | undefined;
const addDocumentToDataroom = async ({
documentId,
folderPathName,
}: {
documentId: string;
folderPathName?: string;
}): Promise<Response | undefined> => {
try {
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
documentId: documentId,
folderPathName: folderPathName,
}),
},
);
if (!response.ok) {
const { message } = await response.json();
toast.error(message);
return undefined;
}
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
);
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${folderPathName}`,
);
toast.success("Document added to dataroom successfully! 🎉");
return response;
} catch (error) {
toast.error("Error adding document to dataroom.");
console.error(
"An error occurred while adding document to the dataroom: ",
error,
);
return undefined;
}
};
const toastErrorMessage = () =>
toast.error(
"Failed to apply default permissions. Update the group permissions in the group settings.",
);
const applyUnifiedPermissionsToDocument = async (
document: any,
dataroomDocument: DataroomDocument & {
dataroom: {
_count: { viewerGroups: number; permissionGroups: number };
};
},
currentFolderPath?: string[],
): Promise<void> => {
const hasAnyGroups =
dataroomDocument.dataroom._count.viewerGroups > 0 ||
dataroomDocument.dataroom._count.permissionGroups > 0;
if (!hasAnyGroups) return;
const strategy =
dataroom?.defaultPermissionStrategy ||
DefaultPermissionStrategy.INHERIT_FROM_PARENT;
if (strategy === DefaultPermissionStrategy.ASK_EVERY_TIME) {
setShowGroupPermissions(true);
setUploadedFiles([
{
documentId: document.id,
dataroomDocumentId: dataroomDocument.id,
fileName: document.name,
},
]);
} else if (strategy === DefaultPermissionStrategy.INHERIT_FROM_PARENT) {
const isRootLevel = !currentFolderPath || currentFolderPath.length === 0;
try {
const result = await applyPermissions(
dataroomId!,
[document.id],
"INHERIT_FROM_PARENT",
isRootLevel ? undefined : currentFolderPath?.join("/"),
toastErrorMessage,
);
if (!result.success) {
console.error("Failed to apply permissions:", result.error);
toastErrorMessage();
}
} catch (error) {
console.error("Failed to apply permissions:", error);
toastErrorMessage();
}
}
// strategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT - do nothing, documents remain hidden
};
const handleFileUpload = async (
event: FormEvent<HTMLFormElement>,
): Promise<void> => {
event.preventDefault();
// Check if the file is chosen
if (!currentFile) {
toast.error("Please select a file to upload.");
return; // prevent form from submitting
}
try {
setUploading(true);
let contentType = currentFile.type;
let supportedFileType = getSupportedContentType(contentType);
if (
currentFile.name.endsWith(".dwg") ||
currentFile.name.endsWith(".dxf")
) {
supportedFileType = "cad";
contentType = `image/vnd.${currentFile.name.split(".").pop()}`;
}
if (currentFile.name.endsWith(".xlsm")) {
supportedFileType = "sheet";
contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
if (!supportedFileType) {
setUploading(false);
toast.error(
"Unsupported file format. Please upload a PDF, Powerpoint, Excel, Word or image file.",
);
return;
}
const { type, data, numPages, fileSize } = await putFile({
file: currentFile,
teamId,
});
const documentData: DocumentData = {
name: currentFile.name,
key: data!,
storageType: type!,
contentType: contentType,
supportedFileType: supportedFileType,
fileSize: fileSize,
};
let response: Response | undefined;
// create a document or new version in the database
if (!newVersion) {
// create a document in the database
response = await createDocument({
documentData,
teamId,
numPages,
folderPathName: currentFolderPath?.join("/"),
});
} else {
// create a new version for existing document in the database
const documentId = router.query.id as string;
response = await createNewDocumentVersion({
documentData,
documentId,
numPages,
teamId,
});
}
if (response) {
const document = await response.json();
if (isDataroom && dataroomId) {
const dataroomResponse = await addDocumentToDataroom({
documentId: document.id,
folderPathName: currentFolderPath?.join("/"),
});
if (dataroomResponse?.ok) {
const dataroomDocument =
(await dataroomResponse.json()) as DataroomDocument & {
dataroom: {
_count: { viewerGroups: number; permissionGroups: number };
};
};
await applyUnifiedPermissionsToDocument(
document,
dataroomDocument,
currentFolderPath,
);
}
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
numPages: document.numPages,
path: router.asPath,
type: document.type,
teamId: teamId,
dataroomId: dataroomId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
return;
}
if (!newVersion) {
mutate(`/api/teams/${teamId}/documents`);
toast.success("Document uploaded. Redirecting to document page...");
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
numPages: document.numPages,
path: router.asPath,
type: document.type,
teamId: teamId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
// redirect to the document page
router.push("/documents/" + document.id);
} else {
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
numPages: document.numPages,
path: router.asPath,
type: document.type,
newVersion: true,
teamId: teamId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
toast.success("New document version uploaded.");
// reload to the document page
router.reload();
}
}
} catch (error) {
setUploading(false);
toast.error("An error occurred while uploading the file.");
console.error("An error occurred while uploading the file: ", error);
} finally {
setUploading(false);
setIsOpen(false);
setAddDocumentModalOpen && setAddDocumentModalOpen(false);
}
};
const createNotionFileName = () => {
// Extract Notion file name from the URL
const urlSegments = (notionLink as string).split("/")[3];
// Remove the last hyphen along with the Notion ID
const extractName = urlSegments.replace(/-([^/-]+)$/, "");
const notionFileName = extractName.replaceAll("-", " ") || "Notion Link";
return notionFileName;
};
const handleNotionUpload = async (
event: FormEvent<HTMLFormElement>,
): Promise<void> => {
event.preventDefault();
// Check if the field is empty or not
if (!notionLink) {
toast.error("Please enter a Notion link to proceed.");
return; // prevent form from submitting
}
// Validate URL format with Zod
const urlSchema = z.string().url();
const urlValidation = urlSchema.safeParse(notionLink);
if (!urlValidation.success) {
toast.error("Please enter a valid URL format.");
return;
}
// Try to validate the Notion page URL
let validateNotionPageId = parsePageId(notionLink);
// If parsePageId fails, try to get page ID from slug
if (validateNotionPageId === null) {
try {
const pageId = await getNotionPageIdFromSlug(notionLink);
validateNotionPageId = pageId || undefined;
} catch (slugError) {
toast.error("Please enter a valid Notion link to proceed.");
return;
}
}
if (!validateNotionPageId) {
toast.error("Please enter a valid Notion link to proceed.");
return;
}
try {
setUploading(true);
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/documents`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: createNotionFileName(),
url: notionLink,
numPages: 1,
type: "notion",
createLink: false,
folderPathName: currentFolderPath?.join("/"),
}),
},
);
if (!response.ok) {
const { error } = await response.json();
toast.error(error);
return;
}
const document = await response.json();
if (isDataroom && dataroomId) {
const dataroomResponse = await addDocumentToDataroom({
documentId: document.id,
folderPathName: currentFolderPath?.join("/"),
});
if (dataroomResponse?.ok) {
const dataroomDocument =
(await dataroomResponse.json()) as DataroomDocument & {
dataroom: {
_count: { viewerGroups: number; permissionGroups: number };
};
};
await applyUnifiedPermissionsToDocument(
document,
dataroomDocument,
currentFolderPath,
);
}
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
numPages: document.numPages,
path: router.asPath,
type: "notion",
teamId: teamId,
dataroomId: dataroomId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
return;
}
if (!newVersion) {
toast.success("Notion Page processed. Redirecting to document page...");
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
fileSize: null,
path: router.asPath,
type: "notion",
teamId: teamId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
// redirect to the document page
router.push("/documents/" + document.id);
}
} catch (error) {
setUploading(false);
toast.error(
"Oops! Can't access the Notion page. Please double-check it's set to 'Public'.",
);
console.error(
"An error occurred while processing the Notion link: ",
error,
);
} finally {
setUploading(false);
setIsOpen(false);
}
};
const handleWebLinkUpload = async (
event: FormEvent<HTMLFormElement>,
): Promise<void> => {
event.preventDefault();
// Check if the field is empty or not
if (!webLink) {
toast.error("Please enter a website URL to proceed.");
return;
}
// Validate URL format with Zod
const urlSchema = z.string().url();
const urlValidation = urlSchema.safeParse(webLink);
if (!urlValidation.success) {
toast.error("Please enter a valid URL format.");
return;
}
try {
setUploading(true);
// Extract domain name from URL for the document name
let linkName = "Web Link";
try {
const url = new URL(webLink);
linkName = url.hostname.replace("www.", "");
} catch (e) {
// Use default name if URL parsing fails
}
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/documents`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: linkName,
url: webLink,
numPages: 1,
type: "link",
createLink: false,
folderPathName: currentFolderPath?.join("/"),
}),
},
);
if (!response.ok) {
const { error } = await response.json();
toast.error(error);
return;
}
const document = await response.json();
if (isDataroom && dataroomId) {
const dataroomResponse = await addDocumentToDataroom({
documentId: document.id,
folderPathName: currentFolderPath?.join("/"),
});
if (dataroomResponse?.ok) {
const dataroomDocument =
(await dataroomResponse.json()) as DataroomDocument & {
dataroom: {
_count: { viewerGroups: number; permissionGroups: number };
};
};
await applyUnifiedPermissionsToDocument(
document,
dataroomDocument,
currentFolderPath,
);
}
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
numPages: document.numPages,
path: router.asPath,
type: "link",
teamId: teamId,
dataroomId: dataroomId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
return;
}
if (!newVersion) {
toast.success("Web link added. Redirecting to document page...");
analytics.capture("Document Added", {
documentId: document.id,
name: document.name,
fileSize: null,
path: router.asPath,
type: "link",
teamId: teamId,
$set: {
teamId: teamId,
teamPlan: plan,
},
});
// redirect to the document page
router.push("/documents/" + document.id);
}
} catch (error) {
setUploading(false);
toast.error("An error occurred while processing the web link.");
console.error("An error occurred while processing the web link: ", error);
} finally {
setUploading(false);
setIsOpen(false);
}
};
const clearModelStates = () => {
currentFile !== null && setCurrentFile(null);
notionLink !== null && setNotionLink(null);
webLink !== null && setWebLink(null);
setUploadMode("file");
setIsOpen(!isOpen);
setAddDocumentModalOpen && setAddDocumentModalOpen(!isOpen);
};
return (
<>
<Dialog open={isOpen} onOpenChange={clearModelStates}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent
className="border-none bg-transparent text-foreground shadow-none"
isDocumentDialog
>
<DialogTitle className="sr-only">Add Document</DialogTitle>
<DialogDescription className="sr-only">
An overlayed modal that can be clicked to upload a document
</DialogDescription>
<Tabs defaultValue="document">
{!newVersion ? (
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="document">Document</TabsTrigger>
<TabsTrigger value="notion">Notion Page</TabsTrigger>
</TabsList>
) : (
<TabsList className="grid w-full grid-cols-1">
<TabsTrigger value="document">Document</TabsTrigger>
</TabsList>
)}
<TabsContent value="document">
<Card>
<CardHeader className="space-y-3">
<CardTitle>
{newVersion ? `Upload a new version` : `Share a document`}
</CardTitle>
<CardDescription>
{newVersion
? `After you upload a new version, the existing links will remain unchanged.`
: `After you upload the document, create a shareable link.`}
</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
{uploadMode === "file" ? (
<form
encType="multipart/form-data"
onSubmit={handleFileUpload}
className="flex flex-col space-y-4"
>
<div className="space-y-1">
<div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
<DocumentUpload
currentFile={currentFile}
setCurrentFile={setCurrentFile}
/>
</div>
</div>
<div className="flex justify-center">
<Button
type="submit"
className="w-full lg:w-1/2"
disabled={uploading || !currentFile}
loading={uploading}
>
{uploading ? "Uploading..." : "Upload Document"}
</Button>
</div>
{!newVersion && (
<div className="flex justify-center">
<p className="text-sm text-muted-foreground">
Want to{" "}
<button
type="button"
className="underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"
onClick={(e) => {
e.stopPropagation();
document
.getElementById("upload-multi-files-zone")
?.click();
clearModelStates();
}}
>
upload multiple files
</button>{" "}
or{" "}
<button
type="button"
className="inline-flex items-center gap-1 underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"
onClick={(e) => {
e.preventDefault();
setUploadMode("link");
}}
>
share link as a document
</button>
?
</p>
</div>
)}
</form>
) : (
<form
encType="multipart/form-data"
onSubmit={handleWebLinkUpload}
className="flex flex-col space-y-4"
>
<div className="space-y-1">
<Label htmlFor="web-link">Website URL</Label>
<div className="mt-2">
<input
type="text"
name="web-link"
id="web-link"
placeholder="https://example.com"
className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
value={webLink || ""}
onChange={(e) => setWebLink(e.target.value)}
/>
</div>
{/* <small className="text-xs text-muted-foreground">
The page will be captured and converted to a document format.
</small> */}
</div>
<div className="flex justify-center">
<Button
type="submit"
className="w-full lg:w-1/2"
disabled={uploading || !webLink}
loading={uploading}
>
{uploading ? "Saving..." : "Save Web Link"}
</Button>
</div>
<div className="flex justify-center">
<button
type="button"
className="flex items-center gap-2 text-sm text-muted-foreground underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"
onClick={(e) => {
e.preventDefault();
setUploadMode("file");
}}
>
<svg
className="h-4 w-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
/>
</svg>
Back to file upload
</button>
</div>
</form>
)}
</CardContent>
</Card>
</TabsContent>
{!newVersion && (
<TabsContent value="notion">
<Card>
<CardHeader className="space-y-3">
<CardTitle>Share a Notion Page</CardTitle>
<CardDescription>
After you submit the Notion link, a shareable link will be
generated and copied to your clipboard. Just like with a
PDF document.
</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<form
encType="multipart/form-data"
onSubmit={handleNotionUpload}
className="flex flex-col"
>
<div className="space-y-1 pb-8">
<Label htmlFor="notion-link">Notion Page Link</Label>
<div className="mt-2">
<input
type="text"
name="notion-link"
id="notion-link"
placeholder="notion.site/..."
className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"
value={notionLink || ""}
onChange={(e) => setNotionLink(e.target.value)}
/>
</div>
<small className="text-xs text-muted-foreground">
Your Notion page needs to be shared publicly.
</small>
</div>
<div className="flex justify-center">
<Button
type="submit"
className="w-full lg:w-1/2"
disabled={uploading || !notionLink}
loading={uploading}
>
{uploading ? "Saving..." : "Save Notion Link"}
</Button>
</div>
</form>
</CardContent>
</Card>
</TabsContent>
)}
</Tabs>
</DialogContent>
</Dialog>
{showGroupPermissions && dataroomId && (
<SetUnifiedPermissionsModal
open={showGroupPermissions}
setOpen={setShowGroupPermissions}
dataroomId={dataroomId}
uploadedFiles={uploadedFiles}
onComplete={() => {
setShowGroupPermissions(false);
setAddDocumentModalOpen?.(false);
setUploadedFiles([]);
}}
/>
)}
</>
);
}