Skip to content

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

feat: transfer link to document or dataroom 9afd

Marc Seitzb6e778d96773
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index 429c9e97..e7e210dd 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -10,6 +10,7 @@ import { PlanEnum } from "@/ee/stripe/constants";
import { DocumentVersion, LinkAudienceType } from "@prisma/client";
import { isWithinInterval, subMinutes } from "date-fns";
import {
+ ArrowRightLeftIcon,
BoxesIcon,
ChevronRightIcon,
ClockFadingIcon,
@@ -82,6 +83,7 @@ import { Label } from "../ui/label";
import { ButtonTooltip } from "../ui/tooltip";
import { useDeleteLinkModal } from "./delete-link-modal";
import EmbedCodeModal from "./embed-code-modal";
+import { useTransferLinkModal } from "./transfer-link-modal";
import LinkActiveControls, {
countActiveSettings,
} from "./link-active-controls";
@@ -378,6 +380,13 @@ export default function LinksTable({
link: linkToDelete,
targetType,
});
+ const [linkToTransfer, setLinkToTransfer] = useState<LinkWithViews | null>(
+ null,
+ );
+ const { setShowTransferLinkModal, TransferLinkModal } = useTransferLinkModal({
+ link: linkToTransfer,
+ targetType,
+ });
const [isInviteModalOpen, setIsInviteModalOpen] = useState<boolean>(false);
const [showInviteUpgrade, setShowInviteUpgrade] = useState<boolean>(false);
const [inviteLink, setInviteLink] = useState<LinkWithViews | null>(null);
@@ -1073,6 +1082,15 @@ export default function LinksTable({
<CopyPlusIcon className="mr-2 h-4 w-4" />
Duplicate Link
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ setLinkToTransfer(link);
+ setShowTransferLinkModal(true);
+ }}
+ >
+ <ArrowRightLeftIcon className="mr-2 h-4 w-4" />
+ Transfer Link
+ </DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setSelectedEmbedLink({
@@ -1251,6 +1269,7 @@ export default function LinksTable({
) : null}
<DeleteLinkModal />
+ <TransferLinkModal />
</div>
</>
);
diff --git a/components/links/transfer-link-modal.tsx b/components/links/transfer-link-modal.tsx
new file mode 100644
index 00000000..d0e551ac
--- /dev/null
+++ b/components/links/transfer-link-modal.tsx
@@ -0,0 +1,356 @@
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+
+import { useRouter } from "next/router";
+
+import { useTeam } from "@/context/team-context";
+import { FileTextIcon, ServerIcon, SnowflakeIcon } from "lucide-react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import useSWR from "swr";
+
+import { useAnalytics } from "@/lib/analytics";
+import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";
+import { LinkWithViews } from "@/lib/types";
+import { fetcher } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { SingleSelect } from "@/components/ui/single-select";
+
+type TransferTargetType = "DOCUMENT" | "DATAROOM";
+
+type DocumentOption = { id: string; name: string };
+
+// Case-insensitive, digit-aware ordering so names like "File 2" sort before
+// "File 10" and casing doesn't split the list into two alphabetical runs.
+const byName: Intl.CollatorOptions = { sensitivity: "base", numeric: true };
+
+function TransferLinkModal({
+ showTransferLinkModal,
+ setShowTransferLinkModal,
+ link,
+ targetType,
+}: {
+ showTransferLinkModal: boolean;
+ setShowTransferLinkModal: Dispatch<SetStateAction<boolean>>;
+ link: LinkWithViews | null;
+ targetType: "DOCUMENT" | "DATAROOM";
+}) {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const analytics = useAnalytics();
+
+ const [destinationType, setDestinationType] =
+ useState<TransferTargetType>(targetType);
+ const [selectedTarget, setSelectedTarget] = useState<string>("");
+ const [transferring, setTransferring] = useState<boolean>(false);
+
+ const currentTargetId = link?.documentId ?? link?.dataroomId ?? "";
+
+ useEffect(() => {
+ if (showTransferLinkModal) {
+ setDestinationType(targetType);
+ setSelectedTarget("");
+ }
+ }, [showTransferLinkModal, targetType, link?.id]);
+
+ // Documents are fetched on demand (only while the modal is open and the
+ // document destination is selected) to keep the picker scoped to documents
+ // the current team/member can access.
+ const { data: documentsData, isLoading: documentsLoading } = useSWR<{
+ documents: DocumentOption[];
+ }>(
+ showTransferLinkModal && destinationType === "DOCUMENT" && teamId
+ ? `/api/teams/${teamId}/documents?sort=name&limit=1000`
+ : null,
+ fetcher,
+ { revalidateOnFocus: false, dedupingInterval: 30000 },
+ );
+
+ const { datarooms, loading: dataroomsLoading } = useDataroomsSimple();
+
+ const documentOptions = useMemo(() => {
+ const docs = documentsData?.documents ?? [];
+ return docs
+ .map((doc) => ({
+ label: doc.name,
+ value: doc.id,
+ searchableText: doc.name,
+ meta: { isCurrent: doc.id === currentTargetId },
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label, undefined, byName));
+ }, [documentsData, currentTargetId]);
+
+ const dataroomOptions = useMemo(() => {
+ return (datarooms ?? [])
+ .map((room) => ({
+ label: room.name,
+ value: room.id,
+ searchableText: room.name,
+ meta: {
+ isFrozen: room.isFrozen,
+ isCurrent: room.id === currentTargetId,
+ },
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label, undefined, byName));
+ }, [datarooms, currentTargetId]);
+
+ const isDocumentDestination = destinationType === "DOCUMENT";
+ const options = isDocumentDestination ? documentOptions : dataroomOptions;
+ const optionsLoading = isDocumentDestination
+ ? documentsLoading
+ : dataroomsLoading;
+
+ const isNoop =
+ destinationType === targetType && selectedTarget === currentTargetId;
+
+ const canSubmit = !!selectedTarget && !isNoop && !transferring;
+
+ const handleDestinationTypeChange = (type: TransferTargetType) => {
+ setDestinationType(type);
+ setSelectedTarget("");
+ };
+
+ async function transferLink() {
+ if (!link || !teamId || !selectedTarget) return;
+
+ setTransferring(true);
+ try {
+ const response = await fetch(`/api/links/${link.id}/transfer`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ teamId,
+ targetType: destinationType,
+ targetId: selectedTarget,
+ }),
+ });
+
+ if (!response.ok) {
+ const { error } = await response.json().catch(() => ({
+ error: "Failed to transfer link",
+ }));
+ throw new Error(error || "Failed to transfer link");
+ }
+
+ analytics.capture("Link Transferred", {
+ teamId,
+ linkId: link.id,
+ fromType: targetType,
+ toType: destinationType,
+ fromTargetId: currentTargetId,
+ toTargetId: selectedTarget,
+ });
+
+ // The transfer has committed server-side, so the modal should close on
+ // success regardless of whether the cache refresh below succeeds.
+ setShowTransferLinkModal(false);
+
+ // Best-effort cache revalidation: drop the link from the current
+ // target's lists (and any group-scoped list) and prime the destination's
+ // list. A failed revalidation must not surface as a transfer failure.
+ const fromEndpoint = `${targetType.toLowerCase()}s`;
+ const toEndpoint = `${destinationType.toLowerCase()}s`;
+ const revalidationKeys = [
+ `/api/teams/${teamId}/${fromEndpoint}/${encodeURIComponent(
+ currentTargetId,
+ )}/links`,
+ `/api/teams/${teamId}/${toEndpoint}/${encodeURIComponent(
+ selectedTarget,
+ )}/links`,
+ ];
+ if (link.groupId) {
+ revalidationKeys.push(
+ `/api/teams/${teamId}/${fromEndpoint}/${encodeURIComponent(
+ currentTargetId,
+ )}/groups/${link.groupId}/links`,
+ );
+ }
+ await Promise.allSettled(revalidationKeys.map((key) => mutate(key)));
+ } finally {
+ setTransferring(false);
+ }
+ }
+
+ if (!link) return null;
+
+ const linkName = link.name || `Link #${link.id.slice(-5)}`;
+ const viewCount = link._count?.views ?? 0;
+
+ return (
+ <Dialog open={showTransferLinkModal} onOpenChange={setShowTransferLinkModal}>
+ <DialogContent className="max-w-[90vw] sm:max-w-[480px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>Transfer link</DialogTitle>
+ <DialogDescription>
+ Move{" "}
+ <span className="font-medium text-foreground">{linkName}</span> to a
+ different document or data room. The link URL stays the same.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-2">
+ <Button
+ type="button"
+ variant={isDocumentDestination ? "default" : "outline"}
+ className="justify-center gap-2"
+ onClick={() => handleDestinationTypeChange("DOCUMENT")}
+ >
+ <FileTextIcon className="h-4 w-4" />
+ Document
+ </Button>
+ <Button
+ type="button"
+ variant={!isDocumentDestination ? "default" : "outline"}
+ className="justify-center gap-2"
+ onClick={() => handleDestinationTypeChange("DATAROOM")}
+ >
+ <ServerIcon className="h-4 w-4" />
+ Data room
+ </Button>
+ </div>
+
+ <SingleSelect
+ options={options}
+ value={selectedTarget}
+ onValueChange={setSelectedTarget}
+ loading={optionsLoading}
+ placeholder={
+ isDocumentDestination
+ ? "Select a document"
+ : "Select a data room"
+ }
+ searchPlaceholder={
+ isDocumentDestination
+ ? "Search documents..."
+ : "Search data rooms..."
+ }
+ triggerIcon={
+ isDocumentDestination ? (
+ <FileTextIcon className="!size-4 shrink-0 text-muted-foreground" />
+ ) : (
+ <ServerIcon className="!size-4 shrink-0 text-muted-foreground" />
+ )
+ }
+ emptyText={
+ isDocumentDestination
+ ? "No documents found."
+ : "No data rooms found."
+ }
+ renderOption={(option) => (
+ <span className="flex w-full items-center gap-1.5">
+ {option.meta?.isFrozen ? (
+ <SnowflakeIcon className="h-3.5 w-3.5 shrink-0 text-blue-500" />
+ ) : null}
+ <span className="truncate">
+ {option.label}
+ {option.meta?.isCurrent ? " (current)" : ""}
+ {option.meta?.isFrozen ? " (frozen)" : ""}
+ </span>
+ </span>
+ )}
+ />
+
+ {isNoop ? (
+ <p className="text-xs text-destructive">
+ The link already points to this {targetType.toLowerCase()}.
+ </p>
+ ) : null}
+
+ <div className="rounded-md border border-border bg-muted/50 p-3 text-xs text-muted-foreground">
+ <p>
+ The link&apos;s existing{" "}
+ <strong>
+ {viewCount} view{viewCount !== 1 ? "s" : ""}
+ </strong>{" "}
+ stay attached to the previous{" "}
+ {targetType === "DATAROOM" ? "data room" : "document"} for
+ historical analytics. Going forward, visitors will see the new
+ target.
+ </p>
+ <p className="mt-2">
+ Data room settings don&apos;t carry over: visitor groups, file
+ permissions, and upload folders will be cleared.
+ </p>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ onClick={async () => {
+ const destination = destinationType;
+ const destinationId = selectedTarget;
+ try {
+ await transferLink();
+ const targetPath =
+ destination === "DATAROOM"
+ ? `/datarooms/${destinationId}`
+ : `/documents/${destinationId}`;
+ toast.success("Link transferred successfully!", {
+ action: {
+ label: "Open",
+ onClick: () => router.push(targetPath),
+ },
+ });
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to transfer",
+ );
+ }
+ }}
+ loading={transferring}
+ disabled={!canSubmit}
+ className="w-full"
+ >
+ Transfer link
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function useTransferLinkModal({
+ link,
+ targetType,
+}: {
+ link: LinkWithViews | null;
+ targetType: "DOCUMENT" | "DATAROOM";
+}) {
+ const [showTransferLinkModal, setShowTransferLinkModal] = useState(false);
+
+ const TransferLinkModalCallback = useCallback(() => {
+ return (
+ <TransferLinkModal
+ showTransferLinkModal={showTransferLinkModal}
+ setShowTransferLinkModal={setShowTransferLinkModal}
+ link={link}
+ targetType={targetType}
+ />
+ );
+ }, [showTransferLinkModal, link, targetType]);
+
+ return useMemo(
+ () => ({
+ setShowTransferLinkModal,
+ TransferLinkModal: TransferLinkModalCallback,
+ }),
+ [setShowTransferLinkModal, TransferLinkModalCallback],
+ );
+}
diff --git a/components/ui/single-select.tsx b/components/ui/single-select.tsx
index 564f3711..2c07de8b 100644
--- a/components/ui/single-select.tsx
+++ b/components/ui/single-select.tsx
@@ -17,7 +17,6 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
-import { ScrollArea } from "@/components/ui/scroll-area";
import LoadingSpinner from "./loading-spinner";
@@ -204,44 +203,42 @@ export const SingleSelect = React.forwardRef<
)}
onKeyDown={handleInputKeyDown}
/>
- <ScrollArea className="max-h-[300px]">
- <CommandList>
- <CommandGroup>
- {loading ? (
- <CommandItem className="justify-center">
- <LoadingSpinner className="size-4 shrink-0" />
- </CommandItem>
- ) : filteredOptions.length > 0 ? (
- filteredOptions.map((option) => {
- const isSelected = value === option.value;
- return (
- <CommandItem
- key={option.value}
- onSelect={() => handleSelect(option.value)}
- className={cn(
- "cursor-pointer gap-2 py-2.5",
- optionClassName,
- )}
- value={option.value}
- >
- {renderOption ? (
- renderOption(option, isSelected)
- ) : (
- <span className="text-sm">{option.label}</span>
- )}
- </CommandItem>
- );
- })
- ) : (
- <CommandItem disabled className="justify-center">
- <span className="text-sm text-muted-foreground">
- {emptyText}
- </span>
- </CommandItem>
- )}
- </CommandGroup>
- </CommandList>
- </ScrollArea>
+ <CommandList className="scroll-mask-y scrollbar-hide">
+ <CommandGroup>
+ {loading ? (
+ <CommandItem className="justify-center">
+ <LoadingSpinner className="size-4 shrink-0" />
+ </CommandItem>
+ ) : filteredOptions.length > 0 ? (
+ filteredOptions.map((option) => {
+ const isSelected = value === option.value;
+ return (
+ <CommandItem
+ key={option.value}
+ onSelect={() => handleSelect(option.value)}
+ className={cn(
+ "cursor-pointer gap-2 py-2.5",
+ optionClassName,
+ )}
+ value={option.value}
+ >
+ {renderOption ? (
+ renderOption(option, isSelected)
+ ) : (
+ <span className="text-sm">{option.label}</span>
+ )}
+ </CommandItem>
+ );
+ })
+ ) : (
+ <CommandItem disabled className="justify-center">
+ <span className="text-sm text-muted-foreground">
+ {emptyText}
+ </span>
+ </CommandItem>
+ )}
+ </CommandGroup>
+ </CommandList>
</Command>
</PopoverContent>
</Popover>
diff --git a/pages/api/links/[id]/transfer.ts b/pages/api/links/[id]/transfer.ts
new file mode 100644
index 00000000..f7cbc37e
--- /dev/null
+++ b/pages/api/links/[id]/transfer.ts
@@ -0,0 +1,256 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { LinkAudienceType, LinkType } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+import {
+ enforceDataroomMemberScope,
+ enforceDocumentMemberScope,
+ enforceLinkMemberScope,
+} from "@/lib/api/rbac/guard";
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { decryptEncrpytedPassword } from "@/lib/utils";
+
+/**
+ * POST /api/links/:id/transfer
+ *
+ * Transfers (re-targets) an existing link to a different document or data room.
+ *
+ * Historical `View` records are intentionally left untouched: each view keeps
+ * the `documentId`/`dataroomId` it was recorded against, so analytics for the
+ * previous target stay accurate. The link itself simply starts pointing at the
+ * new target going forward. Because views are joined to the link by `linkId`,
+ * those historical views continue to surface the (possibly renamed) link name —
+ * this is expected and keeps the audit trail intact.
+ *
+ * Both the source link and the destination target must belong to the current
+ * team, and dataroom-scoped members may only transfer between rooms/documents
+ * they are assigned to.
+ */
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { id } = req.query as { id: string };
+ const { teamId, targetType, targetId } = req.body as {
+ teamId?: string;
+ targetType?: "DOCUMENT" | "DATAROOM";
+ targetId?: string;
+ };
+
+ if (!teamId) {
+ return res.status(400).json({ error: "Missing teamId." });
+ }
+
+ if (targetType !== "DOCUMENT" && targetType !== "DATAROOM") {
+ return res.status(400).json({ error: "Invalid target type." });
+ }
+
+ if (!targetId || typeof targetId !== "string") {
+ return res
+ .status(400)
+ .json({ error: "A destination document or data room is required." });
+ }
+
+ try {
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: { userId_teamId: { userId, teamId } },
+ select: { role: true },
+ });
+ if (!teamAccess) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const existingLink = await prisma.link.findUnique({
+ where: {
+ id,
+ teamId,
+ },
+ select: {
+ id: true,
+ linkType: true,
+ documentId: true,
+ dataroomId: true,
+ dataroom: { select: { isFrozen: true } },
+ },
+ });
+
+ if (!existingLink) {
+ return res.status(404).json({ error: "Link not found or unauthorized" });
+ }
+
+ // Workflow links are not document/dataroom links and cannot be transferred.
+ if (
+ existingLink.linkType !== LinkType.DOCUMENT_LINK &&
+ existingLink.linkType !== LinkType.DATAROOM_LINK
+ ) {
+ return res
+ .status(400)
+ .json({ error: "This link type cannot be transferred." });
+ }
+
+ // Source access: scoped members may only act on links inside their rooms.
+ const sourceDenied = await enforceLinkMemberScope({
+ userId,
+ teamId,
+ linkId: existingLink.id,
+ role: teamAccess.role,
+ res,
+ });
+ if (sourceDenied) return;
+
+ if (existingLink.dataroom?.isFrozen) {
+ return res.status(403).json({
+ error:
+ "This data room is frozen. You cannot transfer links out of a frozen data room.",
+ });
+ }
+
+ const newLinkType =
+ targetType === "DATAROOM"
+ ? LinkType.DATAROOM_LINK
+ : LinkType.DOCUMENT_LINK;
+
+ const currentTargetId =
+ existingLink.linkType === LinkType.DATAROOM_LINK
+ ? existingLink.dataroomId
+ : existingLink.documentId;
+ if (existingLink.linkType === newLinkType && currentTargetId === targetId) {
+ return res
+ .status(400)
+ .json({ error: "The link already points to this target." });
+ }
+
+ if (targetType === "DOCUMENT") {
+ const destinationDocument = await prisma.document.findUnique({
+ where: { id: targetId, teamId },
+ select: { id: true },
+ });
+ if (!destinationDocument) {
+ return res
+ .status(404)
+ .json({ error: "Destination document not found." });
+ }
+
+ const destinationDenied = await enforceDocumentMemberScope({
+ userId,
+ teamId,
+ documentId: targetId,
+ role: teamAccess.role,
+ res,
+ });
+ if (destinationDenied) return;
+ } else {
+ const destinationDataroom = await prisma.dataroom.findUnique({
+ where: { id: targetId, teamId },
+ select: { isFrozen: true },
+ });
+ if (!destinationDataroom) {
+ return res
+ .status(404)
+ .json({ error: "Destination data room not found." });
+ }
+ if (destinationDataroom.isFrozen) {
+ return res.status(403).json({
+ error:
+ "This data room is frozen. You cannot transfer links into a frozen data room.",
+ });
+ }
+
+ const destinationDenied = await enforceDataroomMemberScope({
+ userId,
+ teamId,
+ dataroomId: targetId,
+ role: teamAccess.role,
+ res,
+ });
+ if (destinationDenied) return;
+ }
+
+ const becomingDocumentLink = newLinkType === LinkType.DOCUMENT_LINK;
+
+ const updatedLink = await prisma.$transaction(async (tx) => {
+ // Dataroom-scoped bindings (viewer group, permission group, upload
+ // folders) belong to the *previous* data room and must be dropped on any
+ // transfer so they cannot leak into the new target.
+ const link = await tx.link.update({
+ where: { id, teamId },
+ data: {
+ documentId: targetType === "DOCUMENT" ? targetId : null,
+ dataroomId: targetType === "DATAROOM" ? targetId : null,
+ linkType: newLinkType,
+ groupId: null,
+ permissionGroupId: null,
+ audienceType: LinkAudienceType.GENERAL,
+ uploadFolderIds: [],
+ // Document links cannot use these data-room-only capabilities.
+ ...(becomingDocumentLink && {
+ enableUpload: false,
+ isFileRequestOnly: false,
+ enableIndexFile: false,
+ enableConversation: false,
+ }),
+ },
+ include: {
+ customFields: true,
+ visitorGroups: { select: { visitorGroupId: true } },
+ tags: {
+ select: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
+ },
+ },
+ },
+ views: { orderBy: { viewedAt: "desc" }, take: 1 },
+ _count: { select: { views: true } },
+ },
+ });
+
+ return link;
+ });
+
+ // Refresh the cached link payload (covers both the id and domain routes).
+ // Revalidation is best-effort: the transfer already succeeded, so bound the
+ // request with a timeout and swallow any failure so a slow or unreachable
+ // revalidate endpoint can't stall this response.
+ await fetch(
+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&linkId=${id}&hasDomain=${
+ updatedLink.domainId ? "true" : "false"
+ }`,
+ { signal: AbortSignal.timeout(5000) },
+ ).catch(() => {});
+
+ if (updatedLink.password !== null) {
+ updatedLink.password = decryptEncrpytedPassword(updatedLink.password);
+ }
+
+ const responseLink = {
+ ...updatedLink,
+ tags: updatedLink.tags.map((t) => t.tag),
+ };
+
+ return res.status(200).json(responseLink);
+ } catch (error) {
+ errorhandler(error, res);
+ }
+}
diff --git a/pages/api/teams/[teamId]/links/[id]/visits.ts b/pages/api/teams/[teamId]/links/[id]/visits.ts
index 1c70a441..8e8a459c 100644
--- a/pages/api/teams/[teamId]/links/[id]/visits.ts
+++ b/pages/api/teams/[teamId]/links/[id]/visits.ts
@@ -95,7 +95,7 @@ export default async function handle(
},
});
- const numPages =
+ const currentDocNumPages =
result?.document?.versions[0]?.numPages ||
result?.document?.numPages ||
0;
@@ -134,6 +134,49 @@ export default async function handle(
? views.slice(0, LIMITS.views)
: views;
+ // A link can be transferred between documents over its lifetime, so a
+ // historical view may reference a *different* document than the one the
+ // link currently points at. Resolve each view's completion rate against
+ // the document that was actually viewed (falling back to the link's
+ // current document) instead of assuming a single page count.
+ const otherDocumentIds = Array.from(
+ new Set(
+ limitedViews
+ .map((view) => view.documentId)
+ .filter(
+ (docId): docId is string =>
+ !!docId && docId !== result?.document?.id,
+ ),
+ ),
+ );
+
+ const numPagesByDocumentId = new Map<string, number>();
+ if (result?.document?.id) {
+ numPagesByDocumentId.set(result.document.id, currentDocNumPages);
+ }
+
+ if (otherDocumentIds.length > 0) {
+ const otherDocuments = await prisma.document.findMany({
+ where: { id: { in: otherDocumentIds }, teamId },
+ select: {
+ id: true,
+ numPages: true,
+ versions: {
+ where: { isPrimary: true },
+ orderBy: { createdAt: "desc" },
+ take: 1,
+ select: { numPages: true },
+ },
+ },
+ });
+ for (const doc of otherDocuments) {
+ numPagesByDocumentId.set(
+ doc.id,
+ doc.versions[0]?.numPages || doc.numPages || 0,
+ );
+ }
+ }
+
const durationsPromises = limitedViews.map((view) => {
return getViewPageDuration({
documentId: view.documentId!,
@@ -154,9 +197,11 @@ export default async function handle(
// Construct the response combining views and their respective durations
const viewsWithDuration = limitedViews.map((view, index) => {
- // calculate the completion rate
- const completionRate = numPages
- ? (durations[index].data.length / numPages) * 100
+ const viewNumPages = view.documentId
+ ? (numPagesByDocumentId.get(view.documentId) ?? currentDocNumPages)
+ : currentDocNumPages;
+ const completionRate = viewNumPages
+ ? (durations[index].data.length / viewNumPages) * 100
: 0;
return {