Skip to content

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

feat: add cleaner link presets

Marc Seitz69deb225f129
diff --git a/components/links/link-sheet/agreement-panel/index.tsx b/components/links/link-sheet/agreement-panel/index.tsx
index 34ae635c..e0d2d991 100644
--- a/components/links/link-sheet/agreement-panel/index.tsx
+++ b/components/links/link-sheet/agreement-panel/index.tsx
@@ -10,6 +10,13 @@ import { useTeam } from "@/context/team-context";
import { toast } from "sonner";
import { mutate } from "swr";
+import {
+ DocumentData,
+ createAgreementDocument,
+} from "@/lib/documents/create-document";
+import { putFile } from "@/lib/files/put-file";
+import { getSupportedContentType } from "@/lib/utils/get-content-type";
+
import DocumentUpload from "@/components/document-upload";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -24,13 +31,6 @@ import {
SheetTitle,
} from "@/components/ui/sheet";
-import {
- DocumentData,
- createAgreementDocument,
-} from "@/lib/documents/create-document";
-import { putFile } from "@/lib/files/put-file";
-import { getSupportedContentType } from "@/lib/utils/get-content-type";
-
import LinkItem from "../link-item";
export default function AgreementSheet({
@@ -40,11 +40,11 @@ export default function AgreementSheet({
isOnlyView = false,
onClose,
}: {
- defaultData?: { name: string; link: string; requireName: boolean } | null;
+ defaultData?: { name: string; link: string; requireName: boolean } | null;
isOpen: boolean;
setIsOpen: Dispatch<SetStateAction<boolean>>;
- isOnlyView?: boolean;
- onClose?: () => void;
+ isOnlyView?: boolean;
+ onClose?: () => void;
}) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
@@ -188,12 +188,13 @@ export default function AgreementSheet({
<Sheet open={isOpen} onOpenChange={handleClose}>
<SheetContent className="flex h-full w-[85%] flex-col justify-between bg-background px-4 text-foreground sm:w-[500px] md:px-5">
<SheetHeader className="text-start">
- <SheetTitle>{isOnlyView ? "View Agreement" : "Create a new agreement"}</SheetTitle>
+ <SheetTitle>
+ {isOnlyView ? "View Agreement" : "Create a new agreement"}
+ </SheetTitle>
<SheetDescription>
{isOnlyView
? "View the details of this agreement."
- : "An agreement is a special document that visitors must accept before accessing your link. You can create a new agreement here."
- }
+ : "An agreement is a special document that visitors must accept before accessing your link. You can create a new agreement here."}
</SheetDescription>
</SheetHeader>
@@ -262,29 +263,33 @@ export default function AgreementSheet({
/>
</div>
- {!isOnlyView ? <div className="space-y-12">
- <div className="space-y-2 pb-6">
- <Label>Or upload an agreement</Label>
- <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
- <DocumentUpload
- currentFile={currentFile}
- setCurrentFile={setCurrentFile}
- />
+ {!isOnlyView ? (
+ <div className="space-y-12">
+ <div className="space-y-2 pb-6">
+ <Label>Or upload an agreement</Label>
+ <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
+ <DocumentUpload
+ currentFile={currentFile}
+ setCurrentFile={setCurrentFile}
+ />
+ </div>
</div>
</div>
- </div> : null}
+ ) : null}
</div>
</div>
- <SheetFooter className={`flex-shrink-0 ${isOnlyView ? "mt-6" : ""}`}>
+ <SheetFooter
+ className={`flex-shrink-0 ${isOnlyView ? "mt-6" : ""}`}
+ >
<div className="flex items-center">
{isOnlyView ? (
<Button type="button" onClick={() => handleClose(false)}>
Close
</Button>
) : (
- <Button type="submit" loading={isLoading}>
- Create Agreement
- </Button>
+ <Button type="submit" loading={isLoading}>
+ Create Agreement
+ </Button>
)}
</div>
</SheetFooter>
diff --git a/components/links/link-sheet/allow-list-section.tsx b/components/links/link-sheet/allow-list-section.tsx
index 37b102f4..521dd05d 100644
--- a/components/links/link-sheet/allow-list-section.tsx
+++ b/components/links/link-sheet/allow-list-section.tsx
@@ -1,16 +1,16 @@
import { useEffect, useState } from "react";
+import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
-import { Textarea } from "@/components/ui/textarea";
-
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
import { sanitizeAllowDenyList } from "@/lib/utils";
+import { Textarea } from "@/components/ui/textarea";
+
import { DEFAULT_LINK_TYPE } from ".";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
-import { LinkPreset } from "@prisma/client";
export default function AllowListSection({
data,
@@ -27,7 +27,7 @@ export default function AllowListSection({
trigger,
plan,
}: LinkUpgradeOptions) => void;
- presets: LinkPreset | null;
+ presets: LinkPreset | null;
}) {
const { emailProtected, allowList } = data;
@@ -39,13 +39,6 @@ export default function AllowListSection({
allowList?.join("\n") || "",
);
- useEffect(() => {
- if (isAllowed && presets?.enableAllowList) {
- setEnabled(true);
- setAllowListInput(presets.allowList?.join("\n") || "");
- }
- }, [presets, isAllowed]);
-
useEffect(() => {
// Update the allowList in the data state when their inputs change
const newAllowList = sanitizeAllowDenyList(allowListInput);
@@ -56,6 +49,13 @@ export default function AllowListSection({
}));
}, [allowListInput, emailProtected, enabled, setData]);
+ useEffect(() => {
+ if (isAllowed && presets?.allowList && presets.allowList.length > 0) {
+ setEnabled(true);
+ setAllowListInput(presets.allowList.join("\n") || "");
+ }
+ }, [presets, isAllowed]);
+
const handleEnableAllowList = () => {
const updatedEnabled = !enabled;
setEnabled(updatedEnabled);
diff --git a/components/links/link-sheet/custom-fields-section.tsx b/components/links/link-sheet/custom-fields-section.tsx
index 3aaf0f01..97a5db64 100644
--- a/components/links/link-sheet/custom-fields-section.tsx
+++ b/components/links/link-sheet/custom-fields-section.tsx
@@ -1,44 +1,44 @@
-import { useEffect, useState, useCallback, useMemo } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { LinkPreset } from "@prisma/client";
import { SettingsIcon } from "lucide-react";
import { motion } from "motion/react";
+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
+
import { DEFAULT_LINK_TYPE } from "@/components/links/link-sheet";
import { Button } from "@/components/ui/button";
-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-
import { CustomFieldData } from "./custom-fields-panel";
import CustomFieldsPanel from "./custom-fields-panel";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
-import { LinkPreset } from "@prisma/client";
export default function CustomFieldsSection({
data,
setData,
isAllowed,
handleUpgradeStateChange,
- presets,
+ // presets,
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
isAllowed: boolean;
handleUpgradeStateChange: (options: LinkUpgradeOptions) => void;
- presets: LinkPreset | null;
+ // presets: LinkPreset | null;
}) {
const [enabled, setEnabled] = useState<boolean>(false);
const [isConfigOpen, setIsConfigOpen] = useState<boolean>(false);
- useEffect(() => {
- if (isAllowed && presets?.watermarkConfig) {
- setEnabled(true);
- setData((prevData) => ({
- ...prevData,
- customFields: presets.customFields ? JSON.parse(presets.customFields as string) as CustomFieldData[] : [],
- }));
- }
- }, [presets, isAllowed]);
+ // useEffect(() => {
+ // if (isAllowed && presets?.watermarkConfig) {
+ // setEnabled(true);
+ // setData((prevData) => ({
+ // ...prevData,
+ // customFields: presets.customFields ? JSON.parse(presets.customFields as string) as CustomFieldData[] : [],
+ // }));
+ // }
+ // }, [presets, isAllowed]);
useEffect(() => {
const hasCustomFields = data.customFields.length > 0;
@@ -49,33 +49,39 @@ export default function CustomFieldsSection({
const handleCustomFieldsToggle = useCallback(() => {
const updatedEnabled = !enabled;
- setData(prevData => ({
+ setData((prevData) => ({
...prevData,
customFields: updatedEnabled
? [
- {
- type: "SHORT_TEXT",
- identifier: "",
- label: "",
- placeholder: "",
- required: false,
- disabled: false,
- orderIndex: 0,
- },
- ]
+ {
+ type: "SHORT_TEXT",
+ identifier: "",
+ label: "",
+ placeholder: "",
+ required: false,
+ disabled: false,
+ orderIndex: 0,
+ },
+ ]
: [],
}));
setEnabled(updatedEnabled);
}, [enabled, setData]);
- const handleConfigSave = useCallback((fields: CustomFieldData[]) => {
- setData(prevData => ({
- ...prevData,
- customFields: fields,
- }));
- }, [setData]);
+ const handleConfigSave = useCallback(
+ (fields: CustomFieldData[]) => {
+ setData((prevData) => ({
+ ...prevData,
+ customFields: fields,
+ }));
+ },
+ [setData],
+ );
- const memoizedFields = useMemo(() => data.customFields || [], [data.customFields]);
+ const memoizedFields = useMemo(
+ () => data.customFields || [],
+ [data.customFields],
+ );
return (
<div className="pb-5">
@@ -139,4 +145,4 @@ export default function CustomFieldsSection({
/>
</div>
);
-};
\ No newline at end of file
+}
diff --git a/components/links/link-sheet/deny-list-section.tsx b/components/links/link-sheet/deny-list-section.tsx
index a260dc7e..db79fbcf 100644
--- a/components/links/link-sheet/deny-list-section.tsx
+++ b/components/links/link-sheet/deny-list-section.tsx
@@ -1,16 +1,16 @@
import { useEffect, useState } from "react";
+import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
-import { Textarea } from "@/components/ui/textarea";
-
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
import { sanitizeAllowDenyList } from "@/lib/utils";
+import { Textarea } from "@/components/ui/textarea";
+
import { DEFAULT_LINK_TYPE } from ".";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
-import { LinkPreset } from "@prisma/client";
export default function DenyListSection({
data,
@@ -21,14 +21,13 @@ export default function DenyListSection({
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
-
isAllowed: boolean;
handleUpgradeStateChange: ({
state,
trigger,
plan,
}: LinkUpgradeOptions) => void;
- presets: LinkPreset | null;
+ presets: LinkPreset | null;
}) {
const { emailProtected, denyList } = data;
// Initialize enabled state based on whether denyList is not null and not empty
@@ -39,13 +38,6 @@ export default function DenyListSection({
denyList?.join("\n") || "",
);
- useEffect(() => {
- if (isAllowed && presets?.enableDenyList) {
- setEnabled(true);
- setDenyListInput(presets.denyList?.join("\n") || "");
- }
- }, [presets, isAllowed]);
-
useEffect(() => {
// Update the denyList in the data state when their inputs change
const newDenyList = sanitizeAllowDenyList(denyListInput);
@@ -56,6 +48,13 @@ export default function DenyListSection({
}));
}, [denyListInput, enabled, emailProtected, setData]);
+ useEffect(() => {
+ if (isAllowed && presets?.denyList && presets.denyList.length > 0) {
+ setEnabled(true);
+ setDenyListInput(presets.denyList?.join("\n") || "");
+ }
+ }, [presets, isAllowed]);
+
const handleEnableDenyList = () => {
const updatedEnabled = !enabled;
setEnabled(updatedEnabled);
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index 91a9ce95..e480e9bd 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -1,20 +1,23 @@
+import Link from "next/link";
import { useRouter } from "next/router";
-import { Dispatch, SetStateAction, useEffect, useState } from "react";
+import { Dispatch, SetStateAction, use, useEffect, useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
-import { LinkAudienceType, LinkType } from "@prisma/client";
+import { LinkAudienceType, LinkPreset, LinkType } from "@prisma/client";
import { RefreshCwIcon } from "lucide-react";
import { toast } from "sonner";
import { mutate } from "swr";
+import useSWR from "swr";
import { useAnalytics } from "@/lib/analytics";
import { usePlan } from "@/lib/swr/use-billing";
import useDataroomGroups from "@/lib/swr/use-dataroom-groups";
import { useDomains } from "@/lib/swr/use-domains";
+import useLimits from "@/lib/swr/use-limits";
import { LinkWithViews, WatermarkConfig } from "@/lib/types";
-import { convertDataUrlToFile, uploadImage } from "@/lib/utils";
+import { convertDataUrlToFile, fetcher, uploadImage } from "@/lib/utils";
import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
import { Button } from "@/components/ui/button";
@@ -59,6 +62,8 @@ export const DEFAULT_LINK_PROPS = (
allowDownload: false,
allowList: [],
denyList: [],
+ enableAllowList: false,
+ enableDenyList: false,
enableNotification: true,
enableFeedback: false,
enableScreenshotProtection: false,
@@ -97,6 +102,8 @@ export type DEFAULT_LINK_TYPE = {
allowDownload: boolean;
allowList: string[];
denyList: string[];
+ enableAllowList: boolean;
+ enableDenyList: boolean;
enableNotification: boolean;
enableFeedback: boolean;
enableScreenshotProtection: boolean;
@@ -149,13 +156,33 @@ export default function LinkSheet({
mutate: mutateGroups,
} = useDataroomGroups();
const teamInfo = useTeam();
- const { isFree, isDatarooms, isDataroomsPlus, isTrial } = usePlan();
+ const { isFree, isPro, isBusiness, isDatarooms, isDataroomsPlus, isTrial } =
+ usePlan();
+ const { limits } = useLimits();
const analytics = useAnalytics();
const [data, setData] = useState<DEFAULT_LINK_TYPE>(
DEFAULT_LINK_PROPS(linkType, groupId, !isDatarooms),
);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isSaving, setIsSaving] = useState<boolean>(false);
+ const [currentPreset, setCurrentPreset] = useState<LinkPreset | null>(null);
+
+ const isPresetsAllowed =
+ (isPro && limits?.advancedLinkControlsOnPro) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus;
+
+ // Presets
+ const { data: presets } = useSWR<LinkPreset[]>(
+ teamInfo?.currentTeam?.id
+ ? `/api/teams/${teamInfo.currentTeam.id}/presets`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ },
+ );
useEffect(() => {
setData(currentLink || DEFAULT_LINK_PROPS(linkType, groupId, !isDatarooms));
@@ -184,7 +211,44 @@ export default function LinkSheet({
const { previewToken } = await response.json();
const previewLink = `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}?previewToken=${previewToken}`;
setIsLoading(false);
- window.open(previewLink, "_blank");
+ const linkElement = document.createElement("a");
+ linkElement.href = previewLink;
+ linkElement.target = "_blank";
+ document.body.appendChild(linkElement);
+ linkElement.click();
+
+ setTimeout(() => {
+ document.body.removeChild(linkElement);
+ }, 100);
+ };
+
+ const applyPreset = (presetId: string) => {
+ const preset = presets?.find((p) => p.id === presetId);
+ if (!preset) return;
+
+ setData((prev) => ({
+ ...prev,
+ name: prev.name, // Keep existing name
+ domain: prev.domain, // Keep existing domain
+ slug: prev.slug, // Keep existing slug
+
+ // Apply preset values
+ emailProtected: preset.emailProtected ?? prev.emailProtected,
+ emailAuthenticated: preset.emailAuthenticated ?? prev.emailAuthenticated,
+ allowList: preset.allowList || prev.allowList,
+ denyList: preset.denyList || prev.denyList,
+ password: preset.password || prev.password,
+ enableCustomMetatag:
+ preset.enableCustomMetaTag ?? prev.enableCustomMetatag,
+ metaTitle: preset.metaTitle || prev.metaTitle,
+ metaDescription: preset.metaDescription || prev.metaDescription,
+ metaImage: preset.metaImage || prev.metaImage,
+ metaFavicon: preset.metaFavicon || prev.metaFavicon,
+ allowDownload: preset.allowDownload || prev.allowDownload,
+ expiresAt: preset.expiresAt || prev.expiresAt,
+ }));
+
+ setCurrentPreset(preset);
};
const handleSubmit = async (event: any, shouldPreview: boolean = false) => {
@@ -423,7 +487,6 @@ export default function LinkSheet({
<div className="space-y-6 pb-10 pt-2">
<div className="space-y-2">
<Label htmlFor="link-name">Link Name</Label>
-
<Input
type="text"
name="link-name"
@@ -445,6 +508,46 @@ export default function LinkSheet({
/>
</div>
+ {/* Preset Selector - only show when creating a new link */}
+ {!currentLink &&
+ isPresetsAllowed &&
+ presets &&
+ presets.length > 0 && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="preset">Link Preset</Label>
+ <Link href="/settings/presets">
+ <Button
+ variant="link"
+ size="sm"
+ className="text-xs"
+ >
+ Manage Presets
+ </Button>
+ </Link>
+ </div>
+ <Select onValueChange={applyPreset}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a preset" />
+ </SelectTrigger>
+ <SelectContent>
+ {presets.map((preset) => (
+ <SelectItem
+ key={preset.id}
+ value={preset.id}
+ >
+ {preset.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ Apply a preset to quickly configure link
+ settings
+ </p>
+ </div>
+ )}
+
<div className="relative flex items-center">
<Separator className="absolute bg-muted-foreground" />
<div className="relative mx-auto">
@@ -460,6 +563,7 @@ export default function LinkSheet({
targetId={targetId}
linkType={linkType}
editLink={!!currentLink}
+ currentPreset={currentPreset}
/>
</div>
</TabsContent>
@@ -549,6 +653,38 @@ export default function LinkSheet({
/>
</div>
+ {/* Preset Selector for Group links - only show when creating a new link */}
+ {!currentLink && presets && presets.length > 0 && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="preset">Link Preset</Label>
+ <Button
+ variant="link"
+ size="sm"
+ className="text-xs"
+ onClick={() => router.push("/settings/presets")}
+ >
+ Manage Presets
+ </Button>
+ </div>
+ <Select onValueChange={applyPreset}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a preset" />
+ </SelectTrigger>
+ <SelectContent>
+ {presets.map((preset) => (
+ <SelectItem key={preset.id} value={preset.id}>
+ {preset.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ Apply a preset to quickly configure link settings
+ </p>
+ </div>
+ )}
+
<div className="space-y-2">
<DomainSection
{...{ data, setData, domains }}
diff --git a/components/links/link-sheet/link-options.tsx b/components/links/link-sheet/link-options.tsx
index 1925c118..1222db56 100644
--- a/components/links/link-sheet/link-options.tsx
+++ b/components/links/link-sheet/link-options.tsx
@@ -2,6 +2,7 @@ import { useState } from "react";
import { PlanEnum } from "@/ee/stripe/constants";
import { LinkAudienceType, LinkType } from "@prisma/client";
+import { LinkPreset } from "@prisma/client";
import { usePlan } from "@/lib/swr/use-billing";
import useLimits from "@/lib/swr/use-limits";
@@ -27,10 +28,6 @@ import QuestionSection from "./question-section";
import ScreenshotProtectionSection from "./screenshot-protection-section";
import UploadSection from "./upload-section";
import WatermarkSection from "./watermark-section";
-import useSWRImmutable from "swr/immutable";
-import { LinkPreset } from "@prisma/client";
-import { fetcher } from "@/lib/utils";
-import { useTeam } from "@/context/team-context";
export type LinkUpgradeOptions = {
state: boolean;
@@ -44,12 +41,14 @@ export const LinkOptions = ({
targetId,
linkType,
editLink,
+ currentPreset,
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
targetId?: string;
linkType: LinkType;
editLink?: boolean;
+ currentPreset: LinkPreset | null;
}) => {
const {
isStarter,
@@ -59,12 +58,6 @@ export const LinkOptions = ({
isDataroomsPlus,
isTrial,
} = usePlan();
- const teamInfo = useTeam();
- console.log('data?.id', data?.id)
- const { data: presets } = useSWRImmutable<LinkPreset>(
- `/api/teams/${teamInfo?.currentTeam?.id}/presets`,
- fetcher,
- );
const { limits } = useLimits();
const allowAdvancedLinkControls = limits
? limits?.advancedLinkControlsOnPro
@@ -86,7 +79,6 @@ export const LinkOptions = ({
setUpgradePlan(plan as PlanEnum);
}
};
- const presetsData = editLink ? null : presets!;
return (
<div>
@@ -106,7 +98,6 @@ export const LinkOptions = ({
) : null}
<OGSection
{...{ data, setData }}
- presets={presetsData}
isAllowed={
isTrial ||
(isPro && allowAdvancedLinkControls) ||
@@ -116,6 +107,7 @@ export const LinkOptions = ({
}
handleUpgradeStateChange={handleUpgradeStateChange}
editLink={editLink ?? false}
+ presets={currentPreset}
/>
<EmailAuthenticationSection
@@ -132,7 +124,6 @@ export const LinkOptions = ({
{data.audienceType === LinkAudienceType.GENERAL ? (
<AllowListSection
{...{ data, setData }}
- presets={presetsData}
isAllowed={
isTrial ||
(isPro && allowAdvancedLinkControls) ||
@@ -141,6 +132,7 @@ export const LinkOptions = ({
isDataroomsPlus
}
handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={currentPreset}
/>
) : null}
{data.audienceType === LinkAudienceType.GENERAL ? (
@@ -153,8 +145,8 @@ export const LinkOptions = ({
isDatarooms ||
isDataroomsPlus
}
- presets={presetsData}
handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={currentPreset}
/>
) : null}
<PasswordSection {...{ data, setData }} />
@@ -174,8 +166,8 @@ export const LinkOptions = ({
isAllowed={
isTrial || isDatarooms || isDataroomsPlus || allowWatermarkOnBusiness
}
- presets={presetsData}
handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={currentPreset}
/>
<AgreementSection
{...{ data, setData }}
@@ -213,7 +205,6 @@ export const LinkOptions = ({
) : null}
<CustomFieldsSection
{...{ data, setData }}
- presets={presetsData}
isAllowed={isTrial || isBusiness || isDatarooms || isDataroomsPlus}
handleUpgradeStateChange={handleUpgradeStateChange}
/>
diff --git a/components/links/link-sheet/og-section.tsx b/components/links/link-sheet/og-section.tsx
index 8b6955b9..a496b033 100644
--- a/components/links/link-sheet/og-section.tsx
+++ b/components/links/link-sheet/og-section.tsx
@@ -5,14 +5,14 @@ import { Label } from "@radix-ui/react-label";
import { Upload as ArrowUpTrayIcon, PlusIcon } from "lucide-react";
import { motion } from "motion/react";
-import { Input } from "@/components/ui/input";
-import LoadingSpinner from "@/components/ui/loading-spinner";
-import { Textarea } from "@/components/ui/textarea";
-
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
import { cn, fetcher, validateImageDimensions } from "@/lib/utils";
import { resizeImage } from "@/lib/utils/resize-image";
+import { Input } from "@/components/ui/input";
+import LoadingSpinner from "@/components/ui/loading-spinner";
+import { Textarea } from "@/components/ui/textarea";
+
import { DEFAULT_LINK_TYPE } from ".";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
@@ -34,7 +34,7 @@ export default function OGSection({
plan,
}: LinkUpgradeOptions) => void;
editLink: boolean;
- presets: LinkPreset | null;
+ presets: LinkPreset | null;
}) {
const {
enableCustomMetatag,
@@ -44,11 +44,6 @@ export default function OGSection({
metaFavicon,
} = data;
- console.log(enableCustomMetatag,
- metaTitle,
- metaDescription,
- metaImage,
- metaFavicon, 'presets')
const [enabled, setEnabled] = useState<boolean>(false);
const [fileError, setFileError] = useState<string | null>(null);
const [dragActive, setDragActive] = useState(false);
@@ -80,33 +75,33 @@ export default function OGSection({
setEnabled(enableCustomMetatag);
}, [enableCustomMetatag]);
- useEffect(() => {
- if (
- presets?.enableCustomMetaTag &&
- !(metaTitle || metaDescription || metaImage || metaFavicon)
- ) {
- const preset = presets;
- if (preset) {
- setData((prev) => ({
- ...prev,
- metaFavicon: prev.metaFavicon || preset.metaFavicon,
- metaImage: prev.metaImage || preset.metaImage,
- metaTitle: prev.metaTitle || preset.metaTitle,
- metaDescription: prev.metaDescription || preset.metaDescription,
- enableCustomMetatag: !editLink && true,
- }));
- }
- }
- }, [
- presets,
- setData,
- editLink,
- metaFavicon,
- enableCustomMetatag,
- metaTitle,
- metaDescription,
- metaImage,
- ]);
+ // useEffect(() => {
+ // if (
+ // presets?.enableCustomMetaTag &&
+ // !(metaTitle || metaDescription || metaImage || metaFavicon)
+ // ) {
+ // const preset = presets;
+ // if (preset) {
+ // setData((prev) => ({
+ // ...prev,
+ // metaFavicon: prev.metaFavicon || preset.metaFavicon,
+ // metaImage: prev.metaImage || preset.metaImage,
+ // metaTitle: prev.metaTitle || preset.metaTitle,
+ // metaDescription: prev.metaDescription || preset.metaDescription,
+ // enableCustomMetatag: !editLink && true,
+ // }));
+ // }
+ // }
+ // }, [
+ // presets,
+ // setData,
+ // editLink,
+ // metaFavicon,
+ // enableCustomMetatag,
+ // metaTitle,
+ // metaDescription,
+ // metaImage,
+ // ]);
const handleCustomMetatag = async () => {
const updatedCustomMetatag = !enabled;
diff --git a/components/links/link-sheet/watermark-section.tsx b/components/links/link-sheet/watermark-section.tsx
index ee2b865a..648180b0 100644
--- a/components/links/link-sheet/watermark-section.tsx
+++ b/components/links/link-sheet/watermark-section.tsx
@@ -1,20 +1,20 @@
import { useEffect, useState } from "react";
-import { SettingsIcon, StampIcon } from "lucide-react";
+import { LinkPreset } from "@prisma/client";
+import { SettingsIcon } from "lucide-react";
import { motion } from "motion/react";
+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
+import { WatermarkConfig } from "@/lib/types";
+
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { WatermarkConfig } from "@/lib/types";
-
import { DEFAULT_LINK_TYPE } from ".";
import LinkItem from "./link-item";
import { LinkUpgradeOptions } from "./link-options";
import WatermarkConfigSheet from "./watermark-panel";
-import { LinkPreset } from "@prisma/client";
export default function WatermarkSection({
data,
@@ -26,32 +26,34 @@ export default function WatermarkSection({
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
isAllowed: boolean;
- presets: LinkPreset | null;
handleUpgradeStateChange: ({
state,
trigger,
plan,
}: LinkUpgradeOptions) => void;
+ presets: LinkPreset | null;
}) {
const { enableWatermark, watermarkConfig } = data;
const [enabled, setEnabled] = useState<boolean>(false);
const [isConfigOpen, setIsConfigOpen] = useState<boolean>(false);
useEffect(() => {
- if (isAllowed && presets?.watermarkConfig) {
+ setEnabled(enableWatermark);
+ }, [enableWatermark]);
+
+ useEffect(() => {
+ if (isAllowed && presets?.enableWatermark && presets?.watermarkConfig) {
setEnabled(true);
setData((prevData) => ({
...prevData,
enableWatermark: true,
- watermarkConfig: presets.watermarkConfig ? JSON.parse(presets.watermarkConfig as string) as WatermarkConfig : null,
+ watermarkConfig: presets.watermarkConfig
+ ? (JSON.parse(presets.watermarkConfig as string) as WatermarkConfig)
+ : null,
}));
}
}, [presets, isAllowed]);
- useEffect(() => {
- setEnabled(enableWatermark);
- }, [enableWatermark]);
-
const handleWatermarkToggle = () => {
const updatedWatermark = !enabled;
diff --git a/components/settings/og-preview.tsx b/components/settings/og-preview.tsx
index 2d35de21..5d1e1125 100644
--- a/components/settings/og-preview.tsx
+++ b/components/settings/og-preview.tsx
@@ -3,18 +3,18 @@ import { Dispatch, SetStateAction, useMemo } from "react";
import { ImageIcon } from "lucide-react";
import ReactTextareaAutosize from "react-textarea-autosize";
+import { PresetDataSchema } from "@/lib/zod/schemas/presets";
+
import { Facebook } from "../shared/icons/facebook";
import LinkedIn from "../shared/icons/linkedin";
import Twitter from "../shared/icons/twitter";
-import { PresetData } from "@/pages/settings/presets";
-
export default function Preview({
data,
setData,
}: {
- data: PresetData;
- setData: Dispatch<SetStateAction<PresetData>>;
+ data: Partial<PresetDataSchema>;
+ setData: Dispatch<SetStateAction<Partial<PresetDataSchema>>>;
}) {
const {
metaTitle: title,
@@ -195,7 +195,7 @@ export default function Preview({
);
}
-const ImagePreview = ({ image }: { image: string | null }) => {
+const ImagePreview = ({ image }: { image: string | null | undefined }) => {
const previewImage = useMemo(() => {
if (image) {
return (
diff --git a/components/settings/presets/preset-options.tsx b/components/settings/presets/preset-options.tsx
deleted file mode 100644
index d9bd205b..00000000
--- a/components/settings/presets/preset-options.tsx
+++ /dev/null
@@ -1,585 +0,0 @@
-import { Dispatch, SetStateAction, useCallback, useState, useMemo, useEffect } from "react";
-import { Button } from "@/components/ui/button";
-import { Switch } from "@/components/ui/switch";
-import { Input } from "@/components/ui/input";
-import { Textarea } from "@/components/ui/textarea";
-import { Label } from "@/components/ui/label";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { BadgeTooltip } from "@/components/ui/tooltip";
-import { CircleHelpIcon, PlusIcon, MoreVertical, Pencil, Trash2, SettingsIcon } from "lucide-react";
-import { PresetData } from "@/pages/settings/presets";
-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { motion } from "motion/react";
-import LinkItem from "@/components/links/link-sheet/link-item";
-import { PlanEnum } from "@/ee/stripe/constants";
-import { LinkUpgradeOptions } from "@/components/links/link-sheet/link-options";
-import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
-import AgreementSheet from "@/components/links/link-sheet/agreement-panel";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Checkbox } from "@/components/ui/checkbox";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { format } from "date-fns";
-import { Badge } from "@/components/ui/badge";
-import CustomFieldsPanel, { CustomFieldData } from "@/components/links/link-sheet/custom-fields-panel";
-import { WatermarkConfig } from "@/lib/types";
-import WatermarkConfigSheet from "@/components/links/link-sheet/watermark-panel";
-import { Agreement } from "@prisma/client";
-import { cn, sanitizeAllowDenyList } from "@/lib/utils";
-import PlanBadge from "@/components/billing/plan-badge";
-import { toast } from "sonner";
-import { mutate } from "swr";
-interface PresetOptionsProps {
- data: PresetData;
- setData: Dispatch<SetStateAction<PresetData>>;
- agreements: (Agreement & { _count: { links: number } })[];
- teamId: string;
-};
-
-export default function PresetOptions({ data, setData, agreements, teamId }: PresetOptionsProps) {
- const { watermarkConfig } = data;
- const [openUpgradeModal, setOpenUpgradeModal] = useState(false);
- const [trigger, setTrigger] = useState("");
- const [isLoading, setIsLoading] = useState(false);
- const [isConfigOpen, setIsConfigOpen] = useState(false);
- const [isWatermarkConfigOpen, setIsWatermarkConfigOpen] = useState(false);
- const [isAgreementSheetVisible, setIsAgreementSheetVisible] =
- useState<boolean>(false);
- const [selectedAgreement, setSelectedAgreement] = useState<Agreement | null>(null);
- const [upgradePlan, setUpgradePlan] = useState<PlanEnum>(PlanEnum.Business);
- const [denyListInput, setDenyListInput] = useState<string>(
- data.denyList?.join("\n") || "",
- );
- const [allowListInput, setAllowListInput] = useState<string>(
- data.allowList?.join("\n") || "",
- );
-
- useEffect(() => {
- if (!denyListInput) {
- setDenyListInput(data.denyList?.join("\n") || "");
- }
- if (!allowListInput) {
- setAllowListInput(data.allowList?.join("\n") || "");
- }
- }, [data.denyList, data.allowList]);
-
- useEffect(() => {
- const timer = setTimeout(() => {
- const newDenyList = sanitizeAllowDenyList(denyListInput);
- const newAllowList = sanitizeAllowDenyList(allowListInput);
- setData((prevData) => ({
- ...prevData,
- denyList: newDenyList,
- allowList: newAllowList,
- }));
- }, 500);
-
- return () => clearTimeout(timer);
- }, [denyListInput, allowListInput, setData]);
-
- const handleCustomFieldsToggle = useCallback(() => {
- setData(prevData => {
- const updatedEnabled = !prevData.enableCustomFields;
- return {
- ...prevData,
- enableCustomFields: updatedEnabled,
- customFields: updatedEnabled
- ? [
- {
- type: "SHORT_TEXT",
- identifier: "",
- label: "",
- placeholder: "",
- required: false,
- disabled: false,
- orderIndex: 0,
- },
- ]
- : [],
- };
- });
- }, [setData]);
-
- const handleAllowListToggle = useCallback(() => {
- setData(prevData => ({
- ...prevData,
- enableAllowList: !prevData.enableAllowList,
- allowList: prevData.enableAllowList ? [] : data.allowList,
- }));
- }, [setData]);
-
- const handleDenyListToggle = useCallback(() => {
- setData(prevData => ({
- ...prevData,
- enableDenyList: !prevData.enableDenyList,
- denyList: prevData.enableDenyList ? [] : data.denyList,
- }));
- }, [setData]);
-
- const handleWatermarkToggle = useCallback(() => {
- setData(prevData => ({
- ...prevData,
- enableWatermark: !prevData.enableWatermark,
- watermarkConfig: prevData.enableWatermark ? null : data.watermarkConfig,
- }));
- }, [setData]);
-
- const handleToggle = useCallback((field: keyof PresetData) => {
- if (field === "enableCustomFields") {
- handleCustomFieldsToggle();
- return;
- }
- if (field === "enableAllowList") {
- handleAllowListToggle();
- return;
- }
- if (field === "enableDenyList") {
- handleDenyListToggle();
- return;
- }
- if (field === "enableWatermark") {
- handleWatermarkToggle();
- return;
- }
- setData(prevData => ({
- ...prevData,
- [field]: !prevData[field],
- }));
- }, [handleCustomFieldsToggle, handleAllowListToggle, handleDenyListToggle, setData]);
-
- const handleUpgradeStateChange = ({
- state,
- trigger,
- plan,
- }: LinkUpgradeOptions) => {
- setOpenUpgradeModal(state);
- setTrigger(trigger);
- if (plan) {
- setUpgradePlan(plan as PlanEnum);
- }
- };
-
- const handleConfigSave = useCallback((fields: CustomFieldData[]) => {
- setData(prevData => ({
- ...prevData,
- customFields: fields,
- }));
- }, [setData]);
-
- const handleWatermarkConfigSave = (config: WatermarkConfig) => {
- setData({
- ...data,
- watermarkConfig: config,
- });
- };
-
- const handleDeleteAgreement = async (agreementId: string) => {
- try {
- setIsLoading(true);
- const response = await fetch(`/api/teams/${teamId}/agreements/${agreementId}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- },
- });
- if (response.ok) {
- mutate(`/api/teams/${teamId}/agreements`, null, {
- populateCache: (_, agreements) => {
- return agreements.filter(
- (agreement: Agreement) =>
- agreement.id !== agreementId,
- );
- },
- revalidate: false,
- });
- toast.success("Agreement deleted successfully");
- } else {
- toast.error("Error deleting agreement - please try again");
- }
- } catch (error) {
- console.error('error', error);
- toast.error("Error deleting agreement - please try again");
- } finally {
- setIsLoading(false);
- }
- }
-
- const initialConfig: WatermarkConfig = {
- text: watermarkConfig?.text ?? "",
- isTiled: watermarkConfig?.isTiled ?? false,
- opacity: watermarkConfig?.opacity ?? 0.5,
- color: watermarkConfig?.color ?? "#000000",
- fontSize: watermarkConfig?.fontSize ?? 24,
- rotation: (watermarkConfig?.rotation ?? 45) as 0 | 30 | 45 | 90 | 180,
- position: (watermarkConfig?.position ?? "middle-center") as "top-left" | "top-center" | "top-right" | "middle-left" | "middle-center" | "middle-right" | "bottom-left" | "bottom-center" | "bottom-right",
- };
-
- const memoizedFields = useMemo(() => data.customFields || [], [data.customFields]);
-
- return (
- <div className="space-y-6">
- <Card>
- <CardHeader>
- <CardTitle>Custom Fields</CardTitle>
- <CardDescription>Set default custom fields to collect from viewers on new links</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <LinkItem
- title="Custom Fields"
- tooltipContent="Add custom fields to collect additional information from viewers"
- enabled={data.enableCustomFields}
- action={() => handleToggle("enableCustomFields")}
- isAllowed={true}
- requiredPlan="business"
- upgradeAction={() =>
- handleUpgradeStateChange({
- state: true,
- trigger: "custom_fields",
- plan: "Business",
- })
- }
- />
- {data.enableCustomFields && (
- <motion.div
- className="relative mt-4 space-y-3"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
- <div className="mt-2 flex w-full items-center justify-between">
- <div className="space-y-1">
- {memoizedFields.map((field, index) => (
- <p
- key={`${field.orderIndex}-${index}`}
- className="text-sm text-muted-foreground"
- >
- {field.orderIndex + 1}. {field.label || "Untitled Field"}
- {field.required && (
- <span className="italic"> (required)</span>
- )}
- </p>
- ))}
- </div>
- <Button
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setIsConfigOpen(true);
- }}
- variant="outline"
- className="h-8"
- size="sm"
- >
- <SettingsIcon className="mr-2 h-4 w-4" />
- Configure
- </Button>
- </div>
- </motion.div>
- )}
-
- <CustomFieldsPanel
- fields={memoizedFields}
- onChange={handleConfigSave}
- isConfigOpen={isConfigOpen}
- setIsConfigOpen={setIsConfigOpen}
- />
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between">
- <CardTitle>NDA Requirement</CardTitle>
- <Button
- variant="default"
- size="icon"
- className="w-auto px-2"
- onClick={() => setIsAgreementSheetVisible(true)}
- >
- <PlusIcon className="h-4 w-4" />Create Agreement
- </Button>
- </div>
- <CardDescription>Set a default NDA that's pre-filled when creating new links</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <h2
- className={cn(
- "flex flex-1 cursor-pointer flex-row items-center gap-2 text-sm font-medium leading-6 text-foreground",
- )}
- >
- <span>NDA Agreement</span>
- <BadgeTooltip
- content="Require viewers to accept an NDA before viewing"
- key="link_tooltip"
- link="https://www.papermark.com/help/article/require-nda-to-view"
- >
- <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
- </BadgeTooltip>
- </h2>
- {agreements?.length > 0 ? (
- <div className="mt-4 space-y-3">
- {agreements?.map((agreement) => (
- <Card key={agreement.id} onClick={() => {
- setIsAgreementSheetVisible(true);
- setSelectedAgreement(agreement);
- }}>
- <CardContent className="px-4 py-3">
- <div className="flex items-center justify-between">
- <div className="flex flex-col space-y-1">
- <Label htmlFor={agreement.id} className="cursor-pointer font-medium">
- {agreement.name}
- </Label>
- <div className="text-xs text-muted-foreground">
- Created on {format(
- new Date(agreement.createdAt),
- "MMM d, yyyy",
- )}
- </div>
- </div>
- <div className="flex items-center gap-4">
- <Badge variant="outline" className="flex items-center h-fit">
- {agreement._count.links} links
- </Badge>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- className="h-8 w-8 p-0"
- >
- <span className="sr-only">Open menu</span>
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Actions</DropdownMenuLabel>
- <DropdownMenuItem
- className="text-destructive focus:text-destructive"
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- handleDeleteAgreement(agreement.id);
- }}
- >
- {isLoading ? "Deleting..." : "Delete"}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- ) : (
- <div className="mt-4 flex h-24 items-center justify-center rounded-md border border-dashed border-muted-foreground/25 bg-muted/10">
- <div className="flex flex-col items-center space-y-2 text-center">
- <p className="text-sm text-muted-foreground">No agreements found</p>
- <p className="text-xs text-muted-foreground">Create an agreement to require viewers to accept an NDA</p>
- </div>
- </div>
- )}
- <AgreementSheet
- isOpen={isAgreementSheetVisible}
- setIsOpen={setIsAgreementSheetVisible}
- isOnlyView={!!selectedAgreement}
- defaultData={selectedAgreement ? {
- name: selectedAgreement.name,
- link: selectedAgreement.content,
- requireName: selectedAgreement.requireName,
- } : null}
- onClose={() => {
- setIsAgreementSheetVisible(false);
- setSelectedAgreement(null);
- }}
- />
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle>Watermark</CardTitle>
- <CardDescription>Set a default watermark to apply on documents when creating links</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <LinkItem
- title="Apply Watermark"
- link="https://www.papermark.com/help/article/document-watermark"
- tooltipContent="Add a dynamic watermark to your content."
- enabled={data.enableWatermark}
- action={() => handleToggle("enableWatermark")}
- isAllowed={true}
- requiredPlan="datarooms"
- upgradeAction={() =>
- handleUpgradeStateChange({
- state: true,
- trigger: "link_sheet_watermark_section",
- plan: "Data Rooms",
- })
- }
- />
- {data.enableWatermark && (
- <motion.div
- className="relative mt-4 space-y-3"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
- <div className="flex w-full flex-col items-start gap-6 overflow-x-visible pt-0">
- <div className="w-full space-y-2">
- <Label htmlFor="watermark-text">Watermark Text</Label>
- <Input
- id="watermark-text"
- type="text"
- name="text"
- placeholder="e.g. Confidential {{email}} {{date}}"
- value={data.watermarkConfig?.text ?? ""}
- required={data.enableWatermark}
- onChange={(e) => {
- setData((prevData) => ({
- ...prevData,
- watermarkConfig: {
- ...(data.watermarkConfig || initialConfig),
- text: e.target.value,
- },
- }));
- }}
- className="focus:ring-inset"
- />
- <div className="space-x-1 space-y-1">
- {["email", "date", "time", "link", "ipAddress"].map((item) => (
- <Button
- key={item}
- size="sm"
- variant="outline"
- className="h-7 rounded-3xl bg-muted text-sm font-normal text-foreground/80 hover:bg-muted/70"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setData((prevData) => ({
- ...prevData,
- watermarkConfig: {
- ...(prevData.watermarkConfig || initialConfig),
- text: `${prevData.watermarkConfig?.text || ""} {{${item}}}`,
- },
- }));
- }}
- >{`{{${item}}}`}</Button>
- ))}
- </div>
- </div>
- </div>
-
- <div className="mt-2 flex w-full items-center justify-between">
- <p className="text-sm text-muted-foreground">
- {initialConfig.isTiled ? `tiled` : initialConfig.position},{" "}
- {initialConfig.rotation}º, {initialConfig.fontSize}px,{" "}
- {initialConfig.color.toUpperCase()},{" "}
- {(1 - initialConfig.opacity) * 100}% transparent
- </p>
- <Button
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setIsWatermarkConfigOpen(true);
- }}
- variant="outline"
- className="h-8"
- size="sm"
- >
- <SettingsIcon className="mr-2 h-4 w-4" />
- Configure
- </Button>
- </div>
- </motion.div>
- )}
-
- <WatermarkConfigSheet
- isOpen={isWatermarkConfigOpen}
- onOpenChange={setIsWatermarkConfigOpen}
- initialConfig={initialConfig}
- onSave={handleWatermarkConfigSave}
- />
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Viewer Access Control</CardTitle>
- <CardDescription>Set a default access rule for who can view your documents</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <LinkItem
- title="Allow specified viewers"
- tooltipContent="Restrict access to a selected group of viewers. Enter allowed emails or domains."
- enabled={data.enableAllowList}
- link="https://www.papermark.com/help/article/allow-list"
- action={() => handleToggle("enableAllowList")}
- isAllowed={true}
- requiredPlan="business"
- upgradeAction={() =>
- handleUpgradeStateChange({
- state: true,
- trigger: "link_sheet_allowlist_section",
- plan: "Business",
- })
- }
- />
- {data.enableAllowList && (
- <motion.div
- className="mt-1 block w-full"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
- <Textarea
- className="focus:ring-inset"
- rows={5}
- placeholder={`Enter allowed emails/domains, one per line, e.g.
- value={allowListInput}
- onChange={(e) => setAllowListInput(e.target.value)}
- />
- </motion.div>
- )}
- <LinkItem
- title="Block specified viewers"
- tooltipContent="Prevent certain users from accessing the content. Enter blocked emails or domains."
- enabled={data.enableDenyList}
- link="https://www.papermark.com/help/article/block-list"
- action={() => handleToggle("enableDenyList")}
- isAllowed={true}
- requiredPlan="business"
- upgradeAction={() =>
- handleUpgradeStateChange({
- state: true,
- trigger: "link_sheet_denylist_section",
- plan: "Business",
- })
- }
- />
- {data.enableDenyList && (
- <motion.div
- className="mt-1 block w-full"
- {...FADE_IN_ANIMATION_SETTINGS}
- >
- <Textarea
- className="focus:ring-inset"
- rows={5}
- placeholder={`Enter blocked emails/domains, one per line, e.g.
- value={denyListInput}
- onChange={(e) => setDenyListInput(e.target.value)}
- />
- </motion.div>
- )}
- </CardContent>
- </Card>
-
- <UpgradePlanModal
- clickedPlan={upgradePlan}
- open={openUpgradeModal}
- setOpen={setOpenUpgradeModal}
- trigger={trigger}
- />
- </div >
- );
-}
\ No newline at end of file
diff --git a/components/settings/presets/social-media-card-preset.tsx b/components/settings/presets/social-media-card-preset.tsx
deleted file mode 100644
index dc86fa42..00000000
--- a/components/settings/presets/social-media-card-preset.tsx
+++ /dev/null
@@ -1,364 +0,0 @@
-import { ChangeEvent, useCallback, useState } from "react";
-import { Upload as ArrowUpTrayIcon, PlusIcon } from "lucide-react";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import { cn } from "@/lib/utils";
-import { resizeImage } from "@/lib/utils/resize-image";
-import { validateImageDimensions } from "@/lib/utils";
-import { PresetData } from "@/pages/settings/presets";
-
-interface SocialMediaCardPresetProps {
- data: PresetData;
- setData: React.Dispatch<React.SetStateAction<PresetData>>;
-}
-
-export default function SocialMediaCardPreset({
- data,
- setData,
-}: SocialMediaCardPresetProps) {
- const [fileError, setFileError] = useState<string | null>(null);
- const [faviconFileError, setFaviconFileError] = useState<string | null>(null);
- const [dragActive, setDragActive] = useState(false);
- const [faviconDragActive, setFaviconDragActive] = useState(false);
-
- const onChangePicture = useCallback(
- async (e: ChangeEvent<HTMLInputElement>) => {
- setFileError(null);
- const file = e.target.files && e.target.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 5) {
- setFileError("File size too big (max 5MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/jpeg" &&
- file.type !== "image/jpg"
- ) {
- setFileError("File type not supported (.png or .jpg only)");
- } else {
- const image = await resizeImage(file);
- setData((prev) => ({
- ...prev,
- metaImage: image,
- }));
- }
- }
- },
- [setData],
- );
-
- const onChangeFavicon = useCallback(
- async (e: ChangeEvent<HTMLInputElement>) => {
- setFaviconFileError(null);
- const file = e.target.files && e.target.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 1) {
- setFaviconFileError("File size too big (max 1MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/x-icon" &&
- file.type !== "image/svg+xml"
- ) {
- setFaviconFileError(
- "File type not supported (.png, .ico, .svg only)",
- );
- } else {
- const image = await resizeImage(file, {
- width: 36,
- height: 36,
- quality: 1,
- });
- const isValidDimensions = await validateImageDimensions(
- image,
- 16,
- 48,
- );
- if (!isValidDimensions) {
- setFaviconFileError(
- "Image dimensions must be between 16x16 and 48x48",
- );
- } else {
- setData((prev) => ({
- ...prev,
- metaFavicon: image,
- }));
- }
- }
- }
- },
- [setData],
- );
-
- return (
- <div className="relative mt-5 space-y-3 rounded-md px-5">
- <div>
- <div className="flex items-center justify-between">
- <p className="block text-sm font-medium text-foreground">
- Image
- </p>
- {fileError ? (
- <p className="text-sm text-red-500">{fileError}</p>
- ) : null}
- </div>
- <label
- htmlFor="mainImage"
- className="group relative mt-1 flex aspect-[1200/630] h-full cursor-pointer flex-col items-center justify-center rounded-md border border-input bg-white shadow-sm transition-all hover:border-muted-foreground hover:bg-gray-50 hover:ring-muted-foreground dark:bg-gray-800 hover:dark:bg-transparent"
- >
- <div
- className="absolute z-[5] h-full w-full rounded-md"
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragEnter={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragLeave={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- }}
- onDrop={async (e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- setFileError(null);
- const file =
- e.dataTransfer.files && e.dataTransfer.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 5) {
- setFileError("File size too big (max 5MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/jpeg" &&
- file.type !== "image/jpg"
- ) {
- setFileError(
- "File type not supported (.png or .jpg only)",
- );
- } else {
- const image = await resizeImage(file);
- setData((prev) => ({
- ...prev,
- metaImage: image,
- }));
- }
- }
- }}
- />
- <div
- className={cn(
- "absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md transition-all",
- dragActive &&
- "cursor-copy border-2 border-black bg-gray-50 opacity-100 dark:bg-transparent",
- data.metaImage
- ? "opacity-0 group-hover:opacity-100"
- : "group-hover:bg-gray-50 group-hover:dark:bg-transparent",
- )}
- >
- <ArrowUpTrayIcon
- className={cn(
- "h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95",
- dragActive ? "scale-110" : "scale-100",
- )}
- />
- <p className="mt-2 text-center text-sm text-gray-500">
- Drag and drop or click to upload.
- </p>
- <p className="mt-2 text-center text-sm text-gray-500">
- Recommended: 1200 x 630 pixels (max 5MB)
- </p>
- <span className="sr-only">OG image upload</span>
- </div>
- {data.metaImage && (
- <img
- src={data.metaImage}
- alt="Preview"
- className="h-full w-full rounded-md object-cover"
- />
- )}
- </label>
- <div className="mt-1 hidden rounded-md shadow-sm">
- <input
- id="mainImage"
- name="image"
- type="file"
- accept="image/png,image/jpeg,image/jpg"
- className="sr-only"
- onChange={onChangePicture}
- />
- </div>
- </div>
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between">
- <Label htmlFor="faviconIcon">
- Favicon Icon{" "}
- <span className="text-sm italic text-muted-foreground">
- (max 1 MB)
- </span>
- </Label>
- {faviconFileError ? (
- <p className="text-sm text-red-500">{faviconFileError}</p>
- ) : null}
- </div>
- <label
- htmlFor="faviconIcon"
- className="group relative mt-1 flex size-14 cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"
- style={{
- backgroundImage:
- "linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(135deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(135deg, transparent 75%, #ccc 75%)",
- backgroundSize: "20px 20px",
- backgroundPosition: "0 0, 10px 0, 10px -10px, 0px 10px",
- }}
- >
- <div
- className="absolute z-[5] h-full w-full rounded-md"
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setFaviconDragActive(true);
- }}
- onDragEnter={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setFaviconDragActive(true);
- }}
- onDragLeave={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setFaviconDragActive(false);
- }}
- onDrop={async (e) => {
- e.preventDefault();
- e.stopPropagation();
- setFaviconDragActive(false);
- setFaviconFileError(null);
- const file =
- e.dataTransfer.files && e.dataTransfer.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 1) {
- setFaviconFileError("File size too big (max 1MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/x-icon" &&
- file.type !== "image/svg+xml"
- ) {
- setFaviconFileError(
- "File type not supported (.png, .ico, .svg only)",
- );
- } else {
- const image = await resizeImage(file, {
- width: 36,
- height: 36,
- quality: 1,
- });
- const isValidDimensions =
- await validateImageDimensions(image, 16, 48);
- if (!isValidDimensions) {
- setFaviconFileError(
- "Image dimensions must be between 16x16 and 48x48",
- );
- } else {
- setData((prev) => ({
- ...prev,
- metaFavicon: image,
- }));
- }
- }
- }
- }}
- />
- <div
- className={`${faviconDragActive
- ? "cursor-copy border-2 border-black bg-gray-50 opacity-100"
- : ""
- } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md bg-white transition-all ${data.metaFavicon
- ? "opacity-0 group-hover:opacity-100"
- : "group-hover:bg-gray-50"
- }`}
- >
- <PlusIcon
- className={`${faviconDragActive ? "scale-110" : "scale-100"
- } h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
- />
- <span className="sr-only">OG image upload</span>
- </div>
- {data.metaFavicon && (
- <img
- src={data.metaFavicon}
- alt="Preview"
- className="h-full w-full rounded-md object-contain"
- />
- )}
- </label>
- <div className="mt-1 hidden rounded-md shadow-sm">
- <input
- id="faviconIcon"
- name="favicon"
- type="file"
- accept="image/png,image/x-icon,image/svg+xml"
- className="sr-only"
- onChange={onChangeFavicon}
- />
- </div>
- </div>
-
- <div>
- <div className="flex items-center justify-between">
- <p className="block text-sm font-medium text-foreground">
- Title
- </p>
- <p className="text-sm text-muted-foreground">
- {data.metaTitle?.length || 0}/120
- </p>
- </div>
- <div className="relative mt-1 flex rounded-md shadow-sm">
- <Input
- name="title"
- id="title"
- maxLength={120}
- className="focus:ring-inset"
- placeholder={`Papermark - open-source document sharing infrastructure.`}
- value={data.metaTitle || ""}
- onChange={(e) => {
- setData({ ...data, metaTitle: e.target.value });
- }}
- aria-invalid="true"
- />
- </div>
- </div>
-
- <div>
- <div className="flex items-center justify-between">
- <p className="block text-sm font-medium text-foreground">
- Description
- </p>
- <p className="text-sm text-muted-foreground">
- {data.metaDescription?.length || 0}/240
- </p>
- </div>
- <div className="relative mt-1 flex rounded-md shadow-sm">
- <Textarea
- name="description"
- id="description"
- rows={3}
- maxLength={240}
- className="focus:ring-inset"
- placeholder={`Papermark is an open-source document sharing infrastructure for modern teams.`}
- value={data.metaDescription || ""}
- onChange={(e) => {
- setData({
- ...data,
- metaDescription: e.target.value,
- });
- }}
- aria-invalid="true"
- />
- </div>
- </div>
- </div>
- );
-}
\ No newline at end of file
diff --git a/lib/id-helper.ts b/lib/id-helper.ts
index da458117..2e393610 100644
--- a/lib/id-helper.ts
+++ b/lib/id-helper.ts
@@ -47,4 +47,5 @@ export const newId = new IdGenerator({
webhookSecret: "whsec",
token: "pmk",
clickEvent: "click",
+ preset: "preset",
}).id;
diff --git a/lib/zod/schemas/presets.ts b/lib/zod/schemas/presets.ts
index fbdfd504..71ebcb53 100644
--- a/lib/zod/schemas/presets.ts
+++ b/lib/zod/schemas/presets.ts
@@ -1,16 +1,17 @@
import { z } from "zod";
export const customFieldDataSchema = z.object({
- type: z.enum(["SHORT_TEXT", "LONG_TEXT", "NUMBER", "URL"]),
- identifier: z.string(),
- label: z.string(),
- placeholder: z.string().nullable().optional(),
- required: z.boolean().default(false),
- disabled: z.boolean().default(false),
- orderIndex: z.number().default(0),
+ type: z.enum(["SHORT_TEXT", "LONG_TEXT", "NUMBER", "URL"]),
+ identifier: z.string(),
+ label: z.string(),
+ placeholder: z.string().nullable().optional(),
+ required: z.boolean().default(false),
+ disabled: z.boolean().default(false),
+ orderIndex: z.number().default(0),
});
-export const watermarkConfigSchema = z.object({
+export const watermarkConfigSchema = z
+ .object({
text: z.string(),
isTiled: z.boolean(),
color: z.string(),
@@ -18,30 +19,39 @@ export const watermarkConfigSchema = z.object({
opacity: z.number(),
rotation: z.number(),
position: z.string(),
-}).nullable();
+ })
+ .nullable();
export const presetDataSchema = z.object({
- // Social Media Card
- enableCustomMetaTag: z.boolean(),
- name: z.string(),
- metaFavicon: z.string().nullable(),
- metaImage: z.string().nullable(),
- metaTitle: z.string().nullable(),
- metaDescription: z.string().nullable(),
-
- // Custom Fields
- enableCustomFields: z.boolean(),
- customFields: z.array(customFieldDataSchema).nullable(),
-
- // Watermark
- enableWatermark: z.boolean(),
- watermarkConfig: watermarkConfigSchema,
-
- // Viewer Access Control
- enableAllowList: z.boolean(),
- allowList: z.array(z.string()),
- enableDenyList: z.boolean(),
- denyList: z.array(z.string()),
+ // Social Media Card
+ enableCustomMetaTag: z.boolean(),
+ name: z.string(),
+ metaFavicon: z.string().nullable(),
+ metaImage: z.string().nullable(),
+ metaTitle: z.string().nullable(),
+ metaDescription: z.string().nullable(),
+
+ // // Custom Fields
+ // enableCustomFields: z.boolean(),
+ // customFields: z.array(customFieldDataSchema).nullable(),
+
+ // Watermark
+ enableWatermark: z.boolean(),
+ watermarkConfig: watermarkConfigSchema,
+
+ // Viewer Access Control
+ enableAllowList: z.boolean(),
+ allowList: z.array(z.string()),
+ enableDenyList: z.boolean(),
+ denyList: z.array(z.string()),
+
+ // Email Protection
+ emailProtected: z.boolean(),
+ emailAuthenticated: z.boolean(),
+ allowDownload: z.boolean().optional(),
+ enablePassword: z.boolean(),
+ password: z.string().nullable(),
+ expiresAt: z.string().nullable(),
});
-export type PresetDataSchema = z.infer<typeof presetDataSchema>;
\ No newline at end of file
+export type PresetDataSchema = z.infer<typeof presetDataSchema>;
diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
index 7c11bde8..add7d843 100644
--- a/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/index.ts
@@ -1,51 +1,51 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
-import { authOptions } from "@/pages/api/auth/[...nextauth]";
export default async function handle(
- req: NextApiRequest,
- res: NextApiResponse,
+ req: NextApiRequest,
+ res: NextApiResponse,
) {
- if (req.method === "PUT") {
- // PUT /api/teams/:teamId/agreements/:agreementId
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).end("Unauthorized");
- return;
- }
+ if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/agreements/:agreementId
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
- const userId = (session.user as CustomUser).id;
- const { teamId } = req.query as { teamId: string };
- const { agreementId } = req.query as { agreementId: string };
+ const userId = (session.user as CustomUser).id;
+ const { teamId } = req.query as { teamId: string };
+ const { agreementId } = req.query as { agreementId: string };
- if (!teamId || !agreementId) {
- return res.status(401).json("Unauthorized");
- }
+ if (!teamId || !agreementId) {
+ return res.status(401).json("Unauthorized");
+ }
- try {
- await prisma.agreement.update({
- where: {
- id: agreementId,
- teamId,
- },
- data: {
- deletedAt: new Date(),
- deletedBy: userId,
- },
- });
+ try {
+ await prisma.agreement.update({
+ where: {
+ id: agreementId,
+ teamId,
+ },
+ data: {
+ deletedAt: new Date(),
+ deletedBy: userId,
+ },
+ });
- return res.status(200).json({ message: "Agreement deleted" });
- } catch (error) {
- errorhandler(error, res);
- }
- } else {
- // We only allow GET and POST requests
- res.setHeader("Allow", ["PUT"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
+ return res.status(200).json({ message: "Agreement deleted" });
+ } catch (error) {
+ errorhandler(error, res);
}
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["PUT"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
}
diff --git a/pages/api/teams/[teamId]/presets/[id].ts b/pages/api/teams/[teamId]/presets/[id].ts
new file mode 100644
index 00000000..5ebd9bb8
--- /dev/null
+++ b/pages/api/teams/[teamId]/presets/[id].ts
@@ -0,0 +1,150 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { Prisma } from "@prisma/client";
+import { getServerSession } from "next-auth";
+import { ZodError } from "zod";
+
+import { errorhandler } from "@/lib/errorHandler";
+import { newId } from "@/lib/id-helper";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { presetDataSchema } from "@/lib/zod/schemas/presets";
+
+export const config = {
+ api: {
+ bodyParser: {
+ sizeLimit: "4mb",
+ },
+ },
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id: presetId } = req.query as { teamId: string; id: string };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ },
+ select: {
+ id: true,
+ users: { select: { userId: true } },
+ },
+ });
+
+ // check that the user is member of the team, otherwise return 403
+ const teamUsers = team?.users;
+ const isUserPartOfTeam = teamUsers?.some(
+ (user) => user.userId === (session.user as CustomUser).id,
+ );
+ if (!isUserPartOfTeam) {
+ return res.status(403).end("Unauthorized to access this team");
+ }
+ } catch (error) {
+ errorhandler(error, res);
+ }
+
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/presets/:id
+ try {
+ const preset = await prisma.linkPreset.findFirst({
+ where: {
+ id: presetId,
+ teamId: teamId,
+ },
+ });
+
+ if (!preset) {
+ return res.status(404).json({ message: "Preset not found" });
+ }
+
+ return res.status(200).json(preset);
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/presets/:id
+ try {
+ // Validate request body with Zod schema
+ const validatedData = presetDataSchema.parse(req.body);
+
+ // Check if preset exists and belongs to the team
+ const existingPreset = await prisma.linkPreset.findUnique({
+ where: {
+ id: presetId,
+ teamId: teamId,
+ },
+ });
+
+ if (!existingPreset) {
+ return res.status(404).json({ message: "Preset not found" });
+ }
+
+ // Update the preset
+ const updatedPreset = await prisma.linkPreset.update({
+ where: {
+ id: presetId,
+ },
+ data: {
+ ...validatedData,
+ ...(!existingPreset.pId && { pId: newId("preset") }),
+ // Convert objects to JSON strings for storage
+ watermarkConfig: validatedData.watermarkConfig
+ ? JSON.stringify(validatedData.watermarkConfig)
+ : Prisma.JsonNull,
+ },
+ });
+
+ return res.status(200).json({
+ message: "Preset updated successfully",
+ preset: updatedPreset,
+ });
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return res.status(400).json({
+ message: "Invalid preset data",
+ errors: error.errors,
+ });
+ }
+ errorhandler(error, res);
+ }
+ } else if (req.method === "DELETE") {
+ // DELETE /api/teams/:teamId/presets/:id
+ try {
+ // Check if preset exists and belongs to the team
+ const existingPreset = await prisma.linkPreset.findFirst({
+ where: {
+ id: presetId,
+ teamId: teamId,
+ },
+ });
+
+ if (!existingPreset) {
+ return res.status(404).json({ message: "Preset not found" });
+ }
+
+ await prisma.linkPreset.delete({
+ where: {
+ id: presetId,
+ },
+ });
+
+ return res.status(204).end();
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow GET, PUT, and DELETE requests
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/presets/index.ts b/pages/api/teams/[teamId]/presets/index.ts
index 99076b04..e2878cd2 100644
--- a/pages/api/teams/[teamId]/presets/index.ts
+++ b/pages/api/teams/[teamId]/presets/index.ts
@@ -1,13 +1,13 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { ZodError } from "zod";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth";
+import { ZodError } from "zod";
import { errorhandler } from "@/lib/errorHandler";
+import { newId } from "@/lib/id-helper";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
-import presets, { PresetData } from "@/pages/settings/presets";
import { presetDataSchema } from "@/lib/zod/schemas/presets";
export const config = {
@@ -54,105 +54,52 @@ export default async function handle(
if (req.method === "GET") {
// GET /api/teams/:teamId/presets
- const presets = await prisma.linkPreset.findMany({
- where: {
- teamId: teamId,
- },
- });
-
- if (!presets) {
- return res.status(200).json(null);
- }
-
- return res.status(200).json(presets[0]);
- } else if (req.method === "POST") {
- // POST /api/teams/:teamId/presets
try {
- // Validate request body with Zod schema
- const validatedData = presetDataSchema.parse(req.body);
-
- // update team with new preset
- const preset = await prisma.linkPreset.create({
- data: {
- ...validatedData,
- teamId,
- name: "Default Link Metatag",
- customFields: validatedData.customFields ? JSON.stringify(validatedData.customFields) : undefined,
- watermarkConfig: validatedData.watermarkConfig ? JSON.stringify(validatedData.watermarkConfig) : undefined,
+ const presets = await prisma.linkPreset.findMany({
+ where: {
+ teamId: teamId,
+ },
+ orderBy: {
+ createdAt: "desc",
},
});
- return res.status(200).json({ message: "Preset created successfully" });
+
+ return res.status(200).json(presets);
} catch (error) {
- if (error instanceof ZodError) {
- return res.status(400).json({
- message: "Invalid preset data",
- errors: error.errors
- });
- }
errorhandler(error, res);
}
- } else if (req.method === "PUT") {
- // PUT /api/teams/:teamId/presets
+ } else if (req.method === "POST") {
+ // POST /api/teams/:teamId/presets
try {
// Validate request body with Zod schema
const validatedData = presetDataSchema.parse(req.body);
- const presets = await prisma.linkPreset.findMany({
- where: {
- teamId: teamId,
- },
- });
-
- // if metaImage is different from previous one, delete the previous image
-
- await prisma.linkPreset.update({
- where: {
- teamId: teamId,
- id: presets[0].id,
- },
+ // Create a new preset
+ const preset = await prisma.linkPreset.create({
data: {
...validatedData,
- // Convert objects to JSON strings for storage
- customFields: validatedData.customFields ? JSON.stringify(validatedData.customFields) : undefined,
- watermarkConfig: validatedData.watermarkConfig ? JSON.stringify(validatedData.watermarkConfig) : undefined,
- teamId: teamId,
+ teamId,
+ pId: newId("preset"),
+ watermarkConfig: validatedData.watermarkConfig
+ ? JSON.stringify(validatedData.watermarkConfig)
+ : undefined,
},
});
-
- return res.status(200).json({ message: "Preset updated successfully" });
+ return res
+ .status(201)
+ .json({ message: "Preset created successfully", preset });
} catch (error) {
if (error instanceof ZodError) {
return res.status(400).json({
message: "Invalid preset data",
- errors: error.errors
+ errors: error.errors,
});
}
errorhandler(error, res);
}
- } else if (req.method === "DELETE") {
- // DELETE /api/teams/:teamId/presets
- try {
- const preset = await prisma.linkPreset.findFirst({
- where: {
- teamId: teamId,
- },
- select: { id: true },
- });
-
- await prisma.linkPreset.delete({
- where: {
- teamId: teamId,
- id: preset?.id,
- },
- });
-
- return res.status(204).end();
- } catch (error) {
- errorhandler(error, res);
- }
} else {
- // We only allow GET and DELETE requests
- res.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET", "POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/settings/presets.tsx b/pages/settings/presets.tsx
index 2c32c0fe..0984143d 100644
--- a/pages/settings/presets.tsx
+++ b/pages/settings/presets.tsx
@@ -1,345 +1,141 @@
-import { useEffect, useState, useMemo } from "react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
-import { Agreement, CustomFieldType, LinkPreset } from "@prisma/client";
-import { CircleHelpIcon, Loader2, PlusIcon } from "lucide-react";
-import { toast } from "sonner";
-import { mutate } from "swr";
-import useSWRImmutable from "swr/immutable";
+import { LinkPreset } from "@prisma/client";
+import { format } from "date-fns";
+import { CircleHelpIcon, CrownIcon, PlusIcon } from "lucide-react";
+import useSWR from "swr";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import { fetcher } from "@/lib/utils";
import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
import AppLayout from "@/components/layouts/app";
-import Preview from "@/components/settings/og-preview";
-import SocialMediaCardPreset from "@/components/settings/presets/social-media-card-preset";
-import PresetOptions from "@/components/settings/presets/preset-options";
import { SettingsHeader } from "@/components/settings/settings-header";
import { Button } from "@/components/ui/button";
import { BadgeTooltip } from "@/components/ui/tooltip";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-
-import { usePlan } from "@/lib/swr/use-billing";
-import {
- convertDataUrlToFile,
- fetcher,
- sanitizeAllowDenyList,
- uploadImage,
-} from "@/lib/utils";
-import { CustomFieldData } from "@/components/links/link-sheet/custom-fields-panel";
-import { useAgreements } from "@/lib/swr/use-agreements";
-
-export interface PresetData {
- enableCustomMetaTag: boolean;
- name: string;
- metaFavicon: string | null;
- metaImage: string | null;
- metaTitle: string | null;
- metaDescription: string | null;
-
- enableCustomFields: boolean;
- customFields: CustomFieldData[] | null;
-
- enableWatermark: boolean;
- watermarkConfig: {
- text: string;
- isTiled: boolean;
- color: string;
- fontSize: number;
- opacity: number;
- rotation: number;
- position: string;
- } | null;
-
- enableAllowList: boolean;
- allowList: string[];
- enableDenyList: boolean;
- denyList: string[];
-}
-
-export const defaultPresetData: PresetData = {
- enableCustomMetaTag: false,
- name: "",
- metaFavicon: null,
- metaImage: null,
- metaTitle: null,
- metaDescription: null,
-
- enableCustomFields: false,
- customFields: null,
-
- enableWatermark: false,
- watermarkConfig: null,
-
- enableAllowList: false,
- allowList: [],
- enableDenyList: false,
- denyList: []
-};
export default function Presets() {
+ const router = useRouter();
const teamInfo = useTeam();
- const { plan, isTrial } = usePlan();
- const [isLoading, setIsLoading] = useState(false);
- const { agreements } = useAgreements();
- const { data: presets, mutate: mutatePreset } = useSWRImmutable<LinkPreset>(
- `/api/teams/${teamInfo?.currentTeam?.id}/presets`,
- fetcher,
- );
- const [data, setData] = useState<PresetData>(defaultPresetData);
- const [activeTab, setActiveTab] = useState("social-media");
-
- const filteredAgreements = useMemo(() => agreements.filter((agreement: Agreement) => !agreement.deletedAt), [agreements]);
-
- useEffect(() => {
- if (presets) {
- const customFields = presets.customFields ? JSON.parse(presets.customFields as string) as PresetData['customFields'] : null;
- const watermarkConfig = presets.watermarkConfig ? JSON.parse(presets.watermarkConfig as string) as PresetData['watermarkConfig'] : null;
-
- setData({
- name: presets.name,
- metaFavicon: presets.metaFavicon,
- metaImage: presets.metaImage,
- metaTitle: presets.metaTitle,
- metaDescription: presets.metaDescription,
- enableCustomMetaTag: presets.enableCustomMetaTag || false,
- enableCustomFields: presets.enableCustomFields || false,
- customFields: customFields,
- enableWatermark: presets.enableWatermark || false,
- watermarkConfig: watermarkConfig,
- enableAllowList: presets.enableAllowList || false,
- allowList: presets.allowList,
- enableDenyList: presets.enableDenyList || false,
- denyList: presets.denyList
- });
- }
- }, [presets]);
-
- const handleDelete = async (e: React.MouseEvent) => {
- e.preventDefault();
- setIsLoading(true);
-
- const isPresetEmpty =
- !data.enableCustomFields &&
- !data.enableWatermark &&
- !data.enableAllowList &&
- !data.enableDenyList;
-
- const method = isPresetEmpty ? "DELETE" : "PUT";
-
- const payload = isPresetEmpty
- ? null
- : {
- ...data,
- watermarkConfig: data.watermarkConfig || null,
- metaImage: null,
- metaTitle: null,
- metaDescription: null,
- metaFavicon: null,
- enableCustomMetaTag: false,
- };
-
- try {
- const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {
- method,
- headers: {
- "Content-Type": "application/json",
- },
- ...(payload ? { body: JSON.stringify(payload) } : {}),
- });
-
- if (!response.ok) {
- throw new Error(`Failed to ${method.toLowerCase()} preset`);
- }
-
- if (method === "DELETE") {
- setData(defaultPresetData);
- } else {
- setData(prev => ({
- ...prev,
- metaImage: null,
- metaTitle: null,
- metaDescription: null,
- metaFavicon: null,
- enableCustomMetaTag: false,
- }));
- }
-
- toast.success("Your Social Media preset has been successfully reset");
- } catch (error) {
- console.error("Error resetting preset:", error);
- toast.error(
- `Failed to reset preset: ${error instanceof Error ? error.message : "Unknown error"
- }`
- );
- } finally {
- if (method === "DELETE") {
- await mutatePreset(undefined, false);
- } else {
- await mutatePreset();
- }
- setIsLoading(false);
- }
- };
+ const { isBusiness, isDatarooms, isDataroomsPlus } = usePlan();
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setIsLoading(true);
-
- const isMetaDataPresent =
- data.enableCustomMetaTag ||
- !!(data.metaTitle || data.metaDescription || data.metaImage || data.metaFavicon);
-
- const isPresetEmpty =
- !isMetaDataPresent &&
- !data.enableCustomFields &&
- !data.enableWatermark &&
- !data.enableAllowList &&
- !data.enableDenyList;
-
- const method = isPresetEmpty
- ? "DELETE"
- : presets?.id
- ? "PUT"
- : "POST";
- const payload = !isPresetEmpty
- ? {
- ...data,
- enableCustomMetaTag: isMetaDataPresent,
- customFields: data.customFields || null,
- watermarkConfig: data.watermarkConfig || null,
- }
- : null;
-
- try {
- const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {
- method,
- headers: {
- "Content-Type": "application/json",
- },
- ...(payload ? { body: JSON.stringify(payload) } : {}),
- });
-
- if (!response.ok) throw new Error("Failed to save preset");
-
- const successMessage =
- method === "PUT"
- ? "Your preset has been updated successfully"
- : method === "POST"
- ? "Your preset has been created successfully"
- : "Your preset has been removed successfully";
+ const {
+ data: presets,
+ error,
+ isLoading,
+ } = useSWR<LinkPreset[]>(
+ teamInfo?.currentTeam?.id
+ ? `/api/teams/${teamInfo.currentTeam.id}/presets`
+ : null,
+ fetcher,
+ );
- toast.success(successMessage);
- } catch (error) {
- toast.error("Failed to save preset");
- } finally {
- if (method === "DELETE") {
- await mutatePreset(undefined, false);
- } else {
- await mutatePreset();
- }
- setIsLoading(false);
- }
- };
+ const [showUpgradeModal, setShowUpgradeModal] = useState(false);
return (
<AppLayout>
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
<SettingsHeader />
<div>
- <div className="mb-6 flex items-center justify-between">
+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
<div className="space-y-1">
- <h3 className="flex flex-row items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">
Link Presets
</h3>
<p className="flex flex-row items-center gap-2 text-sm text-muted-foreground">
- Configure your default link settings.
- <BadgeTooltip
- content="Customize how your content appears when shared on social media."
- key="verified"
- link="https://www.papermark.com/help/article/change-social-media-cards"
- >
- <CircleHelpIcon className="h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground" />
+ Configure and save presets for your links
+ <BadgeTooltip content="Create reusable link configurations that can be applied to new links">
+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
</BadgeTooltip>
</p>
</div>
+ {isBusiness || isDatarooms || isDataroomsPlus ? (
+ <Button onClick={() => router.push("/settings/presets/new")}>
+ <PlusIcon className="mr-1.5 h-4 w-4" />
+ Create Preset
+ </Button>
+ ) : (
+ <Button onClick={() => setShowUpgradeModal(true)}>
+ <CrownIcon className="mr-1.5 h-4 w-4" />
+ Upgrade to create presets
+ </Button>
+ )}
</div>
- <Tabs defaultValue="social-media" className="w-full" onValueChange={setActiveTab}>
- <div className="flex items-center justify-between mb-4">
- <TabsList>
- <TabsTrigger value="social-media">Social Media</TabsTrigger>
- <TabsTrigger value="access-control">Link Presets</TabsTrigger>
- </TabsList>
-
- {activeTab === "access-control" && (
+ {/* Presets List */}
+ {isLoading ? (
+ <div className="flex items-center justify-center py-12">
+ <p className="text-muted-foreground">Loading presets...</p>
+ </div>
+ ) : !presets || presets.length === 0 ? (
+ <div className="flex flex-col items-center justify-center space-y-4 py-12">
+ <div className="rounded-full bg-gray-100 p-3">
+ <PlusIcon className="h-6 w-6 text-gray-600" />
+ </div>
+ <div className="text-center">
+ <h3 className="font-medium">No presets configured</h3>
+ <p className="mt-1 max-w-sm text-sm text-gray-500">
+ Create link presets to quickly apply your preferred settings
+ when creating links.
+ </p>
+ </div>
+ {isBusiness || isDatarooms || isDataroomsPlus ? (
<Button
- size="sm"
- className="flex items-center gap-1"
- onClick={handleSubmit}
+ variant="outline"
+ onClick={() => router.push("/settings/presets/new")}
>
- {isLoading ? <><Loader2 className="h-4 w-4 animate-spin" /> <span>Saving...</span></> : <>
- <PlusIcon className="h-4 w-4" />
- <span>Save Preset</span></>
- }
+ Create your first preset
+ </Button>
+ ) : (
+ <Button
+ variant="outline"
+ onClick={() => setShowUpgradeModal(true)}
+ >
+ Upgrade to create presets
</Button>
)}
</div>
-
- <TabsContent value="social-media">
- <div className="grid w-full divide-x divide-border overflow-auto scrollbar-hide md:grid-cols-2 md:overflow-hidden">
- <div className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">
- <div className="sticky top-0 z-10 flex h-10 items-center justify-center border-b border-border bg-white px-5 dark:bg-gray-900 sm:h-14">
- <h2 className="text-lg font-medium">Social Media Card</h2>
- </div>
-
- <SocialMediaCardPreset data={data} setData={setData} />
-
- <div className="flex justify-end px-5 py-4">
- {(plan === "free" || plan === "pro") && !isTrial ? (
- <UpgradePlanModal
- clickedPlan={PlanEnum.Business}
- trigger={"presets_page"}
- >
- <Button>Upgrade to Save Preset</Button>
- </UpgradePlanModal>
- ) : (
- <Button onClick={handleSubmit} loading={isLoading}>
- Save Social Media Preset
- </Button>
- )}
-
- {data.enableCustomMetaTag ? (
- <Button
- variant="link"
- onClick={handleDelete}
- className="ml-2"
- loading={isLoading}
- >
- Reset Social Media Preset
- </Button>
- ) : null}
+ ) : (
+ <div className="grid grid-cols-1 gap-3">
+ {presets.map((preset) => (
+ <Link
+ key={preset.id}
+ href={`/settings/presets/${preset.id}`}
+ className="rounded-xl border border-gray-200 bg-white p-4 transition-[filter] hover:bg-gray-50 dark:border-gray-400 dark:bg-secondary dark:hover:bg-gray-800 sm:p-5"
+ >
+ <div className="flex items-center justify-between">
+ <div>
+ <div className="flex items-center gap-2">
+ <span className="font-semibold">{preset.name}</span>
+ </div>
+ <div className="mt-1 flex items-center gap-4 text-sm text-muted-foreground">
+ <div className="flex items-center gap-1">
+ <span>
+ Created:{" "}
+ {format(new Date(preset.createdAt), "MMM d, yyyy")}
+ </span>
+ </div>
+ </div>
+ </div>
</div>
- </div>
- <div className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">
- <Preview data={data} setData={setData} />
- </div>
- </div>
- </TabsContent>
- <TabsContent value="access-control">
- <div className="grid w-full gap-6">
- <PresetOptions
- data={data}
- setData={setData}
- agreements={filteredAgreements}
- teamId={teamInfo?.currentTeam?.id!}
- />
- </div>
- </TabsContent>
- </Tabs>
+ </Link>
+ ))}
+ </div>
+ )}
</div>
</main>
+ <UpgradePlanModal
+ clickedPlan={PlanEnum.Business}
+ trigger="presets_page"
+ open={showUpgradeModal}
+ setOpen={setShowUpgradeModal}
+ />
</AppLayout>
);
}
-
diff --git a/pages/settings/presets/[id].tsx b/pages/settings/presets/[id].tsx
new file mode 100644
index 00000000..88b1a8fc
--- /dev/null
+++ b/pages/settings/presets/[id].tsx
@@ -0,0 +1,451 @@
+import { useRouter } from "next/router";
+
+import { FormEvent, useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { PlanEnum } from "@/ee/stripe/constants";
+import { LinkPreset } from "@prisma/client";
+import { AlertCircle, ArrowLeft, Trash2, X } from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import useLimits from "@/lib/swr/use-limits";
+import { WatermarkConfig } from "@/lib/types";
+import { fetcher } from "@/lib/utils";
+
+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
+import AppLayout from "@/components/layouts/app";
+import { DEFAULT_LINK_TYPE } from "@/components/links/link-sheet";
+import AllowDownloadSection from "@/components/links/link-sheet/allow-download-section";
+import AllowListSection from "@/components/links/link-sheet/allow-list-section";
+import DenyListSection from "@/components/links/link-sheet/deny-list-section";
+import EmailAuthenticationSection from "@/components/links/link-sheet/email-authentication-section";
+import EmailProtectionSection from "@/components/links/link-sheet/email-protection-section";
+import ExpirationSection from "@/components/links/link-sheet/expiration-section";
+import { LinkUpgradeOptions } from "@/components/links/link-sheet/link-options";
+import OGSection from "@/components/links/link-sheet/og-section";
+import PasswordSection from "@/components/links/link-sheet/password-section";
+import WatermarkSection from "@/components/links/link-sheet/watermark-section";
+import Preview from "@/components/settings/og-preview";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import {
+ Alert,
+ AlertClose,
+ AlertDescription,
+ AlertTitle,
+} from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Separator } from "@/components/ui/separator";
+
+type PRESET_DATA = Partial<DEFAULT_LINK_TYPE> & {
+ name: string;
+ enableAllowList?: boolean;
+ enableDenyList?: boolean;
+ expiresAt?: Date | null;
+ pId?: string | null;
+};
+
+export default function EditPreset() {
+ const router = useRouter();
+ const { id } = router.query;
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const {
+ data: preset,
+ error,
+ isLoading: isLoadingPreset,
+ } = useSWR<LinkPreset>(
+ id && teamId ? `/api/teams/${teamId}/presets/${id}` : null,
+ fetcher,
+ );
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [isDeleting, setIsDeleting] = useState(false);
+ const [data, setData] = useState<PRESET_DATA | null>(null);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [showDeleteAlert, setShowDeleteAlert] = useState(false);
+
+ const {
+ isStarter,
+ isPro,
+ isBusiness,
+ isDatarooms,
+ isDataroomsPlus,
+ isTrial,
+ } = usePlan();
+ const { limits } = useLimits();
+ const allowAdvancedLinkControls = limits
+ ? limits?.advancedLinkControlsOnPro
+ : false;
+ const allowWatermarkOnBusiness = limits?.watermarkOnBusiness ?? false;
+
+ const [openUpgradeModal, setOpenUpgradeModal] = useState<boolean>(false);
+ const [trigger, setTrigger] = useState<string>("");
+ const [upgradePlan, setUpgradePlan] = useState<PlanEnum>(PlanEnum.Business);
+
+ const handleUpgradeStateChange = ({
+ state,
+ trigger,
+ plan,
+ }: LinkUpgradeOptions) => {
+ setOpenUpgradeModal(state);
+ setTrigger(trigger);
+ if (plan) {
+ setUpgradePlan(plan as PlanEnum);
+ }
+ };
+
+ useEffect(() => {
+ if (preset) {
+ const watermarkConfig = preset.watermarkConfig
+ ? (JSON.parse(preset.watermarkConfig as string) as WatermarkConfig)
+ : null;
+
+ setData({
+ id: null,
+ name: preset.name,
+ expiresAt: preset.expiresAt,
+ password: preset.password,
+ emailProtected: preset.emailProtected ?? true,
+ emailAuthenticated: preset.emailAuthenticated ?? false,
+ allowDownload: preset.allowDownload ?? false,
+ allowList: preset.allowList || [],
+ denyList: preset.denyList || [],
+ enableCustomMetatag: preset.enableCustomMetaTag ?? false,
+ metaTitle: preset.metaTitle,
+ metaDescription: preset.metaDescription,
+ metaImage: preset.metaImage,
+ metaFavicon: preset.metaFavicon,
+ enableWatermark: preset.enableWatermark ?? false,
+ watermarkConfig: watermarkConfig,
+ pId: preset.pId,
+ });
+ }
+ }, [preset]);
+
+ const handleSubmit = async (e: FormEvent) => {
+ e.preventDefault();
+ if (!data) return;
+
+ setIsLoading(true);
+
+ try {
+ const response = await fetch(`/api/teams/${teamId}/presets/${id}`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: data.name,
+ emailProtected: data.emailProtected,
+ emailAuthenticated: data.emailAuthenticated,
+ allowList: data.allowList,
+ denyList: data.denyList,
+ enableAllowList: data.allowList ? data.allowList.length > 0 : false,
+ enableDenyList: data.denyList ? data.denyList.length > 0 : false,
+ password: data.password,
+ enablePassword: !!data.password,
+ enableCustomMetaTag: data.enableCustomMetatag,
+ metaTitle: data.metaTitle,
+ metaDescription: data.metaDescription,
+ metaImage: data.metaImage,
+ metaFavicon: data.metaFavicon,
+ enableWatermark: data.enableWatermark,
+ watermarkConfig: data.watermarkConfig,
+ allowDownload: data.allowDownload,
+ expiresAt: data.expiresAt,
+ pId: data.pId,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to update preset");
+ }
+
+ toast.success("Preset updated successfully");
+ } catch (error) {
+ toast.error("Failed to update preset");
+ console.error(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleDelete = async () => {
+ setIsDeleting(true);
+
+ try {
+ const response = await fetch(`/api/teams/${teamId}/presets/${id}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete preset");
+ }
+
+ toast.success("Preset deleted successfully");
+ router.push("/settings/presets");
+ } catch (error) {
+ toast.error("Failed to delete preset");
+ console.error(error);
+ } finally {
+ setIsDeleting(false);
+ setShowDeleteDialog(false);
+ }
+ };
+
+ if (isLoadingPreset) {
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+ <div className="flex items-center justify-center py-12">
+ <p className="text-muted-foreground">Loading preset...</p>
+ </div>
+ </main>
+ </AppLayout>
+ );
+ }
+
+ if (error || !preset || !data) {
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+ <div className="flex items-center justify-center py-12">
+ <p className="text-muted-foreground">Preset not found</p>
+ </div>
+ </main>
+ </AppLayout>
+ );
+ }
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+
+ <Button
+ variant="ghost"
+ size="sm"
+ className="mb-2 flex items-center gap-2 pl-0 text-muted-foreground"
+ onClick={() => router.push("/settings/presets")}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back to presets
+ </Button>
+
+ {showDeleteAlert && (
+ <Alert variant="destructive" className="mb-4">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Are you sure?</AlertTitle>
+ <AlertDescription>
+ This action cannot be undone. This will permanently delete this
+ preset.
+ </AlertDescription>
+ <div className="mt-4 flex justify-end space-x-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowDeleteAlert(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={handleDelete}
+ disabled={isDeleting}
+ >
+ {isDeleting ? "Deleting..." : "Delete"}
+ </Button>
+ </div>
+ <AlertClose onClick={() => setShowDeleteAlert(false)} />
+ </Alert>
+ )}
+
+ <form onSubmit={handleSubmit} className="space-y-8">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ Edit Preset
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ Modify this preset's settings
+ </p>
+ </div>
+
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={isDeleting}
+ onClick={() => setShowDeleteAlert(true)}
+ type="button"
+ >
+ <Trash2 className="mr-1.5 h-4 w-4" />
+ {isDeleting ? "Deleting..." : "Delete"}
+ </Button>
+ </div>
+
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="name">Preset Name</Label>
+ {preset.pId && (
+ <div className="flex items-center justify-end gap-1 rounded-md bg-muted px-2 py-1 font-mono text-xs font-medium text-muted-foreground">
+ <span>ID:</span>
+ <code className="font-mono">{preset.pId}</code>
+ </div>
+ )}
+ </div>
+ <Input
+ id="name"
+ value={data.name || ""}
+ onChange={(e) =>
+ setData((prev) =>
+ prev ? { ...prev, name: e.target.value } : null,
+ )
+ }
+ required
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
+ <div className="space-y-6">
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Link Preview Cards</h3>
+ <OGSection
+ data={data as any}
+ setData={setData as any}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ editLink={true}
+ presets={null}
+ />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Basic Settings</h3>
+ <EmailProtectionSection
+ data={data as any}
+ setData={setData as any}
+ />
+ <EmailAuthenticationSection
+ data={data as any}
+ setData={setData as any}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ />
+
+ <AllowDownloadSection
+ data={data as any}
+ setData={setData as any}
+ />
+ <ExpirationSection
+ data={data as any}
+ setData={setData as any}
+ />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Access Control</h3>
+ <PasswordSection data={data as any} setData={setData as any} />
+ <AllowListSection
+ data={data as any}
+ setData={setData as any}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ <DenyListSection
+ data={data as any}
+ setData={setData as any}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Watermark</h3>
+ <WatermarkSection
+ data={data as any}
+ setData={setData as any}
+ isAllowed={
+ isTrial ||
+ isDatarooms ||
+ isDataroomsPlus ||
+ allowWatermarkOnBusiness
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ </div>
+ </div>
+
+ <div className="sticky top-0 md:max-h-[95vh] md:overflow-auto">
+ <div className="rounded-lg border">
+ {/* <div className="sticky top-0 flex h-14 items-center justify-center border-b bg-white px-5 dark:bg-gray-900">
+ <h2 className="text-lg font-medium">Preview</h2>
+ </div> */}
+ <div className="p-4">
+ <Preview data={data as any} setData={setData as any} />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Separator />
+
+ <div className="flex justify-end space-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => router.push("/settings/presets")}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isLoading}>
+ {isLoading ? "Saving..." : "Save Changes"}
+ </Button>
+ </div>
+ </form>
+ </main>
+ <UpgradePlanModal
+ clickedPlan={upgradePlan}
+ open={openUpgradeModal}
+ setOpen={setOpenUpgradeModal}
+ trigger={trigger}
+ />
+ </AppLayout>
+ );
+}
diff --git a/pages/settings/presets/new.tsx b/pages/settings/presets/new.tsx
new file mode 100644
index 00000000..dc4acb7f
--- /dev/null
+++ b/pages/settings/presets/new.tsx
@@ -0,0 +1,292 @@
+import { useRouter } from "next/router";
+
+import { FormEvent, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { PlanEnum } from "@/ee/stripe/constants";
+import { LinkType } from "@prisma/client";
+import { ArrowLeft } from "lucide-react";
+import { toast } from "sonner";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import useLimits from "@/lib/swr/use-limits";
+
+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
+import AppLayout from "@/components/layouts/app";
+import {
+ DEFAULT_LINK_PROPS,
+ DEFAULT_LINK_TYPE,
+} from "@/components/links/link-sheet";
+import AllowDownloadSection from "@/components/links/link-sheet/allow-download-section";
+import AllowListSection from "@/components/links/link-sheet/allow-list-section";
+import DenyListSection from "@/components/links/link-sheet/deny-list-section";
+import EmailAuthenticationSection from "@/components/links/link-sheet/email-authentication-section";
+import EmailProtectionSection from "@/components/links/link-sheet/email-protection-section";
+import ExpirationSection from "@/components/links/link-sheet/expiration-section";
+import { LinkUpgradeOptions } from "@/components/links/link-sheet/link-options";
+import OGSection from "@/components/links/link-sheet/og-section";
+import PasswordSection from "@/components/links/link-sheet/password-section";
+import WatermarkSection from "@/components/links/link-sheet/watermark-section";
+import Preview from "@/components/settings/og-preview";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Separator } from "@/components/ui/separator";
+
+export default function NewPreset() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [data, setData] = useState<DEFAULT_LINK_TYPE>({
+ ...DEFAULT_LINK_PROPS(LinkType.DOCUMENT_LINK),
+ name: "",
+ });
+
+ const {
+ isStarter,
+ isPro,
+ isBusiness,
+ isDatarooms,
+ isDataroomsPlus,
+ isTrial,
+ } = usePlan();
+ const { limits } = useLimits();
+ const allowAdvancedLinkControls = limits
+ ? limits?.advancedLinkControlsOnPro
+ : false;
+ const allowWatermarkOnBusiness = limits?.watermarkOnBusiness ?? false;
+
+ const [openUpgradeModal, setOpenUpgradeModal] = useState<boolean>(false);
+ const [trigger, setTrigger] = useState<string>("");
+ const [upgradePlan, setUpgradePlan] = useState<PlanEnum>(PlanEnum.Business);
+
+ const handleUpgradeStateChange = ({
+ state,
+ trigger,
+ plan,
+ }: LinkUpgradeOptions) => {
+ setOpenUpgradeModal(state);
+ setTrigger(trigger);
+ if (plan) {
+ setUpgradePlan(plan as PlanEnum);
+ }
+ };
+
+ const handleSubmit = async (e: FormEvent) => {
+ e.preventDefault();
+ if (!data.name) {
+ toast.error("Please provide a name for the preset");
+ return;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const response = await fetch(`/api/teams/${teamId}/presets`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: data.name,
+ emailProtected: data.emailProtected,
+ emailAuthenticated: data.emailAuthenticated,
+ allowList: data.allowList,
+ denyList: data.denyList,
+ enableAllowList: data.allowList ? data.allowList.length > 0 : false,
+ enableDenyList: data.denyList ? data.denyList.length > 0 : false,
+ password: data.password,
+ enablePassword: !!data.password,
+ enableCustomMetaTag: data.enableCustomMetatag,
+ metaTitle: data.metaTitle,
+ metaDescription: data.metaDescription,
+ metaImage: data.metaImage,
+ metaFavicon: data.metaFavicon,
+ enableWatermark: data.enableWatermark,
+ watermarkConfig: data.watermarkConfig,
+ allowDownload: data.allowDownload,
+ expiresAt: data.expiresAt,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to create preset");
+ }
+
+ toast.success("Preset created successfully");
+ router.push("/settings/presets");
+ } catch (error) {
+ toast.error("Failed to create preset");
+ console.error(error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+
+ <Button
+ variant="ghost"
+ size="sm"
+ className="mb-2 flex items-center gap-2 pl-0 text-muted-foreground"
+ onClick={() => router.push("/settings/presets")}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back to presets
+ </Button>
+
+ <form onSubmit={handleSubmit} className="space-y-8">
+ <div className="space-y-4">
+ <h2 className="text-2xl font-semibold tracking-tight">
+ Create New Preset
+ </h2>
+ <div className="space-y-2">
+ <Label htmlFor="name">Preset Name</Label>
+ <p className="text-sm text-muted-foreground">
+ Choose a descriptive name for this preset
+ </p>
+ <Input
+ id="name"
+ placeholder="My Link Preset"
+ value={data.name || ""}
+ onChange={(e) =>
+ setData((prev) => ({ ...prev, name: e.target.value }))
+ }
+ required
+ data-1p-ignore
+ autoComplete="off"
+ autoFocus
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
+ <div className="space-y-6">
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Link Preview Cards</h3>
+ <OGSection
+ data={data}
+ setData={setData}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ editLink={false}
+ presets={null}
+ />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Basic Settings</h3>
+ <EmailProtectionSection data={data} setData={setData} />
+ <EmailAuthenticationSection
+ data={data}
+ setData={setData}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ />
+ <AllowDownloadSection data={data} setData={setData} />
+ <ExpirationSection data={data} setData={setData} />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Access Control</h3>
+ <PasswordSection data={data} setData={setData} />
+ <AllowListSection
+ data={data}
+ setData={setData}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ <DenyListSection
+ data={data}
+ setData={setData}
+ isAllowed={
+ isTrial ||
+ (isPro && allowAdvancedLinkControls) ||
+ isBusiness ||
+ isDatarooms ||
+ isDataroomsPlus
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ </div>
+
+ <div className="rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">Watermark</h3>
+ <WatermarkSection
+ data={data}
+ setData={setData}
+ isAllowed={
+ isTrial ||
+ isDatarooms ||
+ isDataroomsPlus ||
+ allowWatermarkOnBusiness
+ }
+ handleUpgradeStateChange={handleUpgradeStateChange}
+ presets={null}
+ />
+ </div>
+ </div>
+
+ <div className="sticky top-0 md:max-h-[95vh] md:overflow-auto">
+ <div className="rounded-lg border">
+ {/* <div className="sticky top-0 flex h-14 items-center justify-center border-b bg-white px-5 dark:bg-gray-900">
+ <h2 className="text-lg font-medium">Preview</h2>
+ </div> */}
+ <div className="p-4">
+ <Preview data={data} setData={setData} />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Separator />
+
+ <div className="flex justify-end space-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => router.push("/settings/presets")}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isLoading}>
+ {isLoading ? "Creating..." : "Create Preset"}
+ </Button>
+ </div>
+ </form>
+ </main>
+ <UpgradePlanModal
+ clickedPlan={upgradePlan}
+ open={openUpgradeModal}
+ setOpen={setOpenUpgradeModal}
+ trigger={trigger}
+ />
+ </AppLayout>
+ );
+}
diff --git a/prisma/migrations/20250405173206_update_link_preset_option/migration.sql b/prisma/migrations/20250405173206_update_link_preset_option/migration.sql
deleted file mode 100644
index f3feed1f..00000000
--- a/prisma/migrations/20250405173206_update_link_preset_option/migration.sql
+++ /dev/null
@@ -1,13 +0,0 @@
--- AlterTable
-ALTER TABLE "Agreement" ADD COLUMN "deletedAt" TIMESTAMP(3),
-ADD COLUMN "deletedBy" TEXT;
-
--- AlterTable
-ALTER TABLE "LinkPreset" ADD COLUMN "allowList" TEXT[],
-ADD COLUMN "customFields" JSONB,
-ADD COLUMN "denyList" TEXT[],
-ADD COLUMN "enableAllowList" BOOLEAN DEFAULT false,
-ADD COLUMN "enableCustomFields" BOOLEAN DEFAULT false,
-ADD COLUMN "enableDenyList" BOOLEAN DEFAULT false,
-ADD COLUMN "enableWatermark" BOOLEAN DEFAULT false,
-ADD COLUMN "watermarkConfig" JSONB;
diff --git a/prisma/migrations/20250425000000_update_link_presets/migration.sql b/prisma/migrations/20250425000000_update_link_presets/migration.sql
new file mode 100644
index 00000000..5293a42e
--- /dev/null
+++ b/prisma/migrations/20250425000000_update_link_presets/migration.sql
@@ -0,0 +1,24 @@
+-- AlterTable
+ALTER TABLE "Agreement" ADD COLUMN "deletedAt" TIMESTAMP(3),
+ADD COLUMN "deletedBy" TEXT;
+
+-- AlterTable
+ALTER TABLE "LinkPreset" ADD COLUMN "allowDownload" BOOLEAN DEFAULT false,
+ADD COLUMN "allowList" TEXT[],
+ADD COLUMN "denyList" TEXT[],
+ADD COLUMN "emailAuthenticated" BOOLEAN DEFAULT false,
+ADD COLUMN "emailProtected" BOOLEAN DEFAULT true,
+ADD COLUMN "enableAllowList" BOOLEAN DEFAULT false,
+ADD COLUMN "enableDenyList" BOOLEAN DEFAULT false,
+ADD COLUMN "enablePassword" BOOLEAN DEFAULT false,
+ADD COLUMN "enableWatermark" BOOLEAN DEFAULT false,
+ADD COLUMN "expiresAt" TIMESTAMP(3),
+ADD COLUMN "expiresIn" INTEGER,
+ADD COLUMN "isDefault" BOOLEAN NOT NULL DEFAULT false,
+ADD COLUMN "pId" TEXT,
+ADD COLUMN "password" TEXT,
+ADD COLUMN "watermarkConfig" JSONB;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "LinkPreset_pId_key" ON "LinkPreset"("pId" ASC);
+
diff --git a/prisma/schema/conversation.prisma b/prisma/schema/conversation.prisma
index 3d8190bb..2b3ecbc4 100644
--- a/prisma/schema/conversation.prisma
+++ b/prisma/schema/conversation.prisma
@@ -1,48 +1,48 @@
model Conversation {
- id String @id @default(cuid())
- title String? // Optional title for the conversation
- isEnabled Boolean @default(true)
+ id String @id @default(cuid())
+ title String? // Optional title for the conversation
+ isEnabled Boolean @default(true)
// Visibility control
- visibilityMode ConversationVisibility @default(PRIVATE)
+ visibilityMode ConversationVisibility @default(PRIVATE)
// Core relationships
- dataroomId String
- dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+ dataroomId String
+ dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
// Optional attachments
- dataroomDocumentId String?
- dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
- documentVersionNumber Int? // Optional document version number reference
- documentPageNumber Int? // Optional document page number reference
+ dataroomDocumentId String?
+ dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
+ documentVersionNumber Int? // Optional document version number reference
+ documentPageNumber Int? // Optional document page number reference
// Optional link relationship
- linkId String?
- link Link? @relation(fields: [linkId], references: [id], onDelete: SetNull)
+ linkId String?
+ link Link? @relation(fields: [linkId], references: [id], onDelete: SetNull)
// Optional viewer group relationship
- viewerGroupId String?
- viewerGroup ViewerGroup? @relation(fields: [viewerGroupId], references: [id], onDelete: SetNull)
+ viewerGroupId String?
+ viewerGroup ViewerGroup? @relation(fields: [viewerGroupId], references: [id], onDelete: SetNull)
// Original view that initiated the conversation (for reference)
- initialViewId String?
- initialView View? @relation(name: "initialView", fields: [initialViewId], references: [id], onDelete: SetNull)
+ initialViewId String?
+ initialView View? @relation(name: "initialView", fields: [initialViewId], references: [id], onDelete: SetNull)
- teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
// Track all views that accessed this conversation
- views ConversationView[]
+ views ConversationView[]
// Track participants including the owner
- participants ConversationParticipant[]
+ participants ConversationParticipant[]
// Track conversations
- messages Message[]
- lastMessageAt DateTime? // Last message timestamp
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ messages Message[]
+ lastMessageAt DateTime? // Last message timestamp
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([dataroomId])
@@index([dataroomDocumentId])
@@ -54,38 +54,38 @@ model Conversation {
// Define conversation visibility options
enum ConversationVisibility {
- PRIVATE // Only visible to participants and team members
- PUBLIC_LINK // Visible to all viewers with access to the specific link
- PUBLIC_GROUP // Visible to all viewers in the specific group
+ PRIVATE // Only visible to participants and team members
+ PUBLIC_LINK // Visible to all viewers with access to the specific link
+ PUBLIC_GROUP // Visible to all viewers in the specific group
PUBLIC_DOCUMENT // Visible to all viewers with access to the document, across any link
PUBLIC_DATAROOM // Visible to all viewers with access to the dataroom
}
// Define participant roles
enum ParticipantRole {
- OWNER // Created the conversation
- PARTICIPANT // Joined the conversation later
+ OWNER // Created the conversation
+ PARTICIPANT // Joined the conversation later
}
// Track participants in a conversation (including the owner)
model ConversationParticipant {
- id String @id @default(cuid())
- conversationId String
- conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ conversationId String
+ conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
// Role in the conversation
- role ParticipantRole @default(PARTICIPANT)
+ role ParticipantRole @default(PARTICIPANT)
// Participant can be either a viewer or a user
- viewerId String?
- viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
- userId String?
- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
+ viewerId String?
+ viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
+ userId String?
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
// Notification preferences
- receiveNotifications Boolean @default(false)
+ receiveNotifications Boolean @default(false)
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
@@unique([conversationId, viewerId])
@@unique([conversationId, userId])
@@ -95,29 +95,29 @@ model ConversationParticipant {
}
model Message {
- id String @id @default(cuid())
- content String // The actual message content
+ id String @id @default(cuid())
+ content String // The actual message content
// Conversation relationship
- conversationId String
- conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+ conversationId String
+ conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
// Sender information
- userId String? // Optional - for team members
- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
+ userId String? // Optional - for team members
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
- viewerId String? // Optional - for viewers
- viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
+ viewerId String? // Optional - for viewers
+ viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
// The specific view when this message was sent (for tracking)
- viewId String?
- view View? @relation(fields: [viewId], references: [id], onDelete: SetNull)
+ viewId String?
+ view View? @relation(fields: [viewId], references: [id], onDelete: SetNull)
// Tracking
- isRead Boolean @default(false)
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ isRead Boolean @default(false)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([conversationId])
@@index([userId])
@@ -127,15 +127,15 @@ model Message {
// Join table to track all views that accessed a conversation
model ConversationView {
- id String @id @default(cuid())
- conversationId String
- conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
- viewId String
- view View @relation(fields: [viewId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ conversationId String
+ conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
+ viewId String
+ view View @relation(fields: [viewId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
@@unique([conversationId, viewId])
@@index([conversationId])
@@index([viewId])
-}
\ No newline at end of file
+}
diff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prisma
index 2c5f1488..cd7f1348 100644
--- a/prisma/schema/dataroom.prisma
+++ b/prisma/schema/dataroom.prisma
@@ -14,7 +14,7 @@ model Dataroom {
brand DataroomBrand?
// conversation
- conversationsEnabled Boolean @default(false)
+ conversationsEnabled Boolean @default(false)
conversations Conversation[]
// upload external documents
@@ -36,7 +36,7 @@ model DataroomDocument {
folder DataroomFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
orderIndex Int?
- conversations Conversation[]
+ conversations Conversation[]
uploadedDocuments DocumentUpload[]
@@ -95,8 +95,8 @@ model ViewerGroup {
teamId String
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
- views View[]
- conversations Conversation[]
+ views View[]
+ conversations Conversation[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -143,4 +143,4 @@ model ViewerGroupAccessControls {
enum ItemType {
DATAROOM_DOCUMENT
DATAROOM_FOLDER
-}
\ No newline at end of file
+}
diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prisma
index 073ac88b..e5468d90 100644
--- a/prisma/schema/link.prisma
+++ b/prisma/schema/link.prisma
@@ -58,13 +58,13 @@ model Link {
enableCustomMetatag Boolean? @default(false) // Optional give user a option to enable the custom metatag
// conversation
- enableConversation Boolean @default(false) // Controls if conversations are allowed on this link
- conversations Conversation[]
+ enableConversation Boolean @default(false) // Controls if conversations are allowed on this link
+ conversations Conversation[]
// upload
- enableUpload Boolean? @default(false) // Optional give user a option to enable the upload document function
+ enableUpload Boolean? @default(false) // Optional give user a option to enable the upload document function
isFileRequestOnly Boolean? @default(false) // Optional give user a option to enable the file request only
- uploadFolderId String? // This can be nullable, indicating upload to root folder, either document folder or dataroom folder
+ uploadFolderId String? // This can be nullable, indicating upload to root folder, either document folder or dataroom folder
uploadedDocuments DocumentUpload[]
@@ -79,10 +79,11 @@ model Link {
}
model LinkPreset {
- id String @id @default(cuid())
+ id String @id @default(cuid())
name String
teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ pId String? @unique
enableCustomMetaTag Boolean? @default(false) // Optional give user a option to enable the custom metatag
metaTitle String? // This will be the meta title of the link
@@ -90,6 +91,24 @@ model LinkPreset {
metaImage String? // This will be the meta image of the link
metaFavicon String? // This will be the meta favicon of the link
+ emailProtected Boolean? @default(true)
+ emailAuthenticated Boolean? @default(false)
+ allowDownload Boolean? @default(false)
+ enableAllowList Boolean? @default(false)
+ allowList String[]
+ enableDenyList Boolean? @default(false)
+ denyList String[]
+ expiresIn Int? // how many days from link creation until it expires in seconds
+ expiresAt DateTime?
+ enablePassword Boolean? @default(false)
+ password String?
+ enableWatermark Boolean? @default(false)
+ watermarkConfig Json? //{text: "Confidential", isTiled: false, color: "#000000", fontSize: 12, opacity: 0.5, rotation: 30, position: "top-right"}
+ // enableCustomFields Boolean? @default(false)
+ // customFields Json? //[{type: "SHORT_TEXT", identifier: "name", label: "Name", required: true}]
+
+ isDefault Boolean @default(false)
+
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -133,4 +152,4 @@ model CustomFieldResponse {
updatedAt DateTime @updatedAt
@@index([viewId])
-}
\ No newline at end of file
+}
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index c59694d5..6710baa4 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -38,22 +38,22 @@ model Session {
}
model User {
- id String @id @default(cuid())
+ id String @id @default(cuid())
name String?
- email String? @unique
+ email String? @unique
emailVerified DateTime?
image String?
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
accounts Account[]
sessions Session[]
documents Document[]
teams UserTeam[]
domains Domain[]
- chats Chat[]
+ chats Chat[]
contactId String?
- plan String @default("free")
- stripeId String? @unique // Stripe subscription / customer ID
- subscriptionId String? @unique // Stripe subscription ID
+ plan String @default("free")
+ stripeId String? @unique // Stripe subscription / customer ID
+ subscriptionId String? @unique // Stripe subscription ID
startsAt DateTime? // Stripe subscription start date
endsAt DateTime? // Stripe subscription end date
@@ -61,7 +61,7 @@ model User {
// conversation
participatedConversations ConversationParticipant[]
- messages Message[]
+ messages Message[]
}
model Team {
@@ -95,7 +95,7 @@ model Team {
incomingWebhooks IncomingWebhook[]
restrictedTokens RestrictedToken[]
webhooks Webhook[]
-
+
conversations Conversation[]
uploadedDocuments DocumentUpload[]
@@ -166,7 +166,7 @@ model Document {
links Link[]
views View[]
versions DocumentVersion[]
- chats Chat[]
+ chats Chat[]
folderId String? // Optional Folder ID for documents in folders
folder Folder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
@@ -175,7 +175,7 @@ model Document {
// upload external documents
uploadedDocument DocumentUpload[]
- isExternalUpload Boolean @default(false) // Indicates if the document is an external upload
+ isExternalUpload Boolean @default(false) // Indicates if the document is an external upload
@@index([ownerId])
@@index([teamId])
@@ -248,35 +248,35 @@ model Domain {
}
model View {
- id String @id @default(cuid())
- link Link @relation(fields: [linkId], references: [id])
- linkId String
- document Document? @relation(fields: [documentId], references: [id], onDelete: Cascade)
- documentId String?
- dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
- dataroomId String?
- dataroomViewId String? // This is the view ID from the dataroom
- viewerEmail String? // Email of the viewer if known
- viewerName String? // Name of the viewer if known
- verified Boolean @default(false) // Whether the viewer email has been verified
- viewedAt DateTime @default(now())
- downloadedAt DateTime? // This is the time the document was downloaded
- reactions Reaction[]
- viewType ViewType @default(DOCUMENT_VIEW)
- viewerId String? // This is the viewer ID from the dataroom
- viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: Cascade)
- groupId String? // This is the group ID from the dataroom
- group ViewerGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
- feedbackResponse FeedbackResponse?
- agreementResponse AgreementResponse?
+ id String @id @default(cuid())
+ link Link @relation(fields: [linkId], references: [id])
+ linkId String
+ document Document? @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ documentId String?
+ dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+ dataroomId String?
+ dataroomViewId String? // This is the view ID from the dataroom
+ viewerEmail String? // Email of the viewer if known
+ viewerName String? // Name of the viewer if known
+ verified Boolean @default(false) // Whether the viewer email has been verified
+ viewedAt DateTime @default(now())
+ downloadedAt DateTime? // This is the time the document was downloaded
+ reactions Reaction[]
+ viewType ViewType @default(DOCUMENT_VIEW)
+ viewerId String? // This is the viewer ID from the dataroom
+ viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: Cascade)
+ groupId String? // This is the group ID from the dataroom
+ group ViewerGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
+ feedbackResponse FeedbackResponse?
+ agreementResponse AgreementResponse?
customFieldResponse CustomFieldResponse?
isArchived Boolean @default(false) // Indicates if the view is archived and not counted in the analytics
// conversation
- conversationViews ConversationView[]
- messages Message[]
- initialConversations Conversation[] @relation("initialView")
+ conversationViews ConversationView[]
+ messages Message[]
+ initialConversations Conversation[] @relation("initialView")
uploadedDocuments DocumentUpload[] // uploaded documents by this view
@@ -307,10 +307,10 @@ model Viewer {
teamId String
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
- views View[]
- groups ViewerGroupMembership[]
+ views View[]
+ groups ViewerGroupMembership[]
participatedConversations ConversationParticipant[]
- messages Message[]
+ messages Message[]
uploadedDocuments DocumentUpload[] // uploaded documents by this viewer
@@ -463,7 +463,6 @@ model AgreementResponse {
@@index([viewId])
}
-
model IncomingWebhook {
id String @id @default(cuid())
externalId String @unique
@@ -540,35 +539,34 @@ model YearInReview {
@@index([teamId])
}
-
model DocumentUpload {
- id String @id @default(cuid())
- documentId String
- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
- teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
- viewerId String?
- viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
- viewId String?
- view View? @relation(fields: [viewId], references: [id], onDelete: SetNull)
- linkId String
- link Link @relation(fields: [linkId], references: [id], onDelete: Cascade)
-
+ id String @id @default(cuid())
+ documentId String
+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ viewerId String?
+ viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: SetNull)
+ viewId String?
+ view View? @relation(fields: [viewId], references: [id], onDelete: SetNull)
+ linkId String
+ link Link @relation(fields: [linkId], references: [id], onDelete: Cascade)
+
// Optional dataroom relations
- dataroomId String?
- dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: SetNull)
+ dataroomId String?
+ dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: SetNull)
dataroomDocumentId String?
- dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
+ dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
// Additional metadata
- originalFilename String?
- fileSize Int?
- numPages Int?
- mimeType String?
- uploadedAt DateTime @default(now())
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ originalFilename String?
+ fileSize Int?
+ numPages Int?
+ mimeType String?
+ uploadedAt DateTime @default(now())
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([documentId])
@@index([viewerId])
@@ -577,4 +575,4 @@ model DocumentUpload {
@@index([teamId])
@@index([dataroomId])
@@index([dataroomDocumentId])
-}
\ No newline at end of file
+}