Compare commits

...

6 Commits

4 changed files with 186 additions and 58 deletions

View File

@ -1,13 +1,16 @@
import { useState } from 'react';
import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react';
import { Trans } from '@lingui/react/macro';
import { DownloadIcon } from 'lucide-react';
import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useCurrentTeam } from '~/providers/team';
export type DocumentAuditLogDownloadButtonProps = {
className?: string;
documentId: number;
@ -19,44 +22,38 @@ export const DocumentAuditLogDownloadButton = ({
}: DocumentAuditLogDownloadButtonProps) => {
const { toast } = useToast();
const { _ } = useLingui();
const { mutateAsync: downloadAuditLogs, isPending } =
trpc.document.auditLog.download.useMutation();
const [isPending, setIsPending] = useState(false);
const team = useCurrentTeam();
const onDownloadAuditLogsClick = async () => {
setIsPending(true);
try {
const { url } = await downloadAuditLogs({ documentId });
const response = await fetch(`/api/t/${team.url}/download/audit-logs/${documentId}`);
const iframe = Object.assign(document.createElement('iframe'), {
src: url,
});
if (!response.ok) {
throw new Error('Failed to download certificate');
}
Object.assign(iframe.style, {
position: 'fixed',
top: '0',
left: '0',
width: '0',
height: '0',
});
const contentDisposition = response.headers.get('Content-Disposition');
const filename =
contentDisposition?.split('filename="')[1]?.split('"')[0] ||
`document_${documentId}_audit_logs.pdf`;
const onLoaded = () => {
if (iframe.contentDocument?.readyState === 'complete') {
iframe.contentWindow?.print();
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
iframe.contentWindow?.addEventListener('afterprint', () => {
document.body.removeChild(iframe);
});
}
};
link.href = url;
link.download = filename;
// When the iframe has loaded, print the iframe and remove it from the dom
iframe.addEventListener('load', onLoaded);
document.body.appendChild(link);
link.click();
document.body.appendChild(iframe);
onLoaded();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
console.error('Audit logs download error:', error);
toast({
title: _(msg`Something went wrong`),
@ -65,6 +62,8 @@ export const DocumentAuditLogDownloadButton = ({
),
variant: 'destructive',
});
} finally {
setIsPending(false);
}
};

View File

@ -1,3 +1,5 @@
import { useState } from 'react';
import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react';
import { Trans } from '@lingui/react/macro';
@ -5,11 +7,12 @@ import type { DocumentStatus } from '@prisma/client';
import { DownloadIcon } from 'lucide-react';
import { isDocumentCompleted } from '@documenso/lib/utils/document';
import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useCurrentTeam } from '~/providers/team';
export type DocumentCertificateDownloadButtonProps = {
className?: string;
documentId: number;
@ -23,44 +26,38 @@ export const DocumentCertificateDownloadButton = ({
}: DocumentCertificateDownloadButtonProps) => {
const { toast } = useToast();
const { _ } = useLingui();
const { mutateAsync: downloadCertificate, isPending } =
trpc.document.downloadCertificate.useMutation();
const [isPending, setIsPending] = useState(false);
const team = useCurrentTeam();
const onDownloadCertificatesClick = async () => {
setIsPending(true);
try {
const { url } = await downloadCertificate({ documentId });
const response = await fetch(`/api/t/${team.url}/download/certificate/${documentId}`);
const iframe = Object.assign(document.createElement('iframe'), {
src: url,
});
if (!response.ok) {
throw new Error('Failed to download certificate');
}
Object.assign(iframe.style, {
position: 'fixed',
top: '0',
left: '0',
width: '0',
height: '0',
});
const contentDisposition = response.headers.get('Content-Disposition');
const filename =
contentDisposition?.split('filename="')[1]?.split('"')[0] ||
`document_${documentId}_certificate.pdf`;
const onLoaded = () => {
if (iframe.contentDocument?.readyState === 'complete') {
iframe.contentWindow?.print();
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
iframe.contentWindow?.addEventListener('afterprint', () => {
document.body.removeChild(iframe);
});
}
};
link.href = url;
link.download = filename;
// When the iframe has loaded, print the iframe and remove it from the dom
iframe.addEventListener('load', onLoaded);
document.body.appendChild(link);
link.click();
document.body.appendChild(iframe);
onLoaded();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
console.error('Certificate download error:', error);
toast({
title: _(msg`Something went wrong`),
@ -69,6 +66,8 @@ export const DocumentCertificateDownloadButton = ({
),
variant: 'destructive',
});
} finally {
setIsPending(false);
}
};

View File

@ -0,0 +1,61 @@
import { getSession } from '@documenso/auth/server/lib/utils/get-session';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getDocumentById } from '@documenso/lib/server-only/document/get-document-by-id';
import { getAuditLogsPdf } from '@documenso/lib/server-only/htmltopdf/get-audit-logs-pdf';
import { getTeamByUrl } from '@documenso/lib/server-only/team/get-team';
import type { Route } from './+types/t.$teamUrl.download.audit-logs.$documentId';
export async function loader({ request, params }: Route.LoaderArgs) {
const documentId = Number(params.documentId);
const teamUrl = params.teamUrl;
if (!documentId || !teamUrl) {
return Response.json({ error: 'Invalid document ID or team URL' }, { status: 400 });
}
try {
const { user } = await getSession(request);
const team = await getTeamByUrl({ userId: user.id, teamUrl });
if (!team) {
return Response.json({ error: 'Team not found or access denied' }, { status: 404 });
}
const document = await getDocumentById({
documentId,
userId: user.id,
teamId: team.id,
}).catch(() => null);
if (!document || (team.id && document.teamId !== team.id)) {
return Response.json({ error: 'Document not found or access denied' }, { status: 404 });
}
const pdfBuffer = await getAuditLogsPdf({
documentId: document.id,
language: document.documentMeta?.language,
});
const filename = `${document.title.replace(/\.pdf$/, '')}_audit_logs.pdf`;
return new Response(pdfBuffer, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${filename}"`,
'Content-Length': pdfBuffer.length.toString(),
'Cache-Control': 'no-cache, no-store, must-revalidate',
Expires: '0',
},
});
} catch (error) {
if (error instanceof AppError) {
const statusCode = error.code === AppErrorCode.UNAUTHORIZED ? 401 : 400;
return Response.json({ error: error.message }, { status: statusCode });
}
return Response.json({ error: 'Failed to generate audit logs PDF' }, { status: 500 });
}
}

View File

@ -0,0 +1,69 @@
import { getSession } from '@documenso/auth/server/lib/utils/get-session';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getDocumentById } from '@documenso/lib/server-only/document/get-document-by-id';
import { getCertificatePdf } from '@documenso/lib/server-only/htmltopdf/get-certificate-pdf';
import { getTeamByUrl } from '@documenso/lib/server-only/team/get-team';
import { isDocumentCompleted } from '@documenso/lib/utils/document';
import type { Route } from './+types/t.$teamUrl.download.certificate.$documentId';
export async function loader({ request, params }: Route.LoaderArgs) {
const documentId = Number(params.documentId);
const teamUrl = params.teamUrl;
if (!documentId || !teamUrl) {
return Response.json({ error: 'Invalid document ID or team URL' }, { status: 400 });
}
try {
const { user } = await getSession(request);
const team = await getTeamByUrl({ userId: user.id, teamUrl }).catch(() => null);
if (!team) {
return Response.json({ error: 'Team not found or access denied' }, { status: 404 });
}
const document = await getDocumentById({
documentId,
userId: user.id,
teamId: team.id,
}).catch(() => null);
if (!document || document.teamId !== team.id) {
return Response.json({ error: 'Document not found or access denied' }, { status: 404 });
}
if (!isDocumentCompleted(document.status)) {
return Response.json(
{ error: 'Document must be completed to download the certificate' },
{ status: 400 },
);
}
const pdfBuffer = await getCertificatePdf({
documentId: document.id,
language: document.documentMeta?.language,
});
const filename = `${document.title.replace(/\.pdf$/, '')}_certificate.pdf`;
return new Response(pdfBuffer, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${filename}"`,
'Content-Length': pdfBuffer.length.toString(),
'Cache-Control': 'no-cache, no-store, must-revalidate',
Expires: '0',
},
});
} catch (error) {
if (error instanceof AppError) {
const statusCode = error.code === AppErrorCode.UNAUTHORIZED ? 401 : 400;
return Response.json({ error: error.message }, { status: statusCode });
}
return Response.json({ error: 'Failed to generate certificate PDF' }, { status: 500 });
}
}