mirror of
https://github.com/documenso/documenso.git
synced 2025-11-27 06:54:01 +10:00
Compare commits
9 Commits
fix/downlo
...
0bbd9aa9a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bbd9aa9a1 | ||
|
|
5e8c3d5d92 | ||
|
|
c97c2551db | ||
|
|
1863d990c8 | ||
|
|
38483bb88c | ||
|
|
9cbbdfb127 | ||
|
|
fb6e2753df | ||
|
|
a89c781b31 | ||
|
|
8b131e42c7 |
@@ -1,16 +1,13 @@
|
||||
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;
|
||||
@@ -22,38 +19,44 @@ export const DocumentAuditLogDownloadButton = ({
|
||||
}: DocumentAuditLogDownloadButtonProps) => {
|
||||
const { toast } = useToast();
|
||||
const { _ } = useLingui();
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const team = useCurrentTeam();
|
||||
|
||||
const { mutateAsync: downloadAuditLogs, isPending } =
|
||||
trpc.document.auditLog.download.useMutation();
|
||||
|
||||
const onDownloadAuditLogsClick = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/t/${team.url}/download/audit-logs/${documentId}`);
|
||||
const { url } = await downloadAuditLogs({ documentId });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to download certificate');
|
||||
}
|
||||
const iframe = Object.assign(document.createElement('iframe'), {
|
||||
src: url,
|
||||
});
|
||||
|
||||
const contentDisposition = response.headers.get('Content-Disposition');
|
||||
const filename =
|
||||
contentDisposition?.split('filename="')[1]?.split('"')[0] ||
|
||||
`document_${documentId}_audit_logs.pdf`;
|
||||
Object.assign(iframe.style, {
|
||||
position: 'fixed',
|
||||
top: '0',
|
||||
left: '0',
|
||||
width: '0',
|
||||
height: '0',
|
||||
});
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
const onLoaded = () => {
|
||||
if (iframe.contentDocument?.readyState === 'complete') {
|
||||
iframe.contentWindow?.print();
|
||||
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
iframe.contentWindow?.addEventListener('afterprint', () => {
|
||||
document.body.removeChild(iframe);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
// When the iframe has loaded, print the iframe and remove it from the dom
|
||||
iframe.addEventListener('load', onLoaded);
|
||||
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
document.body.appendChild(iframe);
|
||||
|
||||
onLoaded();
|
||||
} catch (error) {
|
||||
console.error('Audit logs download error:', error);
|
||||
console.error(error);
|
||||
|
||||
toast({
|
||||
title: _(msg`Something went wrong`),
|
||||
@@ -62,8 +65,6 @@ export const DocumentAuditLogDownloadButton = ({
|
||||
),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
@@ -7,12 +5,11 @@ 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;
|
||||
@@ -26,38 +23,44 @@ export const DocumentCertificateDownloadButton = ({
|
||||
}: DocumentCertificateDownloadButtonProps) => {
|
||||
const { toast } = useToast();
|
||||
const { _ } = useLingui();
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const team = useCurrentTeam();
|
||||
|
||||
const { mutateAsync: downloadCertificate, isPending } =
|
||||
trpc.document.downloadCertificate.useMutation();
|
||||
|
||||
const onDownloadCertificatesClick = async () => {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/t/${team.url}/download/certificate/${documentId}`);
|
||||
const { url } = await downloadCertificate({ documentId });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to download certificate');
|
||||
}
|
||||
const iframe = Object.assign(document.createElement('iframe'), {
|
||||
src: url,
|
||||
});
|
||||
|
||||
const contentDisposition = response.headers.get('Content-Disposition');
|
||||
const filename =
|
||||
contentDisposition?.split('filename="')[1]?.split('"')[0] ||
|
||||
`document_${documentId}_certificate.pdf`;
|
||||
Object.assign(iframe.style, {
|
||||
position: 'fixed',
|
||||
top: '0',
|
||||
left: '0',
|
||||
width: '0',
|
||||
height: '0',
|
||||
});
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
const onLoaded = () => {
|
||||
if (iframe.contentDocument?.readyState === 'complete') {
|
||||
iframe.contentWindow?.print();
|
||||
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
iframe.contentWindow?.addEventListener('afterprint', () => {
|
||||
document.body.removeChild(iframe);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
// When the iframe has loaded, print the iframe and remove it from the dom
|
||||
iframe.addEventListener('load', onLoaded);
|
||||
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
document.body.appendChild(iframe);
|
||||
|
||||
onLoaded();
|
||||
} catch (error) {
|
||||
console.error('Certificate download error:', error);
|
||||
console.error(error);
|
||||
|
||||
toast({
|
||||
title: _(msg`Something went wrong`),
|
||||
@@ -66,8 +69,6 @@ export const DocumentCertificateDownloadButton = ({
|
||||
),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { deletedAccountServiceAccount } from '@documenso/lib/server-only/user/service-accounts/deleted-account';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { DocumentStatus } from '@documenso/prisma/client';
|
||||
|
||||
type HandleDocumentOwnershipOnDeletionOptions = {
|
||||
documentIds: number[];
|
||||
organisationOwnerId: number;
|
||||
};
|
||||
|
||||
export const handleDocumentOwnershipOnDeletion = async ({
|
||||
documentIds,
|
||||
organisationOwnerId,
|
||||
}: HandleDocumentOwnershipOnDeletionOptions) => {
|
||||
if (documentIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const serviceAccount = await deletedAccountServiceAccount();
|
||||
const serviceAccountTeam = serviceAccount.ownedOrganisations[0].teams[0];
|
||||
|
||||
await prisma.document.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: documentIds,
|
||||
},
|
||||
status: DocumentStatus.DRAFT,
|
||||
},
|
||||
});
|
||||
|
||||
const organisationOwner = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: organisationOwnerId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
ownedOrganisations: {
|
||||
select: {
|
||||
id: true,
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (organisationOwner && organisationOwner.ownedOrganisations.length > 0) {
|
||||
const ownerPersonalTeam = organisationOwner.ownedOrganisations[0].teams[0];
|
||||
|
||||
await prisma.document.updateMany({
|
||||
where: {
|
||||
id: {
|
||||
in: documentIds,
|
||||
},
|
||||
status: {
|
||||
in: [DocumentStatus.PENDING, DocumentStatus.REJECTED, DocumentStatus.COMPLETED],
|
||||
},
|
||||
},
|
||||
data: {
|
||||
userId: organisationOwner.id,
|
||||
teamId: ownerPersonalTeam.id,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await prisma.document.updateMany({
|
||||
where: {
|
||||
id: {
|
||||
in: documentIds,
|
||||
},
|
||||
status: {
|
||||
in: [DocumentStatus.PENDING, DocumentStatus.REJECTED, DocumentStatus.COMPLETED],
|
||||
},
|
||||
},
|
||||
data: {
|
||||
userId: serviceAccount.id,
|
||||
teamId: serviceAccountTeam.id,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -5,6 +5,20 @@ export const deletedAccountServiceAccount = async () => {
|
||||
where: {
|
||||
email: 'deleted-account@documenso.com',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
ownedOrganisations: {
|
||||
select: {
|
||||
id: true,
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!serviceAccount) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ORGANISATION_USER_ACCOUNT_TYPE,
|
||||
} from '@documenso/lib/constants/organisations';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { handleDocumentOwnershipOnDeletion } from '@documenso/lib/server-only/document/handle-document-ownership-on-deletion';
|
||||
import { buildOrganisationWhereQuery } from '@documenso/lib/utils/organisations';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
|
||||
@@ -32,6 +33,24 @@ export const deleteOrganisationRoute = authenticatedProcedure
|
||||
userId: user.id,
|
||||
roles: ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP['DELETE_ORGANISATION'],
|
||||
}),
|
||||
select: {
|
||||
id: true,
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
documents: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!organisation) {
|
||||
@@ -40,6 +59,15 @@ export const deleteOrganisationRoute = authenticatedProcedure
|
||||
});
|
||||
}
|
||||
|
||||
const documentIds = organisation.teams.flatMap((team) => team.documents.map((doc) => doc.id));
|
||||
|
||||
if (documentIds && documentIds.length > 0) {
|
||||
await handleDocumentOwnershipOnDeletion({
|
||||
documentIds,
|
||||
organisationOwnerId: organisation.owner.id,
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.account.deleteMany({
|
||||
where: {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP } from '@documenso/lib/constants/organisations';
|
||||
import { handleDocumentOwnershipOnDeletion } from '@documenso/lib/server-only/document/handle-document-ownership-on-deletion';
|
||||
import { deleteTeam } from '@documenso/lib/server-only/team/delete-team';
|
||||
import { buildOrganisationWhereQuery } from '@documenso/lib/utils/organisations';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
|
||||
import { authenticatedProcedure } from '../trpc';
|
||||
import { ZDeleteTeamRequestSchema, ZDeleteTeamResponseSchema } from './delete-team.types';
|
||||
@@ -11,12 +15,53 @@ export const deleteTeamRoute = authenticatedProcedure
|
||||
const { teamId } = input;
|
||||
const { user } = ctx;
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
});
|
||||
|
||||
const organisation = await prisma.organisation.findFirst({
|
||||
where: buildOrganisationWhereQuery({
|
||||
organisationId: team?.organisationId,
|
||||
userId: user.id,
|
||||
roles: ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP['DELETE_ORGANISATION'],
|
||||
}),
|
||||
select: {
|
||||
id: true,
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
documents: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
ctx.logger.info({
|
||||
input: {
|
||||
teamId,
|
||||
},
|
||||
});
|
||||
|
||||
const documentIds = organisation?.teams.flatMap((team) => team.documents.map((doc) => doc.id));
|
||||
|
||||
if (documentIds && documentIds.length > 0 && organisation) {
|
||||
await handleDocumentOwnershipOnDeletion({
|
||||
documentIds,
|
||||
organisationOwnerId: organisation.owner.id,
|
||||
});
|
||||
}
|
||||
|
||||
await deleteTeam({
|
||||
userId: user.id,
|
||||
teamId,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { KeyboardIcon, UploadCloudIcon } from 'lucide-react';
|
||||
import { match } from 'ts-pattern';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
|
||||
import { DocumentSignatureType } from '@documenso/lib/constants/document';
|
||||
import { isBase64Image } from '@documenso/lib/constants/signatures';
|
||||
|
||||
@@ -216,7 +216,12 @@ export const AddTemplateSettingsFormPartial = ({
|
||||
</FormLabel>
|
||||
|
||||
<FormControl>
|
||||
<Input className="bg-background" {...field} maxLength={255} onBlur={handleAutoSave} />
|
||||
<Input
|
||||
className="bg-background"
|
||||
{...field}
|
||||
maxLength={255}
|
||||
onBlur={handleAutoSave}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -624,7 +629,12 @@ export const AddTemplateSettingsFormPartial = ({
|
||||
</FormLabel>
|
||||
|
||||
<FormControl>
|
||||
<Input className="bg-background" {...field} maxLength={255} onBlur={handleAutoSave} />
|
||||
<Input
|
||||
className="bg-background"
|
||||
{...field}
|
||||
maxLength={255}
|
||||
onBlur={handleAutoSave}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormMessage />
|
||||
@@ -715,7 +725,12 @@ export const AddTemplateSettingsFormPartial = ({
|
||||
</FormLabel>
|
||||
|
||||
<FormControl>
|
||||
<Input className="bg-background" {...field} maxLength={255} onBlur={handleAutoSave} />
|
||||
<Input
|
||||
className="bg-background"
|
||||
{...field}
|
||||
maxLength={255}
|
||||
onBlur={handleAutoSave}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormMessage />
|
||||
|
||||
Reference in New Issue
Block a user