Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Add Notion document accessibility indicator and URL management
Cursor Agent0625b34b55ee
diff --git a/components/documents/notion-accessibility-indicator.tsx b/components/documents/notion-accessibility-indicator.tsxnew file mode 100644index 00000000..1958bc93--- /dev/null+++ b/components/documents/notion-accessibility-indicator.tsx@@ -0,0 +1,259 @@+import { useEffect, useState } from "react";++import { DocumentVersion } from "@prisma/client";+import { AlertCircle, CheckCircle, Edit, ExternalLink, RefreshCw } from "lucide-react";+import { toast } from "sonner";++import { useTeam } from "@/context/team-context";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import LoadingSpinner from "@/components/ui/loading-spinner";++interface NotionAccessibilityIndicatorProps {+ documentId: string;+ primaryVersion: DocumentVersion;+ onUrlUpdate?: () => void;+}++interface AccessibilityStatus {+ isAccessible: boolean;+ url: string;+ statusCode?: number;+ lastChecked: string;+ error?: string;+}++export default function NotionAccessibilityIndicator({+ documentId,+ primaryVersion,+ onUrlUpdate,+}: NotionAccessibilityIndicatorProps) {+ const teamInfo = useTeam();+ const [status, setStatus] = useState<AccessibilityStatus | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [isDialogOpen, setIsDialogOpen] = useState(false);+ const [newUrl, setNewUrl] = useState("");+ const [isUpdating, setIsUpdating] = useState(false);++ // Only render for Notion documents+ if (primaryVersion.type !== "notion") {+ return null;+ }++ const checkAccessibility = async () => {+ if (!teamInfo?.currentTeam?.id) return;++ setIsLoading(true);+ try {+ const response = await fetch(+ `/api/teams/${teamInfo.currentTeam.id}/documents/${documentId}/check-notion-accessibility`,+ );+ const data = await response.json();++ if (response.ok) {+ setStatus(data);+ } else {+ toast.error("Failed to check accessibility");+ }+ } catch (error) {+ console.error("Error checking accessibility:", error);+ toast.error("Failed to check accessibility");+ } finally {+ setIsLoading(false);+ }+ };++ const updateNotionUrl = async () => {+ if (!teamInfo?.currentTeam?.id || !newUrl.trim()) return;++ setIsUpdating(true);+ try {+ const response = await fetch(+ `/api/teams/${teamInfo.currentTeam.id}/documents/${documentId}/update-notion-url`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ notionUrl: newUrl.trim() }),+ },+ );++ const data = await response.json();++ if (response.ok) {+ toast.success("Notion URL updated successfully");+ setIsDialogOpen(false);+ setNewUrl("");+ // Refresh accessibility status+ await checkAccessibility();+ // Trigger parent component update if provided+ if (onUrlUpdate) {+ onUrlUpdate();+ }+ } else {+ toast.error(data.message || "Failed to update URL");+ }+ } catch (error) {+ console.error("Error updating URL:", error);+ toast.error("Failed to update URL");+ } finally {+ setIsUpdating(false);+ }+ };++ const openNotionPage = () => {+ if (status?.url) {+ window.open(status.url, "_blank");+ }+ };++ // Check accessibility on component mount+ useEffect(() => {+ checkAccessibility();+ }, []);++ const getStatusIcon = () => {+ if (isLoading) {+ return <LoadingSpinner className="h-4 w-4" />;+ }++ if (status?.isAccessible) {+ return <CheckCircle className="h-4 w-4 text-green-500" />;+ } else {+ return <AlertCircle className="h-4 w-4 text-red-500" />;+ }+ };++ const getStatusText = () => {+ if (isLoading) {+ return "Checking accessibility...";+ }++ if (status?.isAccessible) {+ return "Publicly accessible";+ } else if (status?.error) {+ return "Unable to check";+ } else {+ return "Not publicly accessible";+ }+ };++ const getStatusColor = () => {+ if (isLoading) {+ return "text-gray-500";+ }++ if (status?.isAccessible) {+ return "text-green-600";+ } else {+ return "text-red-600";+ }+ };++ return (+ <div className="flex items-center gap-2 rounded-lg border bg-white p-3 shadow-sm">+ <div className="flex items-center gap-2">+ {getStatusIcon()}+ <span className={`text-sm font-medium ${getStatusColor()}`}>+ {getStatusText()}+ </span>+ </div>++ <div className="flex items-center gap-1 ml-auto">+ <Button+ variant="ghost"+ size="sm"+ onClick={checkAccessibility}+ disabled={isLoading}+ className="h-7 px-2"+ >+ <RefreshCw className={`h-3 w-3 ${isLoading ? "animate-spin" : ""}`} />+ </Button>++ {status?.url && (+ <Button+ variant="ghost"+ size="sm"+ onClick={openNotionPage}+ className="h-7 px-2"+ >+ <ExternalLink className="h-3 w-3" />+ </Button>+ )}++ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <DialogTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2"+ onClick={() => setNewUrl(status?.url || "")}+ >+ <Edit className="h-3 w-3" />+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Update Notion URL</DialogTitle>+ <DialogDescription>+ Change the URL of the Notion page for this document.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ <div className="grid gap-2">+ <Label htmlFor="notion-url">Notion URL</Label>+ <Input+ id="notion-url"+ value={newUrl}+ onChange={(e) => setNewUrl(e.target.value)}+ placeholder="https://www.notion.so/your-page-url"+ className="w-full"+ />+ </div>+ </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setIsDialogOpen(false)}+ disabled={isUpdating}+ >+ Cancel+ </Button>+ <Button+ onClick={updateNotionUrl}+ disabled={isUpdating || !newUrl.trim()}+ >+ {isUpdating ? (+ <>+ <LoadingSpinner className="mr-2 h-4 w-4" />+ Updating...+ </>+ ) : (+ "Update URL"+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>++ {status?.lastChecked && (+ <div className="text-xs text-gray-400 mt-1">+ Last checked: {new Date(status.lastChecked).toLocaleTimeString()}+ </div>+ )}+ </div>+ );+}\ No newline at end of filediff --git a/package-lock.json b/package-lock.jsonindex adeae941..1fb59913 100644--- a/package-lock.json+++ b/package-lock.json@@ -17458,21 +17458,6 @@"type": "github","url": "https://github.com/sponsors/wooorm"}- },- "node_modules/react-email/node_modules/@next/swc-win32-ia32-msvc": {- "version": "14.2.30",- "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.30.tgz",- "integrity": "sha512-pVZMnFok5qEX4RT59mK2hEVtJX+XFfak+/rjHpyFh7juiT52r177bfFKhnlafm0UOSldhXjj32b+LZIOdswGTg==",- "cpu": [- "ia32"- ],- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">= 10"- }}}}diff --git a/pages/api/teams/[teamId]/documents/[id]/check-notion-accessibility.ts b/pages/api/teams/[teamId]/documents/[id]/check-notion-accessibility.tsnew file mode 100644index 00000000..942e147f--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/check-notion-accessibility.ts@@ -0,0 +1,97 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const userId = (session.user as CustomUser).id;+ const { teamId, id: documentId } = req.query as {+ teamId: string;+ id: string;+ };++ try {+ // Check if user has access to the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const documentVersion = await prisma.documentVersion.findFirst({+ where: {+ documentId: documentId,+ isPrimary: true,+ },+ select: {+ file: true,+ type: true,+ },+ });++ if (!documentVersion) {+ return res.status(404).json({ message: "Document version not found" });+ }++ if (documentVersion.type !== "notion") {+ return res+ .status(400)+ .json({ message: "Document is not a Notion document" });+ }++ // Check if the Notion page is publicly accessible+ try {+ const notionUrl = documentVersion.file;+ const response = await fetch(notionUrl, {+ method: "HEAD",+ headers: {+ "User-Agent": "Papermark/1.0 (accessibility-check)",+ },+ });++ const isAccessible = response.ok && response.status === 200;++ return res.status(200).json({+ isAccessible,+ url: notionUrl,+ statusCode: response.status,+ lastChecked: new Date().toISOString(),+ });+ } catch (error) {+ console.error("Error checking Notion accessibility:", error);+ return res.status(200).json({+ isAccessible: false,+ url: documentVersion.file,+ error: "Failed to check accessibility",+ lastChecked: new Date().toISOString(),+ });+ }+ } catch (error) {+ console.error("Error:", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/documents/[id]/update-notion-url.ts b/pages/api/teams/[teamId]/documents/[id]/update-notion-url.tsnew file mode 100644index 00000000..f73d3b72--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/update-notion-url.ts@@ -0,0 +1,112 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "PATCH") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const userId = (session.user as CustomUser).id;+ const { teamId, id: documentId } = req.query as {+ teamId: string;+ id: string;+ };+ const { notionUrl } = req.body as { notionUrl: string };++ // Basic URL validation+ if (!notionUrl || typeof notionUrl !== "string") {+ return res.status(400).json({ message: "Valid Notion URL is required" });+ }++ // Validate that it's a Notion URL+ try {+ const url = new URL(notionUrl);+ if (!url.hostname.includes("notion.")) {+ return res.status(400).json({ message: "Invalid Notion URL" });+ }+ } catch (error) {+ return res.status(400).json({ message: "Invalid URL format" });+ }++ try {+ // Check if user has access to the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const documentVersion = await prisma.documentVersion.findFirst({+ where: {+ documentId: documentId,+ isPrimary: true,+ },+ select: {+ id: true,+ file: true,+ type: true,+ },+ });++ if (!documentVersion) {+ return res.status(404).json({ message: "Document version not found" });+ }++ if (documentVersion.type !== "notion") {+ return res+ .status(400)+ .json({ message: "Document is not a Notion document" });+ }++ // Preserve any existing query parameters from the old URL (like dark mode)+ const oldUrl = new URL(documentVersion.file);+ const newUrl = new URL(notionUrl);++ // Copy over the mode parameter if it exists+ const mode = oldUrl.searchParams.get("mode");+ if (mode) {+ newUrl.searchParams.set("mode", mode);+ }++ // Update document version+ await prisma.documentVersion.updateMany({+ where: {+ documentId: documentId,+ isPrimary: true,+ },+ data: {+ file: newUrl.toString(),+ },+ });++ return res.status(200).json({+ message: "Notion URL updated successfully",+ newUrl: newUrl.toString(),+ });+ } catch (error) {+ console.error("Error updating Notion URL:", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}\ No newline at end of filediff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 50645452..35e2dfb0 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -12,6 +12,7 @@ import useLimits from "@/lib/swr/use-limits";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import DocumentHeader from "@/components/documents/document-header";import { DocumentPreviewButton } from "@/components/documents/document-preview-button";+import NotionAccessibilityIndicator from "@/components/documents/notion-accessibility-indicator";import { StatsComponent } from "@/components/documents/stats";import VideoAnalytics from "@/components/documents/video-analytics";import AppLayout from "@/components/layouts/app";@@ -88,6 +89,15 @@ export default function DocumentPage() {]}/>+ {/* Notion Accessibility Indicator */}+ {primaryVersion.type === "notion" && (+ <NotionAccessibilityIndicator+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ onUrlUpdate={mutateDocument}+ />+ )}+{/* Document Analytics */}{primaryVersion.type !== "video" && (<StatsComponent