feat: add envelope editor

This commit is contained in:
David Nguyen
2025-10-12 23:35:54 +11:00
parent bf89bc781b
commit 0da8e7dbc6
307 changed files with 24657 additions and 3681 deletions
@@ -16,7 +16,7 @@ import type { ApiRequestMetadata } from '@documenso/lib/universal/extract-reques
import { nanoid, prefixedId } from '@documenso/lib/universal/id';
import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';
import { prisma } from '@documenso/prisma';
import type { TCreateDocumentTemporaryRequest } from '@documenso/trpc/server/document-router/create-document-temporary.types';
import type { TCreateEnvelopeRequest } from '@documenso/trpc/server/envelope-router/create-envelope.types';
import type { TDocumentAccessAuthTypes, TDocumentActionAuthTypes } from '../../types/document-auth';
import type { TDocumentFormValues } from '../../types/document-form-values';
@@ -37,11 +37,12 @@ export type CreateEnvelopeOptions = {
userId: number;
teamId: number;
normalizePdf?: boolean;
internalVersion: 1 | 2;
data: {
type: EnvelopeType;
title: string;
externalId?: string;
envelopeItems: { title?: string; documentDataId: string }[];
envelopeItems: { title?: string; documentDataId: string; order?: number }[];
formValues?: TDocumentFormValues;
timezone?: string;
@@ -54,7 +55,7 @@ export type CreateEnvelopeOptions = {
visibility?: DocumentVisibility;
globalAccessAuth?: TDocumentAccessAuthTypes[];
globalActionAuth?: TDocumentActionAuthTypes[];
recipients?: TCreateDocumentTemporaryRequest['recipients'];
recipients?: TCreateEnvelopeRequest['recipients'];
folderId?: string;
};
meta?: Partial<Omit<DocumentMeta, 'id'>>;
@@ -68,6 +69,7 @@ export const createEnvelope = async ({
data,
meta,
requestMetadata,
internalVersion,
}: CreateEnvelopeOptions) => {
const {
type,
@@ -124,7 +126,14 @@ export const createEnvelope = async ({
teamId,
});
let envelopeItems: { title?: string; documentDataId: string }[] = data.envelopeItems;
if (data.envelopeItems.length !== 1 && internalVersion === 1) {
throw new AppError(AppErrorCode.INVALID_BODY, {
message: 'Envelope items must have exactly 1 item for version 1',
});
}
let envelopeItems: { title?: string; documentDataId: string; order?: number }[] =
data.envelopeItems;
if (normalizePdf) {
envelopeItems = await Promise.all(
@@ -145,15 +154,18 @@ export const createEnvelope = async ({
const normalizedPdf = await makeNormalizedPdf(Buffer.from(buffer));
const titleToUse = item.title || title;
const newDocumentData = await putPdfFileServerSide({
name: title.endsWith('.pdf') ? title : `${title}.pdf`,
name: titleToUse,
type: 'application/pdf',
arrayBuffer: async () => Promise.resolve(normalizedPdf),
});
return {
title: item.title,
title: titleToUse.endsWith('.pdf') ? titleToUse.slice(0, -4) : titleToUse,
documentDataId: newDocumentData.id,
order: item.order,
};
}),
);
@@ -219,15 +231,17 @@ export const createEnvelope = async ({
data: {
id: prefixedId('envelope'),
secondaryId,
internalVersion,
type,
title,
qrToken: prefixedId('qr'),
externalId,
envelopeItems: {
createMany: {
data: envelopeItems.map((item) => ({
data: envelopeItems.map((item, i) => ({
id: prefixedId('envelope_item'),
title: item.title || title,
order: item.order !== undefined ? item.order : i + 1,
documentDataId: item.documentDataId,
})),
},
@@ -238,7 +252,7 @@ export const createEnvelope = async ({
visibility,
folderId,
formValues,
source: DocumentSource.DOCUMENT, // Todo: Migration
source: type === EnvelopeType.DOCUMENT ? DocumentSource.DOCUMENT : DocumentSource.NONE,
documentMetaId: documentMeta.id,
// Template specific fields.
@@ -251,9 +265,6 @@ export const createEnvelope = async ({
},
});
// Todo: Envelopes - Support multiple envelope items.
const firstEnvelopeItemId = envelope.envelopeItems[0].id;
await Promise.all(
(data.recipients || []).map(async (recipient) => {
const recipientAuthOptions = createRecipientAuthOptions({
@@ -261,6 +272,45 @@ export const createEnvelope = async ({
actionAuth: recipient.actionAuth ?? [],
});
// Todo: Envelopes - Allow fields.
// const recipientFieldsToCreate = (recipient.fields || []).map((field) => {
// let envelopeItemId = envelope.envelopeItems[0].id;?
// const foundEnvelopeItem = envelope.envelopeItems.find(
// (item) => item.documentDataId === field.documentDataId,
// );
// if (field.documentDataId && !foundEnvelopeItem) {
// throw new AppError(AppErrorCode.INVALID_REQUEST, {
// message: 'Envelope item not found',
// });
// }
// if (foundEnvelopeItem) {
// envelopeItemId = foundEnvelopeItem.id;
// }
// if (!envelopeItemId) {
// throw new AppError(AppErrorCode.INVALID_REQUEST, {
// message: 'Envelope item not found',
// });
// }
// return {
// envelopeId: envelope.id,
// envelopeItemId,
// type: field.type,
// page: field.page,
// positionX: field.positionX,
// positionY: field.positionY,
// width: field.width,
// height: field.height,
// customText: '',
// inserted: false,
// fieldMeta: field.fieldMeta || undefined,
// };
// });
await tx.recipient.create({
data: {
envelopeId: envelope.id,
@@ -273,23 +323,11 @@ export const createEnvelope = async ({
signingStatus:
recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,
authOptions: recipientAuthOptions,
fields: {
createMany: {
data: (recipient.fields || []).map((field) => ({
envelopeId: envelope.id,
envelopeItemId: firstEnvelopeItemId,
type: field.type,
page: field.pageNumber,
positionX: field.pageX,
positionY: field.pageY,
width: field.width,
height: field.height,
customText: '',
inserted: false,
fieldMeta: field.fieldMeta,
})),
},
},
// fields: {
// createMany: {
// data: recipientFieldsToCreate,
// },
// },
},
});
}),
@@ -0,0 +1,195 @@
import { DocumentSource, EnvelopeType, WebhookTriggerEvents } from '@prisma/client';
import { omit } from 'remeda';
import { prisma } from '@documenso/prisma';
import { AppError, AppErrorCode } from '../../errors/app-error';
import {
ZWebhookDocumentSchema,
mapEnvelopeToWebhookDocumentPayload,
} from '../../types/webhook-payload';
import { nanoid, prefixedId } from '../../universal/id';
import type { EnvelopeIdOptions } from '../../utils/envelope';
import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';
import { incrementDocumentId, incrementTemplateId } from '../envelope/increment-id';
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
export interface DuplicateEnvelopeOptions {
id: EnvelopeIdOptions;
userId: number;
teamId: number;
}
export const duplicateEnvelope = async ({ id, userId, teamId }: DuplicateEnvelopeOptions) => {
const { envelopeWhereInput } = await getEnvelopeWhereInput({
id,
type: null,
userId,
teamId,
});
const envelope = await prisma.envelope.findFirst({
where: envelopeWhereInput,
select: {
type: true,
title: true,
userId: true,
internalVersion: true,
envelopeItems: {
include: {
documentData: {
select: {
data: true,
initialData: true,
type: true,
},
},
},
},
authOptions: true,
visibility: true,
documentMeta: true,
recipients: {
select: {
email: true,
name: true,
role: true,
signingOrder: true,
fields: true,
},
},
teamId: true,
},
});
if (!envelope) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Document not found',
});
}
const { legacyNumberId, secondaryId } =
envelope.type === EnvelopeType.DOCUMENT
? await incrementDocumentId().then(({ documentId, formattedDocumentId }) => ({
legacyNumberId: documentId,
secondaryId: formattedDocumentId,
}))
: await incrementTemplateId().then(({ templateId, formattedTemplateId }) => ({
legacyNumberId: templateId,
secondaryId: formattedTemplateId,
}));
const createdDocumentMeta = await prisma.documentMeta.create({
data: {
...omit(envelope.documentMeta, ['id']),
emailSettings: envelope.documentMeta.emailSettings || undefined,
},
});
const duplicatedEnvelope = await prisma.envelope.create({
data: {
id: prefixedId('envelope'),
secondaryId,
type: envelope.type,
internalVersion: envelope.internalVersion,
userId,
teamId,
title: envelope.title + ' (copy)',
documentMetaId: createdDocumentMeta.id,
authOptions: envelope.authOptions || undefined,
visibility: envelope.visibility,
source: DocumentSource.NONE,
},
include: {
recipients: true,
documentMeta: true,
},
});
// Key = original envelope item ID
// Value = duplicated envelope item ID.
const oldEnvelopeItemToNewEnvelopeItemIdMap: Record<string, string> = {};
// Duplicate the envelope items.
await Promise.all(
envelope.envelopeItems.map(async (envelopeItem) => {
const duplicatedDocumentData = await prisma.documentData.create({
data: {
type: envelopeItem.documentData.type,
data: envelopeItem.documentData.initialData,
initialData: envelopeItem.documentData.initialData,
},
});
const duplicatedEnvelopeItem = await prisma.envelopeItem.create({
data: {
id: prefixedId('envelope_item'),
title: envelopeItem.title,
order: envelopeItem.order,
envelopeId: duplicatedEnvelope.id,
documentDataId: duplicatedDocumentData.id,
},
});
oldEnvelopeItemToNewEnvelopeItemIdMap[envelopeItem.id] = duplicatedEnvelopeItem.id;
}),
);
for (const recipient of envelope.recipients) {
await prisma.recipient.create({
data: {
envelopeId: duplicatedEnvelope.id,
email: recipient.email,
name: recipient.name,
role: recipient.role,
signingOrder: recipient.signingOrder,
token: nanoid(),
fields: {
createMany: {
data: recipient.fields.map((field) => ({
envelopeId: duplicatedEnvelope.id,
envelopeItemId: oldEnvelopeItemToNewEnvelopeItemIdMap[field.envelopeItemId],
type: field.type,
page: field.page,
positionX: field.positionX,
positionY: field.positionY,
width: field.width,
height: field.height,
customText: '',
inserted: false,
fieldMeta: field.fieldMeta as PrismaJson.FieldMeta,
})),
},
},
},
});
}
if (duplicatedEnvelope.type === EnvelopeType.DOCUMENT) {
const refetchedEnvelope = await prisma.envelope.findFirstOrThrow({
where: {
id: duplicatedEnvelope.id,
},
include: {
documentMeta: true,
recipients: true,
},
});
await triggerWebhook({
event: WebhookTriggerEvents.DOCUMENT_CREATED,
data: ZWebhookDocumentSchema.parse(mapEnvelopeToWebhookDocumentPayload(refetchedEnvelope)),
userId: userId,
teamId: teamId,
});
}
return {
id: duplicatedEnvelope.id,
envelope: duplicatedEnvelope,
legacyId: {
type: envelope.type,
id: legacyNumberId,
},
};
};
@@ -45,6 +45,9 @@ export const getEnvelopeById = async ({ id, userId, teamId, type }: GetEnvelopeB
include: {
documentData: true,
},
orderBy: {
order: 'asc',
},
},
folder: true,
documentMeta: true,
@@ -55,7 +58,11 @@ export const getEnvelopeById = async ({ id, userId, teamId, type }: GetEnvelopeB
email: true,
},
},
recipients: true,
recipients: {
orderBy: {
id: 'asc',
},
},
fields: true,
team: {
select: {
@@ -63,6 +70,14 @@ export const getEnvelopeById = async ({ id, userId, teamId, type }: GetEnvelopeB
url: true,
},
},
directLink: {
select: {
directTemplateRecipientId: true,
enabled: true,
id: true,
token: true,
},
},
},
});
@@ -72,7 +87,14 @@ export const getEnvelopeById = async ({ id, userId, teamId, type }: GetEnvelopeB
});
}
return envelope;
return {
...envelope,
user: {
id: envelope.user.id,
name: envelope.user.name || '',
email: envelope.user.email,
},
};
};
export type GetEnvelopeByIdResponse = Awaited<ReturnType<typeof getEnvelopeById>>;
@@ -111,6 +133,15 @@ export const getEnvelopeWhereInput = async ({
teamId,
type,
}: GetEnvelopeWhereInputOptions) => {
// Backup validation incase something goes wrong.
if (!id.id || !userId || !teamId || type === undefined) {
console.error(`[CRTICAL ERROR]: MUST NEVER HAPPEN`);
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Envelope ID not found',
});
}
// Validate that the user belongs to the team provided.
const team = await getTeamById({ teamId, userId });
@@ -0,0 +1,306 @@
import { DocumentSigningOrder, DocumentStatus, EnvelopeType, SigningStatus } from '@prisma/client';
import { z } from 'zod';
import { prisma } from '@documenso/prisma';
import DocumentDataSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentDataSchema';
import DocumentMetaSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentMetaSchema';
import EnvelopeItemSchema from '@documenso/prisma/generated/zod/modelSchema/EnvelopeItemSchema';
import EnvelopeSchema from '@documenso/prisma/generated/zod/modelSchema/EnvelopeSchema';
import SignatureSchema from '@documenso/prisma/generated/zod/modelSchema/SignatureSchema';
import TeamSchema from '@documenso/prisma/generated/zod/modelSchema/TeamSchema';
import UserSchema from '@documenso/prisma/generated/zod/modelSchema/UserSchema';
import { AppError, AppErrorCode } from '../../errors/app-error';
import type { TDocumentAuthMethods } from '../../types/document-auth';
import { ZFieldSchema } from '../../types/field';
import { ZRecipientLiteSchema } from '../../types/recipient';
import { isRecipientAuthorized } from '../document/is-recipient-authorized';
import { getTeamSettings } from '../team/get-team-settings';
export type GetRecipientEnvelopeByTokenOptions = {
token: string;
userId?: number;
accessAuth?: TDocumentAuthMethods;
};
const ZEnvelopeForSigningResponse = z.object({
envelope: EnvelopeSchema.pick({
type: true,
status: true,
id: true,
secondaryId: true,
internalVersion: true,
completedAt: true,
deletedAt: true,
title: true,
authOptions: true,
userId: true,
teamId: true,
}).extend({
documentMeta: DocumentMetaSchema.pick({
signingOrder: true,
distributionMethod: true,
timezone: true,
dateFormat: true,
redirectUrl: true,
typedSignatureEnabled: true,
uploadSignatureEnabled: true,
drawSignatureEnabled: true,
allowDictateNextSigner: true,
language: true,
}),
recipients: ZRecipientLiteSchema.pick({
id: true,
role: true,
signingStatus: true,
email: true,
name: true,
documentDeletedAt: true,
expired: true,
signedAt: true,
authOptions: true,
signingOrder: true,
rejectionReason: true,
})
.extend({
fields: ZFieldSchema.omit({
documentId: true,
templateId: true,
}).array(),
})
.array(),
envelopeItems: EnvelopeItemSchema.pick({
id: true,
title: true,
documentDataId: true,
order: true,
})
.extend({
documentData: DocumentDataSchema.pick({
type: true,
id: true,
data: true,
initialData: true,
}),
})
.array(),
team: TeamSchema.pick({
id: true,
name: true,
}),
user: UserSchema.pick({
name: true,
email: true,
}),
}),
/**
* The recipient that is currently signing.
*/
recipient: ZRecipientLiteSchema.pick({
id: true,
role: true,
envelopeId: true,
readStatus: true,
sendStatus: true,
signingStatus: true,
email: true,
name: true,
documentDeletedAt: true,
expired: true,
signedAt: true,
authOptions: true,
token: true,
signingOrder: true,
rejectionReason: true,
}).extend({
fields: ZFieldSchema.extend({
signature: SignatureSchema.nullish(),
}).array(),
}),
recipientSignature: SignatureSchema.pick({
signatureImageAsBase64: true,
typedSignature: true,
}).nullable(),
isCompleted: z.boolean(),
isRejected: z.boolean(),
isRecipientsTurn: z.boolean(),
sender: z.object({
email: z.string(),
name: z.string(),
}),
settings: z.object({
includeSenderDetails: z.boolean(),
brandingEnabled: z.boolean(),
brandingLogo: z.string(),
}),
});
export type EnvelopeForSigningResponse = z.infer<typeof ZEnvelopeForSigningResponse>;
/**
* Get all the values and details for an envelope that a recipient requires
* to sign an envelope.
*
* Do not overexpose any information that the recipient should not have.
*/
export const getEnvelopeForRecipientSigning = async ({
token,
userId,
accessAuth,
}: GetRecipientEnvelopeByTokenOptions): Promise<EnvelopeForSigningResponse> => {
if (!token) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Missing token',
});
}
const envelope = await prisma.envelope.findFirst({
where: {
type: EnvelopeType.DOCUMENT,
status: {
not: DocumentStatus.DRAFT,
},
recipients: {
some: {
token,
},
},
},
include: {
user: {
select: {
id: true,
email: true,
name: true,
},
},
documentMeta: true,
recipients: {
include: {
fields: {
include: {
signature: true,
},
},
},
orderBy: {
signingOrder: 'asc',
},
},
envelopeItems: {
include: {
documentData: true,
},
},
team: {
select: {
id: true,
name: true,
teamEmail: true,
teamGlobalSettings: {
select: {
includeSigningCertificate: true,
},
},
},
},
},
});
const recipient = (envelope?.recipients || []).find((r) => r.token === token);
if (!envelope || !recipient) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Envelope not found',
});
}
if (envelope.envelopeItems.length === 0) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Envelope has no items',
});
}
const documentAccessValid = await isRecipientAuthorized({
type: 'ACCESS',
documentAuthOptions: envelope.authOptions,
recipient,
userId,
authOptions: accessAuth,
});
if (!documentAccessValid) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'Invalid access values',
});
}
const settings = await getTeamSettings({ teamId: envelope.teamId });
// Get the signature if they have put it in already.
const recipientSignature = await prisma.signature.findFirst({
where: {
field: {
recipientId: recipient.id,
envelopeId: envelope.id,
},
},
select: {
id: true,
recipientId: true,
signatureImageAsBase64: true,
typedSignature: true,
},
});
let isRecipientsTurn = true;
const currentRecipientIndex = envelope.recipients.findIndex((r) => r.token === token);
if (
envelope.documentMeta.signingOrder === DocumentSigningOrder.SEQUENTIAL &&
currentRecipientIndex !== -1
) {
for (let i = 0; i < currentRecipientIndex; i++) {
if (envelope.recipients[i].signingStatus !== SigningStatus.SIGNED) {
isRecipientsTurn = false;
break;
}
}
}
const sender = settings.includeSenderDetails
? {
email: envelope.user.email,
name: envelope.user.name || '',
}
: {
email: envelope.team.teamEmail?.email || '',
name: envelope.team.name || '',
};
return ZEnvelopeForSigningResponse.parse({
envelope,
recipient,
recipientSignature,
isRecipientsTurn,
isCompleted:
recipient.signingStatus === SigningStatus.SIGNED ||
envelope.status === DocumentStatus.COMPLETED,
isRejected:
recipient.signingStatus === SigningStatus.REJECTED ||
envelope.status === DocumentStatus.REJECTED,
sender,
settings: {
includeSenderDetails: settings.includeSenderDetails,
brandingEnabled: settings.brandingEnabled,
brandingLogo: settings.brandingLogo,
},
} satisfies EnvelopeForSigningResponse);
};
@@ -0,0 +1,56 @@
import { DocumentStatus, EnvelopeType } from '@prisma/client';
import { prisma } from '@documenso/prisma';
import { AppError, AppErrorCode } from '../../errors/app-error';
export const getEnvelopeRequiredAccessData = async ({ token }: { token: string }) => {
const envelope = await prisma.envelope.findFirst({
where: {
type: EnvelopeType.DOCUMENT,
status: {
not: DocumentStatus.DRAFT,
},
recipients: {
some: {
token,
},
},
},
include: {
recipients: {
where: {
token,
},
},
},
});
if (!envelope) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Envelope not found',
});
}
const recipient = envelope.recipients.find((r) => r.token === token);
if (!recipient) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Recipient not found',
});
}
const recipientUserAccount = await prisma.user.findFirst({
where: {
email: recipient.email.toLowerCase(),
},
select: {
id: true,
},
});
return {
recipientEmail: recipient.email,
recipientHasAccount: Boolean(recipientUserAccount),
} as const;
};
@@ -0,0 +1,344 @@
import type { DocumentMeta, DocumentVisibility, Prisma, TemplateType } from '@prisma/client';
import { EnvelopeType, FolderType } from '@prisma/client';
import { DocumentStatus } from '@prisma/client';
import { isDeepEqual } from 'remeda';
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
import type { ApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
import type { CreateDocumentAuditLogDataResponse } from '@documenso/lib/utils/document-audit-logs';
import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';
import { prisma } from '@documenso/prisma';
import { TEAM_DOCUMENT_VISIBILITY_MAP } from '../../constants/teams';
import { AppError, AppErrorCode } from '../../errors/app-error';
import type { TDocumentAccessAuthTypes, TDocumentActionAuthTypes } from '../../types/document-auth';
import { createDocumentAuthOptions, extractDocumentAuthMethods } from '../../utils/document-auth';
import type { EnvelopeIdOptions } from '../../utils/envelope';
import { buildTeamWhereQuery, canAccessTeamDocument } from '../../utils/teams';
import { getEnvelopeWhereInput } from './get-envelope-by-id';
export type UpdateEnvelopeOptions = {
userId: number;
teamId: number;
id: EnvelopeIdOptions;
data?: {
title?: string;
folderId?: string | null;
externalId?: string | null;
visibility?: DocumentVisibility;
globalAccessAuth?: TDocumentAccessAuthTypes[];
globalActionAuth?: TDocumentActionAuthTypes[];
publicTitle?: string;
publicDescription?: string;
templateType?: TemplateType;
useLegacyFieldInsertion?: boolean;
};
meta?: Partial<Omit<DocumentMeta, 'id'>>;
requestMetadata: ApiRequestMetadata;
};
export const updateEnvelope = async ({
userId,
teamId,
id,
data = {},
meta = {},
requestMetadata,
}: UpdateEnvelopeOptions) => {
const { envelopeWhereInput, team } = await getEnvelopeWhereInput({
id,
type: null, // Allow updating both documents and templates.
userId,
teamId,
});
const envelope = await prisma.envelope.findFirst({
where: envelopeWhereInput,
include: {
documentMeta: true,
team: {
select: {
organisationId: true,
organisation: {
select: {
organisationClaim: true,
},
},
},
},
},
});
if (!envelope) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Envelope not found',
});
}
if (
envelope.type !== EnvelopeType.TEMPLATE &&
(data.publicTitle || data.publicDescription || data.templateType)
) {
throw new AppError(AppErrorCode.INVALID_BODY, {
message: 'You cannot update the template fields for document type envelopes',
});
}
// If no data just return the document since this function is normally chained after a meta update.
if (Object.values(data).length === 0 && Object.keys(meta).length === 0) {
return envelope;
}
const isEnvelopeOwner = envelope.userId === userId;
// Validate whether the new visibility setting is allowed for the current user.
if (
!isEnvelopeOwner &&
data?.visibility &&
!canAccessTeamDocument(team.currentTeamRole, data.visibility)
) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to update the envelope visibility',
});
}
const { documentAuthOption } = extractDocumentAuthMethods({
documentAuth: envelope.authOptions,
});
const documentGlobalAccessAuth = documentAuthOption?.globalAccessAuth ?? null;
const documentGlobalActionAuth = documentAuthOption?.globalActionAuth ?? null;
// If the new global auth values aren't passed in, fallback to the current document values.
const newGlobalAccessAuth =
data?.globalAccessAuth === undefined ? documentGlobalAccessAuth : data.globalAccessAuth;
const newGlobalActionAuth =
data?.globalActionAuth === undefined ? documentGlobalActionAuth : data.globalActionAuth;
// Check if user has permission to set the global action auth.
if (newGlobalActionAuth.length > 0 && !envelope.team.organisation.organisationClaim.flags.cfr21) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to set the action auth',
});
}
const authOptions = createDocumentAuthOptions({
globalAccessAuth: newGlobalAccessAuth,
globalActionAuth: newGlobalActionAuth,
});
const emailId = meta.emailId;
// Validate the emailId belongs to the organisation.
if (emailId) {
const email = await prisma.organisationEmail.findFirst({
where: {
id: emailId,
organisationId: envelope.team.organisationId,
},
});
if (!email) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Email not found',
});
}
}
let folderUpdateQuery: Prisma.FolderUpdateOneWithoutEnvelopesNestedInput | undefined = undefined;
// Validate folder ID.
if (data.folderId) {
const folder = await prisma.folder.findFirst({
where: {
id: data.folderId,
team: buildTeamWhereQuery({
teamId,
userId,
}),
type: envelope.type === EnvelopeType.TEMPLATE ? FolderType.TEMPLATE : FolderType.DOCUMENT,
visibility: {
in: TEAM_DOCUMENT_VISIBILITY_MAP[team.currentTeamRole],
},
},
});
if (!folder) {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Folder not found',
});
}
folderUpdateQuery = {
connect: {
id: data.folderId,
},
};
}
// Move to root folder if folderId is null.
if (data.folderId === null) {
folderUpdateQuery = {
disconnect: true,
};
}
const isTitleSame = data.title === undefined || data.title === envelope.title;
const isExternalIdSame = data.externalId === undefined || data.externalId === envelope.externalId;
const isGlobalAccessSame =
documentGlobalAccessAuth === undefined ||
isDeepEqual(documentGlobalAccessAuth, newGlobalAccessAuth);
const isGlobalActionSame =
documentGlobalActionAuth === undefined ||
isDeepEqual(documentGlobalActionAuth, newGlobalActionAuth);
const isDocumentVisibilitySame =
data.visibility === undefined || data.visibility === envelope.visibility;
const isFolderSame = data.folderId === undefined || data.folderId === envelope.folderId;
const isTemplateTypeSame =
data.templateType === undefined || data.templateType === envelope.templateType;
const isPublicDescriptionSame =
data.publicDescription === undefined || data.publicDescription === envelope.publicDescription;
const isPublicTitleSame =
data.publicTitle === undefined || data.publicTitle === envelope.publicTitle;
const auditLogs: CreateDocumentAuditLogDataResponse[] = [];
if (!isTitleSame && envelope.status !== DocumentStatus.DRAFT) {
throw new AppError(AppErrorCode.INVALID_BODY, {
message: 'You cannot update the title if the envelope has been sent',
});
}
if (!isTitleSame) {
auditLogs.push(
createDocumentAuditLogData({
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_TITLE_UPDATED,
envelopeId: envelope.id,
metadata: requestMetadata,
data: {
from: envelope.title,
to: data.title || '',
},
}),
);
}
if (!isExternalIdSame) {
auditLogs.push(
createDocumentAuditLogData({
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_EXTERNAL_ID_UPDATED,
envelopeId: envelope.id,
metadata: requestMetadata,
data: {
from: envelope.externalId,
to: data.externalId || '',
},
}),
);
}
if (!isGlobalAccessSame) {
auditLogs.push(
createDocumentAuditLogData({
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED,
envelopeId: envelope.id,
metadata: requestMetadata,
data: {
from: documentGlobalAccessAuth,
to: newGlobalAccessAuth,
},
}),
);
}
if (!isGlobalActionSame) {
auditLogs.push(
createDocumentAuditLogData({
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED,
envelopeId: envelope.id,
metadata: requestMetadata,
data: {
from: documentGlobalActionAuth,
to: newGlobalActionAuth,
},
}),
);
}
if (!isDocumentVisibilitySame) {
auditLogs.push(
createDocumentAuditLogData({
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_VISIBILITY_UPDATED,
envelopeId: envelope.id,
metadata: requestMetadata,
data: {
from: envelope.visibility,
to: data.visibility || '',
},
}),
);
}
// Todo: Decide if we want to log moving the document around.
// if (!isFolderSame) {
// auditLogs.push(
// createDocumentAuditLogData({
// type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FOLDER_UPDATED,
// envelopeId: envelope.id,
// metadata: requestMetadata,
// data: {
// from: envelope.folderId,
// to: data.folderId || '',
// },
// }),
// );
// }
// Todo: Determine if changes are made
// Commented out since we didn't detect the changes to sequence.
// const isMetaSame = isDeepEqual(envelope.documentMeta, meta);
// Early return if nothing is required.
// if (
// auditLogs.length === 0 &&
// data.useLegacyFieldInsertion === undefined &&
// isFolderSame &&
// isTemplateTypeSame &&
// isPublicDescriptionSame &&
// isPublicTitleSame
// ) {
// return envelope;
// }
return await prisma.$transaction(async (tx) => {
const updatedEnvelope = await tx.envelope.update({
where: {
id: envelope.id,
},
data: {
title: data.title,
externalId: data.externalId,
visibility: data.visibility,
templateType: data.templateType,
publicDescription: data.publicDescription,
publicTitle: data.publicTitle,
useLegacyFieldInsertion: data.useLegacyFieldInsertion,
authOptions,
folder: folderUpdateQuery,
documentMeta: {
update: {
...meta,
emailSettings: meta?.emailSettings || undefined,
},
},
},
});
if (envelope.type === EnvelopeType.DOCUMENT) {
await tx.documentAuditLog.createMany({
data: auditLogs,
});
}
return updatedEnvelope;
});
};