Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Add download functionality for agreements with detailed text export
Cursor Agentdb78f059dd4f
diff --git a/components/agreements/agreement-card.tsx b/components/agreements/agreement-card.tsxindex 8eb9f0c8..1533b315 100644--- a/components/agreements/agreement-card.tsx+++ b/components/agreements/agreement-card.tsx@@ -1,7 +1,7 @@import { useState } from "react";import { useTeam } from "@/context/team-context";-import { FileTextIcon, MoreVertical, TrashIcon } from "lucide-react";+import { DownloadIcon, FileTextIcon, MoreVertical, TrashIcon } from "lucide-react";import { toast } from "sonner";import { AgreementWithLinksCount } from "@/lib/swr/use-agreements";@@ -57,6 +57,46 @@ export default function AgreementCard({);};+ const handleDownload = async () => {+ toast.promise(+ fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/agreements/${agreement.id}/download`,+ {+ method: "GET",+ },+ ).then(async (response) => {+ if (!response.ok) {+ throw new Error("Failed to download agreement");+ }++ // Get the filename from the Content-Disposition header or use default+ const contentDisposition = response.headers.get("Content-Disposition");+ const filenameMatch = contentDisposition?.match(/filename="([^"]+)"/);+ const filename = filenameMatch ? filenameMatch[1] : `${agreement.name}.txt`;++ // Create a blob and download+ const blob = await response.blob();+ const url = window.URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = filename;+ document.body.appendChild(link);+ link.click();++ // Cleanup+ setTimeout(() => {+ window.URL.revokeObjectURL(url);+ document.body.removeChild(link);+ }, 100);+ }),+ {+ loading: "Downloading agreement...",+ success: "Agreement downloaded successfully",+ error: "Failed to download agreement",+ },+ );+ };+return (<><div className="flex items-center justify-between rounded-lg border p-4">@@ -85,6 +125,10 @@ export default function AgreementCard({</Button></DropdownMenuTrigger><DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleDownload}>+ <DownloadIcon className="mr-2 h-4 w-4" />+ Download agreement+ </DropdownMenuItem><DropdownMenuItemclassName="text-destructive focus:bg-destructive focus:text-destructive-foreground"onClick={() => setShowDeleteDialog(true)}diff --git a/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts b/pages/api/teams/[teamId]/agreements/[agreementId]/download.tsnew file mode 100644index 00000000..e127fe73--- /dev/null+++ b/pages/api/teams/[teamId]/agreements/[agreementId]/download.ts@@ -0,0 +1,116 @@+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";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/agreements/:agreementId/download+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const userId = (session.user as CustomUser).id;+ const { teamId, agreementId } = req.query as { teamId: string; agreementId: string };++ if (!teamId || !agreementId) {+ return res.status(400).json("Missing required parameters");+ }++ try {+ // Check if user belongs to the team and get the agreement+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ select: {+ id: true,+ name: true,+ agreements: {+ where: {+ id: agreementId,+ deletedAt: null, // Only allow downloading non-deleted agreements+ },+ select: {+ id: true,+ name: true,+ content: true,+ requireName: true,+ createdAt: true,+ updatedAt: true,+ _count: {+ select: {+ links: true,+ responses: true,+ },+ },+ },+ },+ },+ });++ if (!team || team.agreements.length === 0) {+ return res.status(404).json("Agreement not found or unauthorized");+ }++ const agreement = team.agreements[0];++ // Create the agreement content as a formatted text file+ const agreementContent = `+AGREEMENT DETAILS+================++Name: ${agreement.name}+URL: ${agreement.content}+Requires Name: ${agreement.requireName ? "Yes" : "No"}+Created: ${agreement.createdAt.toLocaleDateString()} at ${agreement.createdAt.toLocaleTimeString()}+Last Updated: ${agreement.updatedAt.toLocaleDateString()} at ${agreement.updatedAt.toLocaleTimeString()}+Team: ${team.name}++USAGE STATISTICS+===============++Used in ${agreement._count.links} link${agreement._count.links === 1 ? "" : "s"}+Total responses: ${agreement._count.responses}++AGREEMENT URL+=============++${agreement.content}++---+Downloaded on: ${new Date().toLocaleDateString()} at ${new Date().toLocaleTimeString()}+Agreement ID: ${agreement.id}+ `.trim();++ // Set headers for file download+ const filename = `${agreement.name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_agreement.txt`;+ res.setHeader("Content-Type", "text/plain; charset=utf-8");+ res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);+ res.setHeader("Content-Length", Buffer.byteLength(agreementContent, 'utf8'));++ // Send the agreement content+ return res.send(agreementContent);+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}\ No newline at end of file