From 5b4152ffc5cfe184b2b8f43658877373d19e79ca Mon Sep 17 00:00:00 2001 From: Rohit Saluja Date: Tue, 26 Mar 2024 20:36:45 +0530 Subject: [PATCH] fix: updated the super delete file --- .../document/super-delete-document.ts | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 packages/lib/server-only/document/super-delete-document.ts diff --git a/packages/lib/server-only/document/super-delete-document.ts b/packages/lib/server-only/document/super-delete-document.ts new file mode 100644 index 000000000..c81a5f746 --- /dev/null +++ b/packages/lib/server-only/document/super-delete-document.ts @@ -0,0 +1,90 @@ +'use server'; + +import { createElement } from 'react'; + +import { mailer } from '@documenso/email/mailer'; +import { render } from '@documenso/email/render'; +import DocumentCancelTemplate from '@documenso/email/templates/document-cancel'; +import { prisma } from '@documenso/prisma'; +import { DocumentStatus } from '@documenso/prisma/client'; + +import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app'; +import { FROM_ADDRESS, FROM_NAME } from '../../constants/email'; +import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs'; +import type { RequestMetadata } from '../../universal/extract-request-metadata'; +import { createDocumentAuditLogData } from '../../utils/document-audit-logs'; + +export type SuperDeleteDocumentOptions = { + id: number; + userId: number; + requestMetadata?: RequestMetadata; +}; + +export const SuperDeleteDocument = async ({ + id, + userId, + requestMetadata, +}: SuperDeleteDocumentOptions) => { + const document = await prisma.document.findUnique({ + where: { + id, + userId, + }, + include: { + Recipient: true, + documentMeta: true, + User: true, + }, + }); + + if (!document) { + throw new Error('Document not found'); + } + + const { status, User: user } = document; + + // if the document is pending, send cancellation emails to all recipients + if (status === DocumentStatus.PENDING && document.Recipient.length > 0) { + await Promise.all( + document.Recipient.map(async (recipient) => { + const assetBaseUrl = NEXT_PUBLIC_WEBAPP_URL() || 'http://localhost:3000'; + const template = createElement(DocumentCancelTemplate, { + documentName: document.title, + inviterName: user.name || undefined, + inviterEmail: user.email, + assetBaseUrl, + }); + + await mailer.sendMail({ + to: { + address: recipient.email, + name: recipient.name, + }, + from: { + name: FROM_NAME, + address: FROM_ADDRESS, + }, + subject: 'Document Cancelled', + html: render(template), + text: render(template, { plainText: true }), + }); + }), + ); + } + + // always hard delete if deleted from admin + return await prisma.$transaction(async (tx) => { + await tx.documentAuditLog.create({ + data: createDocumentAuditLogData({ + documentId: id, + type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_DELETED, + user, + requestMetadata, + data: { + type: 'HARD', + }, + }), + }); + return await tx.document.delete({ where: { id } }); + }); +};