2023-08-17 19:56:18 +10:00
|
|
|
'use server';
|
|
|
|
|
2024-02-12 12:04:53 +11:00
|
|
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
|
|
|
import type { RequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
|
|
|
import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';
|
2023-08-17 19:56:18 +10:00
|
|
|
import { prisma } from '@documenso/prisma';
|
|
|
|
import { DocumentStatus, SigningStatus } from '@documenso/prisma/client';
|
|
|
|
|
|
|
|
export type RemovedSignedFieldWithTokenOptions = {
|
|
|
|
token: string;
|
|
|
|
fieldId: number;
|
2024-02-12 12:04:53 +11:00
|
|
|
requestMetadata?: RequestMetadata;
|
2023-08-17 19:56:18 +10:00
|
|
|
};
|
|
|
|
|
|
|
|
export const removeSignedFieldWithToken = async ({
|
|
|
|
token,
|
|
|
|
fieldId,
|
2024-02-12 12:04:53 +11:00
|
|
|
requestMetadata,
|
2023-08-17 19:56:18 +10:00
|
|
|
}: RemovedSignedFieldWithTokenOptions) => {
|
|
|
|
const field = await prisma.field.findFirstOrThrow({
|
|
|
|
where: {
|
|
|
|
id: fieldId,
|
|
|
|
Recipient: {
|
|
|
|
token,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
include: {
|
|
|
|
Document: true,
|
|
|
|
Recipient: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const { Document: document, Recipient: recipient } = field;
|
|
|
|
|
2023-10-06 22:54:24 +00:00
|
|
|
if (!document) {
|
|
|
|
throw new Error(`Document not found for field ${field.id}`);
|
|
|
|
}
|
|
|
|
|
2024-04-19 16:17:32 +07:00
|
|
|
if (document.status !== DocumentStatus.PENDING) {
|
|
|
|
throw new Error(`Document ${document.id} must be pending`);
|
2023-08-17 19:56:18 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
if (recipient?.signingStatus === SigningStatus.SIGNED) {
|
|
|
|
throw new Error(`Recipient ${recipient.id} has already signed`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unreachable code based on the above query but we need to satisfy TypeScript
|
|
|
|
if (field.recipientId === null) {
|
|
|
|
throw new Error(`Field ${fieldId} has no recipientId`);
|
|
|
|
}
|
|
|
|
|
2024-02-12 12:04:53 +11:00
|
|
|
await prisma.$transaction(async (tx) => {
|
|
|
|
await tx.field.update({
|
2023-08-17 19:56:18 +10:00
|
|
|
where: {
|
|
|
|
id: field.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
customText: '',
|
|
|
|
inserted: false,
|
|
|
|
},
|
2024-02-12 12:04:53 +11:00
|
|
|
});
|
|
|
|
|
|
|
|
await tx.signature.deleteMany({
|
2023-08-17 19:56:18 +10:00
|
|
|
where: {
|
|
|
|
fieldId: field.id,
|
|
|
|
},
|
2024-02-12 12:04:53 +11:00
|
|
|
});
|
|
|
|
|
|
|
|
await tx.documentAuditLog.create({
|
|
|
|
data: createDocumentAuditLogData({
|
|
|
|
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FIELD_UNINSERTED,
|
|
|
|
documentId: document.id,
|
|
|
|
user: {
|
|
|
|
name: recipient?.name,
|
|
|
|
email: recipient?.email,
|
|
|
|
},
|
|
|
|
requestMetadata,
|
|
|
|
data: {
|
|
|
|
field: field.type,
|
|
|
|
fieldId: field.secondaryId,
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
});
|
|
|
|
});
|
2023-08-17 19:56:18 +10:00
|
|
|
};
|