The Open Source DocuSign Alternative.
TypeScript digital-signaturedocument-signingdocusign-alternativee-signatureesignesignaturenext-authnextjsopen-sourcepades-standardpdfpdf-signpdf-signaturepostgresqlprismaself-hostedsigningtypescript
feat: add envelopes api (#2105)
David Nguyend05bfa9fed5c
diff --git a/apps/remix/app/components/dialogs/document-duplicate-dialog.tsx b/apps/remix/app/components/dialogs/document-duplicate-dialog.tsxindex 81ec5bdf4..21e788ffa 100644--- a/apps/remix/app/components/dialogs/document-duplicate-dialog.tsx+++ b/apps/remix/app/components/dialogs/document-duplicate-dialog.tsx@@ -19,13 +19,15 @@ import { useToast } from '@documenso/ui/primitives/use-toast';import { useCurrentTeam } from '~/providers/team';type DocumentDuplicateDialogProps = {- id: number;+ id: string;+ token?: string;open: boolean;onOpenChange: (_open: boolean) => void;};export const DocumentDuplicateDialog = ({id,+ token,open,onOpenChange,}: DocumentDuplicateDialogProps) => {@@ -36,27 +38,23 @@ export const DocumentDuplicateDialog = ({const team = useCurrentTeam();- const { data: document, isLoading } = trpcReact.document.get.useQuery(- {- documentId: id,- },- {- queryHash: `document-duplicate-dialog-${id}`,- enabled: open === true,- },- );+ const { data: envelopeItemsPayload, isLoading: isLoadingEnvelopeItems } =+ trpcReact.envelope.item.getManyByToken.useQuery(+ {+ envelopeId: id,+ access: token ? { type: 'recipient', token } : { type: 'user' },+ },+ {+ enabled: open,+ },+ );- const documentData = document?.documentData- ? {- ...document.documentData,- data: document.documentData.initialData,- }- : undefined;+ const envelopeItems = envelopeItemsPayload?.data || [];const documentsPath = formatDocumentsPath(team.url);- const { mutateAsync: duplicateDocument, isPending: isDuplicateLoading } =- trpcReact.document.duplicate.useMutation({+ const { mutateAsync: duplicateEnvelope, isPending: isDuplicating } =+ trpcReact.envelope.duplicate.useMutation({onSuccess: async ({ id }) => {toast({title: _(msg`Document Duplicated`),@@ -71,7 +69,7 @@ export const DocumentDuplicateDialog = ({const onDuplicate = async () => {try {- await duplicateDocument({ documentId: id });+ await duplicateEnvelope({ envelopeId: id });} catch {toast({title: _(msg`Something went wrong`),@@ -83,14 +81,14 @@ export const DocumentDuplicateDialog = ({};return (- <Dialog open={open} onOpenChange={(value) => !isLoading && onOpenChange(value)}>+ <Dialog open={open} onOpenChange={(value) => !isDuplicating && onOpenChange(value)}><DialogContent><DialogHeader><DialogTitle><Trans>Duplicate</Trans></DialogTitle></DialogHeader>- {!documentData || isLoading ? (+ {isLoadingEnvelopeItems || !envelopeItems || envelopeItems.length === 0 ? (<div className="mx-auto -mt-4 flex w-full max-w-screen-xl flex-col px-4 md:px-8"><h1 className="mt-4 grow-0 truncate text-2xl font-semibold md:text-3xl"><Trans>Loading Document...</Trans>@@ -98,7 +96,12 @@ export const DocumentDuplicateDialog = ({</div>) : (<div className="p-2 [&>div]:h-[50vh] [&>div]:overflow-y-scroll">- <PDFViewer key={document?.id} documentData={documentData} />+ <PDFViewer+ key={envelopeItems[0].id}+ envelopeItem={envelopeItems[0]}+ token={undefined}+ version="original"+ /></div>)}@@ -115,8 +118,8 @@ export const DocumentDuplicateDialog = ({<Buttontype="button"- disabled={isDuplicateLoading || isLoading}- loading={isDuplicateLoading}+ disabled={isDuplicating}+ loading={isDuplicating}onClick={onDuplicate}className="flex-1">diff --git a/apps/remix/app/components/dialogs/envelope-download-dialog.tsx b/apps/remix/app/components/dialogs/envelope-download-dialog.tsxindex c735c773c..82d1c9631 100644--- a/apps/remix/app/components/dialogs/envelope-download-dialog.tsx+++ b/apps/remix/app/components/dialogs/envelope-download-dialog.tsx@@ -2,11 +2,10 @@ import { useState } from 'react';import { useLingui } from '@lingui/react/macro';import { Trans } from '@lingui/react/macro';-import { type DocumentData, DocumentStatus, type EnvelopeItem } from '@prisma/client';+import { DocumentStatus, type EnvelopeItem } from '@prisma/client';import { DownloadIcon, FileTextIcon } from 'lucide-react';-import { downloadFile } from '@documenso/lib/client-only/download-file';-import { getFile } from '@documenso/lib/universal/upload/get-file';+import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { trpc } from '@documenso/trpc/react';import { Button } from '@documenso/ui/primitives/button';import {@@ -20,9 +19,7 @@ import {import { Skeleton } from '@documenso/ui/primitives/skeleton';import { useToast } from '@documenso/ui/primitives/use-toast';-type EnvelopeItemToDownload = Pick<EnvelopeItem, 'id' | 'title' | 'order'> & {- documentData: DocumentData;-};+type EnvelopeItemToDownload = Pick<EnvelopeItem, 'id' | 'envelopeId' | 'title' | 'order'>;type EnvelopeDownloadDialogProps = {envelopeId: string;@@ -64,12 +61,12 @@ export const EnvelopeDownloadDialog = ({access: token ? { type: 'recipient', token } : { type: 'user' },},{- initialData: initialEnvelopeItems ? { envelopeItems: initialEnvelopeItems } : undefined,+ initialData: initialEnvelopeItems ? { data: initialEnvelopeItems } : undefined,enabled: open,},);- const envelopeItems = envelopeItemsPayload?.envelopeItems || [];+ const envelopeItems = envelopeItemsPayload?.data || [];const onDownload = async (envelopeItem: EnvelopeItemToDownload,@@ -87,25 +84,11 @@ export const EnvelopeDownloadDialog = ({}));try {- const data = await getFile({- type: envelopeItem.documentData.type,- data:- version === 'signed'- ? envelopeItem.documentData.data- : envelopeItem.documentData.initialData,- });-- const blob = new Blob([data], {- type: 'application/pdf',- });-- const baseTitle = envelopeItem.title.replace(/\.pdf$/, '');- const suffix = version === 'signed' ? '_signed.pdf' : '.pdf';- const filename = `${baseTitle}${suffix}`;-- downloadFile({- filename,- data: blob,+ await downloadPDF({+ envelopeItem,+ token,+ fileName: envelopeItem.title,+ version,});setIsDownloadingState((prev) => ({@@ -146,7 +129,7 @@ export const EnvelopeDownloadDialog = ({<div className="flex flex-col gap-4">{isLoadingEnvelopeItems ? (<>- {Array.from({ length: 2 }).map((_, index) => (+ {Array.from({ length: 1 }).map((_, index) => (<divkey={index}className="border-border bg-card flex items-center gap-2 rounded-lg border p-4"@@ -175,6 +158,7 @@ export const EnvelopeDownloadDialog = ({</div><div className="min-w-0 flex-1">+ {/* Todo: Envelopes - Fix overflow */}<h4 className="text-foreground truncate text-sm font-medium">{item.title}</h4><p className="text-muted-foreground mt-0.5 text-xs"><Trans>PDF Document</Trans>diff --git a/apps/remix/app/components/dialogs/envelope-duplicate-dialog.tsx b/apps/remix/app/components/dialogs/envelope-duplicate-dialog.tsxindex 92d55b71b..b327a1549 100644--- a/apps/remix/app/components/dialogs/envelope-duplicate-dialog.tsx+++ b/apps/remix/app/components/dialogs/envelope-duplicate-dialog.tsx@@ -43,7 +43,7 @@ export const EnvelopeDuplicateDialog = ({const { mutateAsync: duplicateEnvelope, isPending: isDuplicating } =trpc.envelope.duplicate.useMutation({- onSuccess: async ({ duplicatedEnvelopeId }) => {+ onSuccess: async ({ id }) => {toast({title: t`Envelope Duplicated`,description: t`Your envelope has been successfully duplicated.`,@@ -55,7 +55,7 @@ export const EnvelopeDuplicateDialog = ({? formatDocumentsPath(team.url): formatTemplatesPath(team.url);- await navigate(`${path}/${duplicatedEnvelopeId}/edit`);+ await navigate(`${path}/${id}/edit`);setOpen(false);},});diff --git a/apps/remix/app/components/dialogs/template-create-dialog.tsx b/apps/remix/app/components/dialogs/template-create-dialog.tsxindex 76d4e0c8a..160c332db 100644--- a/apps/remix/app/components/dialogs/template-create-dialog.tsx+++ b/apps/remix/app/components/dialogs/template-create-dialog.tsx@@ -7,9 +7,9 @@ import { FilePlus, Loader } from 'lucide-react';import { useNavigate } from 'react-router';import { useSession } from '@documenso/lib/client-only/providers/session';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { formatTemplatesPath } from '@documenso/lib/utils/teams';import { trpc } from '@documenso/trpc/react';+import type { TCreateTemplatePayloadSchema } from '@documenso/trpc/server/template-router/schema';import { Button } from '@documenso/ui/primitives/button';import {Dialog,@@ -54,13 +54,17 @@ export const TemplateCreateDialog = ({ folderId }: TemplateCreateDialogProps) =>setIsUploadingFile(true);try {- const response = await putPdfFile(file);-- const { legacyTemplateId: id } = await createTemplate({+ const payload = {title: file.name,- templateDocumentDataId: response.id,folderId: folderId,- });+ } satisfies TCreateTemplatePayloadSchema;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));+ formData.append('file', file);++ const { envelopeId: id } = await createTemplate(formData);toast({title: _(msg`Template document uploaded`),diff --git a/apps/remix/app/components/dialogs/template-use-dialog.tsx b/apps/remix/app/components/dialogs/template-use-dialog.tsxindex e5a438b3f..129132dd4 100644--- a/apps/remix/app/components/dialogs/template-use-dialog.tsx+++ b/apps/remix/app/components/dialogs/template-use-dialog.tsx@@ -143,7 +143,7 @@ export function TemplateUseDialog({},);- const envelopeItems = response?.envelopeItems ?? [];+ const envelopeItems = response?.data ?? [];const { mutateAsync: createDocumentFromTemplate } =trpc.template.createDocumentFromTemplate.useMutation();diff --git a/apps/remix/app/components/embed/authoring/configure-fields-view.tsx b/apps/remix/app/components/embed/authoring/configure-fields-view.tsxindex 704109a90..aac5f6fc9 100644--- a/apps/remix/app/components/embed/authoring/configure-fields-view.tsx+++ b/apps/remix/app/components/embed/authoring/configure-fields-view.tsx@@ -4,6 +4,7 @@ import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';import type { DocumentData, FieldType } from '@prisma/client';import { ReadStatus, type Recipient, SendStatus, SigningStatus } from '@prisma/client';+import { base64 } from '@scure/base';import { ChevronsUpDown } from 'lucide-react';import { useFieldArray, useForm } from 'react-hook-form';import { useHotkeys } from 'react-hotkeys-hook';@@ -12,7 +13,6 @@ import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-cimport { useDocumentElement } from '@documenso/lib/client-only/hooks/use-document-element';import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';import { type TFieldMetaSchema, ZFieldMetaSchema } from '@documenso/lib/types/field-meta';-import { base64 } from '@documenso/lib/universal/base64';import { nanoid } from '@documenso/lib/universal/id';import { ADVANCED_FIELD_TYPES_WITH_OPTIONAL_SETTING } from '@documenso/lib/utils/advanced-fields-helpers';import { useRecipientColors } from '@documenso/ui/lib/recipient-colors';@@ -83,21 +83,14 @@ export const ConfigureFieldsView = ({const normalizedDocumentData = useMemo(() => {if (documentData) {- return documentData;+ return documentData.data;}if (!configData.documentData) {return null;}- const data = base64.encode(configData.documentData?.data);-- return {- id: 'preview',- type: 'BYTES_64',- data,- initialData: data,- } satisfies DocumentData;+ return base64.encode(configData.documentData.data);}, [configData.documentData]);const recipients = useMemo(() => {@@ -541,7 +534,15 @@ export const ConfigureFieldsView = ({<Form {...form}>{normalizedDocumentData && (<div>- <PDFViewer documentData={normalizedDocumentData} />+ <PDFViewer+ overrideData={normalizedDocumentData}+ envelopeItem={{+ id: '',+ envelopeId: '',+ }}+ token={undefined}+ version="signed"+ /><ElementVisibletarget={`${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${highestPageNumber}"]`}diff --git a/apps/remix/app/components/embed/embed-direct-template-client-page.tsx b/apps/remix/app/components/embed/embed-direct-template-client-page.tsxindex 59a9c0312..f178b433d 100644--- a/apps/remix/app/components/embed/embed-direct-template-client-page.tsx+++ b/apps/remix/app/components/embed/embed-direct-template-client-page.tsx@@ -3,8 +3,8 @@ import { useEffect, useLayoutEffect, useState } from 'react';import { msg } from '@lingui/core/macro';import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';-import type { DocumentMeta, Recipient, Signature } from '@prisma/client';-import { type DocumentData, type Field, FieldType } from '@prisma/client';+import type { DocumentMeta, EnvelopeItem, Recipient, Signature } from '@prisma/client';+import { type Field, FieldType } from '@prisma/client';import { LucideChevronDown, LucideChevronUp } from 'lucide-react';import { DateTime } from 'luxon';import { useSearchParams } from 'react-router';@@ -47,7 +47,7 @@ export type EmbedDirectTemplateClientPageProps = {token: string;envelopeId: string;updatedAt: Date;- documentData: DocumentData;+ envelopeItems: Pick<EnvelopeItem, 'id' | 'envelopeId'>[];recipient: Recipient;fields: Field[];metadata?: DocumentMeta | null;@@ -59,7 +59,7 @@ export const EmbedDirectTemplateClientPage = ({token,envelopeId,updatedAt,- documentData,+ envelopeItems,recipient,fields,metadata,@@ -335,7 +335,9 @@ export const EmbedDirectTemplateClientPage = ({{/* Viewer */}<div className="flex-1"><PDFViewer- documentData={documentData}+ envelopeItem={envelopeItems[0]}+ token={token}+ version="signed"onDocumentLoad={() => setHasDocumentLoaded(true)}/></div>diff --git a/apps/remix/app/components/embed/embed-document-signing-page.tsx b/apps/remix/app/components/embed/embed-document-signing-page-v1.tsxsimilarity index 97%rename from apps/remix/app/components/embed/embed-document-signing-page.tsxrename to apps/remix/app/components/embed/embed-document-signing-page-v1.tsxindex 329a38446..59bd442ec 100644--- a/apps/remix/app/components/embed/embed-document-signing-page.tsx+++ b/apps/remix/app/components/embed/embed-document-signing-page-v1.tsx@@ -3,14 +3,8 @@ import { useEffect, useId, useLayoutEffect, useMemo, useState } from 'react';import { msg } from '@lingui/core/macro';import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';-import type { DocumentMeta } from '@prisma/client';-import {- type DocumentData,- type Field,- FieldType,- RecipientRole,- SigningStatus,-} from '@prisma/client';+import type { DocumentMeta, EnvelopeItem } from '@prisma/client';+import { type Field, FieldType, RecipientRole, SigningStatus } from '@prisma/client';import { LucideChevronDown, LucideChevronUp } from 'lucide-react';import { useThrottleFn } from '@documenso/lib/client-only/hooks/use-throttle-fn';@@ -46,11 +40,11 @@ import { EmbedDocumentCompleted } from './embed-document-completed';import { EmbedDocumentFields } from './embed-document-fields';import { EmbedDocumentRejected } from './embed-document-rejected';-export type EmbedSignDocumentClientPageProps = {+export type EmbedSignDocumentV1ClientPageProps = {token: string;documentId: number;envelopeId: string;- documentData: DocumentData;+ envelopeItems: Pick<EnvelopeItem, 'id' | 'envelopeId'>[];recipient: RecipientWithFields;fields: Field[];completedFields: DocumentField[];@@ -61,11 +55,11 @@ export type EmbedSignDocumentClientPageProps = {allRecipients?: RecipientWithFields[];};-export const EmbedSignDocumentClientPage = ({+export const EmbedSignDocumentV1ClientPage = ({token,documentId,envelopeId,- documentData,+ envelopeItems,recipient,fields,completedFields,@@ -74,7 +68,7 @@ export const EmbedSignDocumentClientPage = ({hidePoweredBy = false,allowWhitelabelling = false,allRecipients = [],-}: EmbedSignDocumentClientPageProps) => {+}: EmbedSignDocumentV1ClientPageProps) => {const { _ } = useLingui();const { toast } = useToast();@@ -293,7 +287,9 @@ export const EmbedSignDocumentClientPage = ({{/* Viewer */}<div className="embed--DocumentViewer flex-1"><PDFViewer- documentData={documentData}+ envelopeItem={envelopeItems[0]}+ token={token}+ version="signed"onDocumentLoad={() => setHasDocumentLoaded(true)}/></div>diff --git a/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx b/apps/remix/app/components/embed/embed-document-signing-page-v2.tsxnew file mode 100644index 000000000..a6069e286--- /dev/null+++ b/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx@@ -0,0 +1,232 @@+import { useEffect, useLayoutEffect, useState } from 'react';++import { useLingui } from '@lingui/react';++import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';++import { ZSignDocumentEmbedDataSchema } from '~/types/embed-document-sign-schema';+import { injectCss } from '~/utils/css-vars';++import { DocumentSigningPageViewV2 } from '../general/document-signing/document-signing-page-view-v2';+import { useRequiredEnvelopeSigningContext } from '../general/document-signing/envelope-signing-provider';+import { EmbedClientLoading } from './embed-client-loading';+import { EmbedDocumentCompleted } from './embed-document-completed';+import { EmbedDocumentRejected } from './embed-document-rejected';+import { EmbedSigningProvider } from './embed-signing-context';++export type EmbedSignDocumentV2ClientPageProps = {+ hidePoweredBy?: boolean;+ allowWhitelabelling?: boolean;+};++export const EmbedSignDocumentV2ClientPage = ({+ hidePoweredBy = false,+ allowWhitelabelling = false,+}: EmbedSignDocumentV2ClientPageProps) => {+ const { _ } = useLingui();++ const { envelope, recipient, envelopeData, setFullName, fullName } =+ useRequiredEnvelopeSigningContext();++ const { isCompleted, isRejected, recipientSignature } = envelopeData;++ // !: Not used at the moment, may be removed in the future.+ // const [hasDocumentLoaded, setHasDocumentLoaded] = useState(false);+ const [hasFinishedInit, setHasFinishedInit] = useState(false);+ const [allowDocumentRejection, setAllowDocumentRejection] = useState(false);+ const [isNameLocked, setIsNameLocked] = useState(false);++ const onDocumentCompleted = (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ }) => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'document-completed',+ data,+ },+ '*',+ );+ }+ };++ const onDocumentError = () => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'document-error',+ data: null,+ },+ '*',+ );+ }+ };++ const onDocumentReady = () => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'document-ready',+ data: null,+ },+ '*',+ );+ }+ };++ const onFieldSigned = (data: { fieldId?: number; value?: string; isBase64?: boolean }) => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'field-signed',+ data,+ },+ '*',+ );+ }+ };++ const onFieldUnsigned = (data: { fieldId?: number }) => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'field-unsigned',+ data,+ },+ '*',+ );+ }+ };++ const onDocumentRejected = (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ reason?: string;+ }) => {+ if (window.parent) {+ window.parent.postMessage(+ {+ action: 'document-rejected',+ data,+ },+ '*',+ );+ }+ };++ useLayoutEffect(() => {+ const hash = window.location.hash.slice(1);++ try {+ const data = ZSignDocumentEmbedDataSchema.parse(JSON.parse(decodeURIComponent(atob(hash))));++ if (!isCompleted && data.name) {+ setFullName(data.name);+ }++ // Since a recipient can be provided a name we can lock it without requiring+ // a to be provided by the parent application, unlike direct templates.+ setIsNameLocked(!!data.lockName);+ setAllowDocumentRejection(!!data.allowDocumentRejection);++ if (data.darkModeDisabled) {+ document.documentElement.classList.add('dark-mode-disabled');+ }++ if (allowWhitelabelling) {+ injectCss({+ css: data.css,+ cssVars: data.cssVars,+ });+ }+ } catch (err) {+ console.error(err);+ }++ setHasFinishedInit(true);++ // !: While the setters are stable we still want to ensure we're avoiding+ // !: re-renders.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [allowWhitelabelling]);++ useEffect(() => {+ if (hasFinishedInit) {+ onDocumentReady();+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [hasFinishedInit]);++ // Listen for document completion events from the envelope signing context+ useEffect(() => {+ if (isCompleted) {+ onDocumentCompleted({+ token: recipient.token,+ envelopeId: envelope.id,+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),+ recipientId: recipient.id,+ });+ }+ }, [isCompleted, envelope.id, recipient.id, recipient.token]);++ // Listen for document rejection events+ useEffect(() => {+ if (isRejected) {+ onDocumentRejected({+ token: recipient.token,+ envelopeId: envelope.id,+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),+ recipientId: recipient.id,+ });+ }+ }, [isRejected, envelope.id, recipient.id, recipient.token]);++ if (isRejected) {+ return <EmbedDocumentRejected />;+ }++ if (isCompleted) {+ return (+ <EmbedDocumentCompleted+ name={fullName}+ signature={+ recipientSignature+ ? {+ id: 1,+ fieldId: 1,+ recipientId: recipient.id,+ created: new Date(),+ signatureImageAsBase64: recipientSignature.signatureImageAsBase64,+ typedSignature: recipientSignature.typedSignature,+ }+ : undefined+ }+ />+ );+ }++ return (+ <EmbedSigningProvider+ isNameLocked={isNameLocked}+ hidePoweredBy={hidePoweredBy}+ allowDocumentRejection={allowDocumentRejection}+ onDocumentCompleted={onDocumentCompleted}+ onDocumentError={onDocumentError}+ onDocumentRejected={onDocumentRejected}+ onDocumentReady={onDocumentReady}+ onFieldSigned={onFieldSigned}+ onFieldUnsigned={onFieldUnsigned}+ >+ <div className="embed--Root relative">+ {!hasFinishedInit && <EmbedClientLoading />}++ <DocumentSigningPageViewV2 />+ </div>+ </EmbedSigningProvider>+ );+};diff --git a/apps/remix/app/components/embed/embed-signing-context.tsx b/apps/remix/app/components/embed/embed-signing-context.tsxnew file mode 100644index 000000000..408bdff49--- /dev/null+++ b/apps/remix/app/components/embed/embed-signing-context.tsx@@ -0,0 +1,101 @@+import { createContext, useContext } from 'react';++export type EmbedSigningContextValue = {+ isEmbed: true;+ allowDocumentRejection: boolean;+ isNameLocked: boolean;+ isEmailLocked: boolean;+ hidePoweredBy: boolean;+ onDocumentCompleted: (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ }) => void;+ onDocumentError: () => void;+ onDocumentRejected: (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ reason?: string;+ }) => void;+ onDocumentReady: () => void;+ onFieldSigned: (data: { fieldId?: number; value?: string; isBase64?: boolean }) => void;+ onFieldUnsigned: (data: { fieldId?: number }) => void;+};++const EmbedSigningContext = createContext<EmbedSigningContextValue | null>(null);++export const useEmbedSigningContext = () => {+ return useContext(EmbedSigningContext);+};++export const useRequiredEmbedSigningContext = () => {+ const context = useEmbedSigningContext();++ if (!context) {+ throw new Error('useRequiredEmbedSigningContext must be used within EmbedSigningProvider');+ }++ return context;+};++export type EmbedSigningProviderProps = {+ allowDocumentRejection?: boolean;+ isNameLocked?: boolean;+ isEmailLocked?: boolean;+ hidePoweredBy?: boolean;+ onDocumentCompleted: (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ }) => void;+ onDocumentError: () => void;+ onDocumentRejected: (data: {+ token: string;+ documentId: number;+ envelopeId: string;+ recipientId: number;+ reason?: string;+ }) => void;+ onDocumentReady: () => void;+ onFieldSigned: (data: { fieldId?: number; value?: string; isBase64?: boolean }) => void;+ onFieldUnsigned: (data: { fieldId?: number }) => void;+ children: React.ReactNode;+};++export const EmbedSigningProvider = ({+ allowDocumentRejection = false,+ isNameLocked = false,+ isEmailLocked = true,+ hidePoweredBy = false,+ onDocumentCompleted,+ onDocumentError,+ onDocumentRejected,+ onDocumentReady,+ onFieldSigned,+ onFieldUnsigned,+ children,+}: EmbedSigningProviderProps) => {+ return (+ <EmbedSigningContext.Provider+ value={{+ isEmbed: true,+ allowDocumentRejection,+ isNameLocked,+ isEmailLocked,+ hidePoweredBy,+ onDocumentCompleted,+ onDocumentError,+ onDocumentRejected,+ onDocumentReady,+ onFieldSigned,+ onFieldUnsigned,+ }}+ >+ {children}+ </EmbedSigningContext.Provider>+ );+};diff --git a/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx b/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsxindex d74b88f2d..14c906704 100644--- a/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx+++ b/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx@@ -226,7 +226,9 @@ export const MultiSignDocumentSigningView = ({})}><PDFViewer- documentData={document.documentData}+ envelopeItem={document.envelopeItems[0]}+ token={token}+ version="signed"onDocumentLoad={() => {setHasDocumentLoaded(true);onDocumentReady?.();diff --git a/apps/remix/app/components/forms/branding-preferences-form.tsx b/apps/remix/app/components/forms/branding-preferences-form.tsxindex 85355a7b1..9c8bc05ce 100644--- a/apps/remix/app/components/forms/branding-preferences-form.tsx+++ b/apps/remix/app/components/forms/branding-preferences-form.tsx@@ -1,14 +1,14 @@import { useEffect, useState } from 'react';import { zodResolver } from '@hookform/resolvers/zod';-import { useLingui } from '@lingui/react/macro';-import { Trans } from '@lingui/react/macro';+import { Trans, useLingui } from '@lingui/react/macro';import type { TeamGlobalSettings } from '@prisma/client';import { Loader } from 'lucide-react';import { useForm } from 'react-hook-form';import { z } from 'zod';-import { getFile } from '@documenso/lib/universal/upload/get-file';+import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';+import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';import { cn } from '@documenso/ui/lib/utils';import { Button } from '@documenso/ui/primitives/button';import {@@ -29,6 +29,8 @@ import {} from '@documenso/ui/primitives/select';import { Textarea } from '@documenso/ui/primitives/textarea';+import { useOptionalCurrentTeam } from '~/providers/team';+const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MBconst ACCEPTED_FILE_TYPES = ['image/jpeg', 'image/png', 'image/webp'];@@ -68,6 +70,9 @@ export function BrandingPreferencesForm({}: BrandingPreferencesFormProps) {const { t } = useLingui();+ const team = useOptionalCurrentTeam();+ const organisation = useCurrentOrganisation();+const [previewUrl, setPreviewUrl] = useState<string>('');const [hasLoadedPreview, setHasLoadedPreview] = useState(false);@@ -88,14 +93,13 @@ export function BrandingPreferencesForm({const file = JSON.parse(settings.brandingLogo);if ('type' in file && 'data' in file) {- void getFile(file).then((binaryData) => {- const objectUrl = URL.createObjectURL(new Blob([binaryData]));-- setPreviewUrl(objectUrl);- setHasLoadedPreview(true);- });+ const logoUrl =+ context === 'Team'+ ? `${NEXT_PUBLIC_WEBAPP_URL()}/api/branding/logo/team/${team?.id}`+ : `${NEXT_PUBLIC_WEBAPP_URL()}/api/branding/logo/organisation/${organisation?.id}`;- return;+ setPreviewUrl(logoUrl);+ setHasLoadedPreview(true);}}diff --git a/apps/remix/app/components/forms/editor/editor-field-text-form.tsx b/apps/remix/app/components/forms/editor/editor-field-text-form.tsxindex c634d3a9c..17432944c 100644--- a/apps/remix/app/components/forms/editor/editor-field-text-form.tsx+++ b/apps/remix/app/components/forms/editor/editor-field-text-form.tsx@@ -152,6 +152,18 @@ export const EditorFieldTextForm = ({className="h-auto"placeholder={t`Add text to the field`}{...field}+ onChange={(e) => {+ const values = form.getValues();+ const characterLimit = values.characterLimit || 0;+ let textValue = e.target.value;++ if (characterLimit > 0 && textValue.length > characterLimit) {+ textValue = textValue.slice(0, characterLimit);+ }++ e.target.value = textValue;+ field.onChange(e);+ }}rows={1}/></FormControl>@@ -175,6 +187,18 @@ export const EditorFieldTextForm = ({className="bg-background"placeholder={t`Field character limit`}{...field}+ onChange={(e) => {+ field.onChange(e);++ const values = form.getValues();+ const characterLimit = parseInt(e.target.value, 10) || 0;++ const textValue = values.text || '';++ if (characterLimit > 0 && textValue.length > characterLimit) {+ form.setValue('text', textValue.slice(0, characterLimit));+ }+ }}/></FormControl><FormMessage />diff --git a/apps/remix/app/components/general/direct-template/direct-template-page.tsx b/apps/remix/app/components/general/direct-template/direct-template-page.tsxindex 9bddf9c0d..8a2145a24 100644--- a/apps/remix/app/components/general/direct-template/direct-template-page.tsx+++ b/apps/remix/app/components/general/direct-template/direct-template-page.tsx@@ -153,7 +153,9 @@ export const DirectTemplatePageView = ({<CardContent className="p-2"><PDFViewerkey={template.id}- documentData={template.templateDocumentData}+ envelopeItem={template.envelopeItems[0]}+ token={directTemplateRecipient.token}+ version="signed"onDocumentLoad={() => setIsDocumentPdfLoaded(true)}/></CardContent>diff --git a/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx b/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsxindex e910b7060..42a81408a 100644--- a/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx@@ -34,6 +34,7 @@ import {} from '@documenso/ui/primitives/form/form';import { Input } from '@documenso/ui/primitives/input';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';import { AccessAuth2FAForm } from '~/components/general/document-signing/access-auth-2fa-form';import { DocumentSigningDisclosure } from '~/components/general/document-signing/document-signing-disclosure';@@ -102,6 +103,8 @@ export const DocumentSigningCompleteDialog = ({const { derivedRecipientAccessAuth } = useRequiredDocumentSigningAuthContext();+ const { isNameLocked, isEmailLocked } = useEmbedSigningContext() || {};+const form = useForm<TNextSignerFormSchema>({resolver: allowDictateNextSigner ? zodResolver(ZNextSignerFormSchema) : undefined,defaultValues: {@@ -267,7 +270,12 @@ export const DocumentSigningCompleteDialog = ({<Trans>Your Name</Trans></FormLabel><FormControl>- <Input {...field} className="mt-2" placeholder={t`Enter your name`} />+ <Input+ {...field}+ className="mt-2"+ placeholder={t`Enter your name`}+ disabled={isNameLocked}+ /></FormControl><FormMessage />@@ -289,6 +297,7 @@ export const DocumentSigningCompleteDialog = ({type="email"className="mt-2"placeholder={t`Enter your email`}+ disabled={!!field.value && isEmailLocked}/></FormControl><FormMessage />diff --git a/apps/remix/app/components/general/document-signing/document-signing-mobile-widget.tsx b/apps/remix/app/components/general/document-signing/document-signing-mobile-widget.tsxindex c066de401..91e58edf3 100644--- a/apps/remix/app/components/general/document-signing/document-signing-mobile-widget.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-mobile-widget.tsx@@ -8,6 +8,9 @@ import { match } from 'ts-pattern';import { Button } from '@documenso/ui/primitives/button';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';++import { BrandingLogo } from '../branding-logo';import EnvelopeSignerForm from '../envelope-signing/envelope-signer-form';import { EnvelopeSignerCompleteDialog } from '../envelope-signing/envelope-signing-complete-dialog';import { useRequiredEnvelopeSigningContext } from './envelope-signing-provider';@@ -15,6 +18,8 @@ import { useRequiredEnvelopeSigningContext } from './envelope-signing-provider';export const DocumentSigningMobileWidget = () => {const [isExpanded, setIsExpanded] = useState(false);+ const { hidePoweredBy = true } = useEmbedSigningContext() || {};+const { recipientFieldsRemaining, recipient, requiredRecipientFields } =useRequiredEnvelopeSigningContext();@@ -29,7 +34,7 @@ export const DocumentSigningMobileWidget = () => {return (<div className="pointer-events-none fixed bottom-0 left-0 right-0 z-50 flex justify-center px-2 pb-2 sm:px-4 sm:pb-6">- <div className="pointer-events-auto w-full max-w-2xl">+ <div className="pointer-events-auto w-full max-w-[760px]"><div className="bg-card border-border overflow-hidden rounded-xl border shadow-2xl">{/* Main Header Bar */}<div className="flex items-center justify-between gap-4 p-4">@@ -114,6 +119,13 @@ export const DocumentSigningMobileWidget = () => {{isExpanded && (<div className="border-border animate-in slide-in-from-bottom-2 border-t p-4 duration-200"><EnvelopeSignerForm />++ {!hidePoweredBy && (+ <div className="bg-primary text-primary-foreground mt-2 inline-block rounded px-2 py-1 text-xs font-medium opacity-60 hover:opacity-100 lg:hidden">+ <span>Powered by</span>+ <BrandingLogo className="ml-2 inline-block h-[14px]" />+ </div>+ )}</div>)}</div>diff --git a/apps/remix/app/components/general/document-signing/document-signing-page-view-v1.tsx b/apps/remix/app/components/general/document-signing/document-signing-page-view-v1.tsxindex b3ee5727e..95e60ce10 100644--- a/apps/remix/app/components/general/document-signing/document-signing-page-view-v1.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-page-view-v1.tsx@@ -245,7 +245,12 @@ export const DocumentSigningPageViewV1 = ({<div className="flex-1"><Card className="rounded-xl before:rounded-xl" gradient><CardContent className="p-2">- <PDFViewer key={documentData.id} documentData={documentData} document={document} />+ <PDFViewer+ key={document.envelopeItems[0].id}+ envelopeItem={document.envelopeItems[0]}+ token={recipient.token}+ version="signed"+ /></CardContent></Card></div>diff --git a/apps/remix/app/components/general/document-signing/document-signing-page-view-v2.tsx b/apps/remix/app/components/general/document-signing/document-signing-page-view-v2.tsxindex c75aba3da..5b0c30102 100644--- a/apps/remix/app/components/general/document-signing/document-signing-page-view-v2.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-page-view-v2.tsx@@ -22,7 +22,9 @@ import { SignFieldNameDialog } from '~/components/dialogs/sign-field-name-dialogimport { SignFieldNumberDialog } from '~/components/dialogs/sign-field-number-dialog';import { SignFieldSignatureDialog } from '~/components/dialogs/sign-field-signature-dialog';import { SignFieldTextDialog } from '~/components/dialogs/sign-field-text-dialog';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';+import { BrandingLogo } from '../branding-logo';import { DocumentSigningAttachmentsPopover } from '../document-signing/document-signing-attachments-popover';import { EnvelopeItemSelector } from '../envelope-editor/envelope-file-selector';import EnvelopeSignerForm from '../envelope-signing/envelope-signer-form';@@ -48,6 +50,13 @@ export const DocumentSigningPageViewV2 = () => {selectedAssistantRecipientFields,} = useRequiredEnvelopeSigningContext();+ const {+ isEmbed = false,+ allowDocumentRejection = true,+ hidePoweredBy = true,+ onDocumentRejected,+ } = useEmbedSigningContext() || {};+/*** The total remaining fields remaining for the current recipient or selected assistant recipient.*@@ -77,7 +86,7 @@ export const DocumentSigningPageViewV2 = () => {{/* Main Content Area */}<div className="flex h-[calc(100vh-4rem)] w-screen">{/* Left Section - Step Navigation */}- <div className="bg-background border-border hidden w-80 flex-shrink-0 flex-col overflow-y-auto border-r py-4 lg:flex">+ <div className="embed--DocumentWidgetContainer bg-background border-border hidden w-80 flex-shrink-0 flex-col overflow-y-auto border-r py-4 lg:flex"><div className="px-4"><h3 className="text-foreground flex items-end justify-between text-sm font-semibold">{match(recipient.role)@@ -107,7 +116,7 @@ export const DocumentSigningPageViewV2 = () => {/></div>- <div className="mt-6 space-y-3">+ <div className="embed--DocumentWidgetContent mt-6 space-y-3"><EnvelopeSignerForm /></div></div>@@ -116,7 +125,7 @@ export const DocumentSigningPageViewV2 = () => {{/* Quick Actions. */}{!isDirectTemplate && (- <div className="space-y-3 px-4">+ <div className="embed--Actions space-y-3 px-4"><h4 className="text-foreground text-sm font-semibold"><Trans>Actions</Trans></h4>@@ -145,10 +154,21 @@ export const DocumentSigningPageViewV2 = () => {}/>- {envelope.type === EnvelopeType.DOCUMENT && (+ {envelope.type === EnvelopeType.DOCUMENT && allowDocumentRejection && (<DocumentSigningRejectDialogdocumentId={mapSecondaryIdToDocumentId(envelope.secondaryId)}token={recipient.token}+ onRejected={+ onDocumentRejected &&+ ((reason) =>+ onDocumentRejected({+ token: recipient.token,+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),+ envelopeId: envelope.id,+ recipientId: recipient.id,+ reason,+ }))+ }trigger={<Buttonvariant="ghost"@@ -164,18 +184,22 @@ export const DocumentSigningPageViewV2 = () => {</div>)}- {/* Footer of left sidebar. */}- <div className="mt-auto px-4">- <Button asChild variant="ghost" className="w-full justify-start">- <Link to="/">- <ArrowLeftIcon className="mr-2 h-4 w-4" />- <Trans>Return</Trans>- </Link>- </Button>+ <div className="embed--DocumentWidgetFooter">+ {/* Footer of left sidebar. */}+ {!isEmbed && (+ <div className="mt-auto px-4">+ <Button asChild variant="ghost" className="w-full justify-start">+ <Link to="/">+ <ArrowLeftIcon className="mr-2 h-4 w-4" />+ <Trans>Return</Trans>+ </Link>+ </Button>+ </div>+ )}</div></div>- <div className="flex-1 overflow-y-auto">+ <div className="embed--DocumentContainer flex-1 overflow-y-auto"><div className="flex flex-col">{/* Horizontal envelope item selector */}{envelopeItems.length > 1 && (@@ -202,11 +226,11 @@ export const DocumentSigningPageViewV2 = () => {)}{/* Document View */}- <div className="flex flex-col items-center justify-center p-2 sm:mt-4 sm:p-4">+ <div className="embed--DocumentViewer flex flex-col items-center justify-center p-2 sm:mt-4 sm:p-4">{currentEnvelopeItem ? (<PDFViewerKonvaLazy+ renderer="signing"key={currentEnvelopeItem.id}- documentDataId={currentEnvelopeItem.documentDataId}customPageRenderer={EnvelopeSignerPageRenderer}/>) : (@@ -218,9 +242,20 @@ export const DocumentSigningPageViewV2 = () => {)}{/* Mobile widget - Additional padding to allow users to scroll */}- <div className="block pb-16 md:hidden">+ <div className="block pb-28 lg:hidden"><DocumentSigningMobileWidget /></div>++ {!hidePoweredBy && (+ <a+ href="https://documenso.com"+ target="_blank"+ className="bg-primary text-primary-foreground fixed bottom-0 right-0 z-40 hidden cursor-pointer rounded-tl px-2 py-1 text-xs font-medium opacity-60 hover:opacity-100 lg:block"+ >+ <span>Powered by</span>+ <BrandingLogo className="ml-2 inline-block h-[14px]" />+ </a>+ )}</div></div></div>diff --git a/apps/remix/app/components/general/document-signing/envelope-signing-provider.tsx b/apps/remix/app/components/general/document-signing/envelope-signing-provider.tsxindex aaecd3ee9..ddaf3c355 100644--- a/apps/remix/app/components/general/document-signing/envelope-signing-provider.tsx+++ b/apps/remix/app/components/general/document-signing/envelope-signing-provider.tsx@@ -13,6 +13,7 @@ import { prop, sortBy } from 'remeda';import { isBase64Image } from '@documenso/lib/constants/signatures';import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';import type { EnvelopeForSigningResponse } from '@documenso/lib/server-only/envelope/get-envelope-for-recipient-signing';+import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';import {isFieldUnsignedAndRequired,isRequiredField,@@ -51,7 +52,11 @@ export type EnvelopeSigningContextValue = {setSelectedAssistantRecipientId: (_value: number | null) => void;selectedAssistantRecipient: EnvelopeForSigningResponse['envelope']['recipients'][number] | null;- signField: (_fieldId: number, _value: TSignEnvelopeFieldValue) => Promise<void>;+ signField: (+ _fieldId: number,+ _value: TSignEnvelopeFieldValue,+ authOptions?: TRecipientActionAuth,+ ) => Promise<Pick<Field, 'id' | 'inserted'>>;};const EnvelopeSigningContext = createContext<EnvelopeSigningContextValue | null>(null);@@ -284,19 +289,26 @@ export const EnvelopeSigningProvider = ({: null;}, [envelope.documentMeta?.signingOrder, envelope.recipients, recipient.id]);- const signField = async (fieldId: number, fieldValue: TSignEnvelopeFieldValue) => {+ const signField = async (+ fieldId: number,+ fieldValue: TSignEnvelopeFieldValue,+ authOptions?: TRecipientActionAuth,+ ) => {// Set the field locally for direct templates.if (isDirectTemplate) {- handleDirectTemplateFieldInsertion(fieldId, fieldValue);- return;+ const signedField = handleDirectTemplateFieldInsertion(fieldId, fieldValue);++ return signedField;}- await signEnvelopeField({+ const { signedField } = await signEnvelopeField({token: envelopeData.recipient.token,fieldId,fieldValue,- authOptions: undefined,+ authOptions,});++ return signedField;};const handleDirectTemplateFieldInsertion = (@@ -354,6 +366,8 @@ export const EnvelopeSigningProvider = ({fields: prev.recipient.fields.map((field) => (field.id === fieldId ? updatedField : field)),},}));++ return updatedField;};return (diff --git a/apps/remix/app/components/general/document/document-certificate-qr-view.tsx b/apps/remix/app/components/general/document/document-certificate-qr-view.tsxindex b4360d6bb..d5ff98f75 100644--- a/apps/remix/app/components/general/document/document-certificate-qr-view.tsx+++ b/apps/remix/app/components/general/document/document-certificate-qr-view.tsx@@ -1,7 +1,8 @@import { useEffect, useState } from 'react';import { Trans } from '@lingui/react/macro';-import type { DocumentData, EnvelopeItem } from '@prisma/client';+import { type DocumentData, DocumentStatus, type EnvelopeItem } from '@prisma/client';+import { DownloadIcon } from 'lucide-react';import { DateTime } from 'luxon';import {@@ -22,9 +23,10 @@ import {} from '@documenso/ui/primitives/dialog';import { PDFViewer } from '@documenso/ui/primitives/pdf-viewer';+import { EnvelopeDownloadDialog } from '~/components/dialogs/envelope-download-dialog';+import { EnvelopeRendererFileSelector } from '../envelope-editor/envelope-file-selector';import EnvelopeGenericPageRenderer from '../envelope-editor/envelope-generic-page-renderer';-import { ShareDocumentDownloadButton } from '../share-document-download-button';export type DocumentCertificateQRViewProps = {documentId: number;@@ -34,6 +36,7 @@ export type DocumentCertificateQRViewProps = {documentTeamUrl: string;recipientCount?: number;completedDate?: Date;+ token: string;};export const DocumentCertificateQRView = ({@@ -44,6 +47,7 @@ export const DocumentCertificateQRView = ({documentTeamUrl,recipientCount = 0,completedDate,+ token,}: DocumentCertificateQRViewProps) => {const { data: documentViaUser } = trpc.document.get.useQuery({documentId,@@ -96,11 +100,12 @@ export const DocumentCertificateQRView = ({)}{internalVersion === 2 ? (- <EnvelopeRenderProvider envelope={{ envelopeItems }}>+ <EnvelopeRenderProvider envelope={{ envelopeItems }} token={token}><DocumentCertificateQrV2title={title}recipientCount={recipientCount}formattedDate={formattedDate}+ token={token}/></EnvelopeRenderProvider>) : (@@ -119,14 +124,27 @@ export const DocumentCertificateQRView = ({</div></div>- <ShareDocumentDownloadButton- title={title}- documentData={envelopeItems[0].documentData}+ <EnvelopeDownloadDialog+ envelopeId={envelopeItems[0].envelopeId}+ envelopeStatus={DocumentStatus.COMPLETED}+ envelopeItems={envelopeItems}+ token={token}+ trigger={+ <Button type="button" variant="outline" className="flex-1">+ <DownloadIcon className="mr-2 h-5 w-5" />+ <Trans>Download</Trans>+ </Button>+ }/></div><div className="mt-12 w-full">- <PDFViewer key={envelopeItems[0].id} documentData={envelopeItems[0].documentData} />+ <PDFViewer+ key={envelopeItems[0].id}+ envelopeItem={envelopeItems[0]}+ token={token}+ version="signed"+ /></div></>)}@@ -138,14 +156,16 @@ type DocumentCertificateQrV2Props = {title: string;recipientCount: number;formattedDate: string;+ token: string;};const DocumentCertificateQrV2 = ({title,recipientCount,formattedDate,+ token,}: DocumentCertificateQrV2Props) => {- const { currentEnvelopeItem } = useCurrentEnvelopeRender();+ const { currentEnvelopeItem, envelopeItems } = useCurrentEnvelopeRender();return (<div className="flex min-h-screen flex-col items-start">@@ -163,18 +183,24 @@ const DocumentCertificateQrV2 = ({</div></div>- {currentEnvelopeItem && (- <ShareDocumentDownloadButton- title={title}- documentData={currentEnvelopeItem.documentData}- />- )}+ <EnvelopeDownloadDialog+ envelopeId={envelopeItems[0].envelopeId}+ envelopeStatus={DocumentStatus.COMPLETED}+ envelopeItems={envelopeItems}+ token={token}+ trigger={+ <Button type="button" variant="outline" className="flex-1">+ <DownloadIcon className="mr-2 h-5 w-5" />+ <Trans>Download</Trans>+ </Button>+ }+ /></div><div className="mt-12 w-full"><EnvelopeRendererFileSelector className="mb-4 p-0" fields={[]} secondaryOverride={''} />- <PDFViewerKonvaLazy customPageRenderer={EnvelopeGenericPageRenderer} />+ <PDFViewerKonvaLazy renderer="preview" customPageRenderer={EnvelopeGenericPageRenderer} /></div></div>);diff --git a/apps/remix/app/components/general/document/document-drop-zone-wrapper.tsx b/apps/remix/app/components/general/document/document-drop-zone-wrapper.tsxindex 01cee5ad3..2dbe7e59c 100644--- a/apps/remix/app/components/general/document/document-drop-zone-wrapper.tsx+++ b/apps/remix/app/components/general/document/document-drop-zone-wrapper.tsx@@ -16,9 +16,9 @@ import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT, IS_BILLING_ENABLED } from '@documenso/limport { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { megabytesToBytes } from '@documenso/lib/universal/unit-convertions';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { formatDocumentsPath } from '@documenso/lib/utils/teams';import { trpc } from '@documenso/trpc/react';+import type { TCreateDocumentPayloadSchema } from '@documenso/trpc/server/document-router/create-document.types';import { cn } from '@documenso/ui/lib/utils';import { useToast } from '@documenso/ui/primitives/use-toast';@@ -62,14 +62,18 @@ export const DocumentDropZoneWrapper = ({ children, className }: DocumentDropZontry {setIsLoading(true);- const response = await putPdfFile(file);-- const { legacyDocumentId: id } = await createDocument({+ const payload = {title: file.name,- documentDataId: response.id,- timezone: userTimezone, // Note: When migrating to v2 document upload remember to pass this through as a 'userTimezone' field.+ timezone: userTimezone,folderId: folderId ?? undefined,- });+ } satisfies TCreateDocumentPayloadSchema;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));+ formData.append('file', file);++ const { envelopeId: id } = await createDocument(formData);void refreshLimits();diff --git a/apps/remix/app/components/general/document/document-edit-form.tsx b/apps/remix/app/components/general/document/document-edit-form.tsxindex 0b731fa35..e31224f70 100644--- a/apps/remix/app/components/general/document/document-edit-form.tsx+++ b/apps/remix/app/components/general/document/document-edit-form.tsx@@ -441,9 +441,10 @@ export const DocumentEditForm = ({><CardContent className="p-2"><PDFViewer- key={document.documentData.id}- documentData={document.documentData}- document={document}+ key={document.envelopeItems[0].id}+ envelopeItem={document.envelopeItems[0]}+ token={undefined}+ version="signed"onDocumentLoad={() => setIsDocumentPdfLoaded(true)}/></CardContent>diff --git a/apps/remix/app/components/general/document/document-page-view-button.tsx b/apps/remix/app/components/general/document/document-page-view-button.tsxindex 361109580..e3e7e0afc 100644--- a/apps/remix/app/components/general/document/document-page-view-button.tsx+++ b/apps/remix/app/components/general/document/document-page-view-button.tsx@@ -1,18 +1,14 @@-import { msg } from '@lingui/core/macro';-import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';import { DocumentStatus, RecipientRole, SigningStatus } from '@prisma/client';import { CheckCircle, Download, EyeIcon, Pencil } from 'lucide-react';import { Link } from 'react-router';import { match } from 'ts-pattern';-import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { useSession } from '@documenso/lib/client-only/providers/session';import type { TEnvelope } from '@documenso/lib/types/envelope';import { isDocumentCompleted } from '@documenso/lib/utils/document';import { formatDocumentsPath } from '@documenso/lib/utils/teams';import { Button } from '@documenso/ui/primitives/button';-import { useToast } from '@documenso/ui/primitives/use-toast';import { EnvelopeDownloadDialog } from '~/components/dialogs/envelope-download-dialog';@@ -23,9 +19,6 @@ export type DocumentPageViewButtonProps = {export const DocumentPageViewButton = ({ envelope }: DocumentPageViewButtonProps) => {const { user } = useSession();- const { toast } = useToast();- const { _ } = useLingui();-const recipient = envelope.recipients.find((recipient) => recipient.email === user.email);const isRecipient = !!recipient;@@ -37,25 +30,6 @@ export const DocumentPageViewButton = ({ envelope }: DocumentPageViewButtonPropsconst documentsPath = formatDocumentsPath(envelope.team.url);const formatPath = `${documentsPath}/${envelope.id}/edit`;- const onDownloadClick = async () => {- try {- // Todo; Envelopes - Support multiple items- const envelopeItem = envelope.envelopeItems[0];-- if (!envelopeItem.documentData) {- throw new Error('No document available');- }-- await downloadPDF({ documentData: envelopeItem.documentData, fileName: envelopeItem.title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-return match({isRecipient,isPending,@@ -95,7 +69,7 @@ export const DocumentPageViewButton = ({ envelope }: DocumentPageViewButtonProps</Link></Button>))- .with({ isComplete: true, internalVersion: 2 }, () => (+ .with({ isComplete: true }, () => (<EnvelopeDownloadDialogenvelopeId={envelope.id}envelopeStatus={envelope.status}@@ -109,11 +83,5 @@ export const DocumentPageViewButton = ({ envelope }: DocumentPageViewButtonProps}/>))- .with({ isComplete: true }, () => (- <Button className="w-full" onClick={onDownloadClick}>- <Download className="-ml-1 mr-2 inline h-4 w-4" />- <Trans>Download</Trans>- </Button>- )).otherwise(() => null);};diff --git a/apps/remix/app/components/general/document/document-page-view-dropdown.tsx b/apps/remix/app/components/general/document/document-page-view-dropdown.tsxindex c5b6c9371..282740369 100644--- a/apps/remix/app/components/general/document/document-page-view-dropdown.tsx+++ b/apps/remix/app/components/general/document/document-page-view-dropdown.tsx@@ -1,6 +1,5 @@import { useState } from 'react';-import { msg } from '@lingui/core/macro';import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';import { DocumentStatus } from '@prisma/client';@@ -16,13 +15,11 @@ import {} from 'lucide-react';import { Link, useNavigate } from 'react-router';-import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { useSession } from '@documenso/lib/client-only/providers/session';import type { TEnvelope } from '@documenso/lib/types/envelope';import { isDocumentCompleted } from '@documenso/lib/utils/document';import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';import { formatDocumentsPath } from '@documenso/lib/utils/teams';-import { trpc as trpcClient } from '@documenso/trpc/client';import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';import {DropdownMenu,@@ -67,64 +64,6 @@ export const DocumentPageViewDropdown = ({ envelope }: DocumentPageViewDropdownPconst documentsPath = formatDocumentsPath(team.url);- const onDownloadClick = async () => {- try {- const documentWithData = await trpcClient.document.get.query(- {- documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),- },- {- context: {- teamId: team?.id?.toString(),- },- },- );-- const documentData = documentWithData?.documentData;-- if (!documentData) {- return;- }-- await downloadPDF({ documentData, fileName: envelope.title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-- const onDownloadOriginalClick = async () => {- try {- const documentWithData = await trpcClient.document.get.query(- {- documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),- },- {- context: {- teamId: team?.id?.toString(),- },- },- );-- const documentData = documentWithData?.documentData;-- if (!documentData) {- return;- }-- await downloadPDF({ documentData, fileName: envelope.title, version: 'original' });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-const nonSignedRecipients = envelope.recipients.filter((item) => item.signingStatus !== 'SIGNED');return (@@ -147,36 +86,20 @@ export const DocumentPageViewDropdown = ({ envelope }: DocumentPageViewDropdownP</DropdownMenuItem>)}- {envelope.internalVersion === 2 ? (- <EnvelopeDownloadDialog- envelopeId={envelope.id}- envelopeStatus={envelope.status}- token={recipient?.token}- envelopeItems={envelope.envelopeItems}- trigger={- <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>- <div>- <Download className="mr-2 h-4 w-4" />- <Trans>Download</Trans>- </div>- </DropdownMenuItem>- }- />- ) : (- <>- {isComplete && (- <DropdownMenuItem onClick={onDownloadClick}>+ <EnvelopeDownloadDialog+ envelopeId={envelope.id}+ envelopeStatus={envelope.status}+ token={recipient?.token}+ envelopeItems={envelope.envelopeItems}+ trigger={+ <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>+ <div><Download className="mr-2 h-4 w-4" /><Trans>Download</Trans>- </DropdownMenuItem>- )}-- <DropdownMenuItem onClick={onDownloadOriginalClick}>- <Download className="mr-2 h-4 w-4" />- <Trans>Download Original</Trans>+ </div></DropdownMenuItem>- </>- )}+ }+ /><DropdownMenuItem asChild><Link to={`${documentsPath}/${envelope.id}/logs`}>@@ -250,7 +173,8 @@ export const DocumentPageViewDropdown = ({ envelope }: DocumentPageViewDropdownP{isDuplicateDialogOpen && (<DocumentDuplicateDialog- id={mapSecondaryIdToDocumentId(envelope.secondaryId)}+ id={envelope.id}+ token={recipient?.token}open={isDuplicateDialogOpen}onOpenChange={setDuplicateDialogOpen}/>diff --git a/apps/remix/app/components/general/document/document-upload-button.tsx b/apps/remix/app/components/general/document/document-upload-button.tsxindex 7e092363e..ea95bae23 100644--- a/apps/remix/app/components/general/document/document-upload-button.tsx+++ b/apps/remix/app/components/general/document/document-upload-button.tsx@@ -13,9 +13,9 @@ import { useSession } from '@documenso/lib/client-only/providers/session';import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { formatDocumentsPath } from '@documenso/lib/utils/teams';import { trpc } from '@documenso/trpc/react';+import type { TCreateDocumentPayloadSchema } from '@documenso/trpc/server/document-router/create-document.types';import { cn } from '@documenso/ui/lib/utils';import { DocumentDropzone } from '@documenso/ui/primitives/document-upload';import {@@ -73,14 +73,18 @@ export const DocumentUploadButton = ({ className }: DocumentUploadButtonProps) =try {setIsLoading(true);- const response = await putPdfFile(file);-- const { legacyDocumentId: id } = await createDocument({+ const payload = {title: file.name,- documentDataId: response.id,timezone: userTimezone,folderId: folderId ?? undefined,- });+ } satisfies TCreateDocumentPayloadSchema;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));+ formData.append('file', file);++ const { envelopeId: id } = await createDocument(formData);void refreshLimits();diff --git a/apps/remix/app/components/general/document/envelope-upload-button.tsx b/apps/remix/app/components/general/document/envelope-upload-button.tsxindex 645c3845f..218235706 100644--- a/apps/remix/app/components/general/document/envelope-upload-button.tsx+++ b/apps/remix/app/components/general/document/envelope-upload-button.tsx@@ -14,9 +14,9 @@ import { useSession } from '@documenso/lib/client-only/providers/session';import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';import { TIME_ZONES } from '@documenso/lib/constants/time-zones';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { formatDocumentsPath, formatTemplatesPath } from '@documenso/lib/utils/teams';import { trpc } from '@documenso/trpc/react';+import type { TCreateEnvelopePayload } from '@documenso/trpc/server/envelope-router/create-envelope.types';import { cn } from '@documenso/ui/lib/utils';import { DocumentDropzone } from '@documenso/ui/primitives/document-upload';import {@@ -78,35 +78,24 @@ export const EnvelopeUploadButton = ({ className, type, folderId }: EnvelopeUplotry {setIsLoading(true);- const result = await Promise.all(- files.map(async (file) => {- try {- const response = await putPdfFile(file);-- return {- title: file.name,- documentDataId: response.id,- };- } catch (err) {- console.error(err);- throw new Error('Failed to upload document');- }- }),- );-- const envelopeItemsToCreate = result.filter(- (item): item is { title: string; documentDataId: string } => item !== undefined,- );-- const { id } = await createEnvelope({+ const payload = {folderId,type,title: files[0].name,- items: envelopeItemsToCreate,meta: {timezone: userTimezone,},- }).catch((error) => {+ } satisfies TCreateEnvelopePayload;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));++ for (const file of files) {+ formData.append('files', file);+ }++ const { id } = await createEnvelope(formData).catch((error) => {console.error(error);throw error;diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page-renderer.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page-renderer.tsxindex c75fb52a5..5c26e5a5d 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page-renderer.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page-renderer.tsx@@ -26,7 +26,7 @@ import { fieldButtonList } from './envelope-editor-fields-drag-drop';export default function EnvelopeEditorFieldsPageRenderer() {const { t, i18n } = useLingui();const { envelope, editorFields, getRecipientColorKey } = useCurrentEnvelopeEditor();- const { currentEnvelopeItem } = useCurrentEnvelopeRender();+ const { currentEnvelopeItem, setRenderError } = useCurrentEnvelopeRender();const interactiveTransformer = useRef<Transformer | null>(null);@@ -103,7 +103,6 @@ export default function EnvelopeEditorFieldsPageRenderer() {fieldUpdates.height = fieldPageHeight;}- // Todo: envelopes Use ideditorFields.updateFieldByFormId(fieldFormId, fieldUpdates);// Select the field if it is not already selected.@@ -114,7 +113,7 @@ export default function EnvelopeEditorFieldsPageRenderer() {pageLayer.current?.batchDraw();};- const renderFieldOnLayer = (field: TLocalField) => {+ const unsafeRenderFieldOnLayer = (field: TLocalField) => {if (!pageLayer.current) {return;}@@ -160,6 +159,15 @@ export default function EnvelopeEditorFieldsPageRenderer() {fieldGroup.on('dragend', handleResizeOrMove);};+ const renderFieldOnLayer = (field: TLocalField) => {+ try {+ unsafeRenderFieldOnLayer(field);+ } catch (err) {+ console.error(err);+ setRenderError(true);+ }+ };+/*** Initialize the Konva page canvas and all fields and interactions.*/diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page.tsxindex 4bd0915da..ceb8e072a 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-fields-page.tsx@@ -27,7 +27,8 @@ import type {import { canRecipientFieldsBeModified } from '@documenso/lib/utils/recipients';import { AnimateGenericFadeInOut } from '@documenso/ui/components/animate/animate-generic-fade-in-out';import PDFViewerKonvaLazy from '@documenso/ui/components/pdf-viewer/pdf-viewer-konva-lazy';-import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';+import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';+import { Button } from '@documenso/ui/primitives/button';import { RecipientSelector } from '@documenso/ui/primitives/recipient-selector';import { Separator } from '@documenso/ui/primitives/separator';@@ -112,9 +113,34 @@ export const EnvelopeEditorFieldsPage = () => {<EnvelopeRendererFileSelector fields={editorFields.localFields} />{/* Document View */}- <div className="mt-4 flex h-full justify-center p-4">+ <div className="mt-4 flex flex-col items-center justify-center">+ {envelope.recipients.length === 0 && (+ <Alert+ variant="neutral"+ className="border-border bg-background mb-4 flex max-w-[800px] flex-row items-center justify-between space-y-0 rounded-sm border"+ >+ <div className="flex flex-col gap-1">+ <AlertTitle>+ <Trans>Missing Recipients</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>You need at least one recipient to add fields</Trans>+ </AlertDescription>+ </div>++ <Button asChild variant="outline">+ <Link to={`${relativePath.editorPath}`}>+ <Trans>Add Recipients</Trans>+ </Link>+ </Button>+ </Alert>+ )}+{currentEnvelopeItem !== null ? (- <PDFViewerKonvaLazy customPageRenderer={EnvelopeEditorFieldsPageRenderer} />+ <PDFViewerKonvaLazy+ renderer="editor"+ customPageRenderer={EnvelopeEditorFieldsPageRenderer}+ />) : (<div className="flex flex-col items-center justify-center py-32"><FileTextIcon className="text-muted-foreground h-10 w-10" />@@ -130,7 +156,7 @@ export const EnvelopeEditorFieldsPage = () => {</div>{/* Right Section - Form Fields Panel */}- {currentEnvelopeItem && (+ {currentEnvelopeItem && envelope.recipients.length > 0 && (<div className="bg-background border-border sticky top-0 h-full w-80 flex-shrink-0 overflow-y-auto border-l py-4">{/* Recipient selector section. */}<section className="px-4">@@ -138,29 +164,15 @@ export const EnvelopeEditorFieldsPage = () => {<Trans>Selected Recipient</Trans></h3>- {envelope.recipients.length === 0 ? (- <Alert variant="warning">- <AlertDescription className="flex flex-col gap-2">- <Trans>You need at least one recipient to add fields</Trans>-- <Link to={`${relativePath.editorPath}`} className="text-sm">- <p>- <Trans>Click here to add a recipient</Trans>- </p>- </Link>- </AlertDescription>- </Alert>- ) : (- <RecipientSelector- selectedRecipient={editorFields.selectedRecipient}- onSelectedRecipientChange={(recipient) =>- editorFields.setSelectedRecipient(recipient.id)- }- recipients={envelope.recipients}- className="w-full"- align="end"- />- )}+ <RecipientSelector+ selectedRecipient={editorFields.selectedRecipient}+ onSelectedRecipientChange={(recipient) =>+ editorFields.setSelectedRecipient(recipient.id)+ }+ recipients={envelope.recipients}+ className="w-full"+ align="end"+ />{editorFields.selectedRecipient &&!canRecipientFieldsBeModified(editorFields.selectedRecipient, envelope.fields) && (diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsxindex e57740cd1..1232573ac 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx@@ -1,10 +1,20 @@-import { lazy, useEffect, useState } from 'react';+import { lazy, useEffect, useMemo, useState } from 'react';+import { faker } from '@faker-js/faker/locale/en';import { Trans } from '@lingui/react/macro';-import { ConstructionIcon, FileTextIcon } from 'lucide-react';+import { FieldType } from '@prisma/client';+import { FileTextIcon } from 'lucide-react';+import { match } from 'ts-pattern';import { useCurrentEnvelopeEditor } from '@documenso/lib/client-only/providers/envelope-editor-provider';-import { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/envelope-render-provider';+import {+ EnvelopeRenderProvider,+ useCurrentEnvelopeRender,+} from '@documenso/lib/client-only/providers/envelope-render-provider';+import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';+import { extractFieldInsertionValues } from '@documenso/lib/utils/envelope-signing';+import { toCheckboxCustomText } from '@documenso/lib/utils/fields';+import { extractInitials } from '@documenso/lib/utils/recipient-formatter';import { AnimateGenericFadeInOut } from '@documenso/ui/components/animate/animate-generic-fade-in-out';import PDFViewerKonvaLazy from '@documenso/ui/components/pdf-viewer/pdf-viewer-konva-lazy';import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';@@ -15,15 +25,169 @@ import { EnvelopeRendererFileSelector } from './envelope-file-selector';const EnvelopeGenericPageRenderer = lazy(async () => import('./envelope-generic-page-renderer'));+// Todo: Envelopes - Dynamically import fakerexport const EnvelopeEditorPreviewPage = () => {const { envelope, editorFields } = useCurrentEnvelopeEditor();- const { currentEnvelopeItem } = useCurrentEnvelopeRender();+ const { currentEnvelopeItem, fields } = useCurrentEnvelopeRender();const [selectedPreviewMode, setSelectedPreviewMode] = useState<'recipient' | 'signed'>('recipient',);+ const fieldsWithPlaceholders = useMemo(() => {+ return fields.map((field) => {+ const fieldMeta = ZFieldAndMetaSchema.parse(field);++ const recipient = envelope.recipients.find((recipient) => recipient.id === field.recipientId);++ if (!recipient) {+ throw new Error('Recipient not found');+ }++ faker.seed(recipient.id);++ const recipientName = recipient.name || faker.person.fullName();+ const recipientEmail = recipient.email || faker.internet.email();++ faker.seed(recipient.id + field.id);++ return {+ ...field,+ inserted: true,+ ...match(fieldMeta)+ .with({ type: FieldType.TEXT }, ({ fieldMeta }) => {+ let text = fieldMeta?.text || faker.lorem.words(5);++ if (fieldMeta?.characterLimit) {+ text = text.slice(0, fieldMeta?.characterLimit);+ }++ return {+ customText: text,+ };+ })+ .with({ type: FieldType.NUMBER }, ({ fieldMeta }) => {+ let number = fieldMeta?.value ?? '';++ if (number === '') {+ number = faker.number+ .int({+ min: fieldMeta?.minValue ?? 0,+ max: fieldMeta?.maxValue ?? 1000,+ })+ .toString();+ }++ return {+ customText: number,+ };+ })+ .with({ type: FieldType.DATE }, () => {+ const date = extractFieldInsertionValues({+ fieldValue: {+ type: FieldType.DATE,+ value: true,+ },+ field,+ documentMeta: envelope.documentMeta,+ });++ return {+ customText: date.customText,+ };+ })+ .with({ type: FieldType.EMAIL }, () => {+ return {+ customText: recipientEmail,+ };+ })+ .with({ type: FieldType.NAME }, () => {+ return {+ customText: recipientName,+ };+ })+ .with({ type: FieldType.INITIALS }, () => {+ return {+ customText: extractInitials(recipientName),+ };+ })+ .with({ type: FieldType.RADIO }, ({ fieldMeta }) => {+ const values = fieldMeta?.values ?? [];++ if (values.length === 0) {+ return '';+ }++ let customText = '';++ const preselectedValue = values.findIndex((value) => value.checked);++ if (preselectedValue !== -1) {+ customText = preselectedValue.toString();+ } else {+ const randomIndex = faker.number.int({ min: 0, max: values.length - 1 });+ customText = randomIndex.toString();+ }++ return {+ customText,+ };+ })+ .with({ type: FieldType.CHECKBOX }, ({ fieldMeta }) => {+ let checkedValues: number[] = [];++ const values = fieldMeta?.values ?? [];++ values.forEach((value, index) => {+ if (value.checked) {+ checkedValues.push(index);+ }+ });++ if (checkedValues.length === 0 && values.length > 0) {+ const numberOfValues = fieldMeta?.validationLength || 1;++ checkedValues = Array.from({ length: numberOfValues }, (_, index) => index);+ }++ return {+ customText: toCheckboxCustomText(checkedValues),+ };+ })+ .with({ type: FieldType.DROPDOWN }, ({ fieldMeta }) => {+ const values = fieldMeta?.values ?? [];++ let customText = fieldMeta?.defaultValue || '';++ if (!customText && values.length > 0) {+ const randomIndex = faker.number.int({ min: 0, max: values.length - 1 });+ customText = values[randomIndex].value;+ }++ return {+ customText,+ };+ })+ .with({ type: FieldType.SIGNATURE }, () => {+ return {+ customText: '',+ signature: {+ signatureImageAsBase64: '',+ typedSignature: recipientName,+ },+ };+ })+ .with({ type: FieldType.FREE_SIGNATURE }, () => {+ return {+ customText: '',+ };+ })+ .exhaustive(),+ };+ });+ }, [fields, envelope, envelope.recipients, envelope.documentMeta]);+/*** Set the selected recipient to the first recipient in the envelope.*/@@ -31,40 +195,38 @@ export const EnvelopeEditorPreviewPage = () => {editorFields.setSelectedRecipient(envelope.recipients[0]?.id ?? null);}, []);+ // Override the parent renderer provider so we can inject custom fields.return (- <div className="relative flex h-full">- <div className="flex w-full flex-col overflow-y-auto">- {/* Horizontal envelope item selector */}- <EnvelopeRendererFileSelector fields={editorFields.localFields} />-- {/* Document View */}- <div className="mt-4 flex flex-col items-center justify-center">- <Alert variant="warning" className="mb-4 max-w-[800px]">- <AlertTitle>- <Trans>Preview Mode</Trans>- </AlertTitle>- <AlertDescription>- <Trans>Preview what the signed document will look like with placeholder data</Trans>- </AlertDescription>- </Alert>-- {/* Coming soon section */}- <div className="border-border bg-card hover:bg-accent/10 flex w-full max-w-[800px] items-center gap-4 rounded-lg border p-4 transition-colors">- <div className="flex w-full flex-col items-center justify-center gap-2 py-32">- <ConstructionIcon className="text-muted-foreground h-10 w-10" />- <h3 className="text-foreground text-sm font-semibold">- <Trans>Coming soon</Trans>- </h3>- <p className="text-muted-foreground text-sm">- <Trans>This feature is coming soon</Trans>- </p>- </div>- </div>+ <EnvelopeRenderProvider+ envelope={envelope}+ token={undefined}+ fields={fieldsWithPlaceholders}+ recipients={envelope.recipients}+ overrideSettings={{+ mode: 'export',+ }}+ >+ <div className="relative flex h-full">+ <div className="flex w-full flex-col overflow-y-auto">+ {/* Horizontal envelope item selector */}+ <EnvelopeRendererFileSelector fields={editorFields.localFields} />++ {/* Document View */}+ <div className="mt-4 flex flex-col items-center justify-center">+ <Alert variant="warning" className="mb-4 max-w-[800px]">+ <AlertTitle>+ <Trans>Preview Mode</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>Preview what the signed document will look like with placeholder data</Trans>+ </AlertDescription>+ </Alert>- {/* Todo: Envelopes - Remove div after preview mode is implemented */}- <div className="hidden">{currentEnvelopeItem !== null ? (- <PDFViewerKonvaLazy customPageRenderer={EnvelopeGenericPageRenderer} />+ <PDFViewerKonvaLazy+ renderer="editor"+ customPageRenderer={EnvelopeGenericPageRenderer}+ />) : (<div className="flex flex-col items-center justify-center py-32"><FileTextIcon className="text-muted-foreground h-10 w-10" />@@ -78,27 +240,28 @@ export const EnvelopeEditorPreviewPage = () => {)}</div></div>- </div>- {/* Right Section - Form Fields Panel */}- {currentEnvelopeItem && false && (- <div className="sticky top-0 h-full w-80 flex-shrink-0 overflow-y-auto border-l border-gray-200 bg-white py-4">- {/* Add fields section. */}- <section className="px-4">- {/* <h3 className="mb-2 text-sm font-semibold text-gray-900">+ {/* Right Section - Form Fields Panel */}+ {currentEnvelopeItem && false && (+ <div className="sticky top-0 h-full w-80 flex-shrink-0 overflow-y-auto border-l border-gray-200 bg-white py-4">+ {/* Add fields section. */}+ <section className="px-4">+ {/* <h3 className="mb-2 text-sm font-semibold text-gray-900"><Trans>Preivew Mode</Trans></h3> */}- <Alert variant="neutral">- <AlertTitle>- <Trans>Preview Mode</Trans>- </AlertTitle>- <AlertDescription>- <Trans>Preview what the signed document will look like with placeholder data</Trans>- </AlertDescription>- </Alert>+ <Alert variant="neutral">+ <AlertTitle>+ <Trans>Preview Mode</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Preview what the signed document will look like with placeholder data+ </Trans>+ </AlertDescription>+ </Alert>- {/* <Alert variant="neutral">+ {/* <Alert variant="neutral"><RadioGroupclassName="gap-y-1"value={selectedPreviewMode}@@ -137,36 +300,37 @@ export const EnvelopeEditorPreviewPage = () => {<div>Preview what a recipient will see</div><div>Preview the signed document</div> */}- </section>-- {false && (- <AnimateGenericFadeInOut key={selectedPreviewMode}>- {selectedPreviewMode === 'recipient' && (- <>- <Separator className="my-4" />-- {/* Recipient selector section. */}- <section className="px-4">- <h3 className="mb-2 text-sm font-semibold text-gray-900">- <Trans>Selected Recipient</Trans>- </h3>-- <RecipientSelector- selectedRecipient={editorFields.selectedRecipient}- onSelectedRecipientChange={(recipient) =>- editorFields.setSelectedRecipient(recipient.id)- }- recipients={envelope.recipients}- className="w-full"- align="end"- />- </section>- </>- )}- </AnimateGenericFadeInOut>- )}- </div>- )}- </div>+ </section>++ {false && (+ <AnimateGenericFadeInOut key={selectedPreviewMode}>+ {selectedPreviewMode === 'recipient' && (+ <>+ <Separator className="my-4" />++ {/* Recipient selector section. */}+ <section className="px-4">+ <h3 className="mb-2 text-sm font-semibold text-gray-900">+ <Trans>Selected Recipient</Trans>+ </h3>++ <RecipientSelector+ selectedRecipient={editorFields.selectedRecipient}+ onSelectedRecipientChange={(recipient) =>+ editorFields.setSelectedRecipient(recipient.id)+ }+ recipients={envelope.recipients}+ className="w-full"+ align="end"+ />+ </section>+ </>+ )}+ </AnimateGenericFadeInOut>+ )}+ </div>+ )}+ </div>+ </EnvelopeRenderProvider>);};diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-recipient-form.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-recipient-form.tsxindex ef8a1288c..375524e68 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-recipient-form.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-recipient-form.tsx@@ -482,30 +482,46 @@ export const EnvelopeEditorRecipientForm = () => {const { data } = validatedFormValues;+ // Weird edge case where the whole envelope is created via API+ // with no signing order. If they come to this page it will show an error+ // since they aren't equal and the recipient is no longer editable.+ const envelopeRecipients = data.signers.map((recipient) => {+ if (!canRecipientBeModified(recipient.id)) {+ return {+ ...recipient,+ signingOrder: recipient.signingOrder,+ };+ }+ return recipient;+ });+const hasSigningOrderChanged = envelope.documentMeta.signingOrder !== data.signingOrder;const hasAllowDictateNextSignerChanged =envelope.documentMeta.allowDictateNextSigner !== data.allowDictateNextSigner;const hasSignersChanged =- data.signers.length !== recipients.length ||- data.signers.some((signer) => {+ envelopeRecipients.length !== recipients.length ||+ envelopeRecipients.some((signer) => {const recipient = recipients.find((recipient) => recipient.id === signer.id);if (!recipient) {return true;}+ const signerActionAuth = signer.actionAuth;+ const recipientActionAuth = recipient.authOptions?.actionAuth || [];+return (signer.email !== recipient.email ||signer.name !== recipient.name ||signer.role !== recipient.role ||signer.signingOrder !== recipient.signingOrder ||- !isDeepEqual(signer.actionAuth, recipient.authOptions?.actionAuth)+ !isDeepEqual(signerActionAuth, recipientActionAuth));});if (hasSignersChanged) {- setRecipientsDebounced(validatedFormValues.data.signers);+ setRecipientsDebounced(envelopeRecipients);}if (hasSigningOrderChanged || hasAllowDictateNextSignerChanged) {diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-settings-dialog.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-settings-dialog.tsxindex 0c505d55c..6593609f5 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-settings-dialog.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-settings-dialog.tsx@@ -174,7 +174,7 @@ export const EnvelopeEditorSettingsDialog = ({const { t, i18n } = useLingui();const { toast } = useToast();- const { envelope } = useCurrentEnvelopeEditor();+ const { envelope, updateEnvelopeAsync } = useCurrentEnvelopeEditor();const team = useCurrentTeam();const organisation = useCurrentOrganisation();@@ -186,14 +186,12 @@ export const EnvelopeEditorSettingsDialog = ({documentAuth: envelope.authOptions,});- const form = useForm<TAddSettingsFormSchema>({- resolver: zodResolver(ZAddSettingsFormSchema),- defaultValues: {- externalId: envelope.externalId || '', // Todo: String or undefined?+ const createDefaultValues = () => {+ return {+ externalId: envelope.externalId || '',visibility: envelope.visibility || '',globalAccessAuth: documentAuthOption?.globalAccessAuth || [],globalActionAuth: documentAuthOption?.globalActionAuth || [],-meta: {subject: envelope.documentMeta.subject ?? '',message: envelope.documentMeta.message ?? '',@@ -210,10 +208,13 @@ export const EnvelopeEditorSettingsDialog = ({emailSettings: ZDocumentEmailSettingsSchema.parse(envelope.documentMeta.emailSettings),signatureTypes: extractTeamSignatureSettings(envelope.documentMeta),},- },- });+ };+ };- const { mutateAsync: updateEnvelope } = trpc.envelope.update.useMutation();+ const form = useForm<TAddSettingsFormSchema>({+ resolver: zodResolver(ZAddSettingsFormSchema),+ defaultValues: createDefaultValues(),+ });const envelopeHasBeenSent =envelope.type === EnvelopeType.DOCUMENT &&@@ -229,7 +230,6 @@ export const EnvelopeEditorSettingsDialog = ({const emails = emailData?.data || [];- // Todo: Envelopes this doesn't make sense (look at previous)const canUpdateVisibility = canAccessTeamDocument(team.currentTeamRole, envelope.visibility);const onFormSubmit = async (data: TAddSettingsFormSchema) => {@@ -240,9 +240,7 @@ export const EnvelopeEditorSettingsDialog = ({.safeParse(data.globalAccessAuth);try {- await updateEnvelope({- envelopeId: envelope.id,- envelopeType: envelope.type,+ await updateEnvelopeAsync({data: {externalId: data.externalId || null,visibility: data.visibility,@@ -297,7 +295,7 @@ export const EnvelopeEditorSettingsDialog = ({]);useEffect(() => {- form.reset();+ form.reset(createDefaultValues());setActiveTab('general');}, [open, form]);@@ -323,7 +321,7 @@ export const EnvelopeEditorSettingsDialog = ({<DialogContent className="flex w-full !max-w-5xl flex-row gap-0 p-0">{/* Sidebar. */}- <div className="flex w-80 flex-col border-r bg-gray-50">+ <div className="bg-accent/20 flex w-80 flex-col border-r"><DialogHeader className="p-6 pb-4"><DialogTitle>Document Settings</DialogTitle></DialogHeader>diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-upload-page.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-upload-page.tsxindex fa19bb6a1..c13ca0d66 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-upload-page.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-upload-page.tsx@@ -18,9 +18,9 @@ import {import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';import { nanoid } from '@documenso/lib/universal/id';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { canEnvelopeItemsBeModified } from '@documenso/lib/utils/envelope';import { trpc } from '@documenso/trpc/react';+import type { TCreateEnvelopeItemsPayload } from '@documenso/trpc/server/envelope-router/create-envelope-items.types';import { Button } from '@documenso/ui/primitives/button';import {Card,@@ -67,8 +67,8 @@ export const EnvelopeEditorUploadPage = () => {const { mutateAsync: createEnvelopeItems, isPending: isCreatingEnvelopeItems } =trpc.envelope.item.createMany.useMutation({- onSuccess: (data) => {- const createdEnvelopes = data.createdEnvelopeItems.filter(+ onSuccess: ({ data }) => {+ const createdEnvelopes = data.filter((item) => !envelope.envelopeItems.find((envelopeItem) => envelopeItem.id === item.id),);@@ -79,10 +79,10 @@ export const EnvelopeEditorUploadPage = () => {});const { mutateAsync: updateEnvelopeItems } = trpc.envelope.item.updateMany.useMutation({- onSuccess: (data) => {+ onSuccess: ({ data }) => {setLocalEnvelope({envelopeItems: envelope.envelopeItems.map((originalItem) => {- const updatedItem = data.updatedEnvelopeItems.find((item) => item.id === originalItem.id);+ const updatedItem = data.find((item) => item.id === originalItem.id);if (updatedItem) {return {@@ -114,36 +114,19 @@ export const EnvelopeEditorUploadPage = () => {setLocalFiles((prev) => [...prev, ...newUploadingFiles]);- const result = await Promise.all(- files.map(async (file, index) => {- try {- const response = await putPdfFile(file);-- // Mark as uploaded (remove from uploading state)- return {- title: file.name,- documentDataId: response.id,- };- } catch (_error) {- setLocalFiles((prev) =>- prev.map((uploadingFile) =>- uploadingFile.id === newUploadingFiles[index].id- ? { ...uploadingFile, isError: true, isUploading: false }- : uploadingFile,- ),- );- }- }),- );+ const payload = {+ envelopeId: envelope.id,+ } satisfies TCreateEnvelopeItemsPayload;- const envelopeItemsToCreate = result.filter(- (item): item is { title: string; documentDataId: string } => item !== undefined,- );+ const formData = new FormData();- const { createdEnvelopeItems } = await createEnvelopeItems({- envelopeId: envelope.id,- items: envelopeItemsToCreate,- }).catch((error) => {+ formData.append('payload', JSON.stringify(payload));++ for (const file of files) {+ formData.append('files', file);+ }++ const { data } = await createEnvelopeItems(formData).catch((error) => {console.error(error);// Set error state on files in batch upload.@@ -165,7 +148,7 @@ export const EnvelopeEditorUploadPage = () => {);return filteredFiles.concat(- createdEnvelopeItems.map((item) => ({+ data.map((item) => ({id: item.id,envelopeItemId: item.id,title: item.title,@@ -203,7 +186,6 @@ export const EnvelopeEditorUploadPage = () => {debouncedUpdateEnvelopeItems(items);};- // Todo: Envelopes - Sync into envelopes dataconst debouncedUpdateEnvelopeItems = useDebounceFunction((files: LocalFile[]) => {void updateEnvelopeItems({envelopeId: envelope.id,diff --git a/apps/remix/app/components/general/envelope-editor/envelope-file-selector.tsx b/apps/remix/app/components/general/envelope-editor/envelope-file-selector.tsxindex 1d570bed7..144a2bc41 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-file-selector.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-file-selector.tsx@@ -29,7 +29,7 @@ export const EnvelopeItemSelector = ({{...buttonProps}><div- className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium ${+ className={`flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-xs font-medium ${isSelected ? 'bg-green-100 text-green-600' : 'bg-gray-200 text-gray-600'}`}>diff --git a/apps/remix/app/components/general/envelope-editor/envelope-generic-page-renderer.tsx b/apps/remix/app/components/general/envelope-editor/envelope-generic-page-renderer.tsxindex f6ae5c5d7..48f13127e 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-generic-page-renderer.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-generic-page-renderer.tsx@@ -1,6 +1,7 @@import { useEffect, useMemo } from 'react';import { useLingui } from '@lingui/react/macro';+import { type Recipient, SigningStatus } from '@prisma/client';import type Konva from 'konva';import { usePageRenderer } from '@documenso/lib/client-only/hooks/use-page-renderer';@@ -8,11 +9,23 @@ import { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/eimport type { TEnvelope } from '@documenso/lib/types/envelope';import { renderField } from '@documenso/lib/universal/field-renderer/render-field';import { getClientSideFieldTranslations } from '@documenso/lib/utils/fields';+import { EnvelopeRecipientFieldTooltip } from '@documenso/ui/components/document/envelope-recipient-field-tooltip';++type GenericLocalField = TEnvelope['fields'][number] & {+ recipient: Pick<Recipient, 'id' | 'name' | 'email' | 'signingStatus'>;+};export default function EnvelopeGenericPageRenderer() {const { i18n } = useLingui();- const { currentEnvelopeItem, fields, getRecipientColorKey } = useCurrentEnvelopeRender();+ const {+ currentEnvelopeItem,+ fields,+ recipients,+ getRecipientColorKey,+ setRenderError,+ overrideSettings,+ } = useCurrentEnvelopeRender();const {stage,@@ -28,44 +41,73 @@ export default function EnvelopeGenericPageRenderer() {const { _className, scale } = pageContext;- const localPageFields = useMemo(- () =>- fields.filter(+ const localPageFields = useMemo((): GenericLocalField[] => {+ return fields+ .filter((field) =>field.page === pageContext.pageNumber && field.envelopeItemId === currentEnvelopeItem?.id,- ),- [fields, pageContext.pageNumber],- );-- const renderFieldOnLayer = (field: TEnvelope['fields'][number]) => {+ )+ .map((field) => {+ const recipient = recipients.find((recipient) => recipient.id === field.recipientId);++ if (!recipient) {+ throw new Error(`Recipient not found for field ${field.id}`);+ }++ return {+ ...field,+ recipient,+ };+ });+ }, [fields, pageContext.pageNumber, currentEnvelopeItem?.id, recipients]);++ const unsafeRenderFieldOnLayer = (field: GenericLocalField) => {if (!pageLayer.current) {console.error('Layer not loaded yet');return;}+ const { recipient } = field;++ const fieldTranslations = getClientSideFieldTranslations(i18n);++ const isInserted = recipient.signingStatus === SigningStatus.SIGNED && field.inserted;+renderField({scale,pageLayer: pageLayer.current,field: {renderId: field.id.toString(),...field,- customText: '',width: Number(field.width),height: Number(field.height),positionX: Number(field.positionX),positionY: Number(field.positionY),- inserted: false,+ customText: isInserted ? field.customText : '',fieldMeta: field.fieldMeta,+ signature: {+ signatureImageAsBase64: '',+ typedSignature: fieldTranslations.SIGNATURE,+ },},- translations: getClientSideFieldTranslations(i18n),+ translations: fieldTranslations,pageWidth: unscaledViewport.width,pageHeight: unscaledViewport.height,color: getRecipientColorKey(field.recipientId),editable: false,- mode: 'sign',+ mode: overrideSettings?.mode ?? 'sign',});};+ const renderFieldOnLayer = (field: GenericLocalField) => {+ try {+ unsafeRenderFieldOnLayer(field);+ } catch (err) {+ console.error(err);+ setRenderError(true);+ }+ };+/*** Initialize the Konva page canvas and all fields and interactions.*/@@ -113,6 +155,16 @@ export default function EnvelopeGenericPageRenderer() {className="relative w-full"key={`${currentEnvelopeItem.id}-renderer-${pageContext.pageNumber}`}>+ {overrideSettings?.showRecipientTooltip &&+ localPageFields.map((field) => (+ <EnvelopeRecipientFieldTooltip+ key={field.id}+ field={field}+ showFieldStatus={overrideSettings?.showRecipientSigningStatus}+ showRecipientTooltip={overrideSettings?.showRecipientTooltip}+ />+ ))}+{/* The element Konva will inject it's canvas into. */}<div className="konva-container absolute inset-0 z-10 w-full" ref={konvaContainer}></div>diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsxindex 98a9173ee..e010e5821 100644--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx@@ -8,6 +8,8 @@ import { Label } from '@documenso/ui/primitives/label';import { RadioGroup, RadioGroupItem } from '@documenso/ui/primitives/radio-group';import { SignaturePadDialog } from '@documenso/ui/primitives/signature-pad/signature-pad-dialog';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';+import { useRequiredEnvelopeSigningContext } from '../document-signing/envelope-signing-provider';export default function EnvelopeSignerForm() {@@ -25,6 +27,8 @@ export default function EnvelopeSignerForm() {setSelectedAssistantRecipientId,} = useRequiredEnvelopeSigningContext();+ const { isNameLocked, isEmailLocked } = useEmbedSigningContext() || {};+const hasSignatureField = useMemo(() => {return recipientFields.some((field) => field.type === FieldType.SIGNATURE);}, [recipientFields]);@@ -37,7 +41,7 @@ export default function EnvelopeSignerForm() {if (recipient.role === RecipientRole.ASSISTANT) {return (- <fieldset className="dark:bg-background border-border rounded-2xl sm:border sm:p-3">+ <fieldset className="embed--DocumentWidgetForm dark:bg-background border-border rounded-2xl sm:border sm:p-3"><RadioGroupclassName="gap-0 space-y-2 shadow-none sm:space-y-3"value={selectedAssistantRecipient?.id?.toString()}@@ -101,7 +105,8 @@ export default function EnvelopeSignerForm() {id="full-name"className="bg-background mt-2"value={fullName}- onChange={(e) => setFullName(e.target.value.trimStart())}+ disabled={isNameLocked}+ onChange={(e) => !isNameLocked && setFullName(e.target.value.trimStart())}/></div>diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-header.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-header.tsxindex b48ee0c55..bf7b2a971 100644--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-header.tsx+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-header.tsx@@ -16,6 +16,7 @@ import {import { Separator } from '@documenso/ui/primitives/separator';import { EnvelopeDownloadDialog } from '~/components/dialogs/envelope-download-dialog';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';import { BrandingLogo } from '~/components/general/branding-logo';import { BrandingLogoIcon } from '../branding-logo-icon';@@ -28,7 +29,7 @@ export const EnvelopeSignerHeader = () => {useRequiredEnvelopeSigningContext();return (- <nav className="bg-background border-border max-w-screen flex flex-row justify-between border-b px-4 py-3 md:px-6">+ <nav className="embed--DocumentWidgetHeader bg-background border-border max-w-screen flex flex-row justify-between border-b px-4 py-3 md:px-6">{/* Left side - Logo and title */}<div className="flex min-w-0 flex-1 items-center space-x-2 md:w-auto md:flex-none"><Link to="/" className="flex-shrink-0">@@ -72,7 +73,7 @@ export const EnvelopeSignerHeader = () => {</div>{/* Right side - Desktop content */}- <div className="hidden items-center space-x-2 md:flex">+ <div className="hidden items-center space-x-2 lg:flex"><p className="text-muted-foreground mr-2 flex-shrink-0 text-sm"><Pluralone="1 Field Remaining"@@ -85,7 +86,7 @@ export const EnvelopeSignerHeader = () => {</div>{/* Mobile Actions button */}- <div className="flex-shrink-0 md:hidden">+ <div className="flex-shrink-0 lg:hidden"><MobileDropdownMenu /></div></nav>@@ -95,6 +96,8 @@ export const EnvelopeSignerHeader = () => {const MobileDropdownMenu = () => {const { envelope, recipient } = useRequiredEnvelopeSigningContext();+ const { allowDocumentRejection } = useEmbedSigningContext() || {};+return (<DropdownMenu><DropdownMenuTrigger asChild>@@ -119,7 +122,7 @@ const MobileDropdownMenu = () => {}/>- {envelope.type === EnvelopeType.DOCUMENT && (+ {envelope.type === EnvelopeType.DOCUMENT && allowDocumentRejection !== false && (<DocumentSigningRejectDialogdocumentId={mapSecondaryIdToDocumentId(envelope.secondaryId)}token={recipient.token}diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsxindex 1c3c324aa..3240f091b 100644--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx@@ -10,15 +10,20 @@ import { usePageRenderer } from '@documenso/lib/client-only/hooks/use-page-rendeimport { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/envelope-render-provider';import { useOptionalSession } from '@documenso/lib/client-only/providers/session';import { DIRECT_TEMPLATE_RECIPIENT_EMAIL } from '@documenso/lib/constants/direct-templates';+import { isBase64Image } from '@documenso/lib/constants/signatures';+import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';import { ZFullFieldSchema } from '@documenso/lib/types/field';import { createSpinner } from '@documenso/lib/universal/field-renderer/field-generic-items';import { renderField } from '@documenso/lib/universal/field-renderer/render-field';import { isFieldUnsignedAndRequired } from '@documenso/lib/utils/advanced-fields-helpers';import { getClientSideFieldTranslations } from '@documenso/lib/utils/fields';import { extractInitials } from '@documenso/lib/utils/recipient-formatter';+import type { TSignEnvelopeFieldValue } from '@documenso/trpc/server/envelope-router/sign-envelope-field.types';import { EnvelopeFieldToolTip } from '@documenso/ui/components/field/envelope-field-tooltip';import type { TRecipientColor } from '@documenso/ui/lib/recipient-colors';+import { useToast } from '@documenso/ui/primitives/use-toast';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';import { handleCheckboxFieldClick } from '~/utils/field-signing/checkbox-field';import { handleDropdownFieldClick } from '~/utils/field-signing/dropdown-field';import { handleEmailFieldClick } from '~/utils/field-signing/email-field';@@ -28,20 +33,24 @@ import { handleNumberFieldClick } from '~/utils/field-signing/number-field';import { handleSignatureFieldClick } from '~/utils/field-signing/signature-field';import { handleTextFieldClick } from '~/utils/field-signing/text-field';+import { useRequiredDocumentSigningAuthContext } from '../document-signing/document-signing-auth-provider';import { useRequiredEnvelopeSigningContext } from '../document-signing/envelope-signing-provider';export default function EnvelopeSignerPageRenderer() {- const { i18n } = useLingui();- const { currentEnvelopeItem } = useCurrentEnvelopeRender();+ const { t, i18n } = useLingui();+ const { currentEnvelopeItem, setRenderError } = useCurrentEnvelopeRender();const { sessionData } = useOptionalSession();+ const { executeActionAuthProcedure } = useRequiredDocumentSigningAuthContext();+ const { toast } = useToast();+const {envelopeData,recipient,recipientFields,recipientFieldsRemaining,showPendingFieldTooltip,- signField,+ signField: signFieldInternal,email,setEmail,fullName,@@ -53,6 +62,8 @@ export default function EnvelopeSignerPageRenderer() {isDirectTemplate,} = useRequiredEnvelopeSigningContext();+ const { onFieldSigned, onFieldUnsigned } = useEmbedSigningContext() || {};+const {stage,pageLayer,@@ -80,7 +91,7 @@ export default function EnvelopeSignerPageRenderer() {);}, [recipientFields, selectedAssistantRecipientFields, pageContext.pageNumber]);- const renderFieldOnLayer = (unparsedField: Field & { signature?: Signature | null }) => {+ const unsafeRenderFieldOnLayer = (unparsedField: Field & { signature?: Signature | null }) => {if (!pageLayer.current) {console.error('Layer not loaded yet');return;@@ -237,7 +248,7 @@ export default function EnvelopeSignerPageRenderer() {.then(async (payload) => {if (payload) {fieldGroup.add(loadingSpinnerGroup);- await signField(field.id, payload); // Todo: Envelopes - Handle errors+ await signField(field.id, payload);}if (payload?.value) {@@ -318,7 +329,6 @@ export default function EnvelopeSignerPageRenderer() {* SIGNATURE FIELD.*/.with({ type: FieldType.SIGNATURE }, (field) => {- // Todo: Envelopes - ReauthhandleSignatureFieldClick({field,signature,@@ -329,11 +339,21 @@ export default function EnvelopeSignerPageRenderer() {.then(async (payload) => {if (payload) {fieldGroup.add(loadingSpinnerGroup);- await signField(field.id, payload);- }- if (payload?.value) {- setSignature(payload.value);+ if (payload.value) {+ void executeActionAuthProcedure({+ onReauthFormSubmit: async (authOptions) => {+ await signField(field.id, payload, authOptions);++ loadingSpinnerGroup.destroy();+ },+ actionTarget: field.type,+ });++ setSignature(payload.value);+ } else {+ await signField(field.id, payload);+ }}}).finally(() => {@@ -347,13 +367,54 @@ export default function EnvelopeSignerPageRenderer() {fieldGroup.on('pointerdown', handleFieldGroupClick);};+ const renderFieldOnLayer = (unparsedField: Field & { signature?: Signature | null }) => {+ try {+ unsafeRenderFieldOnLayer(unparsedField);+ } catch (err) {+ console.error(err);+ setRenderError(true);+ }+ };++ const signField = async (+ fieldId: number,+ payload: TSignEnvelopeFieldValue,+ authOptions?: TRecipientActionAuth,+ ) => {+ try {+ const { inserted } = await signFieldInternal(fieldId, payload, authOptions);++ // ?: The two callbacks below are used within the embedding context+ if (inserted && onFieldSigned) {+ const value = payload.value ? JSON.stringify(payload.value) : undefined;+ const isBase64 = value ? isBase64Image(value) : undefined;++ onFieldSigned({ fieldId, value, isBase64 });+ }++ if (!inserted && onFieldUnsigned) {+ onFieldUnsigned({ fieldId });+ }+ } catch (err) {+ console.error(err);++ toast({+ title: t`Error`,+ description: t`An error occurred while signing the field.`,+ variant: 'destructive',+ });++ throw err;+ }+ };+/*** Initialize the Konva page canvas and all fields and interactions.*/const createPageCanvas = (currentStage: Konva.Stage, currentPageLayer: Konva.Layer) => {// Render the fields.for (const field of localPageFields) {- renderFieldOnLayer(field); // Todo: Envelopes - [CRITICAL] Handle errors which prevent rendering+ renderFieldOnLayer(field);}currentPageLayer.batchDraw();@@ -368,8 +429,7 @@ export default function EnvelopeSignerPageRenderer() {}localPageFields.forEach((field) => {- console.log('Field changed/inserted, rendering on canvas');- renderFieldOnLayer(field); // Todo: Envelopes - [CRITICAL] Handle errors which prevent rendering+ renderFieldOnLayer(field);});pageLayer.current.batchDraw();@@ -387,7 +447,7 @@ export default function EnvelopeSignerPageRenderer() {pageLayer.current.destroyChildren();localPageFields.forEach((field) => {- renderFieldOnLayer(field); // Todo: Envelopes - [CRITICAL] Handle errors which prevent rendering+ renderFieldOnLayer(field);});pageLayer.current.batchDraw();diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsxindex 8b8e64fa5..ce15e2791 100644--- a/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx+++ b/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx@@ -2,16 +2,19 @@ import { useMemo } from 'react';import { useLingui } from '@lingui/react/macro';import { FieldType } from '@prisma/client';-import { useNavigate, useSearchParams } from 'react-router';+import { useNavigate, useRevalidator, useSearchParams } from 'react-router';import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';import { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/envelope-render-provider';import { isBase64Image } from '@documenso/lib/constants/signatures';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import type { TRecipientAccessAuth } from '@documenso/lib/types/document-auth';import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';import { trpc } from '@documenso/trpc/react';import { useToast } from '@documenso/ui/primitives/use-toast';+import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';+import { DocumentSigningCompleteDialog } from '../document-signing/document-signing-complete-dialog';import { useRequiredEnvelopeSigningContext } from '../document-signing/envelope-signing-provider';@@ -19,8 +22,9 @@ export const EnvelopeSignerCompleteDialog = () => {const navigate = useNavigate();const analytics = useAnalytics();- const { toast } = useToast();const { t } = useLingui();+ const { toast } = useToast();+ const { revalidate } = useRevalidator();const [searchParams] = useSearchParams();@@ -37,6 +41,8 @@ export const EnvelopeSignerCompleteDialog = () => {const { currentEnvelopeItem, setCurrentEnvelopeItem } = useCurrentEnvelopeRender();+ const { onDocumentCompleted, onDocumentError } = useEmbedSigningContext() || {};+const { mutateAsync: completeDocument, isPending } =trpc.recipient.completeDocumentWithToken.useMutation();@@ -68,25 +74,54 @@ export const EnvelopeSignerCompleteDialog = () => {nextSigner?: { name: string; email: string },accessAuthOptions?: TRecipientAccessAuth,) => {- const payload = {- token: recipient.token,- documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),- authOptions: accessAuthOptions,- ...(nextSigner?.email && nextSigner?.name ? { nextSigner } : {}),- };+ try {+ const payload = {+ token: recipient.token,+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),+ authOptions: accessAuthOptions,+ ...(nextSigner?.email && nextSigner?.name ? { nextSigner } : {}),+ };++ await completeDocument(payload);++ analytics.capture('App: Recipient has completed signing', {+ signerId: recipient.id,+ documentId: envelope.id,+ timestamp: new Date().toISOString(),+ });++ if (onDocumentCompleted) {+ onDocumentCompleted({+ token: recipient.token,+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),+ recipientId: recipient.id,+ envelopeId: envelope.id,+ });- await completeDocument(payload);+ await revalidate();- analytics.capture('App: Recipient has completed signing', {- signerId: recipient.id,- documentId: envelope.id,- timestamp: new Date().toISOString(),- });+ return;+ }- if (envelope.documentMeta.redirectUrl) {- window.location.href = envelope.documentMeta.redirectUrl;- } else {- await navigate(`/sign/${recipient.token}/complete`);+ if (envelope.documentMeta.redirectUrl) {+ window.location.href = envelope.documentMeta.redirectUrl;+ } else {+ await navigate(`/sign/${recipient.token}/complete`);+ }+ } catch (err) {+ const error = AppError.parseError(err);++ if (error.code !== AppErrorCode.TWO_FACTOR_AUTH_FAILED) {+ toast({+ title: t`Something went wrong`,+ description: t`We were unable to submit this document at this time. Please try again later.`,+ variant: 'destructive',+ });++ onDocumentError?.();+ }++ throw err;}};@@ -105,8 +140,12 @@ export const EnvelopeSignerCompleteDialog = () => {directTemplateExternalId = decodeURIComponent(directTemplateExternalId);}+ if (!recipient.directToken) {+ throw new Error('Recipient direct token is required');+ }+const { token } = await createDocumentFromDirectTemplate({- directTemplateToken: recipient.token, // The direct template token is inserted into the recipient token for ease of use.+ directTemplateToken: recipient.directToken, // The direct template token is inserted into the recipient token for ease of use.directTemplateExternalId,directRecipientName: recipientDetails?.name || fullName,directRecipientEmail: recipientDetails?.email || email,@@ -132,18 +171,31 @@ export const EnvelopeSignerCompleteDialog = () => {const redirectUrl = envelope.documentMeta.redirectUrl;+ if (onDocumentCompleted) {+ await navigate({+ pathname: `/embed/sign/${token}`,+ search: window.location.search,+ hash: window.location.hash,+ });++ return;+ }+if (redirectUrl) {window.location.href = redirectUrl;} else {await navigate(`/sign/${token}/complete`);}} catch (err) {+ console.log('err', err);toast({title: t`Something went wrong`,description: t`We were unable to submit this document at this time. Please try again later.`,variant: 'destructive',});+ onDocumentError?.();+throw err;}};diff --git a/apps/remix/app/components/general/share-document-download-button.tsx b/apps/remix/app/components/general/share-document-download-button.tsxdeleted file mode 100644index 5ee7d0453..000000000--- a/apps/remix/app/components/general/share-document-download-button.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { useState } from 'react';--import { msg } from '@lingui/core/macro';-import { useLingui } from '@lingui/react';-import { Trans } from '@lingui/react/macro';-import { Download } from 'lucide-react';--import { downloadPDF } from '@documenso/lib/client-only/download-pdf';-import type { DocumentData } from '@documenso/prisma/client';-import { Button } from '@documenso/ui/primitives/button';-import { useToast } from '@documenso/ui/primitives/use-toast';--export type ShareDocumentDownloadButtonProps = {- title: string;- documentData: DocumentData;-};--export const ShareDocumentDownloadButton = ({- title,- documentData,-}: ShareDocumentDownloadButtonProps) => {- const { _ } = useLingui();- const { toast } = useToast();-- const [isDownloading, setIsDownloading] = useState(false);-- const onDownloadClick = async () => {- try {- setIsDownloading(true);-- await downloadPDF({ documentData, fileName: title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- } finally {- setIsDownloading(false);- }- };-- return (- <Button loading={isDownloading} onClick={onDownloadClick}>- {!isDownloading && <Download className="mr-2 h-4 w-4" />}- <Trans>Download</Trans>- </Button>- );-};diff --git a/apps/remix/app/components/general/template/template-drop-zone-wrapper.tsx b/apps/remix/app/components/general/template/template-drop-zone-wrapper.tsxindex c0942f693..4daea014b 100644--- a/apps/remix/app/components/general/template/template-drop-zone-wrapper.tsx+++ b/apps/remix/app/components/general/template/template-drop-zone-wrapper.tsx@@ -10,9 +10,9 @@ import { match } from 'ts-pattern';import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';import { megabytesToBytes } from '@documenso/lib/universal/unit-convertions';-import { putPdfFile } from '@documenso/lib/universal/upload/put-file';import { formatTemplatesPath } from '@documenso/lib/utils/teams';import { trpc } from '@documenso/trpc/react';+import type { TCreateTemplatePayloadSchema } from '@documenso/trpc/server/template-router/schema';import { cn } from '@documenso/ui/lib/utils';import { useToast } from '@documenso/ui/primitives/use-toast';@@ -40,13 +40,17 @@ export const TemplateDropZoneWrapper = ({ children, className }: TemplateDropZontry {setIsLoading(true);- const documentData = await putPdfFile(file);-- const { legacyTemplateId: id } = await createTemplate({+ const payload = {title: file.name,- templateDocumentDataId: documentData.id,folderId: folderId ?? undefined,- });+ } satisfies TCreateTemplatePayloadSchema;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));+ formData.append('file', file);++ const { envelopeId: id } = await createTemplate(formData);toast({title: _(msg`Template uploaded`),diff --git a/apps/remix/app/components/general/template/template-edit-form.tsx b/apps/remix/app/components/general/template/template-edit-form.tsxindex 683f82054..bc79d0b16 100644--- a/apps/remix/app/components/general/template/template-edit-form.tsx+++ b/apps/remix/app/components/general/template/template-edit-form.tsx@@ -313,8 +313,10 @@ export const TemplateEditForm = ({><CardContent className="p-2"><PDFViewer- key={templateDocumentData.id}- documentData={templateDocumentData}+ key={template.envelopeItems[0].id}+ envelopeItem={template.envelopeItems[0]}+ token={undefined}+ version="signed"onDocumentLoad={() => setIsDocumentPdfLoaded(true)}/></CardContent>diff --git a/apps/remix/app/components/tables/documents-table-action-button.tsx b/apps/remix/app/components/tables/documents-table-action-button.tsxindex b7c0c8d43..237524c76 100644--- a/apps/remix/app/components/tables/documents-table-action-button.tsx+++ b/apps/remix/app/components/tables/documents-table-action-button.tsx@@ -1,19 +1,14 @@-import { msg } from '@lingui/core/macro';-import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';import { DocumentStatus, RecipientRole, SigningStatus } from '@prisma/client';import { CheckCircle, Download, Edit, EyeIcon, Pencil } from 'lucide-react';import { Link } from 'react-router';import { match } from 'ts-pattern';-import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { useSession } from '@documenso/lib/client-only/providers/session';import type { TDocumentMany as TDocumentRow } from '@documenso/lib/types/document';import { isDocumentCompleted } from '@documenso/lib/utils/document';import { formatDocumentsPath } from '@documenso/lib/utils/teams';-import { trpc as trpcClient } from '@documenso/trpc/client';import { Button } from '@documenso/ui/primitives/button';-import { useToast } from '@documenso/ui/primitives/use-toast';import { useCurrentTeam } from '~/providers/team';@@ -25,8 +20,6 @@ export type DocumentsTableActionButtonProps = {export const DocumentsTableActionButton = ({ row }: DocumentsTableActionButtonProps) => {const { user } = useSession();- const { toast } = useToast();- const { _ } = useLingui();const team = useCurrentTeam();@@ -44,39 +37,6 @@ export const DocumentsTableActionButton = ({ row }: DocumentsTableActionButtonPrconst documentsPath = formatDocumentsPath(team.url);const formatPath = `${documentsPath}/${row.envelopeId}/edit`;- const onDownloadClick = async () => {- try {- const document = !recipient- ? await trpcClient.document.get.query(- {- documentId: row.id,- },- {- context: {- teamId: team?.id?.toString(),- },- },- )- : await trpcClient.document.getDocumentByToken.query({- token: recipient.token,- });-- const documentData = document?.documentData;-- if (!documentData) {- throw Error('No document available');- }-- await downloadPDF({ documentData, fileName: row.title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-// TODO: Consider if want to keep this logic for hiding viewing for CC'ersif (recipient?.role === RecipientRole.CC && isComplete === false) {return null;@@ -134,7 +94,7 @@ export const DocumentsTableActionButton = ({ row }: DocumentsTableActionButtonPr<Trans>View</Trans></Button>))- .with({ isComplete: true, internalVersion: 2 }, () => (+ .with({ isComplete: true }, () => (<EnvelopeDownloadDialogenvelopeId={row.envelopeId}envelopeStatus={row.status}@@ -147,11 +107,5 @@ export const DocumentsTableActionButton = ({ row }: DocumentsTableActionButtonPr}/>))- .with({ isComplete: true }, () => (- <Button className="w-32" onClick={onDownloadClick}>- <Download className="-ml-1 mr-2 inline h-4 w-4" />- <Trans>Download</Trans>- </Button>- )).otherwise(() => <div></div>);};diff --git a/apps/remix/app/components/tables/documents-table-action-dropdown.tsx b/apps/remix/app/components/tables/documents-table-action-dropdown.tsxindex 34c322b81..4f33539ce 100644--- a/apps/remix/app/components/tables/documents-table-action-dropdown.tsx+++ b/apps/remix/app/components/tables/documents-table-action-dropdown.tsx@@ -10,7 +10,6 @@ import {Download,Edit,EyeIcon,- FileDown,FolderInput,Loader,MoreHorizontal,@@ -20,12 +19,10 @@ import {} from 'lucide-react';import { Link } from 'react-router';-import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { useSession } from '@documenso/lib/client-only/providers/session';import type { TDocumentMany as TDocumentRow } from '@documenso/lib/types/document';import { isDocumentCompleted } from '@documenso/lib/utils/document';import { formatDocumentsPath } from '@documenso/lib/utils/teams';-import { trpc as trpcClient } from '@documenso/trpc/client';import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';import {DropdownMenu,@@ -34,7 +31,6 @@ import {DropdownMenuLabel,DropdownMenuTrigger,} from '@documenso/ui/primitives/dropdown-menu';-import { useToast } from '@documenso/ui/primitives/use-toast';import { DocumentDeleteDialog } from '~/components/dialogs/document-delete-dialog';import { DocumentDuplicateDialog } from '~/components/dialogs/document-duplicate-dialog';@@ -56,7 +52,6 @@ export const DocumentsTableActionDropdown = ({const { user } = useSession();const team = useCurrentTeam();- const { toast } = useToast();const { _ } = useLingui();const [isDeleteDialogOpen, setDeleteDialogOpen] = useState(false);@@ -76,58 +71,6 @@ export const DocumentsTableActionDropdown = ({const documentsPath = formatDocumentsPath(team.url);const formatPath = `${documentsPath}/${row.envelopeId}/edit`;- const onDownloadClick = async () => {- try {- const document = !recipient- ? await trpcClient.document.get.query({- documentId: row.id,- })- : await trpcClient.document.getDocumentByToken.query({- token: recipient.token,- });-- const documentData = document?.documentData;-- if (!documentData) {- return;- }-- await downloadPDF({ documentData, fileName: row.title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-- const onDownloadOriginalClick = async () => {- try {- const document = !recipient- ? await trpcClient.document.get.query({- documentId: row.id,- })- : await trpcClient.document.getDocumentByToken.query({- token: recipient.token,- });-- const documentData = document?.documentData;-- if (!documentData) {- return;- }-- await downloadPDF({ documentData, fileName: row.title, version: 'original' });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-const nonSignedRecipients = row.recipients.filter((item) => item.signingStatus !== 'SIGNED');return (@@ -178,33 +121,19 @@ export const DocumentsTableActionDropdown = ({</Link></DropdownMenuItem>- {row.internalVersion === 2 ? (- <EnvelopeDownloadDialog- envelopeId={row.envelopeId}- envelopeStatus={row.status}- token={recipient?.token}- trigger={- <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>- <div>- <Download className="mr-2 h-4 w-4" />- <Trans>Download</Trans>- </div>- </DropdownMenuItem>- }- />- ) : (- <>- <DropdownMenuItem disabled={!isComplete} onClick={onDownloadClick}>- <Download className="mr-2 h-4 w-4" />- <Trans>Download</Trans>- </DropdownMenuItem>-- <DropdownMenuItem onClick={onDownloadOriginalClick}>- <FileDown className="mr-2 h-4 w-4" />- <Trans>Download Original</Trans>+ <EnvelopeDownloadDialog+ envelopeId={row.envelopeId}+ envelopeStatus={row.status}+ token={recipient?.token}+ trigger={+ <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>+ <div>+ <Download className="mr-2 h-4 w-4" />+ <Trans>Download</Trans>+ </div></DropdownMenuItem>- </>- )}+ }+ /><DropdownMenuItem onClick={() => setDuplicateDialogOpen(true)}><Copy className="mr-2 h-4 w-4" />@@ -273,7 +202,8 @@ export const DocumentsTableActionDropdown = ({/><DocumentDuplicateDialog- id={row.id}+ id={row.envelopeId}+ token={recipient?.token}open={isDuplicateDialogOpen}onOpenChange={setDuplicateDialogOpen}/>diff --git a/apps/remix/app/components/tables/inbox-table.tsx b/apps/remix/app/components/tables/inbox-table.tsxindex f2d138e0d..eb72219b4 100644--- a/apps/remix/app/components/tables/inbox-table.tsx+++ b/apps/remix/app/components/tables/inbox-table.tsx@@ -10,11 +10,9 @@ import { DateTime } from 'luxon';import { Link, useSearchParams } from 'react-router';import { match } from 'ts-pattern';-import { downloadPDF } from '@documenso/lib/client-only/download-pdf';import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';import { useSession } from '@documenso/lib/client-only/providers/session';import { isDocumentCompleted } from '@documenso/lib/utils/document';-import { trpc as trpcClient } from '@documenso/trpc/client';import { trpc } from '@documenso/trpc/react';import type { TFindInboxResponse } from '@documenso/trpc/server/document-router/find-inbox.types';import { Button } from '@documenso/ui/primitives/button';@@ -28,6 +26,7 @@ import { useToast } from '@documenso/ui/primitives/use-toast';import { DocumentStatus } from '~/components/general/document/document-status';import { useOptionalCurrentTeam } from '~/providers/team';+import { EnvelopeDownloadDialog } from '../dialogs/envelope-download-dialog';import { StackAvatarsWithTooltip } from '../general/stack-avatars-with-tooltip';export type DocumentsTableProps = {@@ -199,28 +198,6 @@ export const InboxTableActionButton = ({ row }: InboxTableActionButtonProps) =>return null;}- const onDownloadClick = async () => {- try {- const document = await trpcClient.document.getDocumentByToken.query({- token: recipient.token,- });-- const documentData = document?.documentData;-- if (!documentData) {- throw Error('No document available');- }-- await downloadPDF({ documentData, fileName: row.title });- } catch (err) {- toast({- title: _(msg`Something went wrong`),- description: _(msg`An error occurred while downloading your document.`),- variant: 'destructive',- });- }- };-// TODO: Consider if want to keep this logic for hiding viewing for CC'ersif (recipient?.role === RecipientRole.CC && isComplete === false) {return null;@@ -230,6 +207,7 @@ export const InboxTableActionButton = ({ row }: InboxTableActionButtonProps) =>isPending,isComplete,isSigned,+ internalVersion: row.internalVersion,}).with({ isPending: true, isSigned: false }, () => (<Button className="w-32" asChild>@@ -263,10 +241,17 @@ export const InboxTableActionButton = ({ row }: InboxTableActionButtonProps) =></Button>)).with({ isComplete: true }, () => (- <Button className="w-32" onClick={onDownloadClick}>- <DownloadIcon className="-ml-1 mr-2 inline h-4 w-4" />- <Trans>Download</Trans>- </Button>+ <EnvelopeDownloadDialog+ envelopeId={row.envelopeId}+ envelopeStatus={row.status}+ token={recipient?.token}+ trigger={+ <Button className="w-32">+ <DownloadIcon className="-ml-1 mr-2 inline h-4 w-4" />+ <Trans>Download</Trans>+ </Button>+ }+ />)).otherwise(() => <div></div>);};diff --git a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id._index.tsx b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id._index.tsxindex 4e7814a13..4228ec209 100644--- a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id._index.tsx+++ b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id._index.tsx@@ -147,8 +147,13 @@ export default function DocumentPage({ params }: Route.ComponentProps) {<div className="relative col-span-12 lg:col-span-6 xl:col-span-7"><EnvelopeRenderProviderenvelope={envelope}- fields={envelope.status == DocumentStatus.COMPLETED ? [] : envelope.fields}- recipientIds={envelope.recipients.map((recipient) => recipient.id)}+ token={undefined}+ fields={envelope.fields}+ recipients={envelope.recipients}+ overrideSettings={{+ showRecipientSigningStatus: true,+ showRecipientTooltip: true,+ }}>{isMultiEnvelopeItem && (<EnvelopeRendererFileSelector fields={envelope.fields} className="mb-4 p-0" />@@ -156,7 +161,10 @@ export default function DocumentPage({ params }: Route.ComponentProps) {<Card className="rounded-xl before:rounded-xl" gradient><CardContent className="p-2">- <PDFViewerKonvaLazy customPageRenderer={EnvelopeGenericPageRenderer} />+ <PDFViewerKonvaLazy+ renderer="preview"+ customPageRenderer={EnvelopeGenericPageRenderer}+ /></CardContent></Card></EnvelopeRenderProvider>@@ -178,9 +186,10 @@ export default function DocumentPage({ params }: Route.ComponentProps) {)}<PDFViewer- document={envelope}+ envelopeItem={envelope.envelopeItems[0]}+ token={undefined}key={envelope.envelopeItems[0].id}- documentData={envelope.envelopeItems[0].documentData}+ version="signed"/></CardContent></Card>diff --git a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.edit.tsx b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.edit.tsxindex 5494cb9e7..056b0e08a 100644--- a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.edit.tsx+++ b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.edit.tsx@@ -101,8 +101,9 @@ export default function EnvelopeEditorPage({ params }: Route.ComponentProps) {<EnvelopeEditorProvider initialEnvelope={envelope}><EnvelopeRenderProviderenvelope={envelope}+ token={undefined}fields={envelope.fields}- recipientIds={envelope.recipients.map((recipient) => recipient.id)}+ recipients={envelope.recipients}><EnvelopeEditor /></EnvelopeRenderProvider>diff --git a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/templates.$id._index.tsx b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/templates.$id._index.tsxindex 337d85d92..7a497a389 100644--- a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/templates.$id._index.tsx+++ b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/templates.$id._index.tsx@@ -170,8 +170,12 @@ export default function TemplatePage({ params }: Route.ComponentProps) {<div className="relative col-span-12 lg:col-span-6 xl:col-span-7"><EnvelopeRenderProviderenvelope={envelope}+ token={undefined}fields={envelope.fields}- recipientIds={envelope.recipients.map((recipient) => recipient.id)}+ recipients={envelope.recipients}+ overrideSettings={{+ showRecipientTooltip: true,+ }}>{isMultiEnvelopeItem && (<EnvelopeRendererFileSelector fields={envelope.fields} className="mb-4 p-0" />@@ -179,7 +183,10 @@ export default function TemplatePage({ params }: Route.ComponentProps) {<Card className="rounded-xl before:rounded-xl" gradient><CardContent className="p-2">- <PDFViewerKonvaLazy customPageRenderer={EnvelopeGenericPageRenderer} />+ <PDFViewerKonvaLazy+ renderer="preview"+ customPageRenderer={EnvelopeGenericPageRenderer}+ /></CardContent></Card></EnvelopeRenderProvider>@@ -200,9 +207,10 @@ export default function TemplatePage({ params }: Route.ComponentProps) {/><PDFViewer- document={envelope}+ envelopeItem={envelope.envelopeItems[0]}+ token={undefined}+ version="signed"key={envelope.envelopeItems[0].id}- documentData={envelope.envelopeItems[0].documentData}/></CardContent></Card>diff --git a/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx b/apps/remix/app/routes/_recipient+/d.$token+/_index.tsxindex dbe4c5ddd..15bf3ba8a 100644--- a/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx+++ b/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx@@ -245,7 +245,7 @@ const DirectSigningPageV2 = ({ data }: { data: Awaited<ReturnType<typeof handleVrecipient={recipient}user={user}>- <EnvelopeRenderProvider envelope={envelope}>+ <EnvelopeRenderProvider envelope={envelope} token={recipient.token}><DocumentSigningPageViewV2 /></EnvelopeRenderProvider></DocumentSigningAuthProvider>diff --git a/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx b/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsxindex dc7722c5a..b4998bd3b 100644--- a/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx+++ b/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx@@ -492,7 +492,7 @@ const SigningPageV2 = ({ data }: { data: Awaited<ReturnType<typeof handleV2Loaderecipient={recipient}user={user}>- <EnvelopeRenderProvider envelope={envelope}>+ <EnvelopeRenderProvider envelope={envelope} token={recipient.token}><DocumentSigningPageViewV2 /></EnvelopeRenderProvider></DocumentSigningAuthProvider>diff --git a/apps/remix/app/routes/_recipient+/sign.$token+/complete.tsx b/apps/remix/app/routes/_recipient+/sign.$token+/complete.tsxindex 6fa5897cd..eb875fcff 100644--- a/apps/remix/app/routes/_recipient+/sign.$token+/complete.tsx+++ b/apps/remix/app/routes/_recipient+/sign.$token+/complete.tsx@@ -1,10 +1,9 @@import { useEffect } from 'react';-import { msg } from '@lingui/core/macro';import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';import { DocumentStatus, FieldType, RecipientRole } from '@prisma/client';-import { CheckCircle2, Clock8, FileSearch } from 'lucide-react';+import { CheckCircle2, Clock8, DownloadIcon } from 'lucide-react';import { Link, useRevalidator } from 'react-router';import { match } from 'ts-pattern';@@ -20,14 +19,13 @@ import { getUserByEmail } from '@documenso/lib/server-only/user/get-user-by-emaiimport { isDocumentCompleted } from '@documenso/lib/utils/document';import { env } from '@documenso/lib/utils/env';import type { Document } from '@documenso/prisma/types/document-legacy-schema';-import DocumentDialog from '@documenso/ui/components/document/document-dialog';-import { DocumentDownloadButton } from '@documenso/ui/components/document/document-download-button';import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';import { SigningCard3D } from '@documenso/ui/components/signing-card';import { cn } from '@documenso/ui/lib/utils';import { Badge } from '@documenso/ui/primitives/badge';import { Button } from '@documenso/ui/primitives/button';+import { EnvelopeDownloadDialog } from '~/components/dialogs/envelope-download-dialog';import { ClaimAccount } from '~/components/general/claim-account';import { DocumentSigningAuthPageView } from '~/components/general/document-signing/document-signing-auth-page';@@ -207,24 +205,16 @@ export default function CompletedSigningPage({ loaderData }: Route.ComponentProp<div className="mt-8 flex w-full max-w-sm items-center justify-center gap-4"><DocumentShareButton documentId={document.id} token={recipient.token} />- {isDocumentCompleted(document.status) ? (- <DocumentDownloadButton- className="flex-1"- fileName={document.title}- documentData={document.documentData}- disabled={!isDocumentCompleted(document.status)}- />- ) : (- <DocumentDialog- documentData={document.documentData}+ {isDocumentCompleted(document.status) && (+ <EnvelopeDownloadDialog+ envelopeId={document.envelopeId}+ envelopeStatus={document.status}+ envelopeItems={document.envelopeItems}+ token={recipient?.token}trigger={- <Button- className="text-[11px]"- title={_(msg`Signatures will appear once the document has been completed`)}- variant="outline"- >- <FileSearch className="mr-2 h-5 w-5" strokeWidth={1.7} />- <Trans>View Original Document</Trans>+ <Button type="button" variant="outline" className="flex-1">+ <DownloadIcon className="mr-2 h-5 w-5" />+ <Trans>Download</Trans></Button>}/>diff --git a/apps/remix/app/routes/_share+/share.$slug.tsx b/apps/remix/app/routes/_share+/share.$slug.tsxindex ac09db5fb..dd18d3ae3 100644--- a/apps/remix/app/routes/_share+/share.$slug.tsx+++ b/apps/remix/app/routes/_share+/share.$slug.tsx@@ -60,6 +60,7 @@ export const loader = async ({ request, params: { slug } }: Route.LoaderArgs) =>return {document,+ token: slug,};}@@ -74,7 +75,7 @@ export const loader = async ({ request, params: { slug } }: Route.LoaderArgs) =>};export default function SharePage() {- const { document } = useLoaderData<typeof loader>();+ const { document, token } = useLoaderData<typeof loader>();if (document) {return (@@ -86,6 +87,7 @@ export default function SharePage() {envelopeItems={document.envelopeItems}recipientCount={document.recipientCount}completedDate={document.completedAt ?? undefined}+ token={token}/>);}diff --git a/apps/remix/app/routes/embed+/_v0+/_layout.tsx b/apps/remix/app/routes/embed+/_v0+/_layout.tsxindex 64259aa79..10204c63f 100644--- a/apps/remix/app/routes/embed+/_v0+/_layout.tsx+++ b/apps/remix/app/routes/embed+/_v0+/_layout.tsx@@ -7,6 +7,8 @@ import {} from '@documenso/lib/constants/auth';import { EmbedAuthenticationRequired } from '~/components/embed/embed-authentication-required';+import { EmbedDocumentCompleted } from '~/components/embed/embed-document-completed';+import { EmbedDocumentRejected } from '~/components/embed/embed-document-rejected';import { EmbedDocumentWaitingForTurn } from '~/components/embed/embed-document-waiting-for-turn';import { EmbedPaywall } from '~/components/embed/embed-paywall';@@ -48,6 +50,8 @@ export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {const error = useRouteError();+ console.log({ routeError: error });+if (isRouteErrorResponse(error)) {if (error.status === 401 && error.data.type === 'embed-authentication-required') {return (@@ -68,6 +72,16 @@ export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {if (error.status === 403 && error.data.type === 'embed-waiting-for-turn') {return <EmbedDocumentWaitingForTurn />;}++ // !: Not used at the moment, may be removed in the future.+ if (error.status === 403 && error.data.type === 'embed-document-rejected') {+ return <EmbedDocumentRejected />;+ }++ // !: Not used at the moment, may be removed in the future.+ if (error.status === 403 && error.data.type === 'embed-document-completed') {+ return <EmbedDocumentCompleted name={error.data.name} signature={error.data.signature} />;+ }}return <div>Not Found</div>;diff --git a/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsxnew file mode 100644index 000000000..0c9c75cc5--- /dev/null+++ b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx@@ -0,0 +1,332 @@+import { data } from 'react-router';+import { match } from 'ts-pattern';++import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';+import { EnvelopeRenderProvider } from '@documenso/lib/client-only/providers/envelope-render-provider';+import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getEnvelopeForDirectTemplateSigning } from '@documenso/lib/server-only/envelope/get-envelope-for-direct-template-signing';+import { getEnvelopeRequiredAccessData } from '@documenso/lib/server-only/envelope/get-envelope-required-access-data';+import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';+import { getTemplateByDirectLinkToken } from '@documenso/lib/server-only/template/get-template-by-direct-link-token';+import { DocumentAccessAuth } from '@documenso/lib/types/document-auth';+import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';+import { prisma } from '@documenso/prisma';++import { EmbedDirectTemplateClientPage } from '~/components/embed/embed-direct-template-client-page';+import { EmbedSignDocumentV2ClientPage } from '~/components/embed/embed-document-signing-page-v2';+import { DocumentSigningAuthProvider } from '~/components/general/document-signing/document-signing-auth-provider';+import { DocumentSigningProvider } from '~/components/general/document-signing/document-signing-provider';+import { DocumentSigningRecipientProvider } from '~/components/general/document-signing/document-signing-recipient-provider';+import { EnvelopeSigningProvider } from '~/components/general/document-signing/envelope-signing-provider';+import { superLoaderJson, useSuperLoaderData } from '~/utils/super-json-loader';++import type { Route } from './+types/direct.$token';++async function handleV1Loader({ params, request }: Route.LoaderArgs) {+ if (!params.token) {+ throw new Response('Not found', { status: 404 });+ }++ const token = params.token;++ const template = await getTemplateByDirectLinkToken({+ token,+ }).catch(() => null);++ // `template.directLink` is always available but we're doing this to+ // satisfy the type checker.+ if (!template || !template.directLink) {+ throw new Response('Not found', { status: 404 });+ }++ const organisationClaim = await getOrganisationClaimByTeamId({ teamId: template.teamId });++ const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;+ const hidePoweredBy = organisationClaim.flags.hidePoweredBy;++ // TODO: Make this more robust, we need to ensure the owner is either+ // TODO: the member of a team that has an active subscription, is an early+ // TODO: adopter or is an enterprise user.+ if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {+ throw data(+ {+ type: 'embed-paywall',+ },+ {+ status: 403,+ },+ );+ }++ const { user } = await getOptionalSession(request);++ const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({+ documentAuth: template.authOptions,+ });++ const isAccessAuthValid = derivedRecipientAccessAuth.every((auth) =>+ match(auth)+ .with(DocumentAccessAuth.ACCOUNT, () => !!user)+ .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => false) // Not supported for direct links+ .exhaustive(),+ );++ if (!isAccessAuthValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: user?.email,+ returnTo: `/embed/direct/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ const { directTemplateRecipientId } = template.directLink;++ const recipient = template.recipients.find(+ (recipient) => recipient.id === directTemplateRecipientId,+ );++ if (!recipient) {+ throw new Response('Not found', { status: 404 });+ }++ const fields = template.fields.filter((field) => field.recipientId === directTemplateRecipientId);++ return {+ token,+ user,+ template,+ recipient,+ fields,+ hidePoweredBy,+ allowEmbedSigningWhitelabel,+ };+}++async function handleV2Loader({ params, request }: Route.LoaderArgs) {+ if (!params.token) {+ throw new Response('Not found', { status: 404 });+ }++ const token = params.token;++ const { user } = await getOptionalSession(request);++ const envelopeForSigning = await getEnvelopeForDirectTemplateSigning({+ token,+ userId: user?.id,+ })+ .then((envelopeForSigning) => {+ return {+ isDocumentAccessValid: true,+ ...envelopeForSigning,+ } as const;+ })+ .catch(async (e) => {+ const error = AppError.parseError(e);++ if (error.code === AppErrorCode.UNAUTHORIZED) {+ const requiredAccessData = await getEnvelopeRequiredAccessData({ token });++ return {+ isDocumentAccessValid: false,+ ...requiredAccessData,+ } as const;+ }++ throw new Response('Not Found', { status: 404 });+ });++ if (!envelopeForSigning.isDocumentAccessValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: envelopeForSigning.recipientEmail,+ returnTo: `/embed/direct/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ const { envelope, recipient } = envelopeForSigning;++ const organisationClaim = await getOrganisationClaimByTeamId({ teamId: envelope.teamId });++ const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;+ const hidePoweredBy = organisationClaim.flags.hidePoweredBy;++ if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {+ throw data(+ {+ type: 'embed-paywall',+ },+ {+ status: 403,+ },+ );+ }++ const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({+ documentAuth: envelope.authOptions,+ recipientAuth: recipient.authOptions,+ });++ const isAccessAuthValid = derivedRecipientAccessAuth.every((accesssAuth) =>+ match(accesssAuth)+ .with(DocumentAccessAuth.ACCOUNT, () => user && user.email === recipient.email)+ .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => false) // Not supported for direct links+ .exhaustive(),+ );++ if (!isAccessAuthValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: user?.email || recipient.email,+ returnTo: `/embed/direct/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ return {+ token,+ user,+ envelopeForSigning,+ hidePoweredBy,+ allowEmbedSigningWhitelabel,+ };+}++export async function loader(loaderArgs: Route.LoaderArgs) {+ const { token } = loaderArgs.params;++ if (!token) {+ throw new Response('Not Found', { status: 404 });+ }++ // Not efficient but works for now until we remove v1.+ const foundDirectLink = await prisma.templateDirectLink.findFirst({+ where: {+ token,+ },+ select: {+ envelope: {+ select: {+ internalVersion: true,+ },+ },+ },+ });++ if (!foundDirectLink) {+ throw new Response('Not Found', { status: 404 });+ }++ if (foundDirectLink.envelope.internalVersion === 2) {+ const payloadV2 = await handleV2Loader(loaderArgs);++ return superLoaderJson({+ version: 2,+ payload: payloadV2,+ } as const);+ }++ const payloadV1 = await handleV1Loader(loaderArgs);++ return superLoaderJson({+ version: 1,+ payload: payloadV1,+ } as const);+}++export default function EmbedDirectTemplatePage() {+ const { version, payload } = useSuperLoaderData<typeof loader>();++ if (version === 1) {+ return <EmbedDirectTemplatePageV1 data={payload} />;+ }++ return <EmbedDirectTemplatePageV2 data={payload} />;+}++const EmbedDirectTemplatePageV1 = ({+ data,+}: {+ data: Awaited<ReturnType<typeof handleV1Loader>>;+}) => {+ const { token, user, template, recipient, fields, hidePoweredBy, allowEmbedSigningWhitelabel } =+ data;++ return (+ <DocumentSigningProvider+ email={user?.email}+ fullName={user?.name}+ signature={user?.signature}+ typedSignatureEnabled={template.templateMeta?.typedSignatureEnabled}+ uploadSignatureEnabled={template.templateMeta?.uploadSignatureEnabled}+ drawSignatureEnabled={template.templateMeta?.drawSignatureEnabled}+ >+ <DocumentSigningAuthProvider+ documentAuthOptions={template.authOptions}+ recipient={recipient}+ user={user}+ >+ <DocumentSigningRecipientProvider recipient={recipient}>+ <EmbedDirectTemplateClientPage+ token={token}+ envelopeId={template.envelopeId}+ updatedAt={template.updatedAt}+ envelopeItems={template.envelopeItems}+ recipient={recipient}+ fields={fields}+ metadata={template.templateMeta}+ hidePoweredBy={hidePoweredBy}+ allowWhiteLabelling={allowEmbedSigningWhitelabel}+ />+ </DocumentSigningRecipientProvider>+ </DocumentSigningAuthProvider>+ </DocumentSigningProvider>+ );+};++const EmbedDirectTemplatePageV2 = ({+ data,+}: {+ data: Awaited<ReturnType<typeof handleV2Loader>>;+}) => {+ const { token, user, envelopeForSigning, hidePoweredBy, allowEmbedSigningWhitelabel } = data;++ const { envelope, recipient } = envelopeForSigning;++ return (+ <EnvelopeSigningProvider+ envelopeData={envelopeForSigning}+ email={user?.email}+ fullName={user?.name}+ signature={user?.signature}+ >+ <DocumentSigningAuthProvider+ documentAuthOptions={envelope.authOptions}+ recipient={recipient}+ user={user}+ >+ <EnvelopeRenderProvider envelope={envelope} token={recipient.token}>+ <EmbedSignDocumentV2ClientPage+ hidePoweredBy={hidePoweredBy}+ allowWhitelabelling={allowEmbedSigningWhitelabel}+ />+ </EnvelopeRenderProvider>+ </DocumentSigningAuthProvider>+ </EnvelopeSigningProvider>+ );+};diff --git a/apps/remix/app/routes/embed+/_v0+/direct.$url.tsx b/apps/remix/app/routes/embed+/_v0+/direct.$url.tsxdeleted file mode 100644index 32705e5c2..000000000--- a/apps/remix/app/routes/embed+/_v0+/direct.$url.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { data } from 'react-router';-import { match } from 'ts-pattern';--import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';-import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';-import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';-import { getTemplateByDirectLinkToken } from '@documenso/lib/server-only/template/get-template-by-direct-link-token';-import { DocumentAccessAuth } from '@documenso/lib/types/document-auth';-import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';--import { EmbedDirectTemplateClientPage } from '~/components/embed/embed-direct-template-client-page';-import { DocumentSigningAuthProvider } from '~/components/general/document-signing/document-signing-auth-provider';-import { DocumentSigningProvider } from '~/components/general/document-signing/document-signing-provider';-import { DocumentSigningRecipientProvider } from '~/components/general/document-signing/document-signing-recipient-provider';-import { superLoaderJson, useSuperLoaderData } from '~/utils/super-json-loader';--import type { Route } from './+types/direct.$url';--export async function loader({ params, request }: Route.LoaderArgs) {- if (!params.url) {- throw new Response('Not found', { status: 404 });- }-- const token = params.url;-- const template = await getTemplateByDirectLinkToken({- token,- }).catch(() => null);-- // `template.directLink` is always available but we're doing this to- // satisfy the type checker.- if (!template || !template.directLink) {- throw new Response('Not found', { status: 404 });- }-- const organisationClaim = await getOrganisationClaimByTeamId({ teamId: template.teamId });-- const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;- const hidePoweredBy = organisationClaim.flags.hidePoweredBy;-- // TODO: Make this more robust, we need to ensure the owner is either- // TODO: the member of a team that has an active subscription, is an early- // TODO: adopter or is an enterprise user.- if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {- throw data(- {- type: 'embed-paywall',- },- {- status: 403,- },- );- }-- const { user } = await getOptionalSession(request);-- const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({- documentAuth: template.authOptions,- });-- const isAccessAuthValid = derivedRecipientAccessAuth.every((auth) =>- match(auth)- .with(DocumentAccessAuth.ACCOUNT, () => !!user)- .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => false) // Not supported for direct links- .exhaustive(),- );-- if (!isAccessAuthValid) {- throw data(- {- type: 'embed-authentication-required',- email: user?.email,- returnTo: `/embed/direct/${token}`,- },- {- status: 401,- },- );- }-- const { directTemplateRecipientId } = template.directLink;-- const recipient = template.recipients.find(- (recipient) => recipient.id === directTemplateRecipientId,- );-- if (!recipient) {- throw new Response('Not found', { status: 404 });- }-- const fields = template.fields.filter((field) => field.recipientId === directTemplateRecipientId);-- return superLoaderJson({- token,- user,- template,- recipient,- fields,- hidePoweredBy,- allowEmbedSigningWhitelabel,- });-}--export default function EmbedDirectTemplatePage() {- const { token, user, template, recipient, fields, hidePoweredBy, allowEmbedSigningWhitelabel } =- useSuperLoaderData<typeof loader>();-- return (- <DocumentSigningProvider- email={user?.email}- fullName={user?.name}- signature={user?.signature}- typedSignatureEnabled={template.templateMeta?.typedSignatureEnabled}- uploadSignatureEnabled={template.templateMeta?.uploadSignatureEnabled}- drawSignatureEnabled={template.templateMeta?.drawSignatureEnabled}- >- <DocumentSigningAuthProvider- documentAuthOptions={template.authOptions}- recipient={recipient}- user={user}- >- <DocumentSigningRecipientProvider recipient={recipient}>- <EmbedDirectTemplateClientPage- token={token}- envelopeId={template.envelopeId}- updatedAt={template.updatedAt}- documentData={template.templateDocumentData}- recipient={recipient}- fields={fields}- metadata={template.templateMeta}- hidePoweredBy={hidePoweredBy}- allowWhiteLabelling={allowEmbedSigningWhitelabel}- />- </DocumentSigningRecipientProvider>- </DocumentSigningAuthProvider>- </DocumentSigningProvider>- );-}diff --git a/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsxnew file mode 100644index 000000000..e3bf2b03b--- /dev/null+++ b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx@@ -0,0 +1,394 @@+import { RecipientRole } from '@prisma/client';+import { data } from 'react-router';+import { match } from 'ts-pattern';++import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';+import { EnvelopeRenderProvider } from '@documenso/lib/client-only/providers/envelope-render-provider';+import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';+import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';+import { getEnvelopeForRecipientSigning } from '@documenso/lib/server-only/envelope/get-envelope-for-recipient-signing';+import { getEnvelopeRequiredAccessData } from '@documenso/lib/server-only/envelope/get-envelope-required-access-data';+import { getCompletedFieldsForToken } from '@documenso/lib/server-only/field/get-completed-fields-for-token';+import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';+import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';+import { getIsRecipientsTurnToSign } from '@documenso/lib/server-only/recipient/get-is-recipient-turn';+import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';+import { getRecipientsForAssistant } from '@documenso/lib/server-only/recipient/get-recipients-for-assistant';+import { DocumentAccessAuth } from '@documenso/lib/types/document-auth';+import { isDocumentCompleted } from '@documenso/lib/utils/document';+import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';+import { prisma } from '@documenso/prisma';++import { EmbedSignDocumentV1ClientPage } from '~/components/embed/embed-document-signing-page-v1';+import { EmbedSignDocumentV2ClientPage } from '~/components/embed/embed-document-signing-page-v2';+import { DocumentSigningAuthProvider } from '~/components/general/document-signing/document-signing-auth-provider';+import { DocumentSigningProvider } from '~/components/general/document-signing/document-signing-provider';+import { EnvelopeSigningProvider } from '~/components/general/document-signing/envelope-signing-provider';+import { superLoaderJson, useSuperLoaderData } from '~/utils/super-json-loader';++import { getOptionalLoaderContext } from '../../../../server/utils/get-loader-session';+import type { Route } from './+types/sign.$token';++async function handleV1Loader({ params, request }: Route.LoaderArgs) {+ const { requestMetadata } = getOptionalLoaderContext();++ if (!params.token) {+ throw new Response('Not found', { status: 404 });+ }++ const token = params.token;++ const { user } = await getOptionalSession(request);++ const [document, fields, recipient, completedFields] = await Promise.all([+ getDocumentAndSenderByToken({+ token,+ userId: user?.id,+ requireAccessAuth: false,+ }).catch(() => null),+ getFieldsForToken({ token }),+ getRecipientByToken({ token }).catch(() => null),+ getCompletedFieldsForToken({ token }).catch(() => []),+ ]);++ // `document.directLink` is always available but we're doing this to+ // satisfy the type checker.+ if (!document || !recipient) {+ throw new Response('Not found', { status: 404 });+ }++ const organisationClaim = await getOrganisationClaimByTeamId({ teamId: document.teamId });++ const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;+ const hidePoweredBy = organisationClaim.flags.hidePoweredBy;++ // TODO: Make this more robust, we need to ensure the owner is either+ // TODO: the member of a team that has an active subscription, is an early+ // TODO: adopter or is an enterprise user.+ if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {+ throw data(+ {+ type: 'embed-paywall',+ },+ {+ status: 403,+ },+ );+ }++ const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({+ documentAuth: document.authOptions,+ });++ const isAccessAuthValid = derivedRecipientAccessAuth.every((accesssAuth) =>+ match(accesssAuth)+ .with(DocumentAccessAuth.ACCOUNT, () => user && user.email === recipient.email)+ .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => true) // Allow without account requirement+ .exhaustive(),+ );++ if (!isAccessAuthValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: user?.email || recipient.email,+ returnTo: `/embed/sign/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ const isRecipientsTurnToSign = await getIsRecipientsTurnToSign({ token });++ if (!isRecipientsTurnToSign) {+ throw data(+ {+ type: 'embed-waiting-for-turn',+ },+ {+ status: 403,+ },+ );+ }++ await viewedDocument({+ token,+ requestMetadata,+ recipientAccessAuth: derivedRecipientAccessAuth,+ });++ const allRecipients =+ recipient.role === RecipientRole.ASSISTANT+ ? await getRecipientsForAssistant({+ token,+ })+ : [];++ return {+ token,+ user,+ document,+ allRecipients,+ recipient,+ fields,+ completedFields,+ hidePoweredBy,+ allowEmbedSigningWhitelabel,+ };+}++async function handleV2Loader({ params, request }: Route.LoaderArgs) {+ const { requestMetadata } = getOptionalLoaderContext();++ if (!params.token) {+ throw new Response('Not found', { status: 404 });+ }++ const token = params.token;++ const { user } = await getOptionalSession(request);++ const envelopeForSigning = await getEnvelopeForRecipientSigning({+ token,+ userId: user?.id,+ })+ .then((envelopeForSigning) => {+ return {+ isDocumentAccessValid: true,+ ...envelopeForSigning,+ } as const;+ })+ .catch(async (e) => {+ const error = AppError.parseError(e);++ if (error.code === AppErrorCode.UNAUTHORIZED) {+ const requiredAccessData = await getEnvelopeRequiredAccessData({ token });++ return {+ isDocumentAccessValid: false,+ ...requiredAccessData,+ } as const;+ }++ throw new Response('Not Found', { status: 404 });+ });++ if (!envelopeForSigning.isDocumentAccessValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: envelopeForSigning.recipientEmail,+ returnTo: `/embed/sign/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ const { envelope, recipient, isRecipientsTurn } = envelopeForSigning;++ const organisationClaim = await getOrganisationClaimByTeamId({ teamId: envelope.teamId });++ const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;+ const hidePoweredBy = organisationClaim.flags.hidePoweredBy;++ if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {+ throw data(+ {+ type: 'embed-paywall',+ },+ {+ status: 403,+ },+ );+ }++ if (!isRecipientsTurn) {+ throw data(+ {+ type: 'embed-waiting-for-turn',+ },+ {+ status: 403,+ },+ );+ }++ const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({+ documentAuth: envelope.authOptions,+ recipientAuth: recipient.authOptions,+ });++ const isAccessAuthValid = derivedRecipientAccessAuth.every((accesssAuth) =>+ match(accesssAuth)+ .with(DocumentAccessAuth.ACCOUNT, () => user && user.email === recipient.email)+ .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => true)+ .exhaustive(),+ );++ if (!isAccessAuthValid) {+ throw data(+ {+ type: 'embed-authentication-required',+ email: user?.email || recipient.email,+ returnTo: `/embed/sign/${token}`,+ },+ {+ status: 401,+ },+ );+ }++ await viewedDocument({+ token,+ requestMetadata,+ recipientAccessAuth: derivedRecipientAccessAuth,+ }).catch(() => null);++ return {+ token,+ user,+ envelopeForSigning,+ hidePoweredBy,+ allowEmbedSigningWhitelabel,+ };+}++export async function loader(loaderArgs: Route.LoaderArgs) {+ const { token } = loaderArgs.params;++ if (!token) {+ throw new Response('Not Found', { status: 404 });+ }++ // Not efficient but works for now until we remove v1.+ const foundRecipient = await prisma.recipient.findFirst({+ where: {+ token,+ },+ select: {+ envelope: {+ select: {+ internalVersion: true,+ },+ },+ },+ });++ if (!foundRecipient) {+ throw new Response('Not Found', { status: 404 });+ }++ if (foundRecipient.envelope.internalVersion === 2) {+ const payloadV2 = await handleV2Loader(loaderArgs);++ return superLoaderJson({+ version: 2,+ payload: payloadV2,+ } as const);+ }++ const payloadV1 = await handleV1Loader(loaderArgs);++ return superLoaderJson({+ version: 1,+ payload: payloadV1,+ } as const);+}++export default function EmbedSignDocumentPage() {+ const { version, payload } = useSuperLoaderData<typeof loader>();++ if (version === 1) {+ return <EmbedSignDocumentPageV1 data={payload} />;+ }++ return <EmbedSignDocumentPageV2 data={payload} />;+}++const EmbedSignDocumentPageV1 = ({+ data,+}: {+ data: Awaited<ReturnType<typeof handleV1Loader>>;+}) => {+ const {+ token,+ user,+ document,+ allRecipients,+ recipient,+ fields,+ completedFields,+ hidePoweredBy,+ allowEmbedSigningWhitelabel,+ } = data;++ return (+ <DocumentSigningProvider+ email={recipient.email}+ fullName={user?.email === recipient.email ? user?.name : recipient.name}+ signature={user?.email === recipient.email ? user?.signature : undefined}+ typedSignatureEnabled={document.documentMeta?.typedSignatureEnabled}+ uploadSignatureEnabled={document.documentMeta?.uploadSignatureEnabled}+ drawSignatureEnabled={document.documentMeta?.drawSignatureEnabled}+ >+ <DocumentSigningAuthProvider+ documentAuthOptions={document.authOptions}+ recipient={recipient}+ user={user}+ >+ <EmbedSignDocumentV1ClientPage+ token={token}+ documentId={document.id}+ envelopeId={document.envelopeId}+ envelopeItems={document.envelopeItems}+ recipient={recipient}+ fields={fields}+ completedFields={completedFields}+ metadata={document.documentMeta}+ isCompleted={isDocumentCompleted(document.status)}+ hidePoweredBy={hidePoweredBy}+ allowWhitelabelling={allowEmbedSigningWhitelabel}+ allRecipients={allRecipients}+ />+ </DocumentSigningAuthProvider>+ </DocumentSigningProvider>+ );+};++const EmbedSignDocumentPageV2 = ({+ data,+}: {+ data: Awaited<ReturnType<typeof handleV2Loader>>;+}) => {+ const { token, user, envelopeForSigning, hidePoweredBy, allowEmbedSigningWhitelabel } = data;++ const { envelope, recipient } = envelopeForSigning;++ return (+ <EnvelopeSigningProvider+ envelopeData={envelopeForSigning}+ email={recipient.email}+ fullName={user?.email === recipient.email ? user?.name : recipient.name}+ signature={user?.email === recipient.email ? user?.signature : undefined}+ >+ <DocumentSigningAuthProvider+ documentAuthOptions={envelope.authOptions}+ recipient={recipient}+ user={user}+ >+ <EnvelopeRenderProvider envelope={envelope} token={token}>+ <EmbedSignDocumentV2ClientPage+ hidePoweredBy={hidePoweredBy}+ allowWhitelabelling={allowEmbedSigningWhitelabel}+ />+ </EnvelopeRenderProvider>+ </DocumentSigningAuthProvider>+ </EnvelopeSigningProvider>+ );+};diff --git a/apps/remix/app/routes/embed+/_v0+/sign.$url.tsx b/apps/remix/app/routes/embed+/_v0+/sign.$url.tsxdeleted file mode 100644index 6705cce0f..000000000--- a/apps/remix/app/routes/embed+/_v0+/sign.$url.tsx+++ /dev/null@@ -1,181 +0,0 @@-import { RecipientRole } from '@prisma/client';-import { data } from 'react-router';-import { getOptionalLoaderContext } from 'server/utils/get-loader-session';-import { match } from 'ts-pattern';--import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';-import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';-import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';-import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';-import { getCompletedFieldsForToken } from '@documenso/lib/server-only/field/get-completed-fields-for-token';-import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';-import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';-import { getIsRecipientsTurnToSign } from '@documenso/lib/server-only/recipient/get-is-recipient-turn';-import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';-import { getRecipientsForAssistant } from '@documenso/lib/server-only/recipient/get-recipients-for-assistant';-import { DocumentAccessAuth } from '@documenso/lib/types/document-auth';-import { isDocumentCompleted } from '@documenso/lib/utils/document';-import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';--import { EmbedSignDocumentClientPage } from '~/components/embed/embed-document-signing-page';-import { DocumentSigningAuthProvider } from '~/components/general/document-signing/document-signing-auth-provider';-import { DocumentSigningProvider } from '~/components/general/document-signing/document-signing-provider';-import { superLoaderJson, useSuperLoaderData } from '~/utils/super-json-loader';--import type { Route } from './+types/sign.$url';--export async function loader({ params, request }: Route.LoaderArgs) {- const { requestMetadata } = getOptionalLoaderContext();-- if (!params.url) {- throw new Response('Not found', { status: 404 });- }-- const token = params.url;-- const { user } = await getOptionalSession(request);-- const [document, fields, recipient, completedFields] = await Promise.all([- getDocumentAndSenderByToken({- token,- userId: user?.id,- requireAccessAuth: false,- }).catch(() => null),- getFieldsForToken({ token }),- getRecipientByToken({ token }).catch(() => null),- getCompletedFieldsForToken({ token }).catch(() => []),- ]);-- // `document.directLink` is always available but we're doing this to- // satisfy the type checker.- if (!document || !recipient) {- throw new Response('Not found', { status: 404 });- }-- const organisationClaim = await getOrganisationClaimByTeamId({ teamId: document.teamId });-- const allowEmbedSigningWhitelabel = organisationClaim.flags.embedSigningWhiteLabel;- const hidePoweredBy = organisationClaim.flags.hidePoweredBy;-- // TODO: Make this more robust, we need to ensure the owner is either- // TODO: the member of a team that has an active subscription, is an early- // TODO: adopter or is an enterprise user.- if (IS_BILLING_ENABLED() && !organisationClaim.flags.embedSigning) {- throw data(- {- type: 'embed-paywall',- },- {- status: 403,- },- );- }-- const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({- documentAuth: document.authOptions,- });-- const isAccessAuthValid = derivedRecipientAccessAuth.every((accesssAuth) =>- match(accesssAuth)- .with(DocumentAccessAuth.ACCOUNT, () => user && user.email === recipient.email)- .with(DocumentAccessAuth.TWO_FACTOR_AUTH, () => true) // Allow without account requirement- .exhaustive(),- );-- if (!isAccessAuthValid) {- throw data(- {- type: 'embed-authentication-required',- email: user?.email || recipient.email,- returnTo: `/embed/sign/${token}`,- },- {- status: 401,- },- );- }-- const isRecipientsTurnToSign = await getIsRecipientsTurnToSign({ token });-- if (!isRecipientsTurnToSign) {- throw data(- {- type: 'embed-waiting-for-turn',- },- {- status: 403,- },- );- }-- await viewedDocument({- token,- requestMetadata,- recipientAccessAuth: derivedRecipientAccessAuth,- });-- const allRecipients =- recipient.role === RecipientRole.ASSISTANT- ? await getRecipientsForAssistant({- token,- })- : [];-- return superLoaderJson({- token,- user,- document,- allRecipients,- recipient,- fields,- completedFields,- hidePoweredBy,- allowEmbedSigningWhitelabel,- });-}--export default function EmbedSignDocumentPage() {- const {- token,- user,- document,- allRecipients,- recipient,- fields,- completedFields,- hidePoweredBy,- allowEmbedSigningWhitelabel,- } = useSuperLoaderData<typeof loader>();-- return (- <DocumentSigningProvider- email={recipient.email}- fullName={user?.email === recipient.email ? user?.name : recipient.name}- signature={user?.email === recipient.email ? user?.signature : undefined}- typedSignatureEnabled={document.documentMeta?.typedSignatureEnabled}- uploadSignatureEnabled={document.documentMeta?.uploadSignatureEnabled}- drawSignatureEnabled={document.documentMeta?.drawSignatureEnabled}- >- <DocumentSigningAuthProvider- documentAuthOptions={document.authOptions}- recipient={recipient}- user={user}- >- <EmbedSignDocumentClientPage- token={token}- documentId={document.id}- envelopeId={document.envelopeId}- documentData={document.documentData}- recipient={recipient}- fields={fields}- completedFields={completedFields}- metadata={document.documentMeta}- isCompleted={isDocumentCompleted(document.status)}- hidePoweredBy={hidePoweredBy}- allowWhitelabelling={allowEmbedSigningWhitelabel}- allRecipients={allRecipients}- />- </DocumentSigningAuthProvider>- </DocumentSigningProvider>- );-}diff --git a/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx b/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsxindex c84e931ea..be53d68ee 100644--- a/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx+++ b/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx@@ -67,6 +67,7 @@ export async function loader({ request }: Route.LoaderArgs) {export default function MultisignPage() {const { envelopes, user, hidePoweredBy, allowWhitelabelling } =useSuperLoaderData<typeof loader>();+const revalidator = useRevalidator();const [selectedDocument, setSelectedDocument] = useState<diff --git a/apps/remix/app/utils/field-signing/checkbox-field.ts b/apps/remix/app/utils/field-signing/checkbox-field.tsindex 84b11a207..c3bfaca20 100644--- a/apps/remix/app/utils/field-signing/checkbox-field.ts+++ b/apps/remix/app/utils/field-signing/checkbox-field.ts@@ -1,5 +1,6 @@import { FieldType } from '@prisma/client';+import { validateCheckboxLength } from '@documenso/lib/advanced-fields-validation/validate-checkbox';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import type { TFieldCheckbox } from '@documenso/lib/types/field';import { parseCheckboxCustomText } from '@documenso/lib/utils/fields';@@ -44,6 +45,13 @@ export const handleCheckboxFieldClick = async (let checkedValues: number[] | null = newValues.filter((v) => v.isChecked).map((v) => v.index);+ if (checkedValues.length === 0) {+ return {+ type: FieldType.CHECKBOX,+ value: [],+ };+ }+if (validationRule && validationLength) {const checkboxValidationRule = checkboxValidationSigns.find((sign) => sign.label === validationRule,@@ -55,12 +63,33 @@ export const handleCheckboxFieldClick = async (});}- checkedValues = await SignFieldCheckboxDialog.call({- fieldMeta: field.fieldMeta,- validationRule: checkboxValidationRule.value,+ // Custom logic to make it flow better.+ // If "at most" OR "exactly" 1 value then just return the new selected value if exists.+ if (+ (checkboxValidationRule.value === '=' || checkboxValidationRule.value === '<=') &&+ validationLength === 1+ ) {+ return {+ type: FieldType.CHECKBOX,+ value: [clickedCheckboxIndex],+ };+ }++ const isValid = validateCheckboxLength(+ checkedValues.length,+ checkboxValidationRule.value,validationLength,- preselectedIndices: currentCheckedIndices,- });+ );++ // Only render validation dialog if validation is invalid.+ if (!isValid) {+ checkedValues = await SignFieldCheckboxDialog.call({+ fieldMeta: field.fieldMeta,+ validationRule: checkboxValidationRule.value,+ validationLength,+ preselectedIndices: checkedValues,+ });+ }}if (!checkedValues) {diff --git a/apps/remix/package.json b/apps/remix/package.jsonindex 7e3c00771..3454f3285 100644--- a/apps/remix/package.json+++ b/apps/remix/package.json@@ -25,6 +25,7 @@"@documenso/trpc": "*","@documenso/ui": "*","@epic-web/remember": "^1.1.0",+ "@faker-js/faker": "^10.1.0","@hono/node-server": "^1.13.7","@hono/trpc-server": "^0.3.4","@hookform/resolvers": "^3.1.0",@@ -104,4 +105,4 @@"vite-tsconfig-paths": "^5.1.4"},"version": "1.13.1"-}\ No newline at end of file+}diff --git a/apps/remix/server/api/download/download.ts b/apps/remix/server/api/download/download.tsnew file mode 100644index 000000000..a3af42508--- /dev/null+++ b/apps/remix/server/api/download/download.ts@@ -0,0 +1,192 @@+import { sValidator } from '@hono/standard-validator';+import { EnvelopeType } from '@prisma/client';+import { Hono } from 'hono';++import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';+import { getApiTokenByToken } from '@documenso/lib/server-only/public-api/get-api-token-by-token';+import { buildTeamWhereQuery } from '@documenso/lib/utils/teams';+import { prisma } from '@documenso/prisma';++import type { HonoEnv } from '../../router';+import { handleEnvelopeItemFileRequest } from '../files/files.helpers';+import {+ ZDownloadDocumentRequestParamsSchema,+ ZDownloadEnvelopeItemRequestParamsSchema,+} from './download.types';++export const downloadRoute = new Hono<HonoEnv>()+ /**+ * Download an envelope item by its ID.+ * Requires API key authentication via Authorization header.+ */+ .get(+ '/envelopeItem/:envelopeItemId/download',+ sValidator('param', ZDownloadEnvelopeItemRequestParamsSchema),+ async (c) => {+ const logger = c.get('logger');++ try {+ const { envelopeItemId, version } = c.req.valid('param');+ const authorizationHeader = c.req.header('authorization');++ // Support for both "Authorization: Bearer api_xxx" and "Authorization: api_xxx"+ const [token] = (authorizationHeader || '').split('Bearer ').filter((s) => s.length > 0);++ if (!token) {+ throw new AppError(AppErrorCode.UNAUTHORIZED, {+ message: 'API token was not provided',+ });+ }++ const apiToken = await getApiTokenByToken({ token });++ if (apiToken.user.disabled) {+ throw new AppError(AppErrorCode.UNAUTHORIZED, {+ message: 'User is disabled',+ });+ }++ logger.info({+ auth: 'api',+ source: 'apiV2',+ path: c.req.path,+ userId: apiToken.user.id,+ apiTokenId: apiToken.id,+ envelopeItemId,+ version,+ });++ const envelopeItem = await prisma.envelopeItem.findFirst({+ where: {+ id: envelopeItemId,+ envelope: {+ team: buildTeamWhereQuery({ teamId: apiToken.teamId, userId: apiToken.user.id }),+ },+ },+ include: {+ envelope: true,+ documentData: true,+ },+ });++ if (!envelopeItem) {+ return c.json({ error: 'Envelope item not found' }, 404);+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelopeItem.envelope.status,+ documentData: envelopeItem.documentData,+ version: version || 'signed',+ isDownload: true,+ context: c,+ });+ } catch (error) {+ logger.error(error);++ if (error instanceof AppError) {+ if (error.code === AppErrorCode.UNAUTHORIZED) {+ return c.json({ error: error.message }, 401);+ }++ return c.json({ error: error.message }, 400);+ }++ return c.json({ error: 'Internal server error' }, 500);+ }+ },+ )+ /**+ * Download a document by its ID.+ * Requires API key authentication via Authorization header.+ */+ .get(+ '/document/:documentId/download',+ sValidator('param', ZDownloadDocumentRequestParamsSchema),+ async (c) => {+ const logger = c.get('logger');++ try {+ const { documentId, version } = c.req.valid('param');+ const authorizationHeader = c.req.header('authorization');++ // Support for both "Authorization: Bearer api_xxx" and "Authorization: api_xxx"+ const [token] = (authorizationHeader || '').split('Bearer ').filter((s) => s.length > 0);++ if (!token) {+ throw new AppError(AppErrorCode.UNAUTHORIZED, {+ message: 'API token was not provided',+ });+ }++ const apiToken = await getApiTokenByToken({ token });++ if (apiToken.user.disabled) {+ throw new AppError(AppErrorCode.UNAUTHORIZED, {+ message: 'User is disabled',+ });+ }++ logger.info({+ auth: 'api',+ source: 'apiV2',+ path: c.req.path,+ userId: apiToken.user.id,+ apiTokenId: apiToken.id,+ documentId,+ version,+ });++ const envelope = await getEnvelopeById({+ id: {+ type: 'documentId',+ id: documentId,+ },+ type: EnvelopeType.DOCUMENT,+ userId: apiToken.user.id,+ teamId: apiToken.teamId,+ }).catch(() => null);++ if (!envelope) {+ return c.json({ error: 'Document not found' }, 404);+ }++ // Get the first envelope item (documents have exactly one)+ const [envelopeItem] = envelope.envelopeItems;++ if (!envelopeItem) {+ return c.json({ error: 'Document item not found' }, 404);+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelope.status,+ documentData: envelopeItem.documentData,+ version: version || 'signed',+ isDownload: true,+ context: c,+ });+ } catch (error) {+ logger.error(error);++ if (error instanceof AppError) {+ if (error.code === AppErrorCode.UNAUTHORIZED) {+ return c.json({ error: error.message }, 401);+ }++ return c.json({ error: error.message }, 400);+ }++ return c.json({ error: 'Internal server error' }, 500);+ }+ },+ );diff --git a/apps/remix/server/api/download/download.types.ts b/apps/remix/server/api/download/download.types.tsnew file mode 100644index 000000000..b811975ed--- /dev/null+++ b/apps/remix/server/api/download/download.types.ts@@ -0,0 +1,29 @@+import { z } from 'zod';++export const ZDownloadEnvelopeItemRequestParamsSchema = z.object({+ envelopeItemId: z.string().describe('The ID of the envelope item to download.'),+ version: z+ .enum(['original', 'signed'])+ .optional()+ .default('signed')+ .describe(+ 'The version of the envelope item to download. "signed" returns the completed document with signatures, "original" returns the original uploaded document.',+ ),+});++export type TDownloadEnvelopeItemRequestParams = z.infer<+ typeof ZDownloadEnvelopeItemRequestParamsSchema+>;++export const ZDownloadDocumentRequestParamsSchema = z.object({+ documentId: z.coerce.number().describe('The ID of the document to download.'),+ version: z+ .enum(['original', 'signed'])+ .optional()+ .default('signed')+ .describe(+ 'The version of the document to download. "signed" returns the completed document with signatures, "original" returns the original uploaded document.',+ ),+});++export type TDownloadDocumentRequestParams = z.infer<typeof ZDownloadDocumentRequestParamsSchema>;diff --git a/apps/remix/server/api/files.ts b/apps/remix/server/api/files.tsdeleted file mode 100644index 440189c5a..000000000--- a/apps/remix/server/api/files.ts+++ /dev/null@@ -1,100 +0,0 @@-import { PDFDocument } from '@cantoo/pdf-lib';-import { sValidator } from '@hono/standard-validator';-import { Hono } from 'hono';--import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';-import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';-import { createDocumentData } from '@documenso/lib/server-only/document-data/create-document-data';-import { putFileServerSide } from '@documenso/lib/universal/upload/put-file.server';-import {- getPresignGetUrl,- getPresignPostUrl,-} from '@documenso/lib/universal/upload/server-actions';--import type { HonoEnv } from '../router';-import {- type TGetPresignedGetUrlResponse,- type TGetPresignedPostUrlResponse,- ZGetPresignedGetUrlRequestSchema,- ZGetPresignedPostUrlRequestSchema,- ZUploadPdfRequestSchema,-} from './files.types';--export const filesRoute = new Hono<HonoEnv>()- /**- * Uploads a document file to the appropriate storage location and creates- * a document data record.- */- .post('/upload-pdf', sValidator('form', ZUploadPdfRequestSchema), async (c) => {- try {- const { file } = c.req.valid('form');-- if (!file) {- return c.json({ error: 'No file provided' }, 400);- }-- // Todo: (RR7) This is new.- // Add file size validation.- // Convert MB to bytes (1 MB = 1024 * 1024 bytes)- const MAX_FILE_SIZE = APP_DOCUMENT_UPLOAD_SIZE_LIMIT * 1024 * 1024;-- if (file.size > MAX_FILE_SIZE) {- return c.json({ error: 'File too large' }, 400);- }-- const arrayBuffer = await file.arrayBuffer();-- const pdf = await PDFDocument.load(arrayBuffer).catch((e) => {- console.error(`PDF upload parse error: ${e.message}`);-- throw new AppError('INVALID_DOCUMENT_FILE');- });-- if (pdf.isEncrypted) {- throw new AppError('INVALID_DOCUMENT_FILE');- }-- // Todo: (RR7) Test this.- if (!file.name.endsWith('.pdf')) {- Object.defineProperty(file, 'name', {- writable: true,- value: `${file.name}.pdf`,- });- }-- const { type, data } = await putFileServerSide(file);-- const result = await createDocumentData({ type, data });-- return c.json(result);- } catch (error) {- console.error('Upload failed:', error);- return c.json({ error: 'Upload failed' }, 500);- }- })- .post('/presigned-get-url', sValidator('json', ZGetPresignedGetUrlRequestSchema), async (c) => {- const { key } = await c.req.json();-- try {- const { url } = await getPresignGetUrl(key || '');-- return c.json({ url } satisfies TGetPresignedGetUrlResponse);- } catch (err) {- console.error(err);-- throw new AppError(AppErrorCode.UNKNOWN_ERROR);- }- })- .post('/presigned-post-url', sValidator('json', ZGetPresignedPostUrlRequestSchema), async (c) => {- const { fileName, contentType } = c.req.valid('json');-- try {- const { key, url } = await getPresignPostUrl(fileName, contentType);-- return c.json({ key, url } satisfies TGetPresignedPostUrlResponse);- } catch (err) {- console.error(err);-- throw new AppError(AppErrorCode.UNKNOWN_ERROR);- }- });diff --git a/apps/remix/server/api/files.types.ts b/apps/remix/server/api/files.types.tsdeleted file mode 100644index 8c120cccd..000000000--- a/apps/remix/server/api/files.types.ts+++ /dev/null@@ -1,38 +0,0 @@-import { z } from 'zod';--import DocumentDataSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentDataSchema';--export const ZUploadPdfRequestSchema = z.object({- file: z.instanceof(File),-});--export const ZUploadPdfResponseSchema = DocumentDataSchema.pick({- type: true,- id: true,-});--export type TUploadPdfRequest = z.infer<typeof ZUploadPdfRequestSchema>;-export type TUploadPdfResponse = z.infer<typeof ZUploadPdfResponseSchema>;--export const ZGetPresignedPostUrlRequestSchema = z.object({- fileName: z.string().min(1),- contentType: z.string().min(1),-});--export const ZGetPresignedPostUrlResponseSchema = z.object({- key: z.string().min(1),- url: z.string().min(1),-});--export const ZGetPresignedGetUrlRequestSchema = z.object({- key: z.string().min(1),-});--export const ZGetPresignedGetUrlResponseSchema = z.object({- url: z.string().min(1),-});--export type TGetPresignedPostUrlRequest = z.infer<typeof ZGetPresignedPostUrlRequestSchema>;-export type TGetPresignedPostUrlResponse = z.infer<typeof ZGetPresignedPostUrlResponseSchema>;-export type TGetPresignedGetUrlRequest = z.infer<typeof ZGetPresignedGetUrlRequestSchema>;-export type TGetPresignedGetUrlResponse = z.infer<typeof ZGetPresignedGetUrlResponseSchema>;diff --git a/apps/remix/server/api/files/files.helpers.ts b/apps/remix/server/api/files/files.helpers.tsnew file mode 100644index 000000000..abd13a154--- /dev/null+++ b/apps/remix/server/api/files/files.helpers.ts@@ -0,0 +1,81 @@+import { type DocumentDataType, DocumentStatus } from '@prisma/client';+import { type Context } from 'hono';++import { sha256 } from '@documenso/lib/universal/crypto';+import { getFileServerSide } from '@documenso/lib/universal/upload/get-file.server';++import type { HonoEnv } from '../../router';++type HandleEnvelopeItemFileRequestOptions = {+ title: string;+ status: DocumentStatus;+ documentData: {+ type: DocumentDataType;+ data: string;+ initialData: string;+ };+ version: 'signed' | 'original';+ isDownload: boolean;+ context: Context<HonoEnv>;+};++/**+ * Helper function to handle envelope item file requests (both view and download)+ */+export const handleEnvelopeItemFileRequest = async ({+ title,+ status,+ documentData,+ version,+ isDownload,+ context: c,+}: HandleEnvelopeItemFileRequestOptions) => {+ const documentDataToUse = version === 'signed' ? documentData.data : documentData.initialData;++ const etag = Buffer.from(sha256(documentDataToUse)).toString('hex');++ if (c.req.header('If-None-Match') === etag) {+ return c.body(null, 304);+ }++ const file = await getFileServerSide({+ type: documentData.type,+ data: documentDataToUse,+ }).catch((error) => {+ console.error(error);++ return null;+ });++ if (!file) {+ return c.json({ error: 'File not found' }, 404);+ }++ c.header('Content-Type', 'application/pdf');+ c.header('ETag', etag);++ if (!isDownload) {+ if (status === DocumentStatus.COMPLETED) {+ c.header('Cache-Control', 'public, max-age=31536000, immutable');+ } else {+ // Set a tiny 1 minute cache, with must-revalidate to ensure the client always checks for updates.+ c.header('Cache-Control', 'public, max-age=60, must-revalidate');+ }+ }++ if (isDownload) {+ // Generate filename following the pattern from envelope-download-dialog.tsx+ const baseTitle = title.replace(/\.pdf$/, '');+ const suffix = version === 'signed' ? '_signed.pdf' : '.pdf';+ const filename = `${baseTitle}${suffix}`;++ c.header('Content-Disposition', `attachment; filename="${filename}"`);++ // For downloads, prevent caching to ensure fresh data+ c.header('Cache-Control', 'no-cache, no-store, must-revalidate');+ c.header('Pragma', 'no-cache');+ c.header('Expires', '0');+ }++ return c.body(file);+};diff --git a/apps/remix/server/api/files/files.ts b/apps/remix/server/api/files/files.tsnew file mode 100644index 000000000..1f497d56b--- /dev/null+++ b/apps/remix/server/api/files/files.ts@@ -0,0 +1,307 @@+import { sValidator } from '@hono/standard-validator';+import type { Prisma } from '@prisma/client';+import { Hono } from 'hono';++import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';+import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getTeamById } from '@documenso/lib/server-only/team/get-team';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';+import { getPresignPostUrl } from '@documenso/lib/universal/upload/server-actions';+import { prisma } from '@documenso/prisma';++import type { HonoEnv } from '../../router';+import { handleEnvelopeItemFileRequest } from './files.helpers';+import {+ type TGetPresignedPostUrlResponse,+ ZGetEnvelopeItemFileDownloadRequestParamsSchema,+ ZGetEnvelopeItemFileRequestParamsSchema,+ ZGetEnvelopeItemFileTokenDownloadRequestParamsSchema,+ ZGetEnvelopeItemFileTokenRequestParamsSchema,+ ZGetPresignedPostUrlRequestSchema,+ ZUploadPdfRequestSchema,+} from './files.types';++export const filesRoute = new Hono<HonoEnv>()+ /**+ * Uploads a document file to the appropriate storage location and creates+ * a document data record.+ */+ .post('/upload-pdf', sValidator('form', ZUploadPdfRequestSchema), async (c) => {+ try {+ const { file } = c.req.valid('form');++ if (!file) {+ return c.json({ error: 'No file provided' }, 400);+ }++ // Todo: (RR7) This is new.+ // Add file size validation.+ // Convert MB to bytes (1 MB = 1024 * 1024 bytes)+ const MAX_FILE_SIZE = APP_DOCUMENT_UPLOAD_SIZE_LIMIT * 1024 * 1024;++ if (file.size > MAX_FILE_SIZE) {+ return c.json({ error: 'File too large' }, 400);+ }++ const result = await putNormalizedPdfFileServerSide(file);++ return c.json(result);+ } catch (error) {+ console.error('Upload failed:', error);+ return c.json({ error: 'Upload failed' }, 500);+ }+ })+ .post('/presigned-post-url', sValidator('json', ZGetPresignedPostUrlRequestSchema), async (c) => {+ const { fileName, contentType } = c.req.valid('json');++ try {+ const { key, url } = await getPresignPostUrl(fileName, contentType);++ return c.json({ key, url } satisfies TGetPresignedPostUrlResponse);+ } catch (err) {+ console.error(err);++ throw new AppError(AppErrorCode.UNKNOWN_ERROR);+ }+ })+ .get(+ '/envelope/:envelopeId/envelopeItem/:envelopeItemId',+ sValidator('param', ZGetEnvelopeItemFileRequestParamsSchema),+ async (c) => {+ const { envelopeId, envelopeItemId } = c.req.valid('param');++ const session = await getOptionalSession(c);++ if (!session.user) {+ return c.json({ error: 'Unauthorized' }, 401);+ }++ const envelope = await prisma.envelope.findFirst({+ where: {+ id: envelopeId,+ },+ include: {+ envelopeItems: {+ where: {+ id: envelopeItemId,+ },+ include: {+ documentData: true,+ },+ },+ },+ });++ if (!envelope) {+ return c.json({ error: 'Envelope not found' }, 404);+ }++ const [envelopeItem] = envelope.envelopeItems;++ if (!envelopeItem) {+ return c.json({ error: 'Envelope item not found' }, 404);+ }++ const team = await getTeamById({+ userId: session.user.id,+ teamId: envelope.teamId,+ }).catch((error) => {+ console.error(error);++ return null;+ });++ if (!team) {+ return c.json(+ { error: 'User does not have access to the team that this envelope is associated with' },+ 403,+ );+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelope.status,+ documentData: envelopeItem.documentData,+ version: 'signed',+ isDownload: false,+ context: c,+ });+ },+ )+ .get(+ '/envelope/:envelopeId/envelopeItem/:envelopeItemId/download/:version?',+ sValidator('param', ZGetEnvelopeItemFileDownloadRequestParamsSchema),+ async (c) => {+ const { envelopeId, envelopeItemId, version } = c.req.valid('param');++ const session = await getOptionalSession(c);++ if (!session.user) {+ return c.json({ error: 'Unauthorized' }, 401);+ }++ const envelope = await prisma.envelope.findFirst({+ where: {+ id: envelopeId,+ },+ include: {+ envelopeItems: {+ where: {+ id: envelopeItemId,+ },+ include: {+ documentData: true,+ },+ },+ },+ });++ if (!envelope) {+ return c.json({ error: 'Envelope not found' }, 404);+ }++ const [envelopeItem] = envelope.envelopeItems;++ if (!envelopeItem) {+ return c.json({ error: 'Envelope item not found' }, 404);+ }++ const team = await getTeamById({+ userId: session.user.id,+ teamId: envelope.teamId,+ }).catch((error) => {+ console.error(error);++ return null;+ });++ if (!team) {+ return c.json(+ { error: 'User does not have access to the team that this envelope is associated with' },+ 403,+ );+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelope.status,+ documentData: envelopeItem.documentData,+ version,+ isDownload: true,+ context: c,+ });+ },+ )+ .get(+ '/token/:token/envelopeItem/:envelopeItemId',+ sValidator('param', ZGetEnvelopeItemFileTokenRequestParamsSchema),+ async (c) => {+ const { token, envelopeItemId } = c.req.valid('param');++ let envelopeWhereQuery: Prisma.EnvelopeItemWhereUniqueInput = {+ id: envelopeItemId,+ envelope: {+ recipients: {+ some: {+ token,+ },+ },+ },+ };++ if (token.startsWith('qr_')) {+ envelopeWhereQuery = {+ id: envelopeItemId,+ envelope: {+ qrToken: token,+ },+ };+ }++ const envelopeItem = await prisma.envelopeItem.findUnique({+ where: envelopeWhereQuery,+ include: {+ envelope: true,+ documentData: true,+ },+ });++ if (!envelopeItem) {+ return c.json({ error: 'Envelope item not found' }, 404);+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelopeItem.envelope.status,+ documentData: envelopeItem.documentData,+ version: 'signed',+ isDownload: false,+ context: c,+ });+ },+ )+ .get(+ '/token/:token/envelopeItem/:envelopeItemId/download/:version?',+ sValidator('param', ZGetEnvelopeItemFileTokenDownloadRequestParamsSchema),+ async (c) => {+ const { token, envelopeItemId, version } = c.req.valid('param');++ let envelopeWhereQuery: Prisma.EnvelopeItemWhereUniqueInput = {+ id: envelopeItemId,+ envelope: {+ recipients: {+ some: {+ token,+ },+ },+ },+ };++ if (token.startsWith('qr_')) {+ envelopeWhereQuery = {+ id: envelopeItemId,+ envelope: {+ qrToken: token,+ },+ };+ }++ const envelopeItem = await prisma.envelopeItem.findUnique({+ where: envelopeWhereQuery,+ include: {+ envelope: true,+ documentData: true,+ },+ });++ if (!envelopeItem) {+ return c.json({ error: 'Envelope item not found' }, 404);+ }++ if (!envelopeItem.documentData) {+ return c.json({ error: 'Document data not found' }, 404);+ }++ return await handleEnvelopeItemFileRequest({+ title: envelopeItem.title,+ status: envelopeItem.envelope.status,+ documentData: envelopeItem.documentData,+ version,+ isDownload: true,+ context: c,+ });+ },+ );diff --git a/apps/remix/server/api/files/files.types.ts b/apps/remix/server/api/files/files.types.tsnew file mode 100644index 000000000..444dac8ae--- /dev/null+++ b/apps/remix/server/api/files/files.types.ts@@ -0,0 +1,66 @@+import { z } from 'zod';++import DocumentDataSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentDataSchema';++export const ZUploadPdfRequestSchema = z.object({+ file: z.instanceof(File),+});++export const ZUploadPdfResponseSchema = DocumentDataSchema.pick({+ type: true,+ id: true,+});++export type TUploadPdfRequest = z.infer<typeof ZUploadPdfRequestSchema>;+export type TUploadPdfResponse = z.infer<typeof ZUploadPdfResponseSchema>;++export const ZGetPresignedPostUrlRequestSchema = z.object({+ fileName: z.string().min(1),+ contentType: z.string().min(1),+});++export const ZGetPresignedPostUrlResponseSchema = z.object({+ key: z.string().min(1),+ url: z.string().min(1),+});++export type TGetPresignedPostUrlRequest = z.infer<typeof ZGetPresignedPostUrlRequestSchema>;+export type TGetPresignedPostUrlResponse = z.infer<typeof ZGetPresignedPostUrlResponseSchema>;++export const ZGetEnvelopeItemFileRequestParamsSchema = z.object({+ envelopeId: z.string().min(1),+ envelopeItemId: z.string().min(1),+});++export type TGetEnvelopeItemFileRequestParams = z.infer<+ typeof ZGetEnvelopeItemFileRequestParamsSchema+>;++export const ZGetEnvelopeItemFileTokenRequestParamsSchema = z.object({+ token: z.string().min(1),+ envelopeItemId: z.string().min(1),+});++export type TGetEnvelopeItemFileTokenRequestParams = z.infer<+ typeof ZGetEnvelopeItemFileTokenRequestParamsSchema+>;++export const ZGetEnvelopeItemFileDownloadRequestParamsSchema = z.object({+ envelopeId: z.string().min(1),+ envelopeItemId: z.string().min(1),+ version: z.enum(['signed', 'original']).default('signed'),+});++export type TGetEnvelopeItemFileDownloadRequestParams = z.infer<+ typeof ZGetEnvelopeItemFileDownloadRequestParamsSchema+>;++export const ZGetEnvelopeItemFileTokenDownloadRequestParamsSchema = z.object({+ token: z.string().min(1),+ envelopeItemId: z.string().min(1),+ version: z.enum(['signed', 'original']).default('signed'),+});++export type TGetEnvelopeItemFileTokenDownloadRequestParams = z.infer<+ typeof ZGetEnvelopeItemFileTokenDownloadRequestParamsSchema+>;diff --git a/apps/remix/server/router.ts b/apps/remix/server/router.tsindex 5eb448933..35fb832cb 100644--- a/apps/remix/server/router.ts+++ b/apps/remix/server/router.ts@@ -8,13 +8,14 @@ import type { Logger } from 'pino';import { tsRestHonoApp } from '@documenso/api/hono';import { auth } from '@documenso/auth/server';-import { API_V2_BETA_URL } from '@documenso/lib/constants/app';+import { API_V2_BETA_URL, API_V2_URL } from '@documenso/lib/constants/app';import { jobsClient } from '@documenso/lib/jobs/client';import { getIpAddress } from '@documenso/lib/universal/get-ip-address';import { logger } from '@documenso/lib/utils/logger';import { openApiDocument } from '@documenso/trpc/server/open-api';-import { filesRoute } from './api/files';+import { downloadRoute } from './api/download/download';+import { filesRoute } from './api/files/files';import { type AppContext, appContext } from './context';import { appMiddleware } from './middleware';import { openApiTrpcServerHandler } from './trpc/hono-trpc-open-api';@@ -89,9 +90,26 @@ app.route('/api/v1', tsRestHonoApp);app.use('/api/jobs/*', jobsClient.getApiHandler());app.use('/api/trpc/*', reactRouterTrpcServer);+// Unstable API server routes. Order matters for these two.+app.get(`${API_V2_URL}/openapi.json`, (c) => c.json(openApiDocument));+app.use(`${API_V2_URL}/*`, cors());+// Shadows the download routes that tRPC defines since tRPC-to-openapi doesn't support their return types.+app.route(`${API_V2_URL}`, downloadRoute);+app.use(`${API_V2_URL}/*`, async (c) =>+ openApiTrpcServerHandler(c, {+ isBeta: false,+ }),+);+// Unstable API server routes. Order matters for these two.app.get(`${API_V2_BETA_URL}/openapi.json`, (c) => c.json(openApiDocument));app.use(`${API_V2_BETA_URL}/*`, cors());-app.use(`${API_V2_BETA_URL}/*`, async (c) => openApiTrpcServerHandler(c));+// Shadows the download routes that tRPC defines since tRPC-to-openapi doesn't support their return types.+app.route(`${API_V2_BETA_URL}`, downloadRoute);+app.use(`${API_V2_BETA_URL}/*`, async (c) =>+ openApiTrpcServerHandler(c, {+ isBeta: true,+ }),+);export default app;diff --git a/apps/remix/server/trpc/hono-trpc-open-api.ts b/apps/remix/server/trpc/hono-trpc-open-api.tsindex 2a89d6379..36f6951f1 100644--- a/apps/remix/server/trpc/hono-trpc-open-api.ts+++ b/apps/remix/server/trpc/hono-trpc-open-api.ts@@ -1,15 +1,22 @@import type { Context } from 'hono';-import { createOpenApiFetchHandler } from 'trpc-to-openapi';-import { API_V2_BETA_URL } from '@documenso/lib/constants/app';+import { API_V2_BETA_URL, API_V2_URL } from '@documenso/lib/constants/app';import { AppError, genericErrorCodeToTrpcErrorCodeMap } from '@documenso/lib/errors/app-error';import { createTrpcContext } from '@documenso/trpc/server/context';import { appRouter } from '@documenso/trpc/server/router';+import { createOpenApiFetchHandler } from '@documenso/trpc/utils/openapi-fetch-handler';import { handleTrpcRouterError } from '@documenso/trpc/utils/trpc-error-handler';-export const openApiTrpcServerHandler = async (c: Context) => {+type OpenApiTrpcServerHandlerOptions = {+ isBeta: boolean;+};++export const openApiTrpcServerHandler = async (+ c: Context,+ { isBeta }: OpenApiTrpcServerHandlerOptions,+) => {return createOpenApiFetchHandler<typeof appRouter>({- endpoint: API_V2_BETA_URL,+ endpoint: isBeta ? API_V2_BETA_URL : API_V2_URL,router: appRouter,createContext: async () => createTrpcContext({ c, requestSource: 'apiV2' }),req: c.req.raw,diff --git a/assets/field-font-alignment.pdf b/assets/field-font-alignment.pdfnew file mode 100644index 000000000..35dad9311Binary files /dev/null and b/assets/field-font-alignment.pdf differdiff --git a/assets/field-meta.pdf b/assets/field-meta.pdfnew file mode 100644index 000000000..c44bf8d68Binary files /dev/null and b/assets/field-meta.pdf differdiff --git a/package-lock.json b/package-lock.jsonindex ab1b56a2b..783d6865f 100644--- a/package-lock.json+++ b/package-lock.json@@ -21,13 +21,19 @@"mupdf": "^1.0.0","react": "^18","typescript": "5.6.2",- "zod": "3.24.1"+ "zod": "^3.25.76"},"devDependencies": {"@commitlint/cli": "^17.7.1","@commitlint/config-conventional": "^17.7.0","@lingui/cli": "^5.2.0",- "@prisma/client": "^6.8.2",+ "@prisma/client": "^6.18.0",+ "@trpc/client": "11.7.0",+ "@trpc/react-query": "11.7.0",+ "@trpc/server": "11.7.0",+ "@ts-rest/core": "^3.52.1",+ "@ts-rest/open-api": "^3.52.1",+ "@ts-rest/serverless": "^3.52.1","dotenv": "^16.5.0","dotenv-cli": "^8.0.0","eslint": "^8.40.0",@@ -37,12 +43,17 @@"nodemailer": "^6.10.1","playwright": "1.52.0","prettier": "^3.3.3",- "prisma": "^6.8.2",+ "prisma": "^6.18.0","prisma-extension-kysely": "^3.0.0",+ "prisma-json-types-generator": "^3.6.2","prisma-kysely": "^1.8.0","rimraf": "^5.0.1",+ "superjson": "^2.2.5",+ "trpc-to-openapi": "2.4.0","turbo": "^1.9.3",- "vite": "^6.3.5"+ "vite": "^6.3.5",+ "zod-openapi": "^4.2.4",+ "zod-prisma-types": "3.3.5"},"engines": {"node": ">=22.0.0",@@ -102,6 +113,7 @@"@documenso/trpc": "*","@documenso/ui": "*","@epic-web/remember": "^1.1.0",+ "@faker-js/faker": "^10.1.0","@hono/node-server": "^1.13.7","@hono/trpc-server": "^0.3.4","@hookform/resolvers": "^3.1.0",@@ -3501,6 +3513,22 @@"node": "^12.22.0 || ^14.17.0 || >=16.0.0"}},+ "node_modules/@faker-js/faker": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/@faker-js/faker/-/faker-10.1.0.tgz",+ "integrity": "sha512-C3mrr3b5dRVlKPJdfrAXS8+dq+rq8Qm5SNRazca0JKgw1HQERFmrVb0towvMmw5uu8hHKNiQasMaR/tydf3Zsg==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fakerjs"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || ^23.5.0 || >=24.0.0",+ "npm": ">=10"+ }+ },"node_modules/@floating-ui/core": {"version": "1.7.0","resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.0.tgz",@@ -7427,6 +7455,15 @@"integrity": "sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q==","license": "MIT"},+ "node_modules/@paralleldrive/cuid2": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz",+ "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "^1.1.5"+ }+ },"node_modules/@pdf-lib/fontkit": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@pdf-lib/fontkit/-/fontkit-1.1.1.tgz",@@ -7547,9 +7584,9 @@}},"node_modules/@prisma/client": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.8.2.tgz",- "integrity": "sha512-5II+vbyzv4si6Yunwgkj0qT/iY0zyspttoDrL3R4BYgLdp42/d2C8xdi9vqkrYtKt9H32oFIukvyw3Koz5JoDg==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.18.0.tgz",+ "integrity": "sha512-jnL2I9gDnPnw4A+4h5SuNn8Gc+1mL1Z79U/3I9eE2gbxJG1oSA+62ByPW4xkeDgwE0fqMzzpAZ7IHxYnLZ4iQA==","hasInstallScript": true,"license": "Apache-2.0","engines": {@@ -7569,69 +7606,63 @@}},"node_modules/@prisma/config": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.8.2.tgz",- "integrity": "sha512-ZJY1fF4qRBPdLQ/60wxNtX+eu89c3AkYEcP7L3jkp0IPXCNphCYxikTg55kPJLDOG6P0X+QG5tCv6CmsBRZWFQ==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.18.0.tgz",+ "integrity": "sha512-rgFzspCpwsE+q3OF/xkp0fI2SJ3PfNe9LLMmuSVbAZ4nN66WfBiKqJKo/hLz3ysxiPQZf8h1SMf2ilqPMeWATQ==","license": "Apache-2.0","dependencies": {- "jiti": "2.4.2"- }- },- "node_modules/@prisma/config/node_modules/jiti": {- "version": "2.4.2",- "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.4.2.tgz",- "integrity": "sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==",- "license": "MIT",- "bin": {- "jiti": "lib/jiti-cli.mjs"+ "c12": "3.1.0",+ "deepmerge-ts": "7.1.5",+ "effect": "3.18.4",+ "empathic": "2.0.0"}},"node_modules/@prisma/debug": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.8.2.tgz",- "integrity": "sha512-4muBSSUwJJ9BYth5N8tqts8JtiLT8QI/RSAzEogwEfpbYGFo9mYsInsVo8dqXdPO2+Rm5OG5q0qWDDE3nyUbVg==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.18.0.tgz",+ "integrity": "sha512-PMVPMmxPj0ps1VY75DIrT430MoOyQx9hmm174k6cmLZpcI95rAPXOQ+pp8ANQkJtNyLVDxnxVJ0QLbrm/ViBcg==","license": "Apache-2.0"},"node_modules/@prisma/dmmf": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/dmmf/-/dmmf-6.8.2.tgz",- "integrity": "sha512-okGJF/7hQZam/2wt+Y0hPyNxyY5S+L0FzAgtL932Q3YxUWHusRllrN39bCV45oF3QWY992g7rTWYdL2Rynt1qg==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/dmmf/-/dmmf-6.18.0.tgz",+ "integrity": "sha512-x0ItbLDxAnciEMFnGUm90Bkpzx2ja5Lp8Lz+9UkepIClZOMC4WvtMUHaMMfCFqfoBb+KUbxa/xV+FJ6EAaw4wQ==","license": "Apache-2.0"},"node_modules/@prisma/engines": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.8.2.tgz",- "integrity": "sha512-XqAJ//LXjqYRQ1RRabs79KOY4+v6gZOGzbcwDQl0D6n9WBKjV7qdrbd042CwSK0v0lM9MSHsbcFnU2Yn7z8Zlw==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.18.0.tgz",+ "integrity": "sha512-i5RzjGF/ex6AFgqEe2o1IW8iIxJGYVQJVRau13kHPYEL1Ck8Zvwuzamqed/1iIljs5C7L+Opiz5TzSsUebkriA==","hasInstallScript": true,"license": "Apache-2.0","dependencies": {- "@prisma/debug": "6.8.2",- "@prisma/engines-version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e",- "@prisma/fetch-engine": "6.8.2",- "@prisma/get-platform": "6.8.2"+ "@prisma/debug": "6.18.0",+ "@prisma/engines-version": "6.18.0-8.34b5a692b7bd79939a9a2c3ef97d816e749cda2f",+ "@prisma/fetch-engine": "6.18.0",+ "@prisma/get-platform": "6.18.0"}},"node_modules/@prisma/engines-version": {- "version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e",- "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e.tgz",- "integrity": "sha512-Rkik9lMyHpFNGaLpPF3H5q5TQTkm/aE7DsGM5m92FZTvWQsvmi6Va8On3pWvqLHOt5aPUvFb/FeZTmphI4CPiQ==",+ "version": "6.18.0-8.34b5a692b7bd79939a9a2c3ef97d816e749cda2f",+ "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.18.0-8.34b5a692b7bd79939a9a2c3ef97d816e749cda2f.tgz",+ "integrity": "sha512-T7Af4QsJQnSgWN1zBbX+Cha5t4qjHRxoeoWpK4JugJzG/ipmmDMY5S+O0N1ET6sCBNVkf6lz+Y+ZNO9+wFU8pQ==","license": "Apache-2.0"},"node_modules/@prisma/fetch-engine": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.8.2.tgz",- "integrity": "sha512-lCvikWOgaLOfqXGacEKSNeenvj0n3qR5QvZUOmPE2e1Eh8cMYSobxonCg9rqM6FSdTfbpqp9xwhSAOYfNqSW0g==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.18.0.tgz",+ "integrity": "sha512-TdaBvTtBwP3IoqVYoGIYpD4mWlk0pJpjTJjir/xLeNWlwog7Sl3bD2J0jJ8+5+q/6RBg+acb9drsv5W6lqae7A==","license": "Apache-2.0","dependencies": {- "@prisma/debug": "6.8.2",- "@prisma/engines-version": "6.8.0-43.2060c79ba17c6bb9f5823312b6f6b7f4a845738e",- "@prisma/get-platform": "6.8.2"+ "@prisma/debug": "6.18.0",+ "@prisma/engines-version": "6.18.0-8.34b5a692b7bd79939a9a2c3ef97d816e749cda2f",+ "@prisma/get-platform": "6.18.0"}},"node_modules/@prisma/generator": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/generator/-/generator-6.8.2.tgz",- "integrity": "sha512-yExkvgqiKg1WHzjYttz40g5DsOtud8RhapM0Mum6pw+wrDoQyhSAxs5NHyFCV+9VPvRd2v+jAP2CTT07bsibjw==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/generator/-/generator-6.18.0.tgz",+ "integrity": "sha512-8Sz9z8d/X/42uL07qYF4no2hnSSMPk8g6+w0zpINCN7lvnILby5b56xA0uPKRFfR3Wfn3NtFLnyEpMQE9fXeeg==","license": "Apache-2.0"},"node_modules/@prisma/generator-helper": {@@ -7704,12 +7735,12 @@"license": "MIT"},"node_modules/@prisma/get-platform": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.8.2.tgz",- "integrity": "sha512-vXSxyUgX3vm1Q70QwzwkjeYfRryIvKno1SXbIqwSptKwqKzskINnDUcx85oX+ys6ooN2ATGSD0xN2UTfg6Zcow==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.18.0.tgz",+ "integrity": "sha512-uXNJCJGhxTCXo2B25Ta91Rk1/Nmlqg9p7G9GKh8TPhxvAyXCvMNQoogj4JLEUy+3ku8g59cpyQIKFhqY2xO2bg==","license": "Apache-2.0","dependencies": {- "@prisma/debug": "6.8.2"+ "@prisma/debug": "6.18.0"}},"node_modules/@prisma/internals": {@@ -10312,6 +10343,12 @@"integrity": "sha512-zxnHvoMQVqewTJr/W4pKjF0bMGiKJv1WX7bSrkl46Hg0QjESbzBROWK0Wg4RphzSOS5Jiy7eFimmM3UgMrMZbQ==","license": "MIT"},+ "node_modules/@rvf/set-get": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/@rvf/set-get/-/set-get-7.0.1.tgz",+ "integrity": "sha512-GkTSn9K1GrTYoTUqlUs36k6nJnzjQaFBTTEIqUYmzBcsGsoJM8xG7EAx2WLHWAA4QzFjcwWUSHQ3vM3Fbw50Tg==",+ "license": "MIT"+ },"node_modules/@scarf/scarf": {"version": "1.4.0","resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",@@ -11178,6 +11215,12 @@"node": ">=18.0.0"}},+ "node_modules/@standard-schema/spec": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",+ "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",+ "license": "MIT"+ },"node_modules/@swagger-api/apidom-ast": {"version": "1.0.0-beta.39","resolved": "https://registry.npmjs.org/@swagger-api/apidom-ast/-/apidom-ast-1.0.0-beta.39.tgz",@@ -11767,9 +11810,9 @@}},"node_modules/@tanstack/query-core": {- "version": "5.59.13",- "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.59.13.tgz",- "integrity": "sha512-Oou0bBu/P8+oYjXsJQ11j+gcpLAMpqW42UlokQYEz4dE7+hOtVO9rVuolJKgEccqzvyFzqX4/zZWY+R/v1wVsQ==",+ "version": "5.90.5",+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.5.tgz",+ "integrity": "sha512-wLamYp7FaDq6ZnNehypKI5fNvxHPfTYylE0m/ZpuuzJfJqhR5Pxg9gvGBHZx4n7J+V5Rg5mZxHHTlv25Zt5u+w==","license": "MIT","funding": {"type": "github",@@ -11777,12 +11820,12 @@}},"node_modules/@tanstack/react-query": {- "version": "5.59.15",- "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.59.15.tgz",- "integrity": "sha512-QbVlAkTI78wB4Mqgf2RDmgC0AOiJqer2c5k9STOOSXGv1S6ZkY37r/6UpE8DbQ2Du0ohsdoXgFNEyv+4eDoPEw==",+ "version": "5.90.5",+ "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.5.tgz",+ "integrity": "sha512-pN+8UWpxZkEJ/Rnnj2v2Sxpx1WFlaa9L6a4UO89p6tTQbeo+m0MS8oYDjbggrR8QcTyjKoYWKS3xJQGr3ExT8Q==","license": "MIT","dependencies": {- "@tanstack/query-core": "5.59.13"+ "@tanstack/query-core": "5.90.5"},"funding": {"type": "github",@@ -12053,45 +12096,45 @@}},"node_modules/@trpc/client": {- "version": "11.0.0-rc.648",- "resolved": "https://registry.npmjs.org/@trpc/client/-/client-11.0.0-rc.648.tgz",- "integrity": "sha512-k4FfLKvJwbosUH8KYyZkC50RJHYtIyJECi5WhRXsvaf9a6lgrTlcA+osq815zYcAHo7wEgR9E9UdSTrpLdAQFQ==",+ "version": "11.7.0",+ "resolved": "https://registry.npmjs.org/@trpc/client/-/client-11.7.0.tgz",+ "integrity": "sha512-VLMoA9KUIItrD/tXKLw2Hvu71V7cRMBNQhXbmm5weSkFVWdAGwLXzV5f85QPdOM8669dD+a1QbGJCK0LNBPbgQ==","funding": ["https://trpc.io/sponsor"],"license": "MIT","peerDependencies": {- "@trpc/server": "11.0.0-rc.648+77b4d8920",- "typescript": ">=5.6.2"+ "@trpc/server": "11.7.0",+ "typescript": ">=5.7.2"}},"node_modules/@trpc/react-query": {- "version": "11.0.0-rc.648",- "resolved": "https://registry.npmjs.org/@trpc/react-query/-/react-query-11.0.0-rc.648.tgz",- "integrity": "sha512-U3H6o/aN3umEA2QNDGRsaJb6M7zrffor2NQl2UaHOiLBHuXZ3ISI2fJXay7e32s1l6z5F5PGMGwTQtUedzWI2w==",+ "version": "11.7.0",+ "resolved": "https://registry.npmjs.org/@trpc/react-query/-/react-query-11.7.0.tgz",+ "integrity": "sha512-JxMCm1CduoCZj+0xbUXy1MihBAHxnlXQActNSJ14OT4weJa23Qj35u34gYMnIF+fs9w4r70gyqPcV/67D3Nk8Q==","funding": ["https://trpc.io/sponsor"],"license": "MIT","peerDependencies": {- "@tanstack/react-query": "^5.59.15",- "@trpc/client": "11.0.0-rc.648+77b4d8920",- "@trpc/server": "11.0.0-rc.648+77b4d8920",+ "@tanstack/react-query": "^5.80.3",+ "@trpc/client": "11.7.0",+ "@trpc/server": "11.7.0","react": ">=18.2.0","react-dom": ">=18.2.0",- "typescript": ">=5.6.2"+ "typescript": ">=5.7.2"}},"node_modules/@trpc/server": {- "version": "11.0.0-rc.648",- "resolved": "https://registry.npmjs.org/@trpc/server/-/server-11.0.0-rc.648.tgz",- "integrity": "sha512-nKW7FNM+QZrY/CVGlX3hFNIdUvbw6pwSJ+HzEF8GIeSJDKLHK7Ke1QJGI2mRW6oF9dCKMBXfuLaYY2dXfjfn7Q==",+ "version": "11.7.0",+ "resolved": "https://registry.npmjs.org/@trpc/server/-/server-11.7.0.tgz",+ "integrity": "sha512-BPpr3roKWpZnS92fWCg29e6hEwn1kzH8m65yXRkJfFqemgwckiyJ15NgR8zTe7RcMAeBEPpvqyAfL71rwaSJJw==","funding": ["https://trpc.io/sponsor"],"license": "MIT","peerDependencies": {- "typescript": ">=5.6.2"+ "typescript": ">=5.7.2"}},"node_modules/@ts-rest/core": {@@ -12557,6 +12600,16 @@"@types/pg": "*"}},+ "node_modules/@types/pngjs": {+ "version": "6.0.5",+ "resolved": "https://registry.npmjs.org/@types/pngjs/-/pngjs-6.0.5.tgz",+ "integrity": "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/prop-types": {"version": "15.7.14","resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz",@@ -13729,6 +13782,12 @@"node": ">=0.10.0"}},+ "node_modules/asap": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",+ "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",+ "license": "MIT"+ },"node_modules/asn1js": {"version": "3.0.6","resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.6.tgz",@@ -14387,6 +14446,77 @@"node": ">= 0.8"}},+ "node_modules/c12": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz",+ "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==",+ "license": "MIT",+ "dependencies": {+ "chokidar": "^4.0.3",+ "confbox": "^0.2.2",+ "defu": "^6.1.4",+ "dotenv": "^16.6.1",+ "exsolve": "^1.0.7",+ "giget": "^2.0.0",+ "jiti": "^2.4.2",+ "ohash": "^2.0.11",+ "pathe": "^2.0.3",+ "perfect-debounce": "^1.0.0",+ "pkg-types": "^2.2.0",+ "rc9": "^2.1.2"+ },+ "peerDependencies": {+ "magicast": "^0.3.5"+ },+ "peerDependenciesMeta": {+ "magicast": {+ "optional": true+ }+ }+ },+ "node_modules/c12/node_modules/chokidar": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",+ "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",+ "license": "MIT",+ "dependencies": {+ "readdirp": "^4.0.1"+ },+ "engines": {+ "node": ">= 14.16.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/c12/node_modules/jiti": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",+ "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==",+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/c12/node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },+ "node_modules/c12/node_modules/readdirp": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",+ "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",+ "license": "MIT",+ "engines": {+ "node": ">= 14.18.0"+ },+ "funding": {+ "type": "individual",+ "url": "https://paulmillr.com/funding/"+ }+ },"node_modules/cac": {"version": "6.7.14","resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",@@ -14741,6 +14871,15 @@"node": ">=8"}},+ "node_modules/citty": {+ "version": "0.1.6",+ "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz",+ "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==",+ "license": "MIT",+ "dependencies": {+ "consola": "^3.2.3"+ }+ },"node_modules/cjs-module-lexer": {"version": "1.4.3","resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz",@@ -15356,9 +15495,9 @@}},"node_modules/code-block-writer": {- "version": "12.0.0",- "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-12.0.0.tgz",- "integrity": "sha512-q4dMFMlXtKR3XNBHyMHt/3pwYNA69EDk00lloMOaaUMKPUXBw6lpXtbu3MMVG6/uOihGnRDOlkyqsONEUj60+w==",+ "version": "13.0.3",+ "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",+ "integrity": "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==","license": "MIT"},"node_modules/color": {@@ -15620,6 +15759,12 @@"node": ">=0.10.0"}},+ "node_modules/confbox": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz",+ "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==",+ "license": "MIT"+ },"node_modules/config-chain": {"version": "1.1.13","resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz",@@ -15636,6 +15781,15 @@"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==","license": "ISC"},+ "node_modules/consola": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",+ "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",+ "license": "MIT",+ "engines": {+ "node": "^14.18.0 || >=16.10.0"+ }+ },"node_modules/console-control-strings": {"version": "1.1.0","resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",@@ -15738,15 +15892,15 @@"license": "MIT"},"node_modules/copy-anything": {- "version": "3.0.5",- "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.5.tgz",- "integrity": "sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==",+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz",+ "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==","license": "MIT","dependencies": {- "is-what": "^4.1.8"+ "is-what": "^5.2.0"},"engines": {- "node": ">=12.13"+ "node": ">=18"},"funding": {"url": "https://github.com/sponsors/mesqueeb"@@ -16753,6 +16907,15 @@"node": ">=0.10.0"}},+ "node_modules/deepmerge-ts": {+ "version": "7.1.5",+ "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz",+ "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=16.0.0"+ }+ },"node_modules/defaults": {"version": "1.0.4","resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",@@ -17013,6 +17176,16 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/dezalgo": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz",+ "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==",+ "license": "ISC",+ "dependencies": {+ "asap": "^2.0.0",+ "wrappy": "1"+ }+ },"node_modules/didyoumean": {"version": "1.2.2","resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",@@ -17147,10 +17320,9 @@}},"node_modules/dotenv": {- "version": "16.5.0",- "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz",- "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",- "dev": true,+ "version": "16.6.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==","license": "BSD-2-Clause","engines": {"node": ">=12"@@ -17346,6 +17518,16 @@"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==","license": "MIT"},+ "node_modules/effect": {+ "version": "3.18.4",+ "resolved": "https://registry.npmjs.org/effect/-/effect-3.18.4.tgz",+ "integrity": "sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.0.0",+ "fast-check": "^3.23.1"+ }+ },"node_modules/electron-to-chromium": {"version": "1.5.155","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.155.tgz",@@ -17364,6 +17546,15 @@"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==","license": "MIT"},+ "node_modules/empathic": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz",+ "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ }+ },"node_modules/encodeurl": {"version": "2.0.0","resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",@@ -18701,6 +18892,12 @@"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==","license": "MIT"},+ "node_modules/exsolve": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.7.tgz",+ "integrity": "sha512-VO5fQUzZtI6C+vx4w/4BWJpg3s/5l+6pRQEHzFRM8WFi4XffSP1Z+4qi7GbjWbvRQEbdIco5mIMq+zX4rPuLrw==",+ "license": "MIT"+ },"node_modules/extend": {"version": "3.0.2","resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",@@ -18734,6 +18931,28 @@"node": ">=4"}},+ "node_modules/fast-check": {+ "version": "3.23.2",+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",+ "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "pure-rand": "^6.1.0"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },"node_modules/fast-copy": {"version": "3.0.2","resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz",@@ -19210,6 +19429,23 @@"node": ">=0.4.x"}},+ "node_modules/formidable": {+ "version": "3.5.4",+ "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz",+ "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==",+ "license": "MIT",+ "dependencies": {+ "@paralleldrive/cuid2": "^2.2.2",+ "dezalgo": "^1.0.4",+ "once": "^1.4.0"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "funding": {+ "url": "https://ko-fi.com/tunnckoCore/commissions"+ }+ },"node_modules/forwarded": {"version": "0.2.0","resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",@@ -19680,6 +19916,29 @@"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"}},+ "node_modules/giget": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz",+ "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==",+ "license": "MIT",+ "dependencies": {+ "citty": "^0.1.6",+ "consola": "^3.4.0",+ "defu": "^6.1.4",+ "node-fetch-native": "^1.6.6",+ "nypm": "^0.6.0",+ "pathe": "^2.0.3"+ },+ "bin": {+ "giget": "dist/cli.mjs"+ }+ },+ "node_modules/giget/node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },"node_modules/git-hooks-list": {"version": "4.1.1","resolved": "https://registry.npmjs.org/git-hooks-list/-/git-hooks-list-4.1.1.tgz",@@ -19949,19 +20208,19 @@}},"node_modules/h3": {- "version": "1.15.3",- "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.3.tgz",- "integrity": "sha512-z6GknHqyX0h9aQaTx22VZDf6QyZn+0Nh+Ym8O/u0SGSkyF5cuTJYKlc8MkzW3Nzf9LE1ivcpmYC3FUGpywhuUQ==",+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.1.tgz",+ "integrity": "sha512-+ORaOBttdUm1E2Uu/obAyCguiI7MbBvsLTndc3gyK3zU+SYLoZXlyCP9Xgy0gikkGufFLTZXCXD6+4BsufnmHA==","license": "MIT","dependencies": {"cookie-es": "^1.2.2",- "crossws": "^0.3.4",+ "crossws": "^0.3.3","defu": "^6.1.4",- "destr": "^2.0.5",+ "destr": "^2.0.3","iron-webcrypto": "^1.2.1","node-mock-http": "^1.0.0","radix3": "^1.1.2",- "ufo": "^1.6.1",+ "ufo": "^1.5.4","uncrypto": "^0.1.3"}},@@ -22021,12 +22280,12 @@}},"node_modules/is-what": {- "version": "4.1.16",- "resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.16.tgz",- "integrity": "sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==",+ "version": "5.5.0",+ "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz",+ "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==","license": "MIT","engines": {- "node": ">=12.13"+ "node": ">=18"},"funding": {"url": "https://github.com/sponsors/mesqueeb"@@ -23109,12 +23368,6 @@"integrity": "sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q==","license": "MIT"},- "node_modules/lodash.clonedeep": {- "version": "4.5.0",- "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",- "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",- "license": "MIT"- },"node_modules/lodash.debounce": {"version": "4.0.8","resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz",@@ -26181,6 +26434,12 @@"url": "https://opencollective.com/node-fetch"}},+ "node_modules/node-fetch-native": {+ "version": "1.6.7",+ "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",+ "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==",+ "license": "MIT"+ },"node_modules/node-gyp-build": {"version": "4.8.4","resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",@@ -26203,9 +26462,9 @@}},"node_modules/node-mock-http": {- "version": "1.0.0",- "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.0.tgz",- "integrity": "sha512-0uGYQ1WQL1M5kKvGRXWQ3uZCHtLTO8hln3oBjIusM75WoesZ909uQJs/Hb946i2SS+Gsrhkaa6iAO17jRIv6DQ==",+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.3.tgz",+ "integrity": "sha512-jN8dK25fsfnMrVsEhluUTPkBFY+6ybu7jSB1n+ri/vOGjJxU8J9CZhpSGkHXSkFjtUhbmoncG/YG9ta5Ludqog==","license": "MIT"},"node_modules/node-releases": {@@ -26495,6 +26754,31 @@"js-sdsl": "4.3.0"}},+ "node_modules/nypm": {+ "version": "0.6.2",+ "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.2.tgz",+ "integrity": "sha512-7eM+hpOtrKrBDCh7Ypu2lJ9Z7PNZBdi/8AT3AX8xoCj43BBVHD0hPSTEvMtkMpfs8FCqBGhxB+uToIQimA111g==",+ "license": "MIT",+ "dependencies": {+ "citty": "^0.1.6",+ "consola": "^3.4.2",+ "pathe": "^2.0.3",+ "pkg-types": "^2.3.0",+ "tinyexec": "^1.0.1"+ },+ "bin": {+ "nypm": "dist/cli.mjs"+ },+ "engines": {+ "node": "^14.16.0 || >=16.10.0"+ }+ },+ "node_modules/nypm/node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },"node_modules/object-assign": {"version": "4.1.1","resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",@@ -26643,6 +26927,12 @@"integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==","license": "MIT"},+ "node_modules/ohash": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz",+ "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",+ "license": "MIT"+ },"node_modules/on-exit-leak-free": {"version": "2.1.2","resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",@@ -27220,6 +27510,12 @@"url": "https://ko-fi.com/killymxi"}},+ "node_modules/perfect-debounce": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",+ "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",+ "license": "MIT"+ },"node_modules/perfect-freehand": {"version": "1.2.2","resolved": "https://registry.npmjs.org/perfect-freehand/-/perfect-freehand-1.2.2.tgz",@@ -27544,6 +27840,19 @@"node": ">= 6"}},+ "node_modules/pixelmatch": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-7.1.0.tgz",+ "integrity": "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "pngjs": "^7.0.0"+ },+ "bin": {+ "pixelmatch": "bin/pixelmatch"+ }+ },"node_modules/pkg-dir": {"version": "4.2.0","resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",@@ -27608,6 +27917,23 @@"node": ">=8"}},+ "node_modules/pkg-types": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz",+ "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==",+ "license": "MIT",+ "dependencies": {+ "confbox": "^0.2.2",+ "exsolve": "^1.0.7",+ "pathe": "^2.0.3"+ }+ },+ "node_modules/pkg-types/node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },"node_modules/pkg-up": {"version": "3.1.0","resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz",@@ -27740,6 +28066,16 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/pngjs": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz",+ "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.19.0"+ }+ },"node_modules/pofile": {"version": "1.1.4","resolved": "https://registry.npmjs.org/pofile/-/pofile-1.1.4.tgz",@@ -28295,14 +28631,14 @@}},"node_modules/prisma": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.8.2.tgz",- "integrity": "sha512-JNricTXQxzDtRS7lCGGOB4g5DJ91eg3nozdubXze3LpcMl1oWwcFddrj++Up3jnRE6X/3gB/xz3V+ecBk/eEGA==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.18.0.tgz",+ "integrity": "sha512-bXWy3vTk8mnRmT+SLyZBQoC2vtV9Z8u7OHvEu+aULYxwiop/CPiFZ+F56KsNRNf35jw+8wcu8pmLsjxpBxAO9g==","hasInstallScript": true,"license": "Apache-2.0","dependencies": {- "@prisma/config": "6.8.2",- "@prisma/engines": "6.8.2"+ "@prisma/config": "6.18.0",+ "@prisma/engines": "6.18.0"},"bin": {"prisma": "build/index.js"@@ -28329,12 +28665,13 @@}},"node_modules/prisma-json-types-generator": {- "version": "3.4.1",- "resolved": "https://registry.npmjs.org/prisma-json-types-generator/-/prisma-json-types-generator-3.4.1.tgz",- "integrity": "sha512-VWsuvCyHyOHoyyuishw9hPjoDYx9+sa+v0E0ggHheYkQ5N9tt6EXd9AYaR181WWMG+K+1Ua2tW0yEsl52pe9ew==",+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/prisma-json-types-generator/-/prisma-json-types-generator-3.6.2.tgz",+ "integrity": "sha512-WX/oENQ0S74r/Wgd2uuHT5i3KbnwLFCP2Fq5ISzrXkus/htOC4uCaQPYuGP2m/wSeKZZCw1RxptTlD+ib7Ht/A==","license": "MIT","dependencies": {- "@prisma/generator-helper": "^6.7.0",+ "@prisma/generator-helper": "^6.16.1",+ "semver": "^7.7.2","tslib": "^2.8.1"},"bin": {@@ -28347,19 +28684,32 @@"url": "https://github.com/arthurfiorette/prisma-json-types-generator?sponsor=1"},"peerDependencies": {- "prisma": "^6.7",- "typescript": "^5.8"+ "@prisma/client": "^6.14",+ "prisma": "^6.14",+ "typescript": "^5.9.2"}},"node_modules/prisma-json-types-generator/node_modules/@prisma/generator-helper": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/generator-helper/-/generator-helper-6.8.2.tgz",- "integrity": "sha512-KBLW47sbwFBKKYMiICIAEWsG6TdpPapPT7e7hpmpF3xMgYAm6YIXu4JGwfQVDY9Vbcb+0vPdPdSEQtInYOOe5g==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/generator-helper/-/generator-helper-6.18.0.tgz",+ "integrity": "sha512-kmlCDRRewLwBkHpkAjzyuNHD5ISlDLzUTcTsZbwmjDilQVt/S72xvvCAa+hxY16APTkqbtDYn3p7zL/XFO+C0A==","license": "Apache-2.0","dependencies": {- "@prisma/debug": "6.8.2",- "@prisma/dmmf": "6.8.2",- "@prisma/generator": "6.8.2"+ "@prisma/debug": "6.18.0",+ "@prisma/dmmf": "6.18.0",+ "@prisma/generator": "6.18.0"+ }+ },+ "node_modules/prisma-json-types-generator/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"}},"node_modules/prisma-kysely": {@@ -28606,6 +28956,22 @@"node": ">=6"}},+ "node_modules/pure-rand": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",+ "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT"+ },"node_modules/pvtsutils": {"version": "1.3.6","resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",@@ -28795,6 +29161,16 @@"node": ">=0.10.0"}},+ "node_modules/rc9": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz",+ "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==",+ "license": "MIT",+ "dependencies": {+ "defu": "^6.1.4",+ "destr": "^2.0.3"+ }+ },"node_modules/re-resizable": {"version": "6.11.2","resolved": "https://registry.npmjs.org/re-resizable/-/re-resizable-6.11.2.tgz",@@ -32568,15 +32944,15 @@}},"node_modules/superjson": {- "version": "1.13.3",- "resolved": "https://registry.npmjs.org/superjson/-/superjson-1.13.3.tgz",- "integrity": "sha512-mJiVjfd2vokfDxsQPOwJ/PtanO87LhpYY88ubI5dUB1Ab58Txbyje3+jpm+/83R/fevaq/107NNhtYBLuoTrFg==",+ "version": "2.2.5",+ "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz",+ "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==","license": "MIT","dependencies": {- "copy-anything": "^3.0.2"+ "copy-anything": "^4"},"engines": {- "node": ">=10"+ "node": ">=16"}},"node_modules/supports-color": {@@ -33087,6 +33463,12 @@"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==","license": "MIT"},+ "node_modules/tinyexec": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.1.tgz",+ "integrity": "sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==",+ "license": "MIT"+ },"node_modules/tinyglobby": {"version": "0.2.13","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.13.tgz",@@ -33397,9 +33779,9 @@}},"node_modules/trpc-to-openapi": {- "version": "2.0.4",- "resolved": "https://registry.npmjs.org/trpc-to-openapi/-/trpc-to-openapi-2.0.4.tgz",- "integrity": "sha512-jhsTv2oOuZwyKXCSGTXPXRNE6ArT/ArdWTHgxROZRVyikUm/ImLszFzh4jV19J7OVu/6qRfmIihwE3ZY/ZdeVg==",+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/trpc-to-openapi/-/trpc-to-openapi-2.4.0.tgz",+ "integrity": "sha512-B6xrwOC3Ab0q1BWD/QbJzK4OUpCLoT02hAzshSUXEuIZGcJZkMG/OJ4/3gd20dyr8aI+CrFirpWKRIo7JmHbMQ==","license": "MIT","workspaces": [".",@@ -33412,18 +33794,17 @@"examples/with-nuxtjs"],"dependencies": {- "co-body": "^6.1.0",- "h3": "^1.6.4",- "lodash.clonedeep": "^4.5.0",- "openapi3-ts": "4.3.3",- "zod-openapi": "^2.19.0"+ "co-body": "6.2.0",+ "h3": "1.15.1",+ "openapi3-ts": "4.4.0"},"optionalDependencies": {"@rollup/rollup-linux-x64-gnu": "4.6.1"},"peerDependencies": {- "@trpc/server": "^11.0.0-rc.648",- "zod": "^3.23.8"+ "@trpc/server": "^11.1.0",+ "zod": "^3.23.8",+ "zod-openapi": "4.2.4"}},"node_modules/trpc-to-openapi/node_modules/@rollup/rollup-linux-x64-gnu": {@@ -33440,12 +33821,12 @@]},"node_modules/trpc-to-openapi/node_modules/openapi3-ts": {- "version": "4.3.3",- "resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.3.3.tgz",- "integrity": "sha512-LKkzBGJcZ6wdvkKGMoSvpK+0cbN5Xc3XuYkJskO+vjEQWJgs1kgtyUk0pjf8KwPuysv323Er62F5P17XQl96Qg==",+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.4.0.tgz",+ "integrity": "sha512-9asTNB9IkKEzWMcHmVZE7Ts3kC9G7AFHfs8i7caD8HbI76gEjdkId4z/AkP83xdZsH7PLAnnbl47qZkXuxpArw==","license": "MIT","dependencies": {- "yaml": "^2.4.5"+ "yaml": "^2.5.0"}},"node_modules/ts-api-utils": {@@ -36088,54 +36469,68 @@}},"node_modules/zod": {- "version": "3.24.1",- "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz",- "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==",+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==","license": "MIT","funding": {"url": "https://github.com/sponsors/colinhacks"}},+ "node_modules/zod-form-data": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/zod-form-data/-/zod-form-data-2.0.8.tgz",+ "integrity": "sha512-X31GkEc8uk5/L387L4TVI1z7obBbN/0MRHBHfHW3uMOWkVJeSsa+grvkTvY9qyFbNshKEnqK+jLJNlY+d7jpLw==",+ "license": "MIT",+ "dependencies": {+ "@rvf/set-get": "^7.0.0"+ },+ "peerDependencies": {+ "zod": ">= 3.11.0"+ }+ },"node_modules/zod-openapi": {- "version": "2.19.0",- "resolved": "https://registry.npmjs.org/zod-openapi/-/zod-openapi-2.19.0.tgz",- "integrity": "sha512-OUAAyBDPPwZ9u61i4k/LieXUzP2re8kFjqdNh2AvHjsyi/aRNz9leDAtMGcSoSzUT5xUeQoACJufBI6FzzZyxA==",+ "version": "4.2.4",+ "resolved": "https://registry.npmjs.org/zod-openapi/-/zod-openapi-4.2.4.tgz",+ "integrity": "sha512-tsrQpbpqFCXqVXUzi3TPwFhuMtLN3oNZobOtYnK6/5VkXsNdnIgyNr4r8no4wmYluaxzN3F7iS+8xCW8BmMQ8g==","license": "MIT","engines": {- "node": ">=16.11"+ "node": ">=18"},"peerDependencies": {"zod": "^3.21.4"}},"node_modules/zod-prisma-types": {- "version": "3.2.4",- "resolved": "https://registry.npmjs.org/zod-prisma-types/-/zod-prisma-types-3.2.4.tgz",- "integrity": "sha512-S4spVBMJAmecLv+aLyRhXK26qW9nWwcsOf1H1fRcEmiI8DPbftZ99u0fhqHlymuTpmMcUpuKxcNNOIqNY0ScSQ==",+ "version": "3.3.5",+ "resolved": "https://registry.npmjs.org/zod-prisma-types/-/zod-prisma-types-3.3.5.tgz",+ "integrity": "sha512-PDuRRCdX1d6ch6UclNvrqM1SLb2qvuaQPvZT/OHRrcxOQqQUnCz009aBc1uxuwMho1+d42TTDCQr+HPXhTSJtQ==","license": "MIT","dependencies": {- "@prisma/generator-helper": "^6.3.0",- "code-block-writer": "^12.0.0",+ "@prisma/dmmf": "^6.16.3",+ "@prisma/generator-helper": "^6.16.3",+ "code-block-writer": "^13.0.3","lodash": "^4.17.21",- "zod": "^3.24.1"+ "zod": "^4.1.11"},"bin": {"zod-prisma-types": "dist/bin.js"},"peerDependencies": {"@prisma/client": "^4.x.x || ^5.x.x || ^6.x.x",- "prisma": "^4.x.x || ^5.x.x || ^6.x.x"+ "prisma": "^4.x.x || ^5.x.x || ^6.x.x",+ "zod": "^3.25.0 || ^4.0.0"}},"node_modules/zod-prisma-types/node_modules/@prisma/generator-helper": {- "version": "6.8.2",- "resolved": "https://registry.npmjs.org/@prisma/generator-helper/-/generator-helper-6.8.2.tgz",- "integrity": "sha512-KBLW47sbwFBKKYMiICIAEWsG6TdpPapPT7e7hpmpF3xMgYAm6YIXu4JGwfQVDY9Vbcb+0vPdPdSEQtInYOOe5g==",+ "version": "6.18.0",+ "resolved": "https://registry.npmjs.org/@prisma/generator-helper/-/generator-helper-6.18.0.tgz",+ "integrity": "sha512-kmlCDRRewLwBkHpkAjzyuNHD5ISlDLzUTcTsZbwmjDilQVt/S72xvvCAa+hxY16APTkqbtDYn3p7zL/XFO+C0A==","license": "Apache-2.0","dependencies": {- "@prisma/debug": "6.8.2",- "@prisma/dmmf": "6.8.2",- "@prisma/generator": "6.8.2"+ "@prisma/debug": "6.18.0",+ "@prisma/dmmf": "6.18.0",+ "@prisma/generator": "6.18.0"}},"node_modules/zwitch": {@@ -36155,15 +36550,15 @@"dependencies": {"@documenso/lib": "*","@documenso/prisma": "*",- "@ts-rest/core": "^3.30.5",- "@ts-rest/open-api": "^3.33.0",- "@ts-rest/serverless": "^3.30.5",+ "@ts-rest/core": "^3.52.0",+ "@ts-rest/open-api": "^3.52.0",+ "@ts-rest/serverless": "^3.52.0","@types/swagger-ui-react": "^5.18.0","luxon": "^3.4.0",- "superjson": "^1.13.1",+ "superjson": "^2.2.5","swagger-ui-react": "^5.21.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}},"packages/api/node_modules/ts-pattern": {@@ -36183,7 +36578,10 @@"@documenso/lib": "*","@documenso/prisma": "*","@playwright/test": "1.52.0",- "@types/node": "^20"+ "@types/node": "^20",+ "@types/pngjs": "^6.0.5",+ "pixelmatch": "^7.1.0",+ "pngjs": "^7.0.0"}},"packages/app-tests/node_modules/@playwright/test": {@@ -36384,7 +36782,7 @@"luxon": "^3.5.0","nanoid": "^5.1.5","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}},"packages/auth/node_modules/ts-pattern": {@@ -36404,7 +36802,7 @@"micro": "^10.0.1","react": "^18","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}},"packages/ee/node_modules/ts-pattern": {@@ -36734,7 +37132,7 @@"skia-canvas": "^3.0.8","stripe": "^12.7.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"},"devDependencies": {"@playwright/browser-chromium": "1.52.0",@@ -36764,14 +37162,14 @@"version": "0.0.0","license": "MIT","dependencies": {- "@prisma/client": "^6.8.2",+ "@prisma/client": "^6.18.0","kysely": "0.26.3",- "prisma": "^6.8.2",+ "prisma": "^6.18.0","prisma-extension-kysely": "^3.0.0",- "prisma-json-types-generator": "^3.2.2",+ "prisma-json-types-generator": "^3.6.2","prisma-kysely": "^1.8.0","ts-pattern": "^5.0.6",- "zod-prisma-types": "3.2.4"+ "zod-prisma-types": "3.3.5"},"devDependencies": {"dotenv": "^16.5.0",@@ -37155,22 +37553,38 @@"dependencies": {"@documenso/lib": "*","@documenso/prisma": "*",- "@tanstack/react-query": "5.59.15",- "@trpc/client": "11.0.0-rc.648",- "@trpc/react-query": "11.0.0-rc.648",- "@trpc/server": "11.0.0-rc.648",- "@ts-rest/core": "^3.30.5",+ "@tanstack/react-query": "5.90.5",+ "@trpc/client": "11.7.0",+ "@trpc/react-query": "11.7.0",+ "@trpc/server": "11.7.0",+ "@ts-rest/core": "^3.52.0",+ "formidable": "^3.5.4","luxon": "^3.4.0",- "superjson": "^1.13.1",- "trpc-to-openapi": "2.0.4",+ "superjson": "^2.2.5",+ "trpc-to-openapi": "2.4.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76",+ "zod-form-data": "^2.0.8",+ "zod-openapi": "^4.2.4"+ },+ "devDependencies": {+ "@types/formidable": "^3.4.6"+ }+ },+ "packages/trpc/node_modules/@types/formidable": {+ "version": "3.4.6",+ "resolved": "https://registry.npmjs.org/@types/formidable/-/formidable-3.4.6.tgz",+ "integrity": "sha512-LI4Hk+KNsM5q7br4oMVoaWeb+gUqJpz1N8+Y2Q6Cz9cVH33ybahRKUWaRmMboVlkwSbOUGgwc/pEkS7yMSzoWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"}},"packages/trpc/node_modules/ts-pattern": {- "version": "5.7.1",- "resolved": "https://registry.npmjs.org/ts-pattern/-/ts-pattern-5.7.1.tgz",- "integrity": "sha512-EGs8PguQqAAUIcQfK4E9xdXxB6s2GK4sJfT/vcc9V1ELIvC4LH/zXu2t/5fajtv6oiRCxdv7BgtVK3vWgROxag==",+ "version": "5.9.0",+ "resolved": "https://registry.npmjs.org/ts-pattern/-/ts-pattern-5.9.0.tgz",+ "integrity": "sha512-6s5V71mX8qBUmlgbrfL33xDUwO0fq48rxAu2LBE11WBeGdpCPOsXksQbZJHvHwhrd3QjUusd3mAOM5Gg0mFBLg==","license": "MIT"},"packages/tsconfig": {@@ -37235,7 +37649,7 @@"tailwind-merge": "^1.12.0","tailwindcss-animate": "^1.0.5","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"},"devDependencies": {"@documenso/tailwind-config": "*",diff --git a/package.json b/package.jsonindex 1d75e7239..5b2d6d4f7 100644--- a/package.json+++ b/package.json@@ -44,7 +44,7 @@"@commitlint/cli": "^17.7.1","@commitlint/config-conventional": "^17.7.0","@lingui/cli": "^5.2.0",- "@prisma/client": "^6.8.2",+ "@prisma/client": "^6.18.0","dotenv": "^16.5.0","dotenv-cli": "^8.0.0","eslint": "^8.40.0",@@ -54,11 +54,22 @@"nodemailer": "^6.10.1","playwright": "1.52.0","prettier": "^3.3.3",- "prisma": "^6.8.2",+ "prisma": "^6.18.0","prisma-extension-kysely": "^3.0.0",+ "prisma-json-types-generator": "^3.6.2","prisma-kysely": "^1.8.0","rimraf": "^5.0.1","turbo": "^1.9.3",+ "@trpc/client": "11.7.0",+ "@trpc/react-query": "11.7.0",+ "@trpc/server": "11.7.0",+ "superjson": "^2.2.5",+ "trpc-to-openapi": "2.4.0",+ "zod-openapi": "^4.2.4",+ "@ts-rest/core": "^3.52.1",+ "@ts-rest/open-api": "^3.52.1",+ "@ts-rest/serverless": "^3.52.1",+ "zod-prisma-types": "3.3.5","vite": "^6.3.5"},"name": "@documenso/root",@@ -76,12 +87,12 @@"mupdf": "^1.0.0","react": "^18","typescript": "5.6.2",- "zod": "3.24.1"+ "zod": "^3.25.76"},"overrides": {- "zod": "3.24.1"+ "zod": "^3.25.76"},"trigger.dev": {"endpointId": "documenso-app"}-}+}\ No newline at end of filediff --git a/packages/api/package.json b/packages/api/package.jsonindex 437198247..e68af4616 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -17,14 +17,14 @@"dependencies": {"@documenso/lib": "*","@documenso/prisma": "*",- "@ts-rest/core": "^3.30.5",- "@ts-rest/open-api": "^3.33.0",- "@ts-rest/serverless": "^3.30.5",+ "@ts-rest/core": "^3.52.0",+ "@ts-rest/open-api": "^3.52.0",+ "@ts-rest/serverless": "^3.52.0","@types/swagger-ui-react": "^5.18.0","luxon": "^3.4.0",- "superjson": "^1.13.1",+ "superjson": "^2.2.5","swagger-ui-react": "^5.21.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}}\ No newline at end of filediff --git a/packages/api/v1/implementation.ts b/packages/api/v1/implementation.tsindex 83a4b7dc8..c7ec90f2b 100644--- a/packages/api/v1/implementation.ts+++ b/packages/api/v1/implementation.ts@@ -20,12 +20,12 @@ import {getEnvelopeWhereInput,} from '@documenso/lib/server-only/envelope/get-envelope-by-id';import { deleteDocumentField } from '@documenso/lib/server-only/field/delete-document-field';-import { updateDocumentFields } from '@documenso/lib/server-only/field/update-document-fields';+import { updateEnvelopeFields } from '@documenso/lib/server-only/field/update-envelope-fields';import { insertFormValuesInPdf } from '@documenso/lib/server-only/pdf/insert-form-values-in-pdf';-import { deleteDocumentRecipient } from '@documenso/lib/server-only/recipient/delete-document-recipient';+import { deleteEnvelopeRecipient } from '@documenso/lib/server-only/recipient/delete-envelope-recipient';import { getRecipientsForDocument } from '@documenso/lib/server-only/recipient/get-recipients-for-document';import { setDocumentRecipients } from '@documenso/lib/server-only/recipient/set-document-recipients';-import { updateDocumentRecipients } from '@documenso/lib/server-only/recipient/update-document-recipients';+import { updateEnvelopeRecipients } from '@documenso/lib/server-only/recipient/update-envelope-recipients';import { createDocumentFromTemplate } from '@documenso/lib/server-only/template/create-document-from-template';import { deleteTemplate } from '@documenso/lib/server-only/template/delete-template';import { findTemplates } from '@documenso/lib/server-only/template/find-templates';@@ -1285,7 +1285,7 @@ export const ApiContractV1Implementation = tsr.router(ApiContractV1, {};}- const updatedRecipient = await updateDocumentRecipients({+ const updatedRecipient = await updateEnvelopeRecipients({userId: user.id,teamId: team.id,id: {@@ -1336,7 +1336,7 @@ export const ApiContractV1Implementation = tsr.router(ApiContractV1, {},});- const deletedRecipient = await deleteDocumentRecipient({+ const deletedRecipient = await deleteEnvelopeRecipient({userId: user.id,teamId: team.id,recipientId: Number(recipientId),@@ -1634,10 +1634,13 @@ export const ApiContractV1Implementation = tsr.router(ApiContractV1, {};}- const { fields } = await updateDocumentFields({+ const { fields } = await updateEnvelopeFields({userId: user.id,teamId: team.id,- documentId: legacyDocumentId,+ id: {+ type: 'documentId',+ id: legacyDocumentId,+ },fields: [{id: Number(fieldId),diff --git a/packages/app-tests/constants/field-alignment-pdf.ts b/packages/app-tests/constants/field-alignment-pdf.tsnew file mode 100644index 000000000..7f42d9ef5--- /dev/null+++ b/packages/app-tests/constants/field-alignment-pdf.ts@@ -0,0 +1,498 @@+import { FieldType } from '@prisma/client';++import type { TFieldAndMeta } from '@documenso/lib/types/field-meta';+import { toCheckboxCustomText } from '@documenso/lib/utils/fields';++export type FieldTestData = TFieldAndMeta & {+ page: number;+ positionX: number;+ positionY: number;+ width: number;+ height: number;+ customText: string;+ signature?: string;+};++const columnWidth = 19.125;+const rowHeight = 6.7;++const alignmentGridStartX = 31;+const alignmentGridStartY = 19.02;++export const ALIGNMENT_TEST_FIELDS: FieldTestData[] = [+ /**+ * Row 1 EMAIL+ */+ {+ type: FieldType.EMAIL,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'email',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '[email protected]',+ },+ {+ type: FieldType.EMAIL,+ fieldMeta: {+ textAlign: 'center',+ type: 'email',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '[email protected]',+ },+ {+ type: FieldType.EMAIL,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'email',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '[email protected]',+ },+ /**+ * Row 2 NAME+ */+ {+ type: FieldType.NAME,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'name',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'John Doe',+ },+ {+ type: FieldType.NAME,+ fieldMeta: {+ textAlign: 'center',+ type: 'name',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'John Doe',+ },+ {+ type: FieldType.NAME,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'name',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'John Doe',+ },+ /**+ * Row 3 DATE+ */+ {+ type: FieldType.DATE,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'date',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.DATE,+ fieldMeta: {+ textAlign: 'center',+ type: 'date',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.DATE,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'date',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ /**+ * Row 4 TEXT+ */+ {+ type: FieldType.TEXT,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'text',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ textAlign: 'center',+ type: 'text',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'text',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ /**+ * Row 5 NUMBER+ */+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'number',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ textAlign: 'center',+ type: 'number',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'number',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '123456789',+ },+ /**+ * Row 6 Initials+ */+ {+ type: FieldType.INITIALS,+ fieldMeta: {+ fontSize: 10,+ textAlign: 'left',+ type: 'initials',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'JD',+ },+ {+ type: FieldType.INITIALS,+ fieldMeta: {+ textAlign: 'center',+ type: 'initials',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'JD',+ },+ {+ type: FieldType.INITIALS,+ fieldMeta: {+ fontSize: 20,+ textAlign: 'right',+ type: 'initials',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'JD',+ },+ /**+ * Row 7 Radio+ */+ {+ type: FieldType.RADIO,+ fieldMeta: {+ fontSize: 10,+ direction: 'vertical',+ type: 'radio',+ values: [+ { id: 1, checked: true, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '0',+ },+ {+ type: FieldType.RADIO,+ fieldMeta: {+ direction: 'vertical',+ type: 'radio',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: true, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '2',+ },+ {+ type: FieldType.RADIO,+ fieldMeta: {+ fontSize: 20,+ direction: 'horizontal',+ type: 'radio',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '',+ },+ /**+ * Row 8 Checkbox+ */+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ fontSize: 10,+ direction: 'vertical',+ type: 'checkbox',+ values: [+ { id: 1, checked: true, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: toCheckboxCustomText([0]),+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: true, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: toCheckboxCustomText([1]),+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ fontSize: 20,+ direction: 'horizontal',+ type: 'checkbox',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '',+ },+ /**+ * Row 8 Dropdown+ */+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ fontSize: 10,+ values: [{ value: 'Option 1' }, { value: 'Option 2' }],+ type: 'dropdown',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'Option 1',+ },+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ values: [{ value: 'Option 1' }, { value: 'Option 2' }],+ type: 'dropdown',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'Option 1',+ },+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ fontSize: 20,+ values: [{ value: 'Option 1' }, { value: 'Option 2' }, { value: 'Option 3' }],+ type: 'dropdown',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: 'Option 1',+ },+ /**+ * Row 9 Signature+ */+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ fontSize: 10,+ type: 'signature',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '',+ signature: 'My Signature',+ },+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ type: 'signature',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '',+ signature: 'My Signature',+ },+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ fontSize: 20,+ type: 'signature',+ },+ page: 1,+ height: rowHeight,+ width: columnWidth,+ positionX: 0,+ positionY: 0,+ customText: '',+ signature: 'My Signature',+ },+] as const;++export const formatAlignmentTestFields = ALIGNMENT_TEST_FIELDS.map((field, index) => {+ const row = Math.floor(index / 3);+ const column = index % 3;++ return {+ ...field,+ positionX: alignmentGridStartX + column * columnWidth,+ positionY: alignmentGridStartY + row * rowHeight,+ };+});diff --git a/packages/app-tests/constants/field-meta-pdf.ts b/packages/app-tests/constants/field-meta-pdf.tsnew file mode 100644index 000000000..36cb79590--- /dev/null+++ b/packages/app-tests/constants/field-meta-pdf.ts@@ -0,0 +1,482 @@+import { FieldType } from '@prisma/client';++import { toCheckboxCustomText } from '@documenso/lib/utils/fields';+import {+ CheckboxValidationRules,+ numberFormatValues,+} from '@documenso/ui/primitives/document-flow/field-items-advanced-settings/constants';++import type { FieldTestData } from './field-alignment-pdf';++const columnWidth = 20.1;+const fullColumnWidth = 75.8;+const rowHeight = 9.8;+const rowPadding = 1.8;++const alignmentGridStartX = 11.85;+const alignmentGridStartY = 15.07;++const calculatePosition = (row: number, column: number, width: 'full' | 'column' = 'column') => {+ return {+ height: rowHeight,+ width: width === 'full' ? fullColumnWidth : columnWidth,+ positionX: alignmentGridStartX + (column ?? 0) * columnWidth,+ positionY: alignmentGridStartY + row * (rowHeight + rowPadding),+ };+};++export const FIELD_META_TEST_FIELDS: FieldTestData[] = [+ /**+ * PAGE 2 Signature+ */+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ type: 'signature',+ },+ page: 2,+ ...calculatePosition(0, 0),+ customText: '',+ signature: 'My Signature',+ },+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ type: 'signature',+ },+ page: 2,+ ...calculatePosition(1, 0),+ customText: '',+ signature: 'My Signature',+ },+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ type: 'signature',+ },+ page: 2,+ ...calculatePosition(2, 0),+ customText: '',+ signature: 'My Signature',+ },+ {+ type: FieldType.SIGNATURE,+ fieldMeta: {+ type: 'signature',+ },+ page: 2,+ ...calculatePosition(3, 0),+ customText: '',+ signature: 'My Signature',+ },++ /**+ * PAGE 3 TEXT+ */+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ },+ page: 3,+ ...calculatePosition(0, 0, 'full'),+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ },+ page: 3,+ ...calculatePosition(1, 0),+ customText: '123456789123456789123456789123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ characterLimit: 5,+ },+ page: 3,+ ...calculatePosition(2, 0),+ customText: '12345',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ placeholder: 'Demo Placeholder',+ },+ page: 3,+ ...calculatePosition(3, 0),+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ label: 'Demo Label',+ },+ page: 3,+ ...calculatePosition(3, 1),+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ text: 'Prefilled text',+ },+ page: 3,+ ...calculatePosition(3, 2),+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ required: true,+ },+ page: 3,+ ...calculatePosition(4, 0),+ customText: '123456789',+ },+ {+ type: FieldType.TEXT,+ fieldMeta: {+ type: 'text',+ readOnly: true,+ text: 'Readonly Value',+ },+ page: 3,+ ...calculatePosition(4, 1),+ customText: 'Readonly Value',+ },++ /**+ * PAGE 4 NUMBER+ */+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ },+ page: 4,+ ...calculatePosition(0, 0, 'full'),+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ },+ page: 4,+ ...calculatePosition(1, 0),+ customText: '123456789123456789123456789123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ minValue: 0,+ maxValue: 100,+ },+ page: 4,+ ...calculatePosition(2, 0),+ customText: '50',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ numberFormat: numberFormatValues[0].value, // Todo: Envelopes - Check this.+ value: '123,456,789.00',+ },+ page: 4,+ ...calculatePosition(2, 1),+ customText: '123,456,789.00',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ placeholder: 'Demo Placeholder',+ },+ page: 4,+ ...calculatePosition(3, 0),+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ label: 'Demo Label',+ },+ page: 4,+ ...calculatePosition(3, 1),+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ value: '123',+ },+ page: 4,+ ...calculatePosition(3, 2),+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ required: true,+ },+ page: 4,+ ...calculatePosition(4, 0),+ customText: '123456789',+ },+ {+ type: FieldType.NUMBER,+ fieldMeta: {+ type: 'number',+ readOnly: true,+ },+ page: 4,+ ...calculatePosition(4, 1),+ customText: '123456789',+ },++ /**+ * PAGE 5 RADIO+ */+ {+ type: FieldType.RADIO,+ fieldMeta: {+ direction: 'horizontal',+ type: 'radio',+ values: [+ { id: 1, checked: true, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 5,+ ...calculatePosition(0, 0, 'full'),+ customText: '0',+ },+ {+ type: FieldType.RADIO,+ fieldMeta: {+ direction: 'vertical',+ type: 'radio',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: true, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 5,+ ...calculatePosition(1, 0),+ customText: '2',+ },+ {+ type: FieldType.RADIO,+ fieldMeta: {+ direction: 'vertical',+ type: 'radio',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 5,+ ...calculatePosition(2, 0),+ customText: '',+ },+ {+ type: FieldType.RADIO,+ fieldMeta: {+ direction: 'vertical',+ type: 'radio',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 5,+ ...calculatePosition(2, 1),+ customText: '',+ },++ /**+ * PAGE 6 CHECKBOX+ */+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'horizontal',+ type: 'checkbox',+ values: [+ { id: 1, checked: true, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 2, checked: false, value: 'Option 3' },+ { id: 2, checked: false, value: 'Option 4' },+ ],+ },+ page: 6,+ ...calculatePosition(0, 0, 'full'),+ customText: toCheckboxCustomText([0]),+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: true, value: 'Option 2' },+ { id: 2, checked: true, value: 'Option 3' },+ ],+ },+ page: 6,+ ...calculatePosition(1, 0),+ customText: toCheckboxCustomText([1]),+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ required: true,+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 6,+ ...calculatePosition(2, 0),+ customText: '',+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ readOnly: true,+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ ],+ },+ page: 6,+ ...calculatePosition(2, 1),+ customText: '',+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ validationRule: CheckboxValidationRules.SELECT_AT_LEAST,+ validationLength: 2,+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 6,+ ...calculatePosition(3, 0),+ customText: '',+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ validationRule: CheckboxValidationRules.SELECT_EXACTLY,+ validationLength: 2,+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 6,+ ...calculatePosition(3, 1),+ customText: '',+ },+ {+ type: FieldType.CHECKBOX,+ fieldMeta: {+ direction: 'vertical',+ type: 'checkbox',+ validationRule: CheckboxValidationRules.SELECT_AT_MOST,+ validationLength: 2,+ values: [+ { id: 1, checked: false, value: 'Option 1' },+ { id: 2, checked: false, value: 'Option 2' },+ { id: 3, checked: false, value: 'Option 3' },+ ],+ },+ page: 6,+ ...calculatePosition(3, 2),+ customText: '',+ },++ /**+ * PAGE 7 DROPDOWN+ */+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ values: [{ value: 'Option 1' }, { value: 'Option 2' }],+ type: 'dropdown',+ },+ page: 7,+ ...calculatePosition(0, 0, 'full'),+ customText: 'Option 1',+ },+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ values: [{ value: 'Option 1' }, { value: 'Option 2' }],+ type: 'dropdown',+ defaultValue: 'Option 1',+ },+ page: 7,+ ...calculatePosition(1, 0),+ customText: 'Option 1',+ },+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ values: [{ value: 'Option 1' }, { value: 'Option 2' }, { value: 'Option 3' }],+ type: 'dropdown',+ required: true,+ },+ page: 7,+ ...calculatePosition(2, 0),+ customText: 'Option 1',+ },+ {+ type: FieldType.DROPDOWN,+ fieldMeta: {+ values: [{ value: 'Option 1' }, { value: 'Option 2' }, { value: 'Option 3' }],+ type: 'dropdown',+ readOnly: true,+ },+ page: 7,+ ...calculatePosition(2, 1),+ customText: 'Option 1',+ },+] as const;++export const formatFieldMetaTestFields = FIELD_META_TEST_FIELDS.map((field, index) => {+ return {+ ...field,+ };+});diff --git a/packages/app-tests/e2e/api/v2/envelopes-api.spec.ts b/packages/app-tests/e2e/api/v2/envelopes-api.spec.tsnew file mode 100644index 000000000..8e759efd7--- /dev/null+++ b/packages/app-tests/e2e/api/v2/envelopes-api.spec.ts@@ -0,0 +1,560 @@+import { expect, test } from '@playwright/test';+import type { Team, User } from '@prisma/client';+import fs from 'node:fs';+import path from 'node:path';+import { pick } from 'remeda';++import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';+import { createApiToken } from '@documenso/lib/server-only/public-api/create-api-token';+import { prisma } from '@documenso/prisma';+import {+ DocumentDistributionMethod,+ DocumentSigningOrder,+ DocumentStatus,+ DocumentVisibility,+ EnvelopeType,+ FieldType,+ FolderType,+ RecipientRole,+} from '@documenso/prisma/client';+import { seedUser } from '@documenso/prisma/seed/users';+import type { TCreateEnvelopeItemsPayload } from '@documenso/trpc/server/envelope-router/create-envelope-items.types';+import type {+ TCreateEnvelopePayload,+ TCreateEnvelopeResponse,+} from '@documenso/trpc/server/envelope-router/create-envelope.types';+import type { TCreateEnvelopeRecipientsRequest } from '@documenso/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.types';+import type { TGetEnvelopeResponse } from '@documenso/trpc/server/envelope-router/get-envelope.types';+import type { TUpdateEnvelopeRequest } from '@documenso/trpc/server/envelope-router/update-envelope.types';++import { formatAlignmentTestFields } from '../../../constants/field-alignment-pdf';+import { FIELD_META_TEST_FIELDS } from '../../../constants/field-meta-pdf';++const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();+const baseUrl = `${WEBAPP_BASE_URL}/api/v2-beta`;++test.describe.configure({+ mode: 'parallel',+});++test.describe('API V2 Envelopes', () => {+ let userA: User, teamA: Team, userB: User, teamB: Team, tokenA: string, tokenB: string;++ test.beforeEach(async () => {+ ({ user: userA, team: teamA } = await seedUser());+ ({ token: tokenA } = await createApiToken({+ userId: userA.id,+ teamId: teamA.id,+ tokenName: 'userA',+ expiresIn: null,+ }));++ ({ user: userB, team: teamB } = await seedUser());+ ({ token: tokenB } = await createApiToken({+ userId: userB.id,+ teamId: teamB.id,+ tokenName: 'userB',+ expiresIn: null,+ }));+ });++ test.describe('Envelope create endpoint', () => {+ test('should fail on invalid form', async ({ request }) => {+ const payload = {+ type: 'Invalid Type',+ title: 'Test Envelope',+ };++ const formData = new FormData();+ formData.append('payload', JSON.stringify(payload));++ const res = await request.post(`${baseUrl}/envelope/create`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ multipart: formData,+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(400);+ });++ test('should create envelope with single file', async ({ request }) => {+ const payload = {+ type: EnvelopeType.TEMPLATE,+ title: 'Test Envelope',+ } satisfies TCreateEnvelopePayload;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));++ const files = [+ {+ name: 'field-font-alignment.pdf',+ data: fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-font-alignment.pdf'),+ ),+ },+ ];++ for (const file of files) {+ formData.append('files', new File([file.data], file.name, { type: 'application/pdf' }));+ }++ const res = await request.post(`${baseUrl}/envelope/create`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ multipart: formData,+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);++ const response = (await res.json()) as TCreateEnvelopeResponse;++ const envelope = await prisma.envelope.findUnique({+ where: {+ id: response.id,+ },+ include: {+ envelopeItems: true,+ },+ });++ expect(envelope).toBeDefined();+ expect(envelope?.title).toBe('Test Envelope');+ expect(envelope?.type).toBe(EnvelopeType.TEMPLATE);+ expect(envelope?.status).toBe(DocumentStatus.DRAFT);+ expect(envelope?.envelopeItems.length).toBe(1);+ expect(envelope?.envelopeItems[0].title).toBe('field-font-alignment.pdf');+ expect(envelope?.envelopeItems[0].documentDataId).toBeDefined();+ });++ test('should create envelope with multiple file', async ({ request }) => {+ const folder = await prisma.folder.create({+ data: {+ name: 'Test Folder',+ teamId: teamA.id,+ userId: userA.id,+ type: FolderType.DOCUMENT,+ },+ });++ const payload = {+ title: 'Envelope Title',+ type: EnvelopeType.DOCUMENT,+ externalId: 'externalId',+ visibility: DocumentVisibility.MANAGER_AND_ABOVE,+ globalAccessAuth: ['ACCOUNT'],+ formValues: {+ hello: 'world',+ },+ folderId: folder.id,+ recipients: [+ {+ email: userA.email,+ name: 'Name',+ role: RecipientRole.SIGNER,+ accessAuth: ['TWO_FACTOR_AUTH'],+ signingOrder: 1,+ fields: [+ {+ type: FieldType.SIGNATURE,+ identifier: 'field-font-alignment.pdf',+ page: 1,+ positionX: 0,+ positionY: 0,+ width: 0,+ height: 0,+ },+ {+ type: FieldType.SIGNATURE,+ identifier: 0,+ page: 1,+ positionX: 0,+ positionY: 0,+ width: 0,+ height: 0,+ },+ ],+ },+ ],+ meta: {+ subject: 'Subject',+ message: 'Message',+ timezone: 'Europe/Berlin',+ dateFormat: 'dd.MM.yyyy',+ distributionMethod: DocumentDistributionMethod.NONE,+ signingOrder: DocumentSigningOrder.SEQUENTIAL,+ allowDictateNextSigner: true,+ redirectUrl: 'https://documenso.com',+ language: 'de',+ typedSignatureEnabled: true,+ uploadSignatureEnabled: false,+ drawSignatureEnabled: false,+ emailReplyTo: userA.email,+ emailSettings: {+ recipientSigningRequest: false,+ recipientRemoved: false,+ recipientSigned: false,+ documentPending: false,+ documentCompleted: false,+ documentDeleted: false,+ ownerDocumentCompleted: true,+ },+ },+ attachments: [+ {+ label: 'Test Attachment',+ data: 'https://documenso.com',+ type: 'link',+ },+ ],+ } satisfies TCreateEnvelopePayload;++ const formData = new FormData();++ formData.append('payload', JSON.stringify(payload));++ const files = [+ {+ name: 'field-meta.pdf',+ data: fs.readFileSync(path.join(__dirname, '../../../../../assets/field-meta.pdf')),+ },+ {+ name: 'field-font-alignment.pdf',+ data: fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-font-alignment.pdf'),+ ),+ },+ ];++ for (const file of files) {+ formData.append('files', new File([file.data], file.name, { type: 'application/pdf' }));+ }++ // Should error since folder is not owned by the user.+ const invalidRes = await request.post(`${baseUrl}/envelope/create`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ multipart: formData,+ });++ expect(invalidRes.ok()).toBeFalsy();++ const res = await request.post(`${baseUrl}/envelope/create`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: formData,+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);++ const response = (await res.json()) as TCreateEnvelopeResponse;++ const envelope = await prisma.envelope.findUniqueOrThrow({+ where: {+ id: response.id,+ },+ include: {+ documentMeta: true,+ envelopeItems: true,+ recipients: true,+ fields: true,+ envelopeAttachments: true,+ },+ });++ console.log(userB.email);++ expect(envelope.envelopeItems.length).toBe(2);+ expect(envelope.envelopeItems[0].title).toBe('field-meta.pdf');+ expect(envelope.envelopeItems[1].title).toBe('field-font-alignment.pdf');++ expect(envelope.title).toBe(payload.title);+ expect(envelope.type).toBe(payload.type);+ expect(envelope.externalId).toBe(payload.externalId);+ expect(envelope.visibility).toBe(payload.visibility);+ expect(envelope.authOptions).toEqual({+ globalAccessAuth: payload.globalAccessAuth,+ globalActionAuth: [],+ });+ expect(envelope.formValues).toEqual(payload.formValues);+ expect(envelope.folderId).toBe(payload.folderId);++ expect(envelope.documentMeta.subject).toBe(payload.meta.subject);+ expect(envelope.documentMeta.message).toBe(payload.meta.message);+ expect(envelope.documentMeta.timezone).toBe(payload.meta.timezone);+ expect(envelope.documentMeta.dateFormat).toBe(payload.meta.dateFormat);+ expect(envelope.documentMeta.distributionMethod).toBe(payload.meta.distributionMethod);+ expect(envelope.documentMeta.signingOrder).toBe(payload.meta.signingOrder);+ expect(envelope.documentMeta.allowDictateNextSigner).toBe(+ payload.meta.allowDictateNextSigner,+ );+ expect(envelope.documentMeta.redirectUrl).toBe(payload.meta.redirectUrl);+ expect(envelope.documentMeta.language).toBe(payload.meta.language);+ expect(envelope.documentMeta.typedSignatureEnabled).toBe(payload.meta.typedSignatureEnabled);+ expect(envelope.documentMeta.uploadSignatureEnabled).toBe(+ payload.meta.uploadSignatureEnabled,+ );+ expect(envelope.documentMeta.drawSignatureEnabled).toBe(payload.meta.drawSignatureEnabled);+ expect(envelope.documentMeta.emailReplyTo).toBe(payload.meta.emailReplyTo);+ expect(envelope.documentMeta.emailSettings).toEqual(payload.meta.emailSettings);++ expect([+ {+ label: envelope.envelopeAttachments[0].label,+ data: envelope.envelopeAttachments[0].data,+ type: envelope.envelopeAttachments[0].type,+ },+ ]).toEqual(payload.attachments);++ const field = envelope.fields[0];+ const recipient = envelope.recipients[0];++ expect({+ email: recipient.email,+ name: recipient.name,+ role: recipient.role,+ signingOrder: recipient.signingOrder,+ accessAuth: recipient.authOptions?.accessAuth,+ }).toEqual(+ pick(payload.recipients[0], ['email', 'name', 'role', 'signingOrder', 'accessAuth']),+ );++ expect({+ type: field.type,+ page: field.page,+ positionX: field.positionX.toNumber(),+ positionY: field.positionY.toNumber(),+ width: field.width.toNumber(),+ height: field.height.toNumber(),+ }).toEqual(+ pick(payload.recipients[0].fields[0], [+ 'type',+ 'page',+ 'positionX',+ 'positionY',+ 'width',+ 'height',+ ]),+ );++ // Expect string based ID to work.+ expect(field.envelopeItemId).toBe(+ envelope.envelopeItems.find((item) => item.title === 'field-font-alignment.pdf')?.id,+ );++ // Expect index based ID to work.+ expect(envelope.fields[1].envelopeItemId).toBe(+ envelope.envelopeItems.find((item) => item.title === 'field-meta.pdf')?.id,+ );+ });+ });++ /**+ * Creates envelopes with the two field test PDFs.+ */+ test('Envelope full test', async ({ request }) => {+ // Step 1: Create initial envelope with Prisma (with first envelope item)+ const alignmentPdf = fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-font-alignment.pdf'),+ );++ const fieldMetaPdf = fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-meta.pdf'),+ );++ const formData = new FormData();++ formData.append(+ 'payload',+ JSON.stringify({+ type: EnvelopeType.DOCUMENT,+ title: 'Envelope Full Field Test',+ } satisfies TCreateEnvelopePayload),+ );++ // Only add one file for now.+ formData.append(+ 'files',+ new File([alignmentPdf], 'field-font-alignment.pdf', { type: 'application/pdf' }),+ );++ const createEnvelopeRequest = await request.post(`${baseUrl}/envelope/create`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: formData,+ });++ expect(createEnvelopeRequest.ok()).toBeTruthy();+ expect(createEnvelopeRequest.status()).toBe(200);++ const { id: createdEnvelopeId }: TCreateEnvelopeResponse = await createEnvelopeRequest.json();++ const getEnvelopeRequest = await request.get(`${baseUrl}/envelope/${createdEnvelopeId}`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ });++ const createdEnvelope: TGetEnvelopeResponse = await getEnvelopeRequest.json();++ // Might as well testing access control here as well.+ const unauthRequest = await request.get(`${baseUrl}/envelope/${createdEnvelopeId}`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ });++ expect(unauthRequest.ok()).toBeFalsy();+ expect(unauthRequest.status()).toBe(404);++ // Step 2: Create second envelope item via API+ const createEnvelopeItemsPayload: TCreateEnvelopeItemsPayload = {+ envelopeId: createdEnvelope.id,+ };++ const createEnvelopeItemFormData = new FormData();+ createEnvelopeItemFormData.append('payload', JSON.stringify(createEnvelopeItemsPayload));+ createEnvelopeItemFormData.append(+ 'files',+ new File([fieldMetaPdf], 'field-meta.pdf', { type: 'application/pdf' }),+ );++ const createItemsRes = await request.post(`${baseUrl}/envelope/item/create-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: createEnvelopeItemFormData,+ });++ expect(createItemsRes.ok()).toBeTruthy();+ expect(createItemsRes.status()).toBe(200);++ // Step 3: Update envelope via API+ const updateEnvelopeRequest: TUpdateEnvelopeRequest = {+ envelopeId: createdEnvelope.id,+ data: {+ title: 'Envelope Full Field Test',+ visibility: DocumentVisibility.MANAGER_AND_ABOVE,+ },+ };++ const updateRes = await request.post(`${baseUrl}/envelope/update`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: updateEnvelopeRequest,+ });++ expect(updateRes.ok()).toBeTruthy();+ expect(updateRes.status()).toBe(200);++ // Step 4: Create recipient via API+ const createRecipientsRequest: TCreateEnvelopeRecipientsRequest = {+ envelopeId: createdEnvelope.id,+ data: [+ {+ email: userA.email,+ name: userA.name || '',+ role: RecipientRole.SIGNER,+ accessAuth: [],+ actionAuth: [],+ },+ ],+ };++ const createRecipientsRes = await request.post(`${baseUrl}/envelope/recipient/create-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: createRecipientsRequest,+ });++ expect(createRecipientsRes.ok()).toBeTruthy();+ expect(createRecipientsRes.status()).toBe(200);++ // Step 5: Get envelope to retrieve recipients and envelope items+ const getRes = await request.get(`${baseUrl}/envelope/${createdEnvelope.id}`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ });++ expect(getRes.ok()).toBeTruthy();+ expect(getRes.status()).toBe(200);++ const envelopeResponse = (await getRes.json()) as TGetEnvelopeResponse;++ const recipientId = envelopeResponse.recipients[0].id;+ const alignmentItem = envelopeResponse.envelopeItems.find(+ (item: { order: number }) => item.order === 1,+ );+ const fieldMetaItem = envelopeResponse.envelopeItems.find(+ (item: { order: number }) => item.order === 2,+ );++ expect(recipientId).toBeDefined();+ expect(alignmentItem).toBeDefined();+ expect(fieldMetaItem).toBeDefined();++ if (!alignmentItem || !fieldMetaItem) {+ throw new Error('Envelope items not found');+ }++ // Step 6: Create fields for first PDF (alignment fields)+ const alignmentFieldsRequest = {+ envelopeId: createdEnvelope.id,+ data: formatAlignmentTestFields.map((field) => ({+ recipientId,+ envelopeItemId: alignmentItem.id,+ type: field.type,+ page: field.page,+ positionX: field.positionX,+ positionY: field.positionY,+ width: field.width,+ height: field.height,+ fieldMeta: field.fieldMeta,+ })),+ };++ const createAlignmentFieldsRes = await request.post(`${baseUrl}/envelope/field/create-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: alignmentFieldsRequest,+ });++ expect(createAlignmentFieldsRes.ok()).toBeTruthy();+ expect(createAlignmentFieldsRes.status()).toBe(200);++ // Step 7: Create fields for second PDF (field-meta fields)+ const fieldMetaFieldsRequest = {+ envelopeId: createdEnvelope.id,+ data: FIELD_META_TEST_FIELDS.map((field) => ({+ recipientId,+ envelopeItemId: fieldMetaItem.id,+ type: field.type,+ page: field.page,+ positionX: field.positionX,+ positionY: field.positionY,+ width: field.width,+ height: field.height,+ fieldMeta: field.fieldMeta,+ })),+ };++ const createFieldMetaFieldsRes = await request.post(`${baseUrl}/envelope/field/create-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: fieldMetaFieldsRequest,+ });++ expect(createFieldMetaFieldsRes.ok()).toBeTruthy();+ expect(createFieldMetaFieldsRes.status()).toBe(200);++ // Step 8: Verify final envelope structure+ const finalGetRes = await request.get(`${baseUrl}/envelope/${createdEnvelope.id}`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ });++ expect(finalGetRes.ok()).toBeTruthy();+ const finalEnvelope = (await finalGetRes.json()) as TGetEnvelopeResponse;++ // Verify structure+ expect(finalEnvelope.envelopeItems.length).toBe(2);+ expect(finalEnvelope.recipients.length).toBe(1);+ expect(finalEnvelope.fields.length).toBe(+ formatAlignmentTestFields.length + FIELD_META_TEST_FIELDS.length,+ );+ expect(finalEnvelope.title).toBe('Envelope Full Field Test');+ expect(finalEnvelope.type).toBe(EnvelopeType.DOCUMENT);++ console.log({+ createdEnvelopeId: finalEnvelope.id,+ userEmail: userA.email,+ });+ });+});diff --git a/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts b/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.tsindex 77686346e..72fa20518 100644--- a/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts+++ b/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts@@ -1,5 +1,7 @@import { expect, test } from '@playwright/test';import type { Team, User } from '@prisma/client';+import fs from 'node:fs';+import path from 'node:path';import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';import { createApiToken } from '@documenso/lib/server-only/public-api/create-api-token';@@ -11,6 +13,7 @@ import {import { prisma } from '@documenso/prisma';import {DocumentVisibility,+ EnvelopeType,FieldType,Prisma,ReadStatus,@@ -27,6 +30,7 @@ import {import { seedBlankFolder } from '@documenso/prisma/seed/folders';import { seedBlankTemplate } from '@documenso/prisma/seed/templates';import { seedUser } from '@documenso/prisma/seed/users';+import type { TCreateEnvelopeItemsPayload } from '@documenso/trpc/server/envelope-router/create-envelope-items.types';const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();@@ -2856,4 +2860,1374 @@ test.describe('Document API V2', () => {expect(res.status()).toBe(200);});});++ test.describe('Document create endpoint', () => {+ test('should allow authorized access to document create endpoint', async ({ request }) => {+ const payload = {+ title: 'Test Document',+ };++ const formData = new FormData();+ formData.append('payload', JSON.stringify(payload));++ const pdfPath = path.join(__dirname, '../../../../../assets/example.pdf');+ const pdfData = fs.existsSync(pdfPath) ? fs.readFileSync(pdfPath) : Buffer.from('%PDF-1.4\n');++ formData.append('file', new File([pdfData], 'test.pdf', { type: 'application/pdf' }));++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/document/create`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: formData,+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);++ const data = await res.json();+ expect(data.envelopeId).toBeDefined();+ expect(data.id).toBeDefined();++ const envelope = await prisma.envelope.findFirstOrThrow({+ where: {+ id: data.envelopeId,+ },+ include: {+ envelopeItems: true,+ },+ });++ expect(envelope?.title).toBe(payload.title);+ expect(envelope.envelopeItems.length).toBe(1);+ });+ });++ test.describe('Template create endpoint', () => {+ test('should allow authorized access to template create endpoint', async ({ request }) => {+ const payload = {+ title: 'Test Template',+ };++ const formData = new FormData();+ formData.append('payload', JSON.stringify(payload));++ const pdfPath = path.join(__dirname, '../../../../../assets/example.pdf');+ const pdfData = fs.existsSync(pdfPath) ? fs.readFileSync(pdfPath) : Buffer.from('%PDF-1.4\n');++ formData.append('file', new File([pdfData], 'test.pdf', { type: 'application/pdf' }));++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/template/create`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: formData,+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);++ const data = await res.json();+ expect(data.envelopeId).toBeDefined();+ expect(data.id).toBeDefined();++ const envelope = await prisma.envelope.findFirstOrThrow({+ where: {+ id: data.envelopeId,+ },+ include: {+ envelopeItems: true,+ },+ });++ expect(envelope.title).toBe(payload.title);+ expect(envelope.envelopeItems.length).toBe(1);+ });+ });++ test.describe('Envelope API V2', () => {+ let userA: User, teamA: Team, userB: User, teamB: Team, tokenA: string, tokenB: string;++ test.beforeEach(async () => {+ ({ user: userA, team: teamA } = await seedUser());+ ({ token: tokenA } = await createApiToken({+ userId: userA.id,+ teamId: teamA.id,+ tokenName: 'userA',+ expiresIn: null,+ }));++ ({ user: userB, team: teamB } = await seedUser());+ ({ token: tokenB } = await createApiToken({+ userId: userB.id,+ teamId: teamB.id,+ tokenName: 'userB',+ expiresIn: null,+ }));+ });++ test.describe('Envelope get endpoint', () => {+ test('should block unauthorized access to envelope get endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.get(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/${doc.id}`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope get endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.get(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/${doc.id}`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope update endpoint', () => {+ test('should block unauthorized access to envelope update endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/update`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ envelopeType: EnvelopeType.DOCUMENT,+ data: { title: 'Updated Title' },+ },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope update endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/update`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ envelopeType: EnvelopeType.DOCUMENT,+ data: { title: 'Updated Title' },+ },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope delete endpoint', () => {+ test('should block unauthorized access to envelope delete endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/delete`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(401);+ });++ test('should allow authorized access to envelope delete endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/delete`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope duplicate endpoint', () => {+ test('should block unauthorized access to envelope duplicate endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/duplicate`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope duplicate endpoint', async ({ request }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/duplicate`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope distribute endpoint', () => {+ test('should block unauthorized access to envelope distribute endpoint', async ({+ request,+ }) => {+ const doc = await seedDraftDocument(userA, teamA.id, ['[email protected]']);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/distribute`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(500);+ });++ test('should allow authorized access to envelope distribute endpoint', async ({+ request,+ }) => {+ const doc = await seedDraftDocument(userA, teamA.id, ['[email protected]']);++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/distribute`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { envelopeId: doc.id },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope redistribute endpoint', () => {+ test('should block unauthorized access to envelope redistribute endpoint', async ({+ request,+ }) => {+ const doc = await seedPendingDocument(userA, teamA.id, []);++ const userRecipient = await prisma.recipient.create({+ data: {+ email: '[email protected]',+ name: 'Test',+ token: nanoid(),+ readStatus: ReadStatus.NOT_OPENED,+ sendStatus: SendStatus.SENT,+ signingStatus: SigningStatus.NOT_SIGNED,+ signedAt: null,+ envelopeId: doc.id,+ fields: {+ create: {+ page: 1,+ type: FieldType.NAME,+ inserted: true,+ customText: '',+ positionX: new Prisma.Decimal(1),+ positionY: new Prisma.Decimal(1),+ width: new Prisma.Decimal(1),+ height: new Prisma.Decimal(1),+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ },+ },+ },+ });++ const recipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: userRecipient.email,+ },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/redistribute`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ recipients: [recipient!.id],+ },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(500);+ });++ test('should allow authorized access to envelope redistribute endpoint', async ({+ request,+ }) => {+ const doc = await seedPendingDocument(userA, teamA.id, []);++ const userRecipient = await prisma.recipient.create({+ data: {+ email: '[email protected]',+ name: 'Test',+ token: nanoid(),+ readStatus: ReadStatus.NOT_OPENED,+ sendStatus: SendStatus.SENT,+ signingStatus: SigningStatus.NOT_SIGNED,+ signedAt: null,+ envelopeId: doc.id,+ fields: {+ create: {+ page: 1,+ type: FieldType.NAME,+ inserted: true,+ customText: '',+ positionX: new Prisma.Decimal(1),+ positionY: new Prisma.Decimal(1),+ width: new Prisma.Decimal(1),+ height: new Prisma.Decimal(1),+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ },+ },+ },+ });++ const recipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: userRecipient.email,+ },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/redistribute`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ recipients: [recipient!.id],+ },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope field get endpoint', () => {+ test('should block unauthorized access to envelope field get endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: userRecipient.email,+ },+ });++ const field = await prisma.field.create({+ data: {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: 'TEXT',+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ });++ const res = await request.get(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/${field.id}`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope field get endpoint', async ({ request }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirstOrThrow({+ where: {+ envelopeId: doc.id,+ email: userRecipient.email,+ },+ });++ const field = await prisma.field.create({+ data: {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient.id,+ type: 'TEXT',+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ });++ const res = await request.get(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/${field.id}`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope field create-many endpoint', () => {+ test('should block unauthorized access to envelope field create-many endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/create-many`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ recipientId: recipient!.id,+ envelopeItemId: doc.envelopeItems[0].id,+ type: 'TEXT',+ page: 791.77,+ positionX: 0,+ positionY: 0,+ width: 5,+ height: 5,+ fieldMeta: { type: 'text', label: 'First test field' },+ },+ {+ recipientId: recipient!.id,+ envelopeItemId: doc.envelopeItems[0].id,+ type: 'TEXT',+ page: 791.77,+ positionX: 0,+ positionY: 0,+ width: 5,+ height: 5,+ fieldMeta: { type: 'text', label: 'Second test field' },+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope field create-many endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/create-many`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ recipientId: recipient!.id,+ envelopeItemId: doc.envelopeItems[0].id,+ type: 'TEXT',+ page: 791.77,+ positionX: 0,+ positionY: 0,+ width: 5,+ height: 5,+ fieldMeta: { type: 'text', label: 'First test field' },+ },+ {+ recipientId: recipient!.id,+ envelopeItemId: doc.envelopeItems[0].id,+ type: 'TEXT',+ page: 791.77,+ positionX: 0,+ positionY: 0,+ width: 5,+ height: 5,+ fieldMeta: { type: 'text', label: 'Second test field' },+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope field update-many endpoint', () => {+ test('should block unauthorized access to envelope field update-many endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const fields = await prisma.field.createManyAndReturn({+ data: [+ {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.TEXT,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.NUMBER,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ ],+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/update-many`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ id: fields[0].id,+ type: FieldType.TEXT,+ fieldMeta: { type: 'text', label: 'Updated first test field' },+ },+ {+ id: fields[1].id,+ type: FieldType.NUMBER,+ fieldMeta: { type: 'number', label: 'Updated second test field' },+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope field update-many endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const fields = await prisma.field.createManyAndReturn({+ data: [+ {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.TEXT,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.NUMBER,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ ],+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/update-many`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ id: fields[0].id,+ type: FieldType.TEXT,+ fieldMeta: { type: 'text', label: 'Updated first test field' },+ },+ {+ id: fields[1].id,+ type: FieldType.NUMBER,+ fieldMeta: { type: 'number', label: 'Updated second test field' },+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope field delete endpoint', () => {+ test('should block unauthorized access to envelope field delete endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const field = await prisma.field.create({+ data: {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.TEXT,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/delete`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { fieldId: field.id },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope field delete endpoint', async ({+ request,+ }) => {+ const { user: userRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [userRecipient.email]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const field = await prisma.field.create({+ data: {+ envelopeId: doc.id,+ envelopeItemId: doc.envelopeItems[0].id,+ recipientId: recipient!.id,+ type: FieldType.TEXT,+ page: 1,+ positionX: 1,+ positionY: 1,+ width: 1,+ height: 1,+ customText: '',+ inserted: false,+ fieldMeta: { type: 'text', label: 'Test' },+ },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/field/delete`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { fieldId: field.id },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope recipient get endpoint', () => {+ test('should block unauthorized access to envelope recipient get endpoint', async ({+ request,+ }) => {+ const { user: recipientUser } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [recipientUser]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.get(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/${recipient!.id}`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope recipient get endpoint', async ({+ request,+ }) => {+ const { user: recipientUser } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [recipientUser]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.get(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/${recipient!.id}`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope recipient create-many endpoint', () => {+ test('should block unauthorized access to envelope recipient create-many endpoint', async ({+ request,+ }) => {+ const doc = await seedDraftDocument(userA, teamA.id, []);++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/create-many`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ name: 'Test',+ email: '[email protected]',+ role: RecipientRole.SIGNER,+ },+ {+ name: 'Test 2',+ email: '[email protected]',+ role: RecipientRole.SIGNER,+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope recipient create-many endpoint', async ({+ request,+ }) => {+ const doc = await seedDraftDocument(userA, teamA.id, []);++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/create-many`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ name: 'Test',+ email: '[email protected]',+ role: RecipientRole.SIGNER,+ },+ {+ name: 'Test 2',+ email: '[email protected]',+ role: RecipientRole.SIGNER,+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope recipient update-many endpoint', () => {+ test('should block unauthorized access to envelope recipient update-many endpoint', async ({+ request,+ }) => {+ const { user: firstRecipient } = await seedUser();+ const { user: secondRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [firstRecipient, secondRecipient]);++ const firstDocumentRecipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: firstRecipient.email,+ },+ });++ const secondDocumentRecipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: secondRecipient.email,+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/update-many`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ id: firstDocumentRecipient!.id,+ name: 'Updated first recipient',+ },+ {+ id: secondDocumentRecipient!.id,+ name: 'Updated second recipient',+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope recipient update-many endpoint', async ({+ request,+ }) => {+ const { user: firstRecipient } = await seedUser();+ const { user: secondRecipient } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [firstRecipient, secondRecipient]);++ const firstDocumentRecipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: firstRecipient.email,+ },+ });++ const secondDocumentRecipient = await prisma.recipient.findFirst({+ where: {+ envelopeId: doc.id,+ email: secondRecipient.email,+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/update-many`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ id: firstDocumentRecipient!.id,+ name: 'Updated first recipient',+ },+ {+ id: secondDocumentRecipient!.id,+ name: 'Updated second recipient',+ },+ ],+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope recipient delete endpoint', () => {+ test('should block unauthorized access to envelope recipient delete endpoint', async ({+ request,+ }) => {+ const { user: recipientUser } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [recipientUser]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/delete`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { recipientId: recipient!.id },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope recipient delete endpoint', async ({+ request,+ }) => {+ const { user: recipientUser } = await seedUser();++ const doc = await seedDraftDocument(userA, teamA.id, [recipientUser]);++ const recipient = await prisma.recipient.findFirst({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/recipient/delete`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { recipientId: recipient!.id },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope item create-many endpoint', () => {+ test('should block unauthorized access to envelope item create-many endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const fieldMetaPdf = fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-meta.pdf'),+ );++ const createEnvelopeItemsPayload: TCreateEnvelopeItemsPayload = {+ envelopeId: doc.id,+ };++ const formData = new FormData();+ formData.append('payload', JSON.stringify(createEnvelopeItemsPayload));+ formData.append(+ 'files',+ new File([fieldMetaPdf], 'field-meta.pdf', { type: 'application/pdf' }),+ );++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/create-many`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ multipart: formData,+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope item create-many endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const fieldMetaPdf = fs.readFileSync(+ path.join(__dirname, '../../../../../assets/field-meta.pdf'),+ );++ const createEnvelopeItemsPayload: TCreateEnvelopeItemsPayload = {+ envelopeId: doc.id,+ };++ const formData = new FormData();+ formData.append('payload', JSON.stringify(createEnvelopeItemsPayload));+ formData.append(+ 'files',+ new File([fieldMetaPdf], 'field-meta-1.pdf', { type: 'application/pdf' }),+ );+ formData.append(+ 'files',+ new File([fieldMetaPdf], 'field-meta-2.pdf', { type: 'application/pdf' }),+ );++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/create-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ multipart: formData,+ });++ const envelope = await prisma.envelope.findFirstOrThrow({+ where: {+ id: doc.id,+ },+ include: {+ envelopeItems: true,+ },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);++ const envelopeItems = envelope.envelopeItems;++ // 3 Files because seed creates one automatically.+ expect(envelopeItems.length).toBe(3);+ expect(envelopeItems[1].title).toBe('field-meta-1.pdf');+ expect(envelopeItems[2].title).toBe('field-meta-2.pdf');+ });+ });++ test.describe('Envelope item update-many endpoint', () => {+ test('should block unauthorized access to envelope item update-many endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/update-many`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ envelopeItemId: envelopeItem.id,+ title: 'Updated Item Title',+ },+ ],+ },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope item update-many endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/update-many`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: [+ {+ envelopeItemId: envelopeItem.id,+ title: 'Updated Item Title',+ },+ ],+ },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope item delete endpoint', () => {+ test('should block unauthorized access to envelope item delete endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/delete`, {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ envelopeItemId: envelopeItem.id,+ },+ });++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope item delete endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({+ where: { envelopeId: doc.id },+ });++ const res = await request.post(`${WEBAPP_BASE_URL}/api/v2-beta/envelope/item/delete`, {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ envelopeItemId: envelopeItem.id,+ },+ });++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope attachment find endpoint', () => {+ test('should block unauthorized access to envelope attachment find endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.get(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment?envelopeId=${doc.id}`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope attachment find endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.get(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment?envelopeId=${doc.id}`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope attachment create endpoint', () => {+ test('should block unauthorized access to envelope attachment create endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/create`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ envelopeId: doc.id,+ data: {+ label: 'Test Attachment',+ data: 'https://example.com/file.pdf',+ },+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope attachment create endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/create`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ envelopeId: doc.id,+ data: {+ label: 'Test Attachment',+ data: 'https://example.com/file.pdf',+ },+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope attachment update endpoint', () => {+ test('should block unauthorized access to envelope attachment update endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const attachment = await prisma.envelopeAttachment.create({+ data: {+ envelopeId: doc.id,+ type: 'link',+ label: 'Original Label',+ data: 'https://example.com/original.pdf',+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/update`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: {+ id: attachment.id,+ data: {+ label: 'Updated Label',+ data: 'https://example.com/updated.pdf',+ },+ },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope attachment update endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const attachment = await prisma.envelopeAttachment.create({+ data: {+ envelopeId: doc.id,+ type: 'link',+ label: 'Original Label',+ data: 'https://example.com/original.pdf',+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/update`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: {+ id: attachment.id,+ data: {+ label: 'Updated Label',+ data: 'https://example.com/updated.pdf',+ },+ },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });++ test.describe('Envelope attachment delete endpoint', () => {+ test('should block unauthorized access to envelope attachment delete endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const attachment = await prisma.envelopeAttachment.create({+ data: {+ envelopeId: doc.id,+ type: 'link',+ label: 'Test Attachment',+ data: 'https://example.com/file.pdf',+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/delete`,+ {+ headers: { Authorization: `Bearer ${tokenB}` },+ data: { id: attachment.id },+ },+ );++ expect(res.ok()).toBeFalsy();+ expect(res.status()).toBe(404);+ });++ test('should allow authorized access to envelope attachment delete endpoint', async ({+ request,+ }) => {+ const doc = await seedBlankDocument(userA, teamA.id);++ const attachment = await prisma.envelopeAttachment.create({+ data: {+ envelopeId: doc.id,+ type: 'link',+ label: 'Test Attachment',+ data: 'https://example.com/file.pdf',+ },+ });++ const res = await request.post(+ `${WEBAPP_BASE_URL}/api/v2-beta/envelope/attachment/delete`,+ {+ headers: { Authorization: `Bearer ${tokenA}` },+ data: { id: attachment.id },+ },+ );++ expect(res.ok()).toBeTruthy();+ expect(res.status()).toBe(200);+ });+ });+ });});diff --git a/packages/app-tests/e2e/envelopes/envelope-alignment.spec.ts b/packages/app-tests/e2e/envelopes/envelope-alignment.spec.tsnew file mode 100644index 000000000..42e54786d--- /dev/null+++ b/packages/app-tests/e2e/envelopes/envelope-alignment.spec.ts@@ -0,0 +1,293 @@+// sort-imports-ignore++// ---- PATCH pdfjs-dist's canvas require BEFORE importing it ----+import Module from 'module';+import { Canvas, Image } from 'skia-canvas';++// Intercept require('canvas') and return skia-canvas equivalents+const originalRequire = Module.prototype.require;+Module.prototype.require = function (path: string) {+ if (path === 'canvas') {+ return {+ createCanvas: (width: number, height: number) => new Canvas(width, height),+ Image, // needed by pdfjs-dist+ };+ }+ // eslint-disable-next-line prefer-rest-params, @typescript-eslint/consistent-type-assertions+ return originalRequire.apply(this, arguments as unknown as [string]);+};++import pixelMatch from 'pixelmatch';+import { PNG } from 'pngjs';+import type { TestInfo } from '@playwright/test';+import { expect, test } from '@playwright/test';+import { DocumentStatus } from '@prisma/client';+import fs from 'node:fs';+import path from 'node:path';+import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.js';+import { getEnvelopeDownloadUrl } from '@documenso/lib/utils/envelope-download';+import { prisma } from '@documenso/prisma';+import { seedAlignmentTestDocument } from '@documenso/prisma/seed/initial-seed';+import { seedUser } from '@documenso/prisma/seed/users';++import { apiSignin } from '../fixtures/authentication';++test.describe.configure({ mode: 'parallel', timeout: 60000 });++test.skip('field placement visual regression', async ({ page }, testInfo) => {+ const { user, team } = await seedUser();++ const envelope = await seedAlignmentTestDocument({+ userId: user.id,+ teamId: team.id,+ recipientName: user.name || '',+ recipientEmail: user.email,+ insertFields: true,+ status: DocumentStatus.PENDING,+ });++ const token = envelope.recipients[0].token;++ const signUrl = `/sign/${token}`;++ await apiSignin({+ page,+ email: user.email,+ redirectPath: signUrl,+ });++ await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();++ await page.getByRole('button', { name: 'Complete' }).click();+ await page.getByRole('button', { name: 'Sign' }).click();+ await page.waitForURL(`${signUrl}/complete`);++ await expect(async () => {+ const { status } = await prisma.envelope.findFirstOrThrow({+ where: {+ id: envelope.id,+ },+ });++ expect(status).toBe(DocumentStatus.COMPLETED);+ }).toPass({+ timeout: 10000,+ });++ const completedDocument = await prisma.envelope.findFirstOrThrow({+ where: {+ id: envelope.id,+ },+ include: {+ envelopeItems: {+ orderBy: {+ order: 'asc',+ },+ include: {+ documentData: true,+ },+ },+ },+ });++ const storedImages = fs.readdirSync(path.join(__dirname, '../../visual-regression'));++ await Promise.all(+ completedDocument.envelopeItems.map(async (item) => {+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: item,+ token,+ version: 'signed',+ });++ const pdfData = await fetch(documentUrl).then(async (res) => await res.arrayBuffer());++ const loadedImages = storedImages+ .filter((image) => image.includes(item.title))+ .map((image) => fs.readFileSync(path.join(__dirname, '../../visual-regression', image)));++ await compareSignedPdfWithImages({+ id: item.title.replaceAll(' ', '-').toLowerCase(),+ pdfData: new Uint8Array(pdfData),+ images: loadedImages,+ testInfo,+ });+ }),+ );+});++/**+ * Used to download the envelope images when updating the visual regression test.+ *+ * DON'T COMMIT THIS WITHOUT THE "SKIP" COMMAND.+ */+test.skip('download envelope images', async ({ page }) => {+ const { user, team } = await seedUser();++ const envelope = await seedAlignmentTestDocument({+ userId: user.id,+ teamId: team.id,+ recipientName: user.name || '',+ recipientEmail: user.email,+ insertFields: true,+ status: DocumentStatus.PENDING,+ });++ const token = envelope.recipients[0].token;++ const signUrl = `/sign/${token}`;++ await apiSignin({+ page,+ email: user.email,+ redirectPath: signUrl,+ });++ await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();++ await page.getByRole('button', { name: 'Complete' }).click();+ await page.getByRole('button', { name: 'Sign' }).click();+ await page.waitForURL(`${signUrl}/complete`);++ await expect(async () => {+ const { status } = await prisma.envelope.findFirstOrThrow({+ where: {+ id: envelope.id,+ },+ });++ expect(status).toBe(DocumentStatus.COMPLETED);+ }).toPass({+ timeout: 10000,+ });++ const completedDocument = await prisma.envelope.findFirstOrThrow({+ where: {+ id: envelope.id,+ },+ include: {+ envelopeItems: {+ orderBy: {+ order: 'asc',+ },+ include: {+ documentData: true,+ },+ },+ },+ });++ await Promise.all(+ completedDocument.envelopeItems.map(async (item) => {+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: item,+ token,+ version: 'signed',+ });++ const pdfData = await fetch(documentUrl).then(async (res) => await res.arrayBuffer());++ const pdfImages = await renderPdfToImage(new Uint8Array(pdfData));++ for (const [index, { image }] of pdfImages.entries()) {+ fs.writeFileSync(+ path.join(__dirname, '../../visual-regression', `${item.title}-${index}.png`),+ new Uint8Array(image),+ );+ }+ }),+ );+});++async function renderPdfToImage(pdfBytes: Uint8Array) {+ const loadingTask = pdfjsLib.getDocument({ data: pdfBytes });+ const pdf = await loadingTask.promise;++ // Increase for higher resolution+ const scale = 4;++ return await Promise.all(+ Array.from({ length: pdf.numPages }, async (_, index) => {+ const page = await pdf.getPage(index + 1);++ const viewport = page.getViewport({ scale });++ const virtualCanvas = new Canvas(viewport.width, viewport.height);+ const context = virtualCanvas.getContext('2d');+ context.imageSmoothingEnabled = false;++ // @ts-expect-error skia-canvas context satisfies runtime requirements for pdfjs+ await page.render({ canvasContext: context, viewport }).promise;++ return {+ image: await virtualCanvas.toBuffer('png'),++ // Rounded down because the certificate page somehow gives dimensions with decimals+ width: Math.floor(viewport.width),+ height: Math.floor(viewport.height),+ };+ }),+ );+}++type CompareSignedPdfWithImagesOptions = {+ id: string;+ pdfData: Uint8Array;+ images: Buffer[];+ testInfo: TestInfo;+};++const compareSignedPdfWithImages = async ({+ id,+ pdfData,+ images,+ testInfo,+}: CompareSignedPdfWithImagesOptions) => {+ const renderedImages = await renderPdfToImage(pdfData);++ const blankCertificateFile = fs.readFileSync(+ path.join(__dirname, '../../visual-regression/blank-certificate.png'),+ );+ const blankCertificateImage = PNG.sync.read(blankCertificateFile).data;++ for (const [index, { image, width, height }] of renderedImages.entries()) {+ const isCertificate = index === renderedImages.length - 1;++ const diff = new PNG({ width, height });++ const storedImage = PNG.sync.read(images[index]).data;++ const newImage = PNG.sync.read(image).data;++ const oldImage = isCertificate ? blankCertificateImage : storedImage;++ const comparison = pixelMatch(+ new Uint8Array(oldImage),+ new Uint8Array(newImage),+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions+ diff.data as unknown as Uint8Array,+ width,+ height,+ {+ threshold: 0.25,+ // includeAA: true, // This allows stricter testing.+ },+ );+ console.log(`${id}-${index}: ${comparison}`);++ const diffFilePath = path.join(testInfo.outputPath(), `${id}-${index}-diff.png`);+ const oldFilePath = path.join(testInfo.outputPath(), `${id}-${index}-old.png`);+ const newFilePath = path.join(testInfo.outputPath(), `${id}-${index}-new.png`);++ fs.writeFileSync(diffFilePath, new Uint8Array(PNG.sync.write(diff)));+ fs.writeFileSync(oldFilePath, new Uint8Array(images[index]));+ fs.writeFileSync(newFilePath, new Uint8Array(image));++ if (isCertificate) {+ // Expect the certificate to NOT be blank. Since the storedImage is blank.+ expect.soft(comparison).toBeGreaterThan(20000);+ } else {+ expect.soft(comparison).toEqual(0);+ }+ }+};diff --git a/packages/app-tests/e2e/features/include-document-certificate.spec.ts b/packages/app-tests/e2e/features/include-document-certificate.spec.tsindex e1ab6f915..ec5ee5fda 100644--- a/packages/app-tests/e2e/features/include-document-certificate.spec.ts+++ b/packages/app-tests/e2e/features/include-document-certificate.spec.ts@@ -3,7 +3,7 @@ import { expect, test } from '@playwright/test';import { DocumentStatus, FieldType } from '@prisma/client';import { getDocumentByToken } from '@documenso/lib/server-only/document/get-document-by-token';-import { getFile } from '@documenso/lib/universal/upload/get-file';+import { getEnvelopeDownloadUrl } from '@documenso/lib/utils/envelope-download';import { prisma } from '@documenso/prisma';import { seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';import { seedTeam } from '@documenso/prisma/seed/teams';@@ -25,20 +25,25 @@ test.describe('Signing Certificate Tests', () => {teamId: team.id,});- const documentData = await prisma.documentData+ const recipient = recipients[0];++ const documentData = await prisma.envelopeItem.findFirstOrThrow({where: {- envelopeItem: {- envelopeId: document.id,- },+ envelopeId: document.id,},})- .then(async (data) => getFile(data));+ .then(async (data) => {+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: data,+ token: recipient.token,+ version: 'signed',+ });+ return fetch(documentUrl).then(async (res) => await res.arrayBuffer());+ });const originalPdf = await PDFDocument.load(documentData);- const recipient = recipients[0];-// Sign the documentawait page.goto(`/sign/${recipient.token}`);@@ -78,10 +83,17 @@ test.describe('Signing Certificate Tests', () => {},});- // Todo: Envelopes- const firstDocumentData = completedDocument.envelopeItems[0].documentData;+ const firstDocumentData = completedDocument.envelopeItems[0];++ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: firstDocumentData,+ token: recipient.token,+ version: 'signed',+ });++ const pdfData = await fetch(documentUrl).then(async (res) => await res.arrayBuffer());- const completedDocumentData = await getFile(firstDocumentData);+ const completedDocumentData = new Uint8Array(pdfData);// Load the PDF and check number of pagesconst pdfDoc = await PDFDocument.load(completedDocumentData);@@ -118,20 +130,25 @@ test.describe('Signing Certificate Tests', () => {},});- const documentData = await prisma.documentData+ const recipient = recipients[0];++ const documentData = await prisma.envelopeItem.findFirstOrThrow({where: {- envelopeItem: {- envelopeId: document.id,- },+ envelopeId: document.id,},})- .then(async (data) => getFile(data));+ .then(async (data) => {+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: data,+ token: recipient.token,+ version: 'signed',+ });+ return fetch(documentUrl).then(async (res) => await res.arrayBuffer());+ });const originalPdf = await PDFDocument.load(documentData);- const recipient = recipients[0];-// Sign the documentawait page.goto(`/sign/${recipient.token}`);@@ -169,10 +186,17 @@ test.describe('Signing Certificate Tests', () => {},});- // Todo: Envelopes- const firstDocumentData = completedDocument.envelopeItems[0].documentData;+ const firstDocumentData = completedDocument.envelopeItems[0];++ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: firstDocumentData,+ token: recipient.token,+ version: 'signed',+ });++ const pdfData = await fetch(documentUrl).then(async (res) => await res.arrayBuffer());- const completedDocumentData = await getFile(firstDocumentData);+ const completedDocumentData = new Uint8Array(pdfData);// Load the PDF and check number of pagesconst completedPdf = await PDFDocument.load(completedDocumentData);@@ -209,19 +233,24 @@ test.describe('Signing Certificate Tests', () => {},});- const documentData = await prisma.documentData+ const recipient = recipients[0];++ const documentData = await prisma.envelopeItem.findFirstOrThrow({where: {- envelopeItem: {- envelopeId: document.id,- },+ envelopeId: document.id,},})- .then(async (data) => getFile(data));-- const originalPdf = await PDFDocument.load(documentData);+ .then(async (data) => {+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: data,+ token: recipient.token,+ version: 'signed',+ });+ return fetch(documentUrl).then(async (res) => await res.arrayBuffer());+ });- const recipient = recipients[0];+ const originalPdf = await PDFDocument.load(new Uint8Array(documentData));// Sign the documentawait page.goto(`/sign/${recipient.token}`);@@ -260,7 +289,15 @@ test.describe('Signing Certificate Tests', () => {},});- const completedDocumentData = await getFile(completedDocument.envelopeItems[0].documentData);+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: completedDocument.envelopeItems[0],+ token: recipient.token,+ version: 'signed',+ });++ const completedDocumentData = await fetch(documentUrl).then(+ async (res) => await res.arrayBuffer(),+ );// Load the PDF and check number of pagesconst completedPdf = await PDFDocument.load(completedDocumentData);diff --git a/packages/app-tests/e2e/templates/create-document-from-template.spec.ts b/packages/app-tests/e2e/templates/create-document-from-template.spec.tsindex 92b21dfb0..e9ca3d6b8 100644--- a/packages/app-tests/e2e/templates/create-document-from-template.spec.ts+++ b/packages/app-tests/e2e/templates/create-document-from-template.spec.ts@@ -1,6 +1,5 @@import { expect, test } from '@playwright/test';import { DocumentDataType, TeamMemberRole } from '@prisma/client';-import fs from 'fs';import path from 'path';import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';@@ -12,6 +11,10 @@ import { seedUser } from '@documenso/prisma/seed/users';import { apiSignin } from '../fixtures/authentication';const EXAMPLE_PDF_PATH = path.join(__dirname, '../../../../assets/example.pdf');+const FIELD_ALIGNMENT_TEST_PDF_PATH = path.join(+ __dirname,+ '../../../../assets/field-font-alignment.pdf',+);/*** 1. Create a template with all settings filled out@@ -233,10 +236,6 @@ test('[TEMPLATE]: should create a document from a template with custom document'const { user, team } = await seedUser();const template = await seedBlankTemplate(user, team.id);- // Create a temporary PDF file for upload-- const pdfContent = fs.readFileSync(EXAMPLE_PDF_PATH).toString('base64');-await apiSignin({page,email: user.email,@@ -277,7 +276,7 @@ test('[TEMPLATE]: should create a document from a template with custom document'}),]);- await fileChooser.setFiles(EXAMPLE_PDF_PATH);+ await fileChooser.setFiles(FIELD_ALIGNMENT_TEST_PDF_PATH);// Wait for upload to completeawait expect(page.getByText('Remove')).toBeVisible();@@ -314,8 +313,12 @@ test('[TEMPLATE]: should create a document from a template with custom document'expect(firstDocumentData.type).toEqual(expectedDocumentDataType);if (expectedDocumentDataType === DocumentDataType.BYTES_64) {- expect(firstDocumentData.data).toEqual(pdfContent);- expect(firstDocumentData.initialData).toEqual(pdfContent);+ // Todo: Doesn't really work due to normalization of the PDF which won't let us directly compare the data.+ // Probably need to do a pixel match+ expect(firstDocumentData.data).not.toEqual(template.envelopeItems[0].documentData.data);+ expect(firstDocumentData.initialData).not.toEqual(+ template.envelopeItems[0].documentData.initialData,+ );} else {// For S3, we expect the data/initialData to be the S3 path (non-empty string)expect(firstDocumentData.data).toBeTruthy();@@ -336,8 +339,6 @@ test('[TEMPLATE]: should create a team document from a template with custom docuconst template = await seedBlankTemplate(owner, team.id);- const pdfContent = fs.readFileSync(EXAMPLE_PDF_PATH).toString('base64');-await apiSignin({page,email: owner.email,@@ -378,7 +379,7 @@ test('[TEMPLATE]: should create a team document from a template with custom docu}),]);- await fileChooser.setFiles(EXAMPLE_PDF_PATH);+ await fileChooser.setFiles(FIELD_ALIGNMENT_TEST_PDF_PATH);// Wait for upload to completeawait expect(page.getByText('Remove')).toBeVisible();@@ -416,8 +417,12 @@ test('[TEMPLATE]: should create a team document from a template with custom docuexpect(firstDocumentData.type).toEqual(expectedDocumentDataType);if (expectedDocumentDataType === DocumentDataType.BYTES_64) {- expect(firstDocumentData.data).toEqual(pdfContent);- expect(firstDocumentData.initialData).toEqual(pdfContent);+ // Todo: Doesn't really work due to normalization of the PDF which won't let us directly compare the data.+ // Probably need to do a pixel match+ expect(firstDocumentData.data).not.toEqual(template.envelopeItems[0].documentData.data);+ expect(firstDocumentData.initialData).not.toEqual(+ template.envelopeItems[0].documentData.initialData,+ );} else {// For S3, we expect the data/initialData to be the S3 path (non-empty string)expect(firstDocumentData.data).toBeTruthy();diff --git a/packages/app-tests/package.json b/packages/app-tests/package.jsonindex 2df81aa87..2afae0845 100644--- a/packages/app-tests/package.json+++ b/packages/app-tests/package.json@@ -15,7 +15,10 @@"@documenso/lib": "*","@documenso/prisma": "*","@playwright/test": "1.52.0",- "@types/node": "^20"+ "@types/node": "^20",+ "@types/pngjs": "^6.0.5",+ "pixelmatch": "^7.1.0",+ "pngjs": "^7.0.0"},"dependencies": {"start-server-and-test": "^2.0.12"diff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 41090db70..7f612e06b 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -20,6 +20,6 @@"luxon": "^3.5.0","nanoid": "^5.1.5","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}}\ No newline at end of filediff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 4dc669053..4578bc5e9 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -19,6 +19,6 @@"micro": "^10.0.1","react": "^18","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}}\ No newline at end of filediff --git a/packages/lib/client-only/download-pdf.ts b/packages/lib/client-only/download-pdf.tsindex f6db9b629..ca2d4c289 100644--- a/packages/lib/client-only/download-pdf.ts+++ b/packages/lib/client-only/download-pdf.ts@@ -1,12 +1,14 @@-import type { DocumentData } from '@prisma/client';+import type { EnvelopeItem } from '@prisma/client';-import { getFile } from '../universal/upload/get-file';+import { getEnvelopeDownloadUrl } from '../utils/envelope-download';import { downloadFile } from './download-file';type DocumentVersion = 'original' | 'signed';type DownloadPDFProps = {- documentData: DocumentData;+ envelopeItem: Pick<EnvelopeItem, 'id' | 'envelopeId'>;+ token: string | undefined;+fileName?: string;/*** Specifies which version of the document to download.@@ -17,18 +19,18 @@ type DownloadPDFProps = {};export const downloadPDF = async ({- documentData,+ envelopeItem,+ token,fileName,version = 'signed',}: DownloadPDFProps) => {- const bytes = await getFile({- type: documentData.type,- data: version === 'signed' ? documentData.data : documentData.initialData,+ const downloadUrl = getEnvelopeDownloadUrl({+ envelopeItem: envelopeItem,+ token,+ version,});- const blob = new Blob([bytes], {- type: 'application/pdf',- });+ const blob = await fetch(downloadUrl).then(async (res) => await res.blob());const baseTitle = (fileName ?? 'document').replace(/\.pdf$/, '');const suffix = version === 'signed' ? '_signed.pdf' : '.pdf';diff --git a/packages/lib/client-only/hooks/use-editor-fields.ts b/packages/lib/client-only/hooks/use-editor-fields.tsindex 68320856e..14b56a882 100644--- a/packages/lib/client-only/hooks/use-editor-fields.ts+++ b/packages/lib/client-only/hooks/use-editor-fields.ts@@ -165,10 +165,7 @@ export const useEditorFields = ({const index = localFields.findIndex((field) => field.formId === formId);if (index !== -1) {- update(index, {- ...localFields[index],- id,- });+ form.setValue(`fields.${index}.id`, id);}};diff --git a/packages/lib/client-only/hooks/use-page-renderer.ts b/packages/lib/client-only/hooks/use-page-renderer.tsindex c2f03e6be..6aa6bd3a2 100644--- a/packages/lib/client-only/hooks/use-page-renderer.ts+++ b/packages/lib/client-only/hooks/use-page-renderer.ts@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import Konva from 'konva';import type { RenderParameters } from 'pdfjs-dist/types/src/display/api';@@ -25,6 +25,8 @@ export function usePageRenderer(renderFunction: RenderFunction) {const stage = useRef<Konva.Stage | null>(null);const pageLayer = useRef<Konva.Layer | null>(null);+ const [renderError, setRenderError] = useState<boolean>(false);+/*** The raw viewport with no scaling. Basically the actual PDF size.*/@@ -122,5 +124,7 @@ export function usePageRenderer(renderFunction: RenderFunction) {unscaledViewport,scaledViewport,pageContext,+ renderError,+ setRenderError,};}diff --git a/packages/lib/client-only/providers/envelope-editor-provider.tsx b/packages/lib/client-only/providers/envelope-editor-provider.tsxindex a7473c9b0..a15721775 100644--- a/packages/lib/client-only/providers/envelope-editor-provider.tsx+++ b/packages/lib/client-only/providers/envelope-editor-provider.tsx@@ -46,6 +46,7 @@ type EnvelopeEditorProviderValue = {setLocalEnvelope: (localEnvelope: Partial<TEnvelope>) => void;updateEnvelope: (envelopeUpdates: UpdateEnvelopePayload) => void;+ updateEnvelopeAsync: (envelopeUpdates: UpdateEnvelopePayload) => Promise<void>;setRecipientsDebounced: (recipients: TSetEnvelopeRecipientsRequest['recipients']) => void;setRecipientsAsync: (recipients: TSetEnvelopeRecipientsRequest['recipients']) => Promise<void>;@@ -66,8 +67,6 @@ type EnvelopeEditorProviderValue = {};syncEnvelope: () => Promise<void>;- // refetchEnvelope: () => Promise<void>;- // updateEnvelope: (envelope: TEnvelope) => Promise<void>;};interface EnvelopeEditorProviderProps {@@ -151,7 +150,7 @@ export const EnvelopeEditorProvider = ({});const envelopeRecipientSetMutationQuery = trpc.envelope.recipient.set.useMutation({- onSuccess: ({ recipients }) => {+ onSuccess: ({ data: recipients }) => {setEnvelope((prev) => ({...prev,recipients,@@ -197,7 +196,7 @@ export const EnvelopeEditorProvider = ({});// Insert the IDs into the local fields.- envelopeFields.fields.forEach((field) => {+ envelopeFields.data.forEach((field) => {const localField = localFields.find((localField) => localField.formId === field.formId);if (localField && !localField.id) {@@ -215,7 +214,6 @@ export const EnvelopeEditorProvider = ({} = useEnvelopeAutosave(async (envelopeUpdates: UpdateEnvelopePayload) => {await envelopeUpdateMutationQuery.mutateAsync({envelopeId: envelope.id,- envelopeType: envelope.type,data: envelopeUpdates.data,meta: envelopeUpdates.meta,});@@ -237,6 +235,13 @@ export const EnvelopeEditorProvider = ({setEnvelopeDebounced(envelopeUpdates);};+ const updateEnvelopeAsync = async (envelopeUpdates: UpdateEnvelopePayload) => {+ await envelopeUpdateMutationQuery.mutateAsync({+ envelopeId: envelope.id,+ ...envelopeUpdates,+ });+ };+const getRecipientColorKey = useCallback((recipientId: number) => {const recipientIndex = envelope.recipients.findIndex(@@ -324,6 +329,7 @@ export const EnvelopeEditorProvider = ({setLocalEnvelope,getRecipientColorKey,updateEnvelope,+ updateEnvelopeAsync,setRecipientsDebounced,setRecipientsAsync,editorFields,diff --git a/packages/lib/client-only/providers/envelope-render-provider.tsx b/packages/lib/client-only/providers/envelope-render-provider.tsxindex 367693dac..3682f311a 100644--- a/packages/lib/client-only/providers/envelope-render-provider.tsx+++ b/packages/lib/client-only/providers/envelope-render-provider.tsx@@ -1,13 +1,14 @@import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';import React from 'react';-import type { DocumentData } from '@prisma/client';+import type { Field, Recipient } from '@prisma/client';import type { TRecipientColor } from '@documenso/ui/lib/recipient-colors';import { AVAILABLE_RECIPIENT_COLORS } from '@documenso/ui/lib/recipient-colors';import type { TEnvelope } from '../../types/envelope';-import { getFile } from '../../universal/upload/get-file';+import type { FieldRenderMode } from '../../universal/field-renderer/render-field';+import { getEnvelopeDownloadUrl } from '../../utils/envelope-download';type FileData =| {@@ -18,19 +19,31 @@ type FileData =status: 'loaded';};+type EnvelopeRenderOverrideSettings = {+ mode?: FieldRenderMode;+ showRecipientTooltip?: boolean;+ showRecipientSigningStatus?: boolean;+};+type EnvelopeRenderItem = TEnvelope['envelopeItems'][number];type EnvelopeRenderProviderValue = {- getPdfBuffer: (documentDataId: string) => FileData | null;+ getPdfBuffer: (envelopeItemId: string) => FileData | null;envelopeItems: EnvelopeRenderItem[];currentEnvelopeItem: EnvelopeRenderItem | null;setCurrentEnvelopeItem: (envelopeItemId: string) => void;- fields: TEnvelope['fields'];+ fields: Field[];+ recipients: Pick<Recipient, 'id' | 'name' | 'email' | 'signingStatus'>[];getRecipientColorKey: (recipientId: number) => TRecipientColor;++ renderError: boolean;+ setRenderError: (renderError: boolean) => void;+ overrideSettings?: EnvelopeRenderOverrideSettings;};interface EnvelopeRenderProviderProps {children: React.ReactNode;+envelope: Pick<TEnvelope, 'envelopeItems'>;/**@@ -38,14 +51,27 @@ interface EnvelopeRenderProviderProps {** Only pass if the CustomRenderer you are passing in wants fields.*/- fields?: TEnvelope['fields'];+ fields?: Field[];/**- * Optional recipient IDs used to determine the color of the fields.+ * Optional recipient used to determine the color of the fields and hover+ * previews.** Only required for generic page renderers.*/- recipientIds?: number[];+ recipients?: Pick<Recipient, 'id' | 'name' | 'email' | 'signingStatus'>[];++ /**+ * The token to access the envelope.+ *+ * If not provided, it will be assumed that the current user can access the document.+ */+ token: string | undefined;++ /**+ * Custom override settings for generic page renderers.+ */+ overrideSettings?: EnvelopeRenderOverrideSettings;}const EnvelopeRenderContext = createContext<EnvelopeRenderProviderValue | null>(null);@@ -67,39 +93,51 @@ export const EnvelopeRenderProvider = ({children,envelope,fields,- recipientIds = [],+ token,+ recipients = [],+ overrideSettings,}: EnvelopeRenderProviderProps) => {// Indexed by documentDataId.const [files, setFiles] = useState<Record<string, FileData>>({});const [currentItem, setItem] = useState<EnvelopeRenderItem | null>(null);+ const [renderError, setRenderError] = useState<boolean>(false);+const envelopeItems = useMemo(() => envelope.envelopeItems.sort((a, b) => a.order - b.order),[envelope.envelopeItems],);- const loadEnvelopeItemPdfFile = async (documentData: DocumentData) => {- if (files[documentData.id]?.status === 'loading') {+ const loadEnvelopeItemPdfFile = async (envelopeItem: EnvelopeRenderItem) => {+ if (files[envelopeItem.id]?.status === 'loading') {return;}- if (!files[documentData.id]) {+ if (!files[envelopeItem.id]) {setFiles((prev) => ({...prev,- [documentData.id]: {+ [envelopeItem.id]: {status: 'loading',},}));}try {- const file = await getFile(documentData);+ const downloadUrl = getEnvelopeDownloadUrl({+ envelopeItem: envelopeItem,+ token,+ version: 'signed',+ });++ const blob = await fetch(downloadUrl).then(async (res) => await res.blob());++ const file = await blob.arrayBuffer();setFiles((prev) => ({...prev,- [documentData.id]: {- file,+ [envelopeItem.id]: {+ file: new Uint8Array(file),status: 'loaded',},}));@@ -108,7 +146,7 @@ export const EnvelopeRenderProvider = ({setFiles((prev) => ({...prev,- [documentData.id]: {+ [envelopeItem.id]: {status: 'error',},}));@@ -116,8 +154,8 @@ export const EnvelopeRenderProvider = ({};const getPdfBuffer = useCallback(- (documentDataId: string) => {- return files[documentDataId] || null;+ (envelopeItemId: string) => {+ return files[envelopeItemId] || null;},[files],);@@ -137,13 +175,18 @@ export const EnvelopeRenderProvider = ({// Look for any missing pdf files and load them.useEffect(() => {- const missingFiles = envelope.envelopeItems.filter((item) => !files[item.documentDataId]);+ const missingFiles = envelope.envelopeItems.filter((item) => !files[item.id]);for (const item of missingFiles) {- void loadEnvelopeItemPdfFile(item.documentData);+ void loadEnvelopeItemPdfFile(item);}}, [envelope.envelopeItems]);+ const recipientIds = useMemo(+ () => recipients.map((recipient) => recipient.id).sort(),+ [recipients],+ );+const getRecipientColorKey = useCallback((recipientId: number) => {const recipientIndex = recipientIds.findIndex((id) => id === recipientId);@@ -163,7 +206,11 @@ export const EnvelopeRenderProvider = ({currentEnvelopeItem: currentItem,setCurrentEnvelopeItem,fields: fields ?? [],+ recipients,getRecipientColorKey,+ renderError,+ setRenderError,+ overrideSettings,}}>{children}diff --git a/packages/lib/constants/app.ts b/packages/lib/constants/app.tsindex 5c2f39a65..43e6d6d8a 100644--- a/packages/lib/constants/app.ts+++ b/packages/lib/constants/app.ts@@ -12,6 +12,7 @@ export const NEXT_PRIVATE_INTERNAL_WEBAPP_URL =export const IS_BILLING_ENABLED = () => env('NEXT_PUBLIC_FEATURE_BILLING_ENABLED') === 'true';export const API_V2_BETA_URL = '/api/v2-beta';+export const API_V2_URL = '/api/v2';export const SUPPORT_EMAIL = env('NEXT_PUBLIC_SUPPORT_EMAIL') ?? '[email protected]';diff --git a/packages/lib/package.json b/packages/lib/package.jsonindex eaab3057b..dfef560cc 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -55,11 +55,11 @@"skia-canvas": "^3.0.8","stripe": "^12.7.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"},"devDependencies": {"@playwright/browser-chromium": "1.52.0","@types/luxon": "^3.3.1","@types/pg": "^8.11.4"}-}+}\ No newline at end of filediff --git a/packages/lib/server-only/admin/admin-find-documents.ts b/packages/lib/server-only/admin/admin-find-documents.tsindex 78f85b238..062a873c5 100644--- a/packages/lib/server-only/admin/admin-find-documents.ts+++ b/packages/lib/server-only/admin/admin-find-documents.ts@@ -78,6 +78,14 @@ export const adminFindDocuments = async ({url: true,},},+ envelopeItems: {+ select: {+ id: true,+ envelopeId: true,+ title: true,+ order: true,+ },+ },},}),prisma.envelope.count({diff --git a/packages/lib/server-only/document/find-documents.ts b/packages/lib/server-only/document/find-documents.tsindex d839c2f38..8b1eafcc7 100644--- a/packages/lib/server-only/document/find-documents.ts+++ b/packages/lib/server-only/document/find-documents.ts@@ -248,6 +248,14 @@ export const findDocuments = async ({url: true,},},+ envelopeItems: {+ select: {+ id: true,+ envelopeId: true,+ title: true,+ order: true,+ },+ },},}),prisma.envelope.count({diff --git a/packages/lib/server-only/document/get-document-by-token.ts b/packages/lib/server-only/document/get-document-by-token.tsindex 10781c297..fd264c5d8 100644--- a/packages/lib/server-only/document/get-document-by-token.ts+++ b/packages/lib/server-only/document/get-document-by-token.ts@@ -92,6 +92,10 @@ export const getDocumentAndSenderByToken = async ({},envelopeItems: {select: {+ id: true,+ title: true,+ order: true,+ envelopeId: true,documentData: true,},},diff --git a/packages/lib/server-only/document/get-document-with-details-by-id.ts b/packages/lib/server-only/document/get-document-with-details-by-id.tsindex 4c1b11df7..86a2e78a8 100644--- a/packages/lib/server-only/document/get-document-with-details-by-id.ts+++ b/packages/lib/server-only/document/get-document-with-details-by-id.ts@@ -63,5 +63,8 @@ export const getDocumentWithDetailsById = async ({documentId: legacyDocumentId,password: null,},+ envelopeItems: envelope.envelopeItems.map((envelopeItem) => ({+ ...envelopeItem,+ })),};};diff --git a/packages/lib/server-only/document/send-document.ts b/packages/lib/server-only/document/send-document.tsindex c9a982430..3b897da7f 100644--- a/packages/lib/server-only/document/send-document.ts+++ b/packages/lib/server-only/document/send-document.ts@@ -20,7 +20,12 @@ import { validateCheckboxLength } from '../../advanced-fields-validation/validatimport { AppError, AppErrorCode } from '../../errors/app-error';import { jobs } from '../../jobs/client';import { extractDerivedDocumentEmailSettings } from '../../types/document-email';-import { ZCheckboxFieldMeta, ZDropdownFieldMeta, ZRadioFieldMeta } from '../../types/field-meta';+import {+ ZCheckboxFieldMeta,+ ZDropdownFieldMeta,+ ZFieldAndMetaSchema,+ ZRadioFieldMeta,+} from '../../types/field-meta';import {ZWebhookDocumentSchema,mapEnvelopeToWebhookDocumentPayload,@@ -174,9 +179,20 @@ export const sendDocument = async ({const fieldsToAutoInsert: { fieldId: number; customText: string }[] = [];- // Auto insert radio and checkboxes that have default values.+ // Validate and autoinsert fields for V2 envelopes.if (envelope.internalVersion === 2) {- for (const field of envelope.fields) {+ for (const unknownField of envelope.fields) {+ const parsedField = ZFieldAndMetaSchema.safeParse(unknownField);++ if (parsedField.error) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'One or more fields have invalid metadata. Error: ' + parsedField.error.message,+ });+ }++ const field = parsedField.data;+ const fieldId = unknownField.id;+if (field.type === FieldType.RADIO) {const { values = [] } = ZRadioFieldMeta.parse(field.fieldMeta);@@ -184,7 +200,7 @@ export const sendDocument = async ({if (checkedItemIndex !== -1) {fieldsToAutoInsert.push({- fieldId: field.id,+ fieldId,customText: toRadioCustomText(checkedItemIndex),});}@@ -195,7 +211,7 @@ export const sendDocument = async ({if (defaultValue && values.some((value) => value.value === defaultValue)) {fieldsToAutoInsert.push({- fieldId: field.id,+ fieldId,customText: defaultValue,});}@@ -234,9 +250,9 @@ export const sendDocument = async ({);}- if (isValid) {+ if (isValid && checkedIndices.length > 0) {fieldsToAutoInsert.push({- fieldId: field.id,+ fieldId,customText: toCheckboxCustomText(checkedIndices),});}diff --git a/packages/lib/server-only/envelope/create-envelope.ts b/packages/lib/server-only/envelope/create-envelope.tsindex 5f4198377..210346b4d 100644--- a/packages/lib/server-only/envelope/create-envelope.ts+++ b/packages/lib/server-only/envelope/create-envelope.ts@@ -16,11 +16,16 @@ import type { ApiRequestMetadata } from '@documenso/lib/universal/extract-requesimport { nanoid, prefixedId } from '@documenso/lib/universal/id';import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';import { prisma } from '@documenso/prisma';-import type { TCreateEnvelopeRequest } from '@documenso/trpc/server/envelope-router/create-envelope.types';-import type { TDocumentAccessAuthTypes, TDocumentActionAuthTypes } from '../../types/document-auth';+import type {+ TDocumentAccessAuthTypes,+ TDocumentActionAuthTypes,+ TRecipientAccessAuthTypes,+ TRecipientActionAuthTypes,+} from '../../types/document-auth';import type { TDocumentFormValues } from '../../types/document-form-values';import type { TEnvelopeAttachmentType } from '../../types/envelope-attachment';+import type { TFieldAndMeta } from '../../types/field-meta';import {ZWebhookDocumentSchema,mapEnvelopeToWebhookDocumentPayload,@@ -34,6 +39,25 @@ import { incrementDocumentId, incrementTemplateId } from '../envelope/increment-import { getTeamSettings } from '../team/get-team-settings';import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';+type CreateEnvelopeRecipientFieldOptions = TFieldAndMeta & {+ documentDataId: string;+ page: number;+ positionX: number;+ positionY: number;+ width: number;+ height: number;+};++type CreateEnvelopeRecipientOptions = {+ email: string;+ name: string;+ role: RecipientRole;+ signingOrder?: number;+ accessAuth?: TRecipientAccessAuthTypes[];+ actionAuth?: TRecipientActionAuthTypes[];+ fields?: CreateEnvelopeRecipientFieldOptions[];+};+export type CreateEnvelopeOptions = {userId: number;teamId: number;@@ -46,7 +70,6 @@ export type CreateEnvelopeOptions = {envelopeItems: { title?: string; documentDataId: string; order?: number }[];formValues?: TDocumentFormValues;- timezone?: string;userTimezone?: string;templateType?: TemplateType;@@ -56,7 +79,7 @@ export type CreateEnvelopeOptions = {visibility?: DocumentVisibility;globalAccessAuth?: TDocumentAccessAuthTypes[];globalActionAuth?: TDocumentActionAuthTypes[];- recipients?: TCreateEnvelopeRequest['recipients'];+ recipients?: CreateEnvelopeRecipientOptions[];folderId?: string;};attachments?: Array<{@@ -83,7 +106,6 @@ export const createEnvelope = async ({title,externalId,formValues,- timezone,userTimezone,folderId,templateType,@@ -142,6 +164,7 @@ export const createEnvelope = async ({let envelopeItems: { title?: string; documentDataId: string; order?: number }[] =data.envelopeItems;+ // Todo: Envelopes - Removeif (normalizePdf) {envelopeItems = await Promise.all(data.envelopeItems.map(async (item) => {@@ -219,7 +242,7 @@ export const createEnvelope = async ({// userTimezone is last because it's always passed in regardless of the organisation/team settings// for uploads from the frontend- const timezoneToUse = timezone || settings.documentTimezone || userTimezone;+ const timezoneToUse = meta?.timezone || settings.documentTimezone || userTimezone;const documentMeta = await prisma.documentMeta.create({data: extractDerivedDocumentMeta(settings, {diff --git a/packages/lib/server-only/envelope/get-envelope-for-direct-template-signing.ts b/packages/lib/server-only/envelope/get-envelope-for-direct-template-signing.tsindex e9547885c..3e6fc2af5 100644--- a/packages/lib/server-only/envelope/get-envelope-for-direct-template-signing.ts+++ b/packages/lib/server-only/envelope/get-envelope-for-direct-template-signing.ts@@ -143,7 +143,7 @@ export const getEnvelopeForDirectTemplateSigning = async ({envelope,recipient: {...recipient,- token: envelope.directLink?.token || '',+ directToken: envelope.directLink?.token || '',},recipientSignature: null,isRecipientsTurn: true,diff --git a/packages/lib/server-only/envelope/get-envelope-for-recipient-signing.ts b/packages/lib/server-only/envelope/get-envelope-for-recipient-signing.tsindex 8ab1d77ff..c8ab1ab19 100644--- a/packages/lib/server-only/envelope/get-envelope-for-recipient-signing.ts+++ b/packages/lib/server-only/envelope/get-envelope-for-recipient-signing.ts@@ -2,7 +2,6 @@ import { DocumentSigningOrder, DocumentStatus, EnvelopeType, SigningStatus } froimport { 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';@@ -72,20 +71,11 @@ export const ZEnvelopeForSigningResponse = z.object({.array(),envelopeItems: EnvelopeItemSchema.pick({+ envelopeId: true,id: true,title: true,- documentDataId: true,order: true,- })- .extend({- documentData: DocumentDataSchema.pick({- type: true,- id: true,- data: true,- initialData: true,- }),- })- .array(),+ }).array(),team: TeamSchema.pick({id: true,@@ -117,6 +107,7 @@ export const ZEnvelopeForSigningResponse = z.object({signingOrder: true,rejectionReason: true,}).extend({+ directToken: z.string().nullish(),fields: ZFieldSchema.omit({documentId: true,templateId: true,@@ -199,11 +190,7 @@ export const getEnvelopeForRecipientSigning = async ({signingOrder: 'asc',},},- envelopeItems: {- include: {- documentData: true,- },- },+ envelopeItems: true,team: {select: {id: true,diff --git a/packages/lib/server-only/field/create-envelope-fields.ts b/packages/lib/server-only/field/create-envelope-fields.tsindex 32a41b89f..3412d1e4a 100644--- a/packages/lib/server-only/field/create-envelope-fields.ts+++ b/packages/lib/server-only/field/create-envelope-fields.ts@@ -26,9 +26,9 @@ export interface CreateEnvelopeFieldsOptions {envelopeItemId?: string;recipientId: number;- pageNumber: number;- pageX: number;- pageY: number;+ page: number;+ positionX: number;+ positionY: number;width: number;height: number;})[];@@ -122,9 +122,9 @@ export const createEnvelopeFields = async ({const newlyCreatedFields = await tx.field.createManyAndReturn({data: validatedFields.map((field) => ({type: field.type,- page: field.pageNumber,- positionX: field.pageX,- positionY: field.pageY,+ page: field.page,+ positionX: field.positionX,+ positionY: field.positionY,width: field.width,height: field.height,customText: '',diff --git a/packages/lib/server-only/field/get-field-by-id.ts b/packages/lib/server-only/field/get-field-by-id.tsindex dee488ff6..5a1437e34 100644--- a/packages/lib/server-only/field/get-field-by-id.ts+++ b/packages/lib/server-only/field/get-field-by-id.ts@@ -11,7 +11,7 @@ export type GetFieldByIdOptions = {userId: number;teamId: number;fieldId: number;- envelopeType: EnvelopeType;+ envelopeType?: EnvelopeType;};export const getFieldById = async ({@@ -41,7 +41,7 @@ export const getFieldById = async ({type: 'envelopeId',id: field.envelopeId,},- type: envelopeType,+ type: envelopeType ?? null,userId,teamId,});diff --git a/packages/lib/server-only/field/set-fields-for-document.ts b/packages/lib/server-only/field/set-fields-for-document.tsindex ef1bf3000..c69a7f77a 100644--- a/packages/lib/server-only/field/set-fields-for-document.ts+++ b/packages/lib/server-only/field/set-fields-for-document.ts@@ -158,7 +158,7 @@ export const setFieldsForDocument = async ({const numberFieldParsedMeta = ZNumberFieldMeta.parse(field.fieldMeta);const errors = validateNumberField(- String(numberFieldParsedMeta.value),+ String(numberFieldParsedMeta.value || ''),numberFieldParsedMeta,false,);diff --git a/packages/lib/server-only/field/update-document-fields.ts b/packages/lib/server-only/field/update-envelope-fields.tssimilarity index 63%rename from packages/lib/server-only/field/update-document-fields.tsrename to packages/lib/server-only/field/update-envelope-fields.tsindex 2df65d436..80e18efbd 100644--- a/packages/lib/server-only/field/update-document-fields.ts+++ b/packages/lib/server-only/field/update-envelope-fields.ts@@ -10,18 +10,21 @@ import {import { prisma } from '@documenso/prisma';import { AppError, AppErrorCode } from '../../errors/app-error';+import { type EnvelopeIdOptions } from '../../utils/envelope';import { mapFieldToLegacyField } from '../../utils/fields';import { canRecipientFieldsBeModified } from '../../utils/recipients';import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';-export interface UpdateDocumentFieldsOptions {+export interface UpdateEnvelopeFieldsOptions {userId: number;teamId: number;- documentId: number;+ id: EnvelopeIdOptions;+ type?: EnvelopeType | null; // Only used to enforce the type.fields: {id: number;type?: FieldType;pageNumber?: number;+ envelopeItemId?: string;pageX?: number;pageY?: number;width?: number;@@ -31,19 +34,17 @@ export interface UpdateDocumentFieldsOptions {requestMetadata: ApiRequestMetadata;}-export const updateDocumentFields = async ({+export const updateEnvelopeFields = async ({userId,teamId,- documentId,+ id,+ type = null,fields,requestMetadata,-}: UpdateDocumentFieldsOptions) => {+}: UpdateEnvelopeFieldsOptions) => {const { envelopeWhereInput } = await getEnvelopeWhereInput({- id: {- type: 'documentId',- id: documentId,- },- type: EnvelopeType.DOCUMENT,+ id,+ type,userId,teamId,});@@ -53,18 +54,19 @@ export const updateDocumentFields = async ({include: {recipients: true,fields: true,+ envelopeItems: true,},});if (!envelope) {throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Document not found',+ message: 'Envelope not found',});}if (envelope.completedAt) {throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document already complete',+ message: 'Envelope already complete',});}@@ -96,6 +98,29 @@ export const updateDocumentFields = async ({});}+ const fieldType = field.type || originalField.type;+ const fieldMetaType = field.fieldMeta?.type || originalField.fieldMeta?.type;++ // Not going to mess with V1 envelopes.+ if (+ envelope.internalVersion === 2 &&+ fieldMetaType &&+ fieldMetaType.toLowerCase() !== fieldType.toLowerCase()+ ) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Field meta type does not match the field type',+ });+ }++ if (+ field.envelopeItemId &&+ !envelope.envelopeItems.some((item) => item.id === field.envelopeItemId)+ ) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Envelope item not found',+ });+ }+return {originalField,updateData: field,@@ -118,27 +143,30 @@ export const updateDocumentFields = async ({width: updateData.width,height: updateData.height,fieldMeta: updateData.fieldMeta,+ envelopeItemId: updateData.envelopeItemId,},});- const changes = diffFieldChanges(originalField, updatedField);-// Handle field updated audit log.- if (changes.length > 0) {- await tx.documentAuditLog.create({- data: createDocumentAuditLogData({- type: DOCUMENT_AUDIT_LOG_TYPE.FIELD_UPDATED,- envelopeId: envelope.id,- metadata: requestMetadata,- data: {- fieldId: updatedField.secondaryId,- fieldRecipientEmail: recipientEmail,- fieldRecipientId: updatedField.recipientId,- fieldType: updatedField.type,- changes,- },- }),- });+ if (envelope.type === EnvelopeType.DOCUMENT) {+ const changes = diffFieldChanges(originalField, updatedField);++ if (changes.length > 0) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.FIELD_UPDATED,+ envelopeId: envelope.id,+ metadata: requestMetadata,+ data: {+ fieldId: updatedField.secondaryId,+ fieldRecipientEmail: recipientEmail,+ fieldRecipientId: updatedField.recipientId,+ fieldType: updatedField.type,+ changes,+ },+ }),+ });+ }}return updatedField;diff --git a/packages/lib/server-only/field/update-template-fields.ts b/packages/lib/server-only/field/update-template-fields.tsdeleted file mode 100644index cd05ebbd7..000000000--- a/packages/lib/server-only/field/update-template-fields.ts+++ /dev/null@@ -1,116 +0,0 @@-import { EnvelopeType, type FieldType } from '@prisma/client';--import type { TFieldMetaSchema } from '@documenso/lib/types/field-meta';-import { prisma } from '@documenso/prisma';--import { AppError, AppErrorCode } from '../../errors/app-error';-import { mapFieldToLegacyField } from '../../utils/fields';-import { canRecipientFieldsBeModified } from '../../utils/recipients';-import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';--export interface UpdateTemplateFieldsOptions {- userId: number;- teamId: number;- templateId: number;- fields: {- id: number;- type?: FieldType;- pageNumber?: number;- pageX?: number;- pageY?: number;- width?: number;- height?: number;- fieldMeta?: TFieldMetaSchema;- }[];-}--export const updateTemplateFields = async ({- userId,- teamId,- templateId,- fields,-}: UpdateTemplateFieldsOptions) => {- const { envelopeWhereInput } = await getEnvelopeWhereInput({- id: {- type: 'templateId',- id: templateId,- },- type: EnvelopeType.TEMPLATE,- userId,- teamId,- });-- const envelope = await prisma.envelope.findFirst({- where: envelopeWhereInput,- include: {- recipients: true,- fields: true,- },- });-- if (!envelope) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Document not found',- });- }-- const fieldsToUpdate = fields.map((field) => {- const originalField = envelope.fields.find((existingField) => existingField.id === field.id);-- if (!originalField) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: `Field with id ${field.id} not found`,- });- }-- const recipient = envelope.recipients.find(- (recipient) => recipient.id === originalField.recipientId,- );-- // Each field MUST have a recipient associated with it.- if (!recipient) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: `Recipient attached to field ${field.id} not found`,- });- }-- // Check whether the recipient associated with the field can be modified.- if (!canRecipientFieldsBeModified(recipient, envelope.fields)) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message:- 'Cannot modify a field where the recipient has already interacted with the document',- });- }-- return {- updateData: field,- };- });-- const updatedFields = await prisma.$transaction(async (tx) => {- return await Promise.all(- fieldsToUpdate.map(async ({ updateData }) => {- const updatedField = await tx.field.update({- where: {- id: updateData.id,- },- data: {- type: updateData.type,- page: updateData.pageNumber,- positionX: updateData.pageX,- positionY: updateData.pageY,- width: updateData.width,- height: updateData.height,- fieldMeta: updateData.fieldMeta,- },- });-- return updatedField;- }),- );- });-- return {- fields: updatedFields.map((field) => mapFieldToLegacyField(field, envelope)),- };-};diff --git a/packages/lib/server-only/pdf/normalize-pdf.ts b/packages/lib/server-only/pdf/normalize-pdf.tsindex ffbe5be06..071134411 100644--- a/packages/lib/server-only/pdf/normalize-pdf.ts+++ b/packages/lib/server-only/pdf/normalize-pdf.ts@@ -1,13 +1,22 @@import { PDFDocument } from '@cantoo/pdf-lib';+import { AppError } from '../../errors/app-error';import { flattenAnnotations } from './flatten-annotations';import { flattenForm, removeOptionalContentGroups } from './flatten-form';export const normalizePdf = async (pdf: Buffer) => {- const pdfDoc = await PDFDocument.load(pdf).catch(() => null);+ const pdfDoc = await PDFDocument.load(pdf).catch((e) => {+ console.error(`PDF normalization error: ${e.message}`);- if (!pdfDoc) {- return pdf;+ throw new AppError('INVALID_DOCUMENT_FILE', {+ message: 'The document is not a valid PDF',+ });+ });++ if (pdfDoc.isEncrypted) {+ throw new AppError('INVALID_DOCUMENT_FILE', {+ message: 'The document is encrypted',+ });}removeOptionalContentGroups(pdfDoc);diff --git a/packages/lib/server-only/recipient/create-document-recipients.ts b/packages/lib/server-only/recipient/create-envelope-recipients.tssimilarity index 79%rename from packages/lib/server-only/recipient/create-document-recipients.tsrename to packages/lib/server-only/recipient/create-envelope-recipients.tsindex d2b2e0d13..eaa5651f1 100644--- a/packages/lib/server-only/recipient/create-document-recipients.ts+++ b/packages/lib/server-only/recipient/create-envelope-recipients.ts@@ -15,7 +15,7 @@ import type { EnvelopeIdOptions } from '../../utils/envelope';import { mapRecipientToLegacyRecipient } from '../../utils/recipients';import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';-export interface CreateDocumentRecipientsOptions {+export interface CreateEnvelopeRecipientsOptions {userId: number;teamId: number;id: EnvelopeIdOptions;@@ -30,16 +30,16 @@ export interface CreateDocumentRecipientsOptions {requestMetadata: ApiRequestMetadata;}-export const createDocumentRecipients = async ({+export const createEnvelopeRecipients = async ({userId,teamId,id,recipients: recipientsToCreate,requestMetadata,-}: CreateDocumentRecipientsOptions) => {+}: CreateEnvelopeRecipientsOptions) => {const { envelopeWhereInput } = await getEnvelopeWhereInput({id,- type: EnvelopeType.DOCUMENT,+ type: null,userId,teamId,});@@ -62,13 +62,13 @@ export const createDocumentRecipients = async ({if (!envelope) {throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Document not found',+ message: 'Envelope not found',});}if (envelope.completedAt) {throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document already complete',+ message: 'Envelope already complete',});}@@ -112,21 +112,23 @@ export const createDocumentRecipients = async ({});// Handle recipient created audit log.- await tx.documentAuditLog.create({- data: createDocumentAuditLogData({- type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_CREATED,- envelopeId: envelope.id,- metadata: requestMetadata,- data: {- recipientEmail: createdRecipient.email,- recipientName: createdRecipient.name,- recipientId: createdRecipient.id,- recipientRole: createdRecipient.role,- accessAuth: recipient.accessAuth ?? [],- actionAuth: recipient.actionAuth ?? [],- },- }),- });+ if (envelope.type === EnvelopeType.DOCUMENT) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_CREATED,+ envelopeId: envelope.id,+ metadata: requestMetadata,+ data: {+ recipientEmail: createdRecipient.email,+ recipientName: createdRecipient.name,+ recipientId: createdRecipient.id,+ recipientRole: createdRecipient.role,+ accessAuth: recipient.accessAuth ?? [],+ actionAuth: recipient.actionAuth ?? [],+ },+ }),+ });+ }return createdRecipient;}),diff --git a/packages/lib/server-only/recipient/create-template-recipients.ts b/packages/lib/server-only/recipient/create-template-recipients.tsdeleted file mode 100644index e64e00cfe..000000000--- a/packages/lib/server-only/recipient/create-template-recipients.ts+++ /dev/null@@ -1,115 +0,0 @@-import { EnvelopeType, RecipientRole } from '@prisma/client';-import { SendStatus, SigningStatus } from '@prisma/client';--import type { TRecipientAccessAuthTypes } from '@documenso/lib/types/document-auth';-import { type TRecipientActionAuthTypes } from '@documenso/lib/types/document-auth';-import { nanoid } from '@documenso/lib/universal/id';-import { createRecipientAuthOptions } from '@documenso/lib/utils/document-auth';-import { prisma } from '@documenso/prisma';--import { AppError, AppErrorCode } from '../../errors/app-error';-import { mapRecipientToLegacyRecipient } from '../../utils/recipients';-import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';--export interface CreateTemplateRecipientsOptions {- userId: number;- teamId: number;- templateId: number;- recipients: {- email: string;- name: string;- role: RecipientRole;- signingOrder?: number | null;- accessAuth?: TRecipientAccessAuthTypes[];- actionAuth?: TRecipientActionAuthTypes[];- }[];-}--export const createTemplateRecipients = async ({- userId,- teamId,- templateId,- recipients: recipientsToCreate,-}: CreateTemplateRecipientsOptions) => {- const { envelopeWhereInput } = await getEnvelopeWhereInput({- id: {- type: 'templateId',- id: templateId,- },- type: EnvelopeType.TEMPLATE,- userId,- teamId,- });-- const template = await prisma.envelope.findFirst({- where: envelopeWhereInput,- include: {- recipients: true,- team: {- select: {- organisation: {- select: {- organisationClaim: true,- },- },- },- },- },- });-- if (!template) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Template not found',- });- }-- const recipientsHaveActionAuth = recipientsToCreate.some(- (recipient) => recipient.actionAuth && recipient.actionAuth.length > 0,- );-- // Check if user has permission to set the global action auth.- if (recipientsHaveActionAuth && !template.team.organisation.organisationClaim.flags.cfr21) {- throw new AppError(AppErrorCode.UNAUTHORIZED, {- message: 'You do not have permission to set the action auth',- });- }-- const normalizedRecipients = recipientsToCreate.map((recipient) => ({- ...recipient,- email: recipient.email.toLowerCase(),- }));-- const createdRecipients = await prisma.$transaction(async (tx) => {- return await Promise.all(- normalizedRecipients.map(async (recipient) => {- const authOptions = createRecipientAuthOptions({- accessAuth: recipient.accessAuth ?? [],- actionAuth: recipient.actionAuth ?? [],- });-- const createdRecipient = await tx.recipient.create({- data: {- envelopeId: template.id,- name: recipient.name,- email: recipient.email,- role: recipient.role,- signingOrder: recipient.signingOrder,- token: nanoid(),- sendStatus: recipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,- signingStatus:- recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,- authOptions,- },- });-- return createdRecipient;- }),- );- });-- return {- recipients: createdRecipients.map((recipient) =>- mapRecipientToLegacyRecipient(recipient, template),- ),- };-};diff --git a/packages/lib/server-only/recipient/delete-document-recipient.ts b/packages/lib/server-only/recipient/delete-envelope-recipient.tssimilarity index 72%rename from packages/lib/server-only/recipient/delete-document-recipient.tsrename to packages/lib/server-only/recipient/delete-envelope-recipient.tsindex dfefd1f23..29004c3a6 100644--- a/packages/lib/server-only/recipient/delete-document-recipient.ts+++ b/packages/lib/server-only/recipient/delete-envelope-recipient.ts@@ -14,26 +14,27 @@ import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';import { AppError, AppErrorCode } from '../../errors/app-error';import { extractDerivedDocumentEmailSettings } from '../../types/document-email';import { createDocumentAuditLogData } from '../../utils/document-audit-logs';+import { canRecipientBeModified } from '../../utils/recipients';import { renderEmailWithI18N } from '../../utils/render-email-with-i18n';import { buildTeamWhereQuery } from '../../utils/teams';import { getEmailContext } from '../email/get-email-context';+import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';-export interface DeleteDocumentRecipientOptions {+export interface DeleteEnvelopeRecipientOptions {userId: number;teamId: number;recipientId: number;requestMetadata: ApiRequestMetadata;}-export const deleteDocumentRecipient = async ({+export const deleteEnvelopeRecipient = async ({userId,teamId,recipientId,requestMetadata,-}: DeleteDocumentRecipientOptions) => {+}: DeleteEnvelopeRecipientOptions) => {const envelope = await prisma.envelope.findFirst({where: {- type: EnvelopeType.DOCUMENT,recipients: {some: {id: recipientId,@@ -48,6 +49,9 @@ export const deleteDocumentRecipient = async ({where: {id: recipientId,},+ include: {+ fields: true,+ },},},});@@ -89,24 +93,43 @@ export const deleteDocumentRecipient = async ({});}- const deletedRecipient = await prisma.$transaction(async (tx) => {- await tx.documentAuditLog.create({- data: createDocumentAuditLogData({- type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_DELETED,- envelopeId: envelope.id,- metadata: requestMetadata,- data: {- recipientEmail: recipientToDelete.email,- recipientName: recipientToDelete.name,- recipientId: recipientToDelete.id,- recipientRole: recipientToDelete.role,- },- }),+ if (!canRecipientBeModified(recipientToDelete, recipientToDelete.fields)) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Recipient has already interacted with the document.',});+ }++ const { envelopeWhereInput } = await getEnvelopeWhereInput({+ id: {+ type: 'envelopeId',+ id: envelope.id,+ },+ type: null,+ userId,+ teamId,+ });++ const deletedRecipient = await prisma.$transaction(async (tx) => {+ if (envelope.type === EnvelopeType.DOCUMENT) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_DELETED,+ envelopeId: envelope.id,+ metadata: requestMetadata,+ data: {+ recipientEmail: recipientToDelete.email,+ recipientName: recipientToDelete.name,+ recipientId: recipientToDelete.id,+ recipientRole: recipientToDelete.role,+ },+ }),+ });+ }return await tx.recipient.delete({where: {id: recipientId,+ envelope: envelopeWhereInput,},});});@@ -116,7 +139,11 @@ export const deleteDocumentRecipient = async ({).recipientRemoved;// Send email to deleted recipient.- if (recipientToDelete.sendStatus === SendStatus.SENT && isRecipientRemovedEmailEnabled) {+ if (+ recipientToDelete.sendStatus === SendStatus.SENT &&+ isRecipientRemovedEmailEnabled &&+ envelope.type === EnvelopeType.DOCUMENT+ ) {const assetBaseUrl = NEXT_PUBLIC_WEBAPP_URL() || 'http://localhost:3000';const template = createElement(RecipientRemovedFromDocumentTemplate, {diff --git a/packages/lib/server-only/recipient/delete-template-recipient.ts b/packages/lib/server-only/recipient/delete-template-recipient.tsdeleted file mode 100644index 839526f3b..000000000--- a/packages/lib/server-only/recipient/delete-template-recipient.ts+++ /dev/null@@ -1,58 +0,0 @@-import { EnvelopeType } from '@prisma/client';--import { prisma } from '@documenso/prisma';--import { AppError, AppErrorCode } from '../../errors/app-error';-import { buildTeamWhereQuery } from '../../utils/teams';-import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';--export interface DeleteTemplateRecipientOptions {- userId: number;- teamId: number;- recipientId: number;-}--export const deleteTemplateRecipient = async ({- userId,- teamId,- recipientId,-}: DeleteTemplateRecipientOptions): Promise<void> => {- const recipientToDelete = await prisma.recipient.findFirst({- where: {- id: recipientId,- envelope: {- type: EnvelopeType.TEMPLATE,- team: buildTeamWhereQuery({ teamId, userId }),- },- },- });-- if (!recipientToDelete) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Recipient not found',- });- }-- const { envelopeWhereInput } = await getEnvelopeWhereInput({- id: {- type: 'envelopeId',- id: recipientToDelete.envelopeId,- },- type: EnvelopeType.TEMPLATE,- userId,- teamId,- });-- if (!recipientToDelete || recipientToDelete.id !== recipientId) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Recipient not found',- });- }-- await prisma.recipient.delete({- where: {- id: recipientId,- envelope: envelopeWhereInput,- },- });-};diff --git a/packages/lib/server-only/recipient/update-document-recipients.ts b/packages/lib/server-only/recipient/update-envelope-recipients.tssimilarity index 77%rename from packages/lib/server-only/recipient/update-document-recipients.tsrename to packages/lib/server-only/recipient/update-envelope-recipients.tsindex bede48dfe..92c365177 100644--- a/packages/lib/server-only/recipient/update-document-recipients.ts+++ b/packages/lib/server-only/recipient/update-envelope-recipients.ts@@ -1,5 +1,4 @@-import { EnvelopeType, RecipientRole } from '@prisma/client';-import { SendStatus, SigningStatus } from '@prisma/client';+import { EnvelopeType, RecipientRole, SendStatus, SigningStatus } from '@prisma/client';import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';import type { TRecipientAccessAuthTypes } from '@documenso/lib/types/document-auth';@@ -16,29 +15,38 @@ import { createRecipientAuthOptions } from '@documenso/lib/utils/document-auth';import { prisma } from '@documenso/prisma';import { AppError, AppErrorCode } from '../../errors/app-error';-import { type EnvelopeIdOptions, mapSecondaryIdToDocumentId } from '../../utils/envelope';+import { extractLegacyIds } from '../../universal/id';+import { type EnvelopeIdOptions } from '../../utils/envelope';import { mapFieldToLegacyField } from '../../utils/fields';import { canRecipientBeModified } from '../../utils/recipients';import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';-export interface UpdateDocumentRecipientsOptions {+export interface UpdateEnvelopeRecipientsOptions {userId: number;teamId: number;id: EnvelopeIdOptions;- recipients: RecipientData[];+ recipients: {+ id: number;+ email?: string;+ name?: string;+ role?: RecipientRole;+ signingOrder?: number | null;+ accessAuth?: TRecipientAccessAuthTypes[];+ actionAuth?: TRecipientActionAuthTypes[];+ }[];requestMetadata: ApiRequestMetadata;}-export const updateDocumentRecipients = async ({+export const updateEnvelopeRecipients = async ({userId,teamId,id,recipients,requestMetadata,-}: UpdateDocumentRecipientsOptions) => {+}: UpdateEnvelopeRecipientsOptions) => {const { envelopeWhereInput } = await getEnvelopeWhereInput({id,- type: EnvelopeType.DOCUMENT,+ type: null,userId,teamId,});@@ -62,13 +70,13 @@ export const updateDocumentRecipients = async ({if (!envelope) {throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Document not found',+ message: 'Envelope not found',});}if (envelope.completedAt) {throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document already complete',+ message: 'Envelope already complete',});}@@ -160,24 +168,26 @@ export const updateDocumentRecipients = async ({});}- const changes = diffRecipientChanges(originalRecipient, updatedRecipient);-// Handle recipient updated audit log.- if (changes.length > 0) {- await tx.documentAuditLog.create({- data: createDocumentAuditLogData({- type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_UPDATED,- envelopeId: envelope.id,- metadata: requestMetadata,- data: {- recipientEmail: updatedRecipient.email,- recipientName: updatedRecipient.name,- recipientId: updatedRecipient.id,- recipientRole: updatedRecipient.role,- changes,- },- }),- });+ if (envelope.type === EnvelopeType.DOCUMENT) {+ const changes = diffRecipientChanges(originalRecipient, updatedRecipient);++ if (changes.length > 0) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_UPDATED,+ envelopeId: envelope.id,+ metadata: requestMetadata,+ data: {+ recipientEmail: updatedRecipient.email,+ recipientName: updatedRecipient.name,+ recipientId: updatedRecipient.id,+ recipientRole: updatedRecipient.role,+ changes,+ },+ }),+ });+ }}return updatedRecipient;@@ -188,19 +198,8 @@ export const updateDocumentRecipients = async ({return {recipients: updatedRecipients.map((recipient) => ({...recipient,- documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),- templateId: null,+ ...extractLegacyIds(envelope),fields: recipient.fields.map((field) => mapFieldToLegacyField(field, envelope)),})),};};--type RecipientData = {- id: number;- email?: string;- name?: string;- role?: RecipientRole;- signingOrder?: number | null;- accessAuth?: TRecipientAccessAuthTypes[];- actionAuth?: TRecipientActionAuthTypes[];-};diff --git a/packages/lib/server-only/recipient/update-template-recipients.ts b/packages/lib/server-only/recipient/update-template-recipients.tsdeleted file mode 100644index 45bdff76b..000000000--- a/packages/lib/server-only/recipient/update-template-recipients.ts+++ /dev/null@@ -1,168 +0,0 @@-import { EnvelopeType, RecipientRole } from '@prisma/client';-import { SendStatus, SigningStatus } from '@prisma/client';--import type { TRecipientAccessAuthTypes } from '@documenso/lib/types/document-auth';-import {- type TRecipientActionAuthTypes,- ZRecipientAuthOptionsSchema,-} from '@documenso/lib/types/document-auth';-import { createRecipientAuthOptions } from '@documenso/lib/utils/document-auth';-import { prisma } from '@documenso/prisma';--import { AppError, AppErrorCode } from '../../errors/app-error';-import { mapSecondaryIdToTemplateId } from '../../utils/envelope';-import { mapFieldToLegacyField } from '../../utils/fields';-import { getEnvelopeWhereInput } from '../envelope/get-envelope-by-id';--export interface UpdateTemplateRecipientsOptions {- userId: number;- teamId: number;- templateId: number;- recipients: {- id: number;- email?: string;- name?: string;- role?: RecipientRole;- signingOrder?: number | null;- accessAuth?: TRecipientAccessAuthTypes[];- actionAuth?: TRecipientActionAuthTypes[];- }[];-}--export const updateTemplateRecipients = async ({- userId,- teamId,- templateId,- recipients,-}: UpdateTemplateRecipientsOptions) => {- const { envelopeWhereInput } = await getEnvelopeWhereInput({- id: {- type: 'templateId',- id: templateId,- },- type: EnvelopeType.TEMPLATE,- userId,- teamId,- });-- const envelope = await prisma.envelope.findFirst({- where: envelopeWhereInput,- include: {- recipients: true,- team: {- select: {- organisation: {- select: {- organisationClaim: true,- },- },- },- },- },- });-- if (!envelope) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Template not found',- });- }-- const recipientsHaveActionAuth = recipients.some(- (recipient) => recipient.actionAuth && recipient.actionAuth.length > 0,- );-- // Check if user has permission to set the global action auth.- if (recipientsHaveActionAuth && !envelope.team.organisation.organisationClaim.flags.cfr21) {- throw new AppError(AppErrorCode.UNAUTHORIZED, {- message: 'You do not have permission to set the action auth',- });- }-- const recipientsToUpdate = recipients.map((recipient) => {- const originalRecipient = envelope.recipients.find(- (existingRecipient) => existingRecipient.id === recipient.id,- );-- if (!originalRecipient) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: `Recipient with id ${recipient.id} not found`,- });- }-- return {- originalRecipient,- recipientUpdateData: recipient,- };- });-- const updatedRecipients = await prisma.$transaction(async (tx) => {- return await Promise.all(- recipientsToUpdate.map(async ({ originalRecipient, recipientUpdateData }) => {- let authOptions = ZRecipientAuthOptionsSchema.parse(originalRecipient.authOptions);-- if (- recipientUpdateData.actionAuth !== undefined ||- recipientUpdateData.accessAuth !== undefined- ) {- authOptions = createRecipientAuthOptions({- accessAuth: recipientUpdateData.accessAuth || authOptions.accessAuth,- actionAuth: recipientUpdateData.actionAuth || authOptions.actionAuth,- });- }-- const mergedRecipient = {- ...originalRecipient,- ...recipientUpdateData,- };-- const updatedRecipient = await tx.recipient.update({- where: {- id: originalRecipient.id,- envelopeId: envelope.id,- },- data: {- name: mergedRecipient.name,- email: mergedRecipient.email,- role: mergedRecipient.role,- signingOrder: mergedRecipient.signingOrder,- envelopeId: envelope.id,- sendStatus:- mergedRecipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,- signingStatus:- mergedRecipient.role === RecipientRole.CC- ? SigningStatus.SIGNED- : SigningStatus.NOT_SIGNED,- authOptions,- },- include: {- fields: true,- },- });-- // Clear all fields if the recipient role is changed to a type that cannot have fields.- if (- originalRecipient.role !== updatedRecipient.role &&- (updatedRecipient.role === RecipientRole.CC ||- updatedRecipient.role === RecipientRole.VIEWER)- ) {- await tx.field.deleteMany({- where: {- recipientId: updatedRecipient.id,- },- });- }-- return updatedRecipient;- }),- );- });-- return {- recipients: updatedRecipients.map((recipient) => ({- ...recipient,- documentId: null,- templateId: mapSecondaryIdToTemplateId(envelope.secondaryId),- fields: recipient.fields.map((field) => mapFieldToLegacyField(field, envelope)),- })),- };-};diff --git a/packages/lib/server-only/template/create-document-from-direct-template.ts b/packages/lib/server-only/template/create-document-from-direct-template.tsindex bda55ee7a..18f6133a9 100644--- a/packages/lib/server-only/template/create-document-from-direct-template.ts+++ b/packages/lib/server-only/template/create-document-from-direct-template.ts@@ -82,6 +82,7 @@ type CreatedDirectRecipientField = {export const ZCreateDocumentFromDirectTemplateResponseSchema = z.object({token: z.string(),+ envelopeId: z.string(),documentId: z.number(),recipientId: z.number(),});@@ -815,6 +816,7 @@ export const createDocumentFromDirectTemplate = async ({return {token,+ envelopeId: createdEnvelope.id,documentId: incrementedDocumentId.documentId,recipientId,};diff --git a/packages/lib/server-only/template/get-template-by-direct-link-token.ts b/packages/lib/server-only/template/get-template-by-direct-link-token.tsindex e6a51d30f..6ede281f8 100644--- a/packages/lib/server-only/template/get-template-by-direct-link-token.ts+++ b/packages/lib/server-only/template/get-template-by-direct-link-token.ts@@ -87,5 +87,9 @@ export const getTemplateByDirectLinkToken = async ({},recipients: recipientsWithMappedFields,fields: recipientsWithMappedFields.flatMap((recipient) => recipient.fields),+ envelopeItems: envelope.envelopeItems.map((item) => ({+ id: item.id,+ envelopeId: item.envelopeId,+ })),};};diff --git a/packages/lib/server-only/template/get-template-by-id.ts b/packages/lib/server-only/template/get-template-by-id.tsindex 546e16e39..0b87e5c87 100644--- a/packages/lib/server-only/template/get-template-by-id.ts+++ b/packages/lib/server-only/template/get-template-by-id.ts@@ -29,6 +29,7 @@ export const getTemplateById = async ({ id, userId, teamId }: GetTemplateByIdOptenvelopeItems: {select: {id: true,+ envelopeId: true,documentData: true,},},@@ -94,5 +95,9 @@ export const getTemplateById = async ({ id, userId, teamId }: GetTemplateByIdOpt}: null,id: mapSecondaryIdToTemplateId(envelope.secondaryId),+ envelopeItems: envelope.envelopeItems.map((envelopeItem) => ({+ id: envelopeItem.id,+ envelopeId: envelopeItem.envelopeId,+ })),};};diff --git a/packages/lib/types/document.ts b/packages/lib/types/document.tsindex a1fcdc1d7..140e453cb 100644--- a/packages/lib/types/document.ts+++ b/packages/lib/types/document.ts@@ -2,6 +2,7 @@ import { z } from 'zod';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 { FolderSchema } from '@documenso/prisma/generated/zod/modelSchema/FolderSchema';import { TeamSchema } from '@documenso/prisma/generated/zod/modelSchema/TeamSchema';import { UserSchema } from '@documenso/prisma/generated/zod/modelSchema/UserSchema';@@ -74,6 +75,10 @@ export const ZDocumentSchema = LegacyDocumentSchema.pick({password: z.string().nullable().default(null),documentId: z.number().default(-1).optional(),}),+ envelopeItems: EnvelopeItemSchema.pick({+ id: true,+ envelopeId: true,+ }).array(),folder: FolderSchema.pick({id: true,diff --git a/packages/lib/types/envelope.ts b/packages/lib/types/envelope.tsindex e0a432821..a0b4cea62 100644--- a/packages/lib/types/envelope.ts+++ b/packages/lib/types/envelope.ts@@ -1,14 +1,13 @@import { z } from 'zod';-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 { TeamSchema } from '@documenso/prisma/generated/zod/modelSchema/TeamSchema';import TemplateDirectLinkSchema from '@documenso/prisma/generated/zod/modelSchema/TemplateDirectLinkSchema';-import { ZFieldSchema } from './field';-import { ZRecipientLiteSchema } from './recipient';+import { ZEnvelopeFieldSchema } from './field';+import { ZEnvelopeRecipientLiteSchema } from './recipient';/*** The full envelope response schema.@@ -37,11 +36,8 @@ export const ZEnvelopeSchema = EnvelopeSchema.pick({userId: true,teamId: true,folderId: true,+ templateId: true,}).extend({- templateId: z- .number()- .nullish()- .describe('The ID of the template that the document was created from, if any.'),documentMeta: DocumentMetaSchema.pick({signingOrder: true,distributionMethod: true,@@ -60,29 +56,14 @@ export const ZEnvelopeSchema = EnvelopeSchema.pick({emailId: true,emailReplyTo: true,}),- recipients: ZRecipientLiteSchema.omit({- documentId: true,- templateId: true,- }).array(),- fields: ZFieldSchema.omit({- documentId: true,- templateId: true,- }).array(),+ recipients: ZEnvelopeRecipientLiteSchema.array(),+ fields: ZEnvelopeFieldSchema.array(),envelopeItems: EnvelopeItemSchema.pick({+ envelopeId: true,id: true,title: true,- documentDataId: true,order: true,- })- .extend({- documentData: DocumentDataSchema.pick({- type: true,- id: true,- data: true,- initialData: true,- }),- })- .array(),+ }).array(),directLink: TemplateDirectLinkSchema.pick({directTemplateRecipientId: true,enabled: true,diff --git a/packages/lib/types/field-meta.ts b/packages/lib/types/field-meta.tsindex b71c15a3f..590b77d0e 100644--- a/packages/lib/types/field-meta.ts+++ b/packages/lib/types/field-meta.ts@@ -188,7 +188,7 @@ export type TFieldMetaSchema = z.infer<typeof ZFieldMetaSchema>;export const ZFieldAndMetaSchema = z.discriminatedUnion('type', [z.object({type: z.literal(FieldType.SIGNATURE),- fieldMeta: z.undefined(),+ fieldMeta: ZSignatureFieldMeta.optional(),}),z.object({type: z.literal(FieldType.FREE_SIGNATURE),diff --git a/packages/lib/types/field.ts b/packages/lib/types/field.tsindex 133bfc671..26aba6535 100644--- a/packages/lib/types/field.ts+++ b/packages/lib/types/field.ts@@ -50,6 +50,11 @@ export const ZFieldSchema = FieldSchema.pick({templateId: z.number().nullish(),});+export const ZEnvelopeFieldSchema = ZFieldSchema.omit({+ documentId: true,+ templateId: true,+});+export const ZFieldPageNumberSchema = z.number().min(1)@@ -69,6 +74,30 @@ export const ZFieldWidthSchema = z.number().min(1).describe('The width of the fiexport const ZFieldHeightSchema = z.number().min(1).describe('The height of the field.');+export const ZClampedFieldPositionXSchema = z+ .number()+ .min(0)+ .max(100)+ .describe('The percentage based X coordinate where the field will be placed.');++export const ZClampedFieldPositionYSchema = z+ .number()+ .min(0)+ .max(100)+ .describe('The percentage based Y coordinate where the field will be placed.');++export const ZClampedFieldWidthSchema = z+ .number()+ .min(0)+ .max(100)+ .describe('The percentage based width of the field on the page.');++export const ZClampedFieldHeightSchema = z+ .number()+ .min(0)+ .max(100)+ .describe('The percentage based height of the field on the page.');+// ---------------------------------------------const PrismaDecimalSchema = z.preprocess(diff --git a/packages/lib/types/recipient.ts b/packages/lib/types/recipient.tsindex 0a09bdf46..ea2a0a912 100644--- a/packages/lib/types/recipient.ts+++ b/packages/lib/types/recipient.ts@@ -95,3 +95,18 @@ export const ZRecipientManySchema = RecipientSchema.pick({documentId: z.number().nullish(),templateId: z.number().nullish(),});++export const ZEnvelopeRecipientSchema = ZRecipientSchema.omit({+ documentId: true,+ templateId: true,+});++export const ZEnvelopeRecipientLiteSchema = ZRecipientLiteSchema.omit({+ documentId: true,+ templateId: true,+});++export const ZEnvelopeRecipientManySchema = ZRecipientManySchema.omit({+ documentId: true,+ templateId: true,+});diff --git a/packages/lib/types/template.ts b/packages/lib/types/template.tsindex 0ba6b0010..3b8fcd0d8 100644--- a/packages/lib/types/template.ts+++ b/packages/lib/types/template.ts@@ -2,6 +2,7 @@ import { z } from 'zod';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 { FolderSchema } from '@documenso/prisma/generated/zod/modelSchema/FolderSchema';import TeamSchema from '@documenso/prisma/generated/zod/modelSchema/TeamSchema';import { UserSchema } from '@documenso/prisma/generated/zod/modelSchema/UserSchema';@@ -87,6 +88,10 @@ export const ZTemplateSchema = TemplateSchema.pick({createdAt: true,updatedAt: true,}).nullable(),+ envelopeItems: EnvelopeItemSchema.pick({+ id: true,+ envelopeId: true,+ }).array(),});export type TTemplate = z.infer<typeof ZTemplateSchema>;diff --git a/packages/lib/universal/crypto.ts b/packages/lib/universal/crypto.tsindex 405208d7f..22d64a1f2 100644--- a/packages/lib/universal/crypto.ts+++ b/packages/lib/universal/crypto.ts@@ -30,3 +30,5 @@ export const symmetricDecrypt = ({ key, data }: SymmetricDecryptOptions) => {return chacha.decrypt(dataAsBytes);};++export { sha256 };diff --git a/packages/lib/universal/field-renderer/field-generic-items.ts b/packages/lib/universal/field-renderer/field-generic-items.tsindex 9b5d948b1..af196c000 100644--- a/packages/lib/universal/field-renderer/field-generic-items.ts+++ b/packages/lib/universal/field-renderer/field-generic-items.ts@@ -153,6 +153,11 @@ export const createFieldHoverInteraction = ({const hoverColor = RECIPIENT_COLOR_STYLES[options.color].baseRingHover;fieldGroup.on('mouseover', () => {+ const layer = fieldRect.getLayer();+ if (!layer) {+ return;+ }+new Konva.Tween({node: fieldRect,duration: 0.3,@@ -161,6 +166,11 @@ export const createFieldHoverInteraction = ({});fieldGroup.on('mouseout', () => {+ const layer = fieldRect.getLayer();+ if (!layer) {+ return;+ }+new Konva.Tween({node: fieldRect,duration: 0.3,@@ -169,6 +179,11 @@ export const createFieldHoverInteraction = ({});fieldGroup.on('transformstart', () => {+ const layer = fieldRect.getLayer();+ if (!layer) {+ return;+ }+new Konva.Tween({node: fieldRect,duration: 0.3,@@ -177,6 +192,11 @@ export const createFieldHoverInteraction = ({});fieldGroup.on('transformend', () => {+ const layer = fieldRect.getLayer();+ if (!layer) {+ return;+ }+new Konva.Tween({node: fieldRect,duration: 0.3,diff --git a/packages/lib/universal/field-renderer/field-renderer.ts b/packages/lib/universal/field-renderer/field-renderer.tsindex e925cb0f9..8f66084e2 100644--- a/packages/lib/universal/field-renderer/field-renderer.ts+++ b/packages/lib/universal/field-renderer/field-renderer.ts@@ -19,7 +19,7 @@ export type FieldToRender = Pick<positionX: number;positionY: number;fieldMeta?: TFieldMetaSchema | null;- signature?: Signature | null;+ signature?: Pick<Signature, 'signatureImageAsBase64' | 'typedSignature'> | null;};export type RenderFieldElementOptions = {diff --git a/packages/lib/universal/field-renderer/render-checkbox-field.ts b/packages/lib/universal/field-renderer/render-checkbox-field.tsindex 28a2cefdc..8a927201d 100644--- a/packages/lib/universal/field-renderer/render-checkbox-field.ts+++ b/packages/lib/universal/field-renderer/render-checkbox-field.ts@@ -3,6 +3,7 @@ import { match } from 'ts-pattern';import { DEFAULT_STANDARD_FONT_SIZE } from '../../constants/pdf';import type { TCheckboxFieldMeta } from '../../types/field-meta';+import { parseCheckboxCustomText } from '../../utils/fields';import {createFieldHoverInteraction,konvaTextFill,@@ -62,16 +63,15 @@ export const renderCheckboxFieldElement = (const rectWidth = fieldRect.width() * groupScaleX;const rectHeight = fieldRect.height() * groupScaleY;- // Todo: Envelopes - check sorting more than 10- // arr.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));-const squares = fieldGroup.find('.checkbox-square')- .sort((a, b) => a.id().localeCompare(b.id()));+ .sort((a, b) => a.id().localeCompare(b.id(), undefined, { numeric: true }));const checkmarks = fieldGroup.find('.checkbox-checkmark')- .sort((a, b) => a.id().localeCompare(b.id()));- const text = fieldGroup.find('.checkbox-text').sort((a, b) => a.id().localeCompare(b.id()));+ .sort((a, b) => a.id().localeCompare(b.id(), undefined, { numeric: true }));+ const text = fieldGroup+ .find('.checkbox-text')+ .sort((a, b) => a.id().localeCompare(b.id(), undefined, { numeric: true }));const groupedItems = squares.map((square, i) => ({squareElement: square,@@ -130,7 +130,7 @@ export const renderCheckboxFieldElement = (pageLayer.batchDraw();});- const checkedValues: number[] = field.customText ? JSON.parse(field.customText) : [];+ const checkedValues: number[] = field.customText ? parseCheckboxCustomText(field.customText) : [];checkboxValues.forEach(({ value, checked }, index) => {const isCheckboxChecked = match(mode)@@ -170,7 +170,7 @@ export const renderCheckboxFieldElement = (width: itemSize,height: itemSize,stroke: '#374151',- strokeWidth: 2,+ strokeWidth: 1.5,cornerRadius: 2,fill: 'white',});diff --git a/packages/lib/universal/field-renderer/render-field.ts b/packages/lib/universal/field-renderer/render-field.tsindex 6e866b6be..2d657f06c 100644--- a/packages/lib/universal/field-renderer/render-field.ts+++ b/packages/lib/universal/field-renderer/render-field.ts@@ -8,13 +8,24 @@ import type { TRecipientColor } from '@documenso/ui/lib/recipient-colors';import type { TFieldMetaSchema } from '../../types/field-meta';import { renderCheckboxFieldElement } from './render-checkbox-field';import { renderDropdownFieldElement } from './render-dropdown-field';+import { renderGenericTextFieldElement } from './render-generic-text-field';import { renderRadioFieldElement } from './render-radio-field';import { renderSignatureFieldElement } from './render-signature-field';-import { renderTextFieldElement } from './render-text-field';export const MIN_FIELD_HEIGHT_PX = 12;export const MIN_FIELD_WIDTH_PX = 36;+/**+ * The render type.+ *+ * @default 'edit'+ *+ * - `edit` - The field is rendered in editor page.+ * - `sign` - The field is rendered for the signing page.+ * - `export` - The field is rendered for exporting and sealing into the PDF. No backgrounds, interactive elements, etc.+ */+export type FieldRenderMode = 'edit' | 'sign' | 'export';+export type FieldToRender = Pick<Field,'envelopeItemId' | 'recipientId' | 'type' | 'page' | 'customText' | 'inserted' | 'recipientId'@@ -25,7 +36,7 @@ export type FieldToRender = Pick<positionX: number;positionY: number;fieldMeta?: TFieldMetaSchema | null;- signature?: Signature | null;+ signature?: Pick<Signature, 'signatureImageAsBase64' | 'typedSignature'> | null;};type RenderFieldOptions = {@@ -38,16 +49,7 @@ type RenderFieldOptions = {translations: Record<FieldType, string> | null;- /**- * The render type.- *- * @default 'edit'- *- * - `edit` - The field is rendered in edit mode.- * - `sign` - The field is rendered in sign mode. No interactive elements.- * - `export` - The field is rendered in export mode. No backgrounds, interactive elements, etc.- */- mode: 'edit' | 'sign' | 'export';+ mode: FieldRenderMode;scale: number;editable?: boolean;@@ -76,10 +78,21 @@ export const renderField = ({};return match(field.type)- .with(FieldType.TEXT, () => renderTextFieldElement(field, options))+ .with(+ FieldType.INITIALS,+ FieldType.NAME,+ FieldType.EMAIL,+ FieldType.DATE,+ FieldType.TEXT,+ FieldType.NUMBER,+ () => renderGenericTextFieldElement(field, options),+ ).with(FieldType.CHECKBOX, () => renderCheckboxFieldElement(field, options)).with(FieldType.RADIO, () => renderRadioFieldElement(field, options)).with(FieldType.DROPDOWN, () => renderDropdownFieldElement(field, options)).with(FieldType.SIGNATURE, () => renderSignatureFieldElement(field, options))- .otherwise(() => renderTextFieldElement(field, options)); // Todo: Envelopes+ .with(FieldType.FREE_SIGNATURE, () => {+ throw new Error('Free signature fields are not supported');+ })+ .exhaustive();};diff --git a/packages/lib/universal/field-renderer/render-text-field.ts b/packages/lib/universal/field-renderer/render-generic-text-field.tssimilarity index 76%rename from packages/lib/universal/field-renderer/render-text-field.tsrename to packages/lib/universal/field-renderer/render-generic-text-field.tsindex c1fc95227..20fd87d6a 100644--- a/packages/lib/universal/field-renderer/render-text-field.ts+++ b/packages/lib/universal/field-renderer/render-generic-text-field.ts@@ -12,6 +12,8 @@ import {import type { FieldToRender, RenderFieldElementOptions } from './field-renderer';import { calculateFieldPosition } from './field-renderer';+const DEFAULT_TEXT_ALIGN = 'left';+const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOptions): Konva.Text => {const { pageWidth, pageHeight, mode = 'edit', pageLayer, translations } = options;@@ -31,8 +33,8 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOption// Calculate text positioning based on alignmentconst textX = 0;const textY = 0;- let textAlign: 'left' | 'center' | 'right' = textMeta?.textAlign || 'left';- let textVerticalAlign: 'top' | 'middle' | 'bottom' = 'top';+ let textAlign: 'left' | 'center' | 'right' = textMeta?.textAlign || DEFAULT_TEXT_ALIGN;+ const textVerticalAlign: 'top' | 'middle' | 'bottom' = 'middle';const textFontSize = textMeta?.fontSize || DEFAULT_STANDARD_FONT_SIZE;const textPadding = 10;@@ -40,51 +42,29 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOption// Handle edit mode.if (mode === 'edit') {- textToRender = fieldTypeName;- textAlign = 'center';- textVerticalAlign = 'middle';-- if (textMeta?.label) {- textToRender = textMeta.label;- } else if (textMeta?.text) {+ if (textMeta?.text) {textToRender = textMeta.text;- textAlign = textMeta.textAlign || 'center'; // Todo: Envelopes - What is the default-- // Todo: Envelopes - Handle this on signatures- if (textMeta.characterLimit) {- textToRender = textToRender.slice(0, textMeta.characterLimit);- }+ } else {+ // Show field name which is centered for the edit mode if no label/text is avaliable.+ textToRender = textMeta?.label || fieldTypeName;+ textAlign = 'center';}}// Handle sign mode.if (mode === 'sign' || mode === 'export') {- textToRender = fieldTypeName;- textAlign = 'center';- textVerticalAlign = 'middle';-- if (textMeta?.label) {- textToRender = textMeta.label;- }-- if (textMeta?.text) {- textToRender = textMeta.text;- textAlign = textMeta.textAlign || 'center'; // Todo: Envelopes - What is the default-- // Todo: Envelopes - Handle this on signatures- if (textMeta.characterLimit) {- textToRender = textToRender.slice(0, textMeta.characterLimit);+ if (!field.inserted) {+ if (textMeta?.text) {+ textToRender = textMeta.text;+ } else if (mode === 'sign') {+ // Only show the field name in sign mode if no text/label is avaliable.+ textToRender = textMeta?.label || fieldTypeName;+ textAlign = 'center';}}if (field.inserted) {textToRender = field.customText;- textAlign = textMeta?.textAlign || 'center'; // Todo: Envelopes - What is the default-- // Todo: Envelopes - Handle this on signatures- if (textMeta?.characterLimit) {- textToRender = textToRender.slice(0, textMeta.characterLimit);- }}}@@ -106,7 +86,7 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOptionreturn fieldText;};-export const renderTextFieldElement = (+export const renderGenericTextFieldElement = (field: FieldToRender,options: RenderFieldElementOptions,) => {diff --git a/packages/lib/universal/field-renderer/render-radio-field.ts b/packages/lib/universal/field-renderer/render-radio-field.tsindex fa329938a..5d173b0e3 100644--- a/packages/lib/universal/field-renderer/render-radio-field.ts+++ b/packages/lib/universal/field-renderer/render-radio-field.ts@@ -159,7 +159,7 @@ export const renderRadioFieldElement = (y: itemInputY,radius: calculateRadioSize(fontSize) / 2,stroke: '#374151',- strokeWidth: 2,+ strokeWidth: 1.5,fill: 'white',});diff --git a/packages/lib/universal/upload/get-file.ts b/packages/lib/universal/upload/get-file.tsindex 6ac631c13..ac62b1744 100644--- a/packages/lib/universal/upload/get-file.ts+++ b/packages/lib/universal/upload/get-file.ts@@ -7,7 +7,13 @@ export type GetFileOptions = {data: string;};-export const getFile = async ({ type, data }: GetFileOptions) => {+/**+ * KEPT FOR POSTERITY, SHOULD BE REMOVED IN THE FUTURE+ * DO NOT USE OR I WILL FIRE YOU+ *+ * - Lucas, 2025-11-04+ */+const getFile = async ({ type, data }: GetFileOptions) => {return await match(type).with(DocumentDataType.BYTES, () => getFileFromBytes(data)).with(DocumentDataType.BYTES_64, () => getFileFromBytes64(data))diff --git a/packages/lib/universal/upload/put-file.server.ts b/packages/lib/universal/upload/put-file.server.tsindex f414be62f..47c2be747 100644--- a/packages/lib/universal/upload/put-file.server.ts+++ b/packages/lib/universal/upload/put-file.server.ts@@ -7,6 +7,7 @@ import { env } from '@documenso/lib/utils/env';import { AppError } from '../../errors/app-error';import { createDocumentData } from '../../server-only/document-data/create-document-data';+import { normalizePdf } from '../../server-only/pdf/normalize-pdf';import { uploadS3File } from './server-actions';type File = {@@ -43,6 +44,28 @@ export const putPdfFileServerSide = async (file: File) => {return await createDocumentData({ type, data });};+/**+ * Uploads a pdf file and normalizes it.+ */+export const putNormalizedPdfFileServerSide = async (file: File) => {+ const buffer = Buffer.from(await file.arrayBuffer());++ const normalized = await normalizePdf(buffer);++ const fileName = file.name.endsWith('.pdf') ? file.name : `${file.name}.pdf`;++ const documentData = await putFileServerSide({+ name: fileName,+ type: 'application/pdf',+ arrayBuffer: async () => Promise.resolve(normalized),+ });++ return await createDocumentData({+ type: documentData.type,+ data: documentData.data,+ });+};+/*** Uploads a file to the appropriate storage location.*/diff --git a/packages/lib/universal/upload/put-file.ts b/packages/lib/universal/upload/put-file.tsindex 64f8d9be9..a33d0dab9 100644--- a/packages/lib/universal/upload/put-file.ts+++ b/packages/lib/universal/upload/put-file.ts@@ -6,7 +6,7 @@ import { env } from '@documenso/lib/utils/env';import type {TGetPresignedPostUrlResponse,TUploadPdfResponse,-} from '@documenso/remix/server/api/files.types';+} from '@documenso/remix/server/api/files/files.types';import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';import { AppError } from '../../errors/app-error';diff --git a/packages/lib/utils/envelope-download.ts b/packages/lib/utils/envelope-download.tsnew file mode 100644index 000000000..9f896928f--- /dev/null+++ b/packages/lib/utils/envelope-download.ts@@ -0,0 +1,19 @@+import type { EnvelopeItem } from '@prisma/client';++import { NEXT_PUBLIC_WEBAPP_URL } from '../constants/app';++export type EnvelopeDownloadUrlOptions = {+ envelopeItem: Pick<EnvelopeItem, 'id' | 'envelopeId'>;+ token: string | undefined;+ version: 'original' | 'signed';+};++export const getEnvelopeDownloadUrl = (options: EnvelopeDownloadUrlOptions) => {+ const { envelopeItem, token, version } = options;++ const { id, envelopeId } = envelopeItem;++ return token+ ? `${NEXT_PUBLIC_WEBAPP_URL()}/api/files/token/${token}/envelopeItem/${id}/download/${version}`+ : `${NEXT_PUBLIC_WEBAPP_URL()}/api/files/envelope/${envelopeId}/envelopeItem/${id}/download/${version}`;+};diff --git a/packages/lib/utils/envelope-signing.ts b/packages/lib/utils/envelope-signing.tsindex 8f43773e9..10bc01593 100644--- a/packages/lib/utils/envelope-signing.ts+++ b/packages/lib/utils/envelope-signing.ts@@ -104,7 +104,6 @@ export const extractFieldInsertionValues = ({const numberFieldParsedMeta = ZNumberFieldMeta.parse(field.fieldMeta);const errors = validateNumberField(fieldValue.value.toString(), numberFieldParsedMeta, true);- // Todoif (errors.length > 0) {throw new AppError(AppErrorCode.INVALID_BODY, {message: 'Invalid number',@@ -127,7 +126,6 @@ export const extractFieldInsertionValues = ({const parsedTextFieldMeta = ZTextFieldMeta.parse(field.fieldMeta);const errors = validateTextField(fieldValue.value, parsedTextFieldMeta, true);- // Todoif (errors.length > 0) {throw new AppError(AppErrorCode.INVALID_BODY, {message: 'Invalid email',@@ -189,7 +187,6 @@ export const extractFieldInsertionValues = ({(sign) => sign.label === validationRule,);- // Todo: Envelopes - Test this.if (checkboxValidationRule) {const isValid = validateCheckboxLength(selectedValues.length,@@ -224,7 +221,6 @@ export const extractFieldInsertionValues = ({const parsedDropdownFieldMeta = ZDropdownFieldMeta.parse(field.fieldMeta);const errors = validateDropdownField(fieldValue.value, parsedDropdownFieldMeta, true);- // Todo: Envelopesif (errors.length > 0) {throw new AppError(AppErrorCode.INVALID_BODY, {message: 'Invalid dropdown value',diff --git a/packages/lib/utils/fields.ts b/packages/lib/utils/fields.tsindex d56fe084e..ec26192eb 100644--- a/packages/lib/utils/fields.ts+++ b/packages/lib/utils/fields.ts@@ -81,6 +81,10 @@ export const mapFieldToLegacyField = (};export const parseCheckboxCustomText = (customText: string): number[] => {+ if (!customText) {+ return [];+ }+return JSON.parse(customText);};diff --git a/packages/prisma/package.json b/packages/prisma/package.jsonindex 4f37e020b..166b70f81 100644--- a/packages/prisma/package.json+++ b/packages/prisma/package.json@@ -21,14 +21,14 @@"seed": "tsx ./seed-database.ts"},"dependencies": {- "@prisma/client": "^6.8.2",+ "@prisma/client": "^6.18.0","kysely": "0.26.3",- "prisma": "^6.8.2",+ "prisma": "^6.18.0","prisma-extension-kysely": "^3.0.0","prisma-kysely": "^1.8.0",- "prisma-json-types-generator": "^3.2.2",+ "prisma-json-types-generator": "^3.6.2","ts-pattern": "^5.0.6",- "zod-prisma-types": "3.2.4"+ "zod-prisma-types": "3.3.5"},"devDependencies": {"dotenv": "^16.5.0",diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 40047c01e..6cf6ecfe8 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -134,8 +134,8 @@ model Passkey {createdAt DateTime @default(now())updatedAt DateTime @default(now())lastUsedAt DateTime?- credentialId Bytes- credentialPublicKey Bytes+ credentialId Bytes /// @zod.custom.use(z.instanceof(Uint8Array))+ credentialPublicKey Bytes /// @zod.custom.use(z.instanceof(Uint8Array))counter BigIntcredentialDeviceType StringcredentialBackedUp Booleandiff --git a/packages/prisma/seed/initial-seed.ts b/packages/prisma/seed/initial-seed.tsindex 3cb050bdb..352b9d23f 100644--- a/packages/prisma/seed/initial-seed.ts+++ b/packages/prisma/seed/initial-seed.ts@@ -1,11 +1,22 @@import fs from 'node:fs';import path from 'node:path';+import { formatAlignmentTestFields } from '@documenso/app-tests/constants/field-alignment-pdf';+import { FIELD_META_TEST_FIELDS } from '@documenso/app-tests/constants/field-meta-pdf';+import { isBase64Image } from '@documenso/lib/constants/signatures';import { incrementDocumentId } from '@documenso/lib/server-only/envelope/increment-id';-import { prefixedId } from '@documenso/lib/universal/id';+import { nanoid, prefixedId } from '@documenso/lib/universal/id';import { prisma } from '..';-import { DocumentDataType, DocumentSource, EnvelopeType } from '../client';+import {+ DocumentDataType,+ DocumentSource,+ DocumentStatus,+ EnvelopeType,+ ReadStatus,+ SendStatus,+ SigningStatus,+} from '../client';import { seedPendingDocument } from './documents';import { seedDirectTemplate, seedTemplate } from './templates';import { seedUser } from './users';@@ -155,7 +166,6 @@ export const seedDatabase = async () => {userId: exampleUser.user.id,teamId: exampleUser.team.id,}),-seedTemplate({title: 'Template 1',userId: adminUser.user.id,@@ -166,5 +176,185 @@ export const seedDatabase = async () => {userId: adminUser.user.id,teamId: adminUser.team.id,}),+ seedAlignmentTestDocument({+ userId: exampleUser.user.id,+ teamId: exampleUser.team.id,+ recipientName: exampleUser.user.name || '',+ recipientEmail: exampleUser.user.email,+ insertFields: false,+ status: DocumentStatus.DRAFT,+ }),+ seedAlignmentTestDocument({+ userId: exampleUser.user.id,+ teamId: exampleUser.team.id,+ recipientName: exampleUser.user.name || '',+ recipientEmail: exampleUser.user.email,+ insertFields: true,+ status: DocumentStatus.PENDING,+ }),+ seedAlignmentTestDocument({+ userId: adminUser.user.id,+ teamId: adminUser.team.id,+ recipientName: adminUser.user.name || '',+ recipientEmail: adminUser.user.email,+ insertFields: false,+ status: DocumentStatus.DRAFT,+ }),+ seedAlignmentTestDocument({+ userId: adminUser.user.id,+ teamId: adminUser.team.id,+ recipientName: adminUser.user.name || '',+ recipientEmail: adminUser.user.email,+ insertFields: true,+ status: DocumentStatus.PENDING,+ }),]);};++export const seedAlignmentTestDocument = async ({+ userId,+ teamId,+ recipientName,+ recipientEmail,+ insertFields,+ status,+}: {+ userId: number;+ teamId: number;+ recipientName: string;+ recipientEmail: string;+ insertFields: boolean;+ status: DocumentStatus;+}) => {+ const alignmentPdf = fs+ .readFileSync(path.join(__dirname, '../../../assets/field-font-alignment.pdf'))+ .toString('base64');++ const fieldMetaPdf = fs+ .readFileSync(path.join(__dirname, '../../../assets/field-meta.pdf'))+ .toString('base64');++ const alignmentDocumentData = await createDocumentData({ documentData: alignmentPdf });+ const fieldMetaDocumentData = await createDocumentData({ documentData: fieldMetaPdf });++ const documentId = await incrementDocumentId();++ const documentMeta = await prisma.documentMeta.create({+ data: {},+ });++ const createdEnvelope = await prisma.envelope.create({+ data: {+ id: prefixedId('envelope'),+ secondaryId: documentId.formattedDocumentId,+ internalVersion: 2,+ type: EnvelopeType.DOCUMENT,+ documentMetaId: documentMeta.id,+ source: DocumentSource.DOCUMENT,+ title: `Envelope Full Field Test`,+ status,+ envelopeItems: {+ createMany: {+ data: [+ {+ id: prefixedId('envelope_item'),+ title: `alignment-pdf`,+ documentDataId: alignmentDocumentData.id,+ order: 1,+ },+ {+ id: prefixedId('envelope_item'),+ title: `field-meta-pdf`,+ documentDataId: fieldMetaDocumentData.id,+ order: 2,+ },+ ],+ },+ },+ userId,+ teamId,+ recipients: {+ create: {+ name: recipientName,+ email: recipientEmail,+ token: nanoid(),+ sendStatus: status === 'DRAFT' ? SendStatus.NOT_SENT : SendStatus.SENT,+ signingStatus: status === 'COMPLETED' ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,+ readStatus: status !== 'DRAFT' ? ReadStatus.OPENED : ReadStatus.NOT_OPENED,+ },+ },+ },+ include: {+ recipients: true,+ envelopeItems: true,+ },+ });++ const { id, recipients, envelopeItems } = createdEnvelope;++ const recipientId = recipients[0].id;+ const envelopeItemAlignmentItem = envelopeItems.find((item) => item.order === 1)?.id;+ const envelopeItemFieldMetaItem = envelopeItems.find((item) => item.order === 2)?.id;++ if (!envelopeItemAlignmentItem || !envelopeItemFieldMetaItem) {+ throw new Error('Envelope item not found');+ }++ await Promise.all(+ formatAlignmentTestFields.map(async (field) => {+ await prisma.field.create({+ data: {+ ...field,+ recipientId,+ envelopeItemId: envelopeItemAlignmentItem,+ envelopeId: id,+ customText: insertFields ? field.customText : '',+ inserted: insertFields,+ signature: field.signature+ ? {+ create: {+ recipientId,+ signatureImageAsBase64: isBase64Image(field.signature) ? field.signature : null,+ typedSignature: isBase64Image(field.signature) ? null : field.signature,+ },+ }+ : undefined,+ },+ });+ }),+ );++ await Promise.all(+ FIELD_META_TEST_FIELDS.map(async (field) => {+ await prisma.field.create({+ data: {+ ...field,+ recipientId,+ envelopeItemId: envelopeItemFieldMetaItem,+ envelopeId: id,+ customText: insertFields ? field.customText : '',+ inserted: insertFields,+ signature: field.signature+ ? {+ create: {+ recipientId,+ signatureImageAsBase64: isBase64Image(field.signature) ? field.signature : null,+ typedSignature: isBase64Image(field.signature) ? null : field.signature,+ },+ }+ : undefined,+ },+ });+ }),+ );++ return await prisma.envelope.findFirstOrThrow({+ where: {+ id: createdEnvelope.id,+ },+ include: {+ recipients: true,+ envelopeItems: true,+ },+ });+};diff --git a/packages/trpc/client/index.ts b/packages/trpc/client/index.tsindex 5f0e37ab6..ac8e62fef 100644--- a/packages/trpc/client/index.ts+++ b/packages/trpc/client/index.ts@@ -1,17 +1,23 @@-import { createTRPCClient, httpBatchLink, httpLink, splitLink } from '@trpc/client';-import SuperJSON from 'superjson';+import {+ createTRPCClient,+ httpBatchLink,+ httpLink,+ isNonJsonSerializable,+ splitLink,+} from '@trpc/client';import { getBaseUrl } from '@documenso/lib/universal/get-base-url';import type { AppRouter } from '../server/router';+import { dataTransformer } from '../utils/data-transformer';export const trpc = createTRPCClient<AppRouter>({links: [splitLink({- condition: (op) => op.context.skipBatch === true,+ condition: (op) => op.context.skipBatch === true || isNonJsonSerializable(op.input),true: httpLink({url: `${getBaseUrl()}/api/trpc`,- transformer: SuperJSON,+ transformer: dataTransformer,headers: (opts) => {if (typeof opts.op.context.teamId === 'string') {return {@@ -24,7 +30,7 @@ export const trpc = createTRPCClient<AppRouter>({}),false: httpBatchLink({url: `${getBaseUrl()}/api/trpc`,- transformer: SuperJSON,+ transformer: dataTransformer,headers: (opts) => {const operationWithTeamId = opts.opList.find((op) => op.context.teamId && typeof op.context.teamId === 'string',diff --git a/packages/trpc/package.json b/packages/trpc/package.jsonindex 891c0ab00..34945fae4 100644--- a/packages/trpc/package.json+++ b/packages/trpc/package.json@@ -12,15 +12,21 @@"dependencies": {"@documenso/lib": "*","@documenso/prisma": "*",- "@tanstack/react-query": "5.59.15",- "@trpc/client": "11.0.0-rc.648",- "@trpc/react-query": "11.0.0-rc.648",- "@trpc/server": "11.0.0-rc.648",- "@ts-rest/core": "^3.30.5",+ "@tanstack/react-query": "5.90.5",+ "@trpc/client": "11.7.0",+ "@trpc/react-query": "11.7.0",+ "@trpc/server": "11.7.0",+ "@ts-rest/core": "^3.52.0",+ "formidable": "^3.5.4","luxon": "^3.4.0",- "superjson": "^1.13.1",- "trpc-to-openapi": "2.0.4",+ "superjson": "^2.2.5",+ "trpc-to-openapi": "2.4.0","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76",+ "zod-form-data": "^2.0.8",+ "zod-openapi": "^4.2.4"+ },+ "devDependencies": {+ "@types/formidable": "^3.4.6"}}diff --git a/packages/trpc/react/index.tsx b/packages/trpc/react/index.tsxindex 69c485e2c..087fc5626 100644--- a/packages/trpc/react/index.tsx+++ b/packages/trpc/react/index.tsx@@ -1,13 +1,13 @@import { useMemo, useState } from 'react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { httpBatchLink, httpLink, splitLink } from '@trpc/client';+import { httpBatchLink, httpLink, isNonJsonSerializable, splitLink } from '@trpc/client';import { createTRPCReact } from '@trpc/react-query';-import SuperJSON from 'superjson';import { getBaseUrl } from '@documenso/lib/universal/get-base-url';import type { AppRouter } from '../server/router';+import { dataTransformer } from '../utils/data-transformer';export { getQueryKey } from '@trpc/react-query';@@ -44,16 +44,16 @@ export function TrpcProvider({ children, headers }: TrpcProviderProps) {trpc.createClient({links: [splitLink({- condition: (op) => op.context.skipBatch === true,+ condition: (op) => op.context.skipBatch === true || isNonJsonSerializable(op.input),true: httpLink({url: `${getBaseUrl()}/api/trpc`,headers,- transformer: SuperJSON,+ transformer: dataTransformer,}),false: httpBatchLink({url: `${getBaseUrl()}/api/trpc`,headers,- transformer: SuperJSON,+ transformer: dataTransformer,}),}),],diff --git a/packages/trpc/server/context.ts b/packages/trpc/server/context.tsindex ae319c4ce..7d0d94de8 100644--- a/packages/trpc/server/context.ts+++ b/packages/trpc/server/context.ts@@ -24,6 +24,7 @@ export const createTrpcContext = async ({const { session, user } = await getOptionalSession(c);const req = c.req.raw;+ const res = c.res;const requestMetadata = c.get('context').requestMetadata;@@ -54,6 +55,7 @@ export const createTrpcContext = async ({user: null,teamId,req,+ res,metadata,};}@@ -64,6 +66,7 @@ export const createTrpcContext = async ({user,teamId,req,+ res,metadata,};};@@ -80,6 +83,7 @@ export type TrpcContext = () & {teamId: number | undefined;req: Request;+ res: Response;metadata: ApiRequestMetadata;logger: Logger;};diff --git a/packages/trpc/server/document-router/create-document-formdata.ts b/packages/trpc/server/document-router/create-document-formdata.tsnew file mode 100644index 000000000..8a3baa8ed--- /dev/null+++ b/packages/trpc/server/document-router/create-document-formdata.ts@@ -0,0 +1,136 @@+import { EnvelopeType } from '@prisma/client';++import { getServerLimits } from '@documenso/ee/server-only/limits/server';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { createEnvelope } from '@documenso/lib/server-only/envelope/create-envelope';+import { putPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';+import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';+import { prisma } from '@documenso/prisma';++import { authenticatedProcedure } from '../trpc';+import {+ ZCreateDocumentFormDataRequestSchema,+ ZCreateDocumentFormDataResponseSchema,+ createDocumentFormDataMeta,+} from './create-document-formdata.types';++/**+ * Temporary endpoint for V2 Beta until we allow passthrough documents on create.+ *+ * @public+ */+export const createDocumentFormDataRoute = authenticatedProcedure+ .meta(createDocumentFormDataMeta)+ .input(ZCreateDocumentFormDataRequestSchema)+ .output(ZCreateDocumentFormDataResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { teamId, user } = ctx;++ const { payload, file } = input;++ const {+ title,+ externalId,+ visibility,+ globalAccessAuth,+ globalActionAuth,+ recipients,+ meta,+ folderId,+ attachments,+ } = payload;++ const { remaining } = await getServerLimits({ userId: user.id, teamId });++ if (remaining.documents <= 0) {+ throw new AppError(AppErrorCode.LIMIT_EXCEEDED, {+ message: 'You have reached your document limit for this month. Please upgrade your plan.',+ statusCode: 400,+ });+ }++ const documentData = await putPdfFileServerSide(file);++ const createdEnvelope = await createEnvelope({+ userId: ctx.user.id,+ teamId,+ normalizePdf: false, // Not normalizing because of presigned URL.+ internalVersion: 1,+ data: {+ type: EnvelopeType.DOCUMENT,+ title,+ externalId,+ visibility,+ globalAccessAuth,+ globalActionAuth,+ recipients: (recipients || []).map((recipient) => ({+ ...recipient,+ fields: (recipient.fields || []).map((field) => ({+ ...field,+ page: field.pageNumber,+ positionX: field.pageX,+ positionY: field.pageY,+ documentDataId: documentData.id,+ })),+ })),+ folderId,+ envelopeItems: [+ {+ // If you ever allow more than 1 in this endpoint, make sure to use `maximumEnvelopeItemCount` to limit it.+ documentDataId: documentData.id,+ },+ ],+ },+ attachments,+ meta: {+ ...meta,+ emailSettings: meta?.emailSettings ?? undefined,+ },+ requestMetadata: ctx.metadata,+ });++ const envelopeItems = await prisma.envelopeItem.findMany({+ where: {+ envelopeId: createdEnvelope.id,+ },+ include: {+ documentData: true,+ },+ });++ const legacyDocumentId = mapSecondaryIdToDocumentId(createdEnvelope.secondaryId);++ const firstDocumentData = envelopeItems[0].documentData;++ if (!firstDocumentData) {+ throw new Error('Document data not found');+ }++ return {+ document: {+ ...createdEnvelope,+ envelopeId: createdEnvelope.id,+ documentDataId: firstDocumentData.id,+ documentData: {+ ...firstDocumentData,+ envelopeItemId: envelopeItems[0].id,+ },+ documentMeta: {+ ...createdEnvelope.documentMeta,+ documentId: legacyDocumentId,+ },+ id: legacyDocumentId,+ fields: createdEnvelope.fields.map((field) => ({+ ...field,+ documentId: legacyDocumentId,+ templateId: null,+ })),+ recipients: createdEnvelope.recipients.map((recipient) => ({+ ...recipient,+ documentId: legacyDocumentId,+ templateId: null,+ })),+ },+ folder: createdEnvelope.folder, // Todo: Remove this prior to api-v2 release.+ };+ });diff --git a/packages/trpc/server/document-router/create-document-formdata.types.ts b/packages/trpc/server/document-router/create-document-formdata.types.tsnew file mode 100644index 000000000..6c308795f--- /dev/null+++ b/packages/trpc/server/document-router/create-document-formdata.types.ts@@ -0,0 +1,97 @@+import { z } from 'zod';+import { zfd } from 'zod-form-data';++import { ZDocumentSchema } from '@documenso/lib/types/document';+import {+ ZDocumentAccessAuthTypesSchema,+ ZDocumentActionAuthTypesSchema,+} from '@documenso/lib/types/document-auth';+import { ZDocumentFormValuesSchema } from '@documenso/lib/types/document-form-values';+import { ZDocumentMetaCreateSchema } from '@documenso/lib/types/document-meta';+import { ZEnvelopeAttachmentTypeSchema } from '@documenso/lib/types/envelope-attachment';+import {+ ZFieldHeightSchema,+ ZFieldPageNumberSchema,+ ZFieldPageXSchema,+ ZFieldPageYSchema,+ ZFieldWidthSchema,+} from '@documenso/lib/types/field';+import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';++import { zodFormData } from '../../utils/zod-form-data';+import { ZCreateRecipientSchema } from '../recipient-router/schema';+import type { TrpcRouteMeta } from '../trpc';+import {+ ZDocumentExternalIdSchema,+ ZDocumentTitleSchema,+ ZDocumentVisibilitySchema,+} from './schema';++export const createDocumentFormDataMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/document/create/formdata',+ contentTypes: ['multipart/form-data'],+ summary: 'Create document',+ description: 'Create a document using form data.',+ tags: ['Document'],+ },+};++const ZCreateDocumentFormDataPayloadRequestSchema = z.object({+ title: ZDocumentTitleSchema,+ externalId: ZDocumentExternalIdSchema.optional(),+ visibility: ZDocumentVisibilitySchema.optional(),+ globalAccessAuth: z.array(ZDocumentAccessAuthTypesSchema).optional(),+ globalActionAuth: z.array(ZDocumentActionAuthTypesSchema).optional(),+ formValues: ZDocumentFormValuesSchema.optional(),+ folderId: z+ .string()+ .describe(+ 'The ID of the folder to create the document in. If not provided, the document will be created in the root folder.',+ )+ .optional(),+ recipients: z+ .array(+ ZCreateRecipientSchema.extend({+ fields: ZFieldAndMetaSchema.and(+ z.object({+ pageNumber: ZFieldPageNumberSchema,+ pageX: ZFieldPageXSchema,+ pageY: ZFieldPageYSchema,+ width: ZFieldWidthSchema,+ height: ZFieldHeightSchema,+ }),+ )+ .array()+ .optional(),+ }),+ )++ .optional(),+ attachments: z+ .array(+ z.object({+ label: z.string().min(1, 'Label is required'),+ data: z.string().url('Must be a valid URL'),+ type: ZEnvelopeAttachmentTypeSchema.optional().default('link'),+ }),+ )+ .optional(),+ meta: ZDocumentMetaCreateSchema.optional(),+});++// !: Can't use zfd.formData() here because it receives `undefined`+// !: somewhere in the pipeline of our openapi schema generation and throws+// !: an error.+export const ZCreateDocumentFormDataRequestSchema = zodFormData({+ payload: zfd.json(ZCreateDocumentFormDataPayloadRequestSchema),+ file: zfd.file(),+});++export const ZCreateDocumentFormDataResponseSchema = z.object({+ document: ZDocumentSchema,+});++export type TCreateDocumentFormDataRequest = z.infer<typeof ZCreateDocumentFormDataRequestSchema>;+export type TCreateDocumentFormDataResponse = z.infer<typeof ZCreateDocumentFormDataResponseSchema>;diff --git a/packages/trpc/server/document-router/create-document.ts b/packages/trpc/server/document-router/create-document.tsindex 9a845090d..a5f915ffb 100644--- a/packages/trpc/server/document-router/create-document.ts+++ b/packages/trpc/server/document-router/create-document.ts@@ -3,20 +3,28 @@ import { EnvelopeType } from '@prisma/client';import { getServerLimits } from '@documenso/ee/server-only/limits/server';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { createEnvelope } from '@documenso/lib/server-only/envelope/create-envelope';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';import { authenticatedProcedure } from '../trpc';import {ZCreateDocumentRequestSchema,ZCreateDocumentResponseSchema,+ createDocumentMeta,} from './create-document.types';export const createDocumentRoute = authenticatedProcedure- .input(ZCreateDocumentRequestSchema) // Note: Before releasing this to public, update the response schema to be correct.+ .meta(createDocumentMeta)+ .input(ZCreateDocumentRequestSchema).output(ZCreateDocumentResponseSchema).mutation(async ({ input, ctx }) => {const { user, teamId } = ctx;- const { title, documentDataId, timezone, folderId, attachments } = input;++ const { payload, file } = input;++ const { title, timezone, folderId, attachments } = payload;++ const { id: documentDataId } = await putNormalizedPdfFileServerSide(file);ctx.logger.info({input: {@@ -55,6 +63,7 @@ export const createDocumentRoute = authenticatedProcedure});return {- legacyDocumentId: mapSecondaryIdToDocumentId(document.secondaryId),+ envelopeId: document.id,+ id: mapSecondaryIdToDocumentId(document.secondaryId),};});diff --git a/packages/trpc/server/document-router/create-document.types.ts b/packages/trpc/server/document-router/create-document.types.tsindex 43fa32291..07ccc8302 100644--- a/packages/trpc/server/document-router/create-document.types.ts+++ b/packages/trpc/server/document-router/create-document.types.ts@@ -1,23 +1,26 @@import { z } from 'zod';+import { zfd } from 'zod-form-data';import { ZDocumentMetaTimezoneSchema } from '@documenso/lib/types/document-meta';import { ZEnvelopeAttachmentTypeSchema } from '@documenso/lib/types/envelope-attachment';+import { zodFormData } from '../../utils/zod-form-data';+import type { TrpcRouteMeta } from '../trpc';import { ZDocumentTitleSchema } from './schema';-// Currently not in use until we allow passthrough documents on create.-// export const createDocumentMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/document/create',-// summary: 'Create document',-// tags: ['Document'],-// },-// };+export const createDocumentMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/document/create',+ contentTypes: ['multipart/form-data'],+ summary: 'Create document',+ description: 'Create a document using form data.',+ tags: ['Document'],+ },+};-export const ZCreateDocumentRequestSchema = z.object({+export const ZCreateDocumentPayloadSchema = z.object({title: ZDocumentTitleSchema,- documentDataId: z.string().min(1),timezone: ZDocumentMetaTimezoneSchema.optional(),folderId: z.string().describe('The ID of the folder to create the document in').optional(),attachments: z@@ -31,9 +34,16 @@ export const ZCreateDocumentRequestSchema = z.object({.optional(),});+export const ZCreateDocumentRequestSchema = zodFormData({+ payload: zfd.json(ZCreateDocumentPayloadSchema),+ file: zfd.file(),+});+export const ZCreateDocumentResponseSchema = z.object({- legacyDocumentId: z.number(),+ envelopeId: z.string(),+ id: z.number(),});+export type TCreateDocumentPayloadSchema = z.infer<typeof ZCreateDocumentPayloadSchema>;export type TCreateDocumentRequest = z.infer<typeof ZCreateDocumentRequestSchema>;export type TCreateDocumentResponse = z.infer<typeof ZCreateDocumentResponseSchema>;diff --git a/packages/trpc/server/document-router/download-document-beta.ts b/packages/trpc/server/document-router/download-document-beta.tsnew file mode 100644index 000000000..5755fc425--- /dev/null+++ b/packages/trpc/server/document-router/download-document-beta.ts@@ -0,0 +1,96 @@+import type { DocumentData } from '@prisma/client';+import { DocumentDataType, EnvelopeType } from '@prisma/client';++import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';+import { getPresignGetUrl } from '@documenso/lib/universal/upload/server-actions';+import { isDocumentCompleted } from '@documenso/lib/utils/document';++import { authenticatedProcedure } from '../trpc';+import {+ ZDownloadDocumentRequestSchema,+ ZDownloadDocumentResponseSchema,+ downloadDocumentMeta,+} from './download-document-beta.types';++export const downloadDocumentBetaRoute = authenticatedProcedure+ .meta(downloadDocumentMeta)+ .input(ZDownloadDocumentRequestSchema)+ .output(ZDownloadDocumentResponseSchema)+ .query(async ({ input, ctx }) => {+ const { teamId, user } = ctx;+ const { documentId, version } = input;++ ctx.logger.info({+ input: {+ documentId,+ version,+ },+ });++ const envelope = await getEnvelopeById({+ id: {+ type: 'documentId',+ id: documentId,+ },+ type: EnvelopeType.DOCUMENT,+ userId: user.id,+ teamId,+ });++ // This error is done AFTER the get envelope so we can test access controls without S3.+ if (process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT !== 's3') {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Document downloads are only available when S3 storage is configured.',+ });+ }++ const documentData: DocumentData | undefined = envelope.envelopeItems[0]?.documentData;++ if (envelope.envelopeItems.length !== 1 || !documentData) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message:+ 'This endpoint only supports documents with a single item. Use envelopes API instead.',+ });+ }++ if (documentData.type !== DocumentDataType.S3_PATH) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Document is not stored in S3 and cannot be downloaded via URL.',+ });+ }++ if (version === 'signed' && !isDocumentCompleted(envelope.status)) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Document is not completed yet.',+ });+ }++ try {+ const data =+ version === 'original' ? documentData.initialData || documentData.data : documentData.data;++ const { url } = await getPresignGetUrl(data);++ const baseTitle = envelope.title.replace(/\.pdf$/, '');+ const suffix = version === 'signed' ? '_signed.pdf' : '.pdf';+ const filename = `${baseTitle}${suffix}`;++ return {+ downloadUrl: url,+ filename,+ contentType: 'application/pdf',+ };+ } catch (error) {+ ctx.logger.error({+ error,+ message: 'Failed to generate download URL',+ documentId,+ version,+ });++ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {+ message: 'Failed to generate download URL',+ });+ }+ });diff --git a/packages/trpc/server/document-router/download-document-beta.types.ts b/packages/trpc/server/document-router/download-document-beta.types.tsnew file mode 100644index 000000000..be4f454f8--- /dev/null+++ b/packages/trpc/server/document-router/download-document-beta.types.ts@@ -0,0 +1,32 @@+import { z } from 'zod';++import type { TrpcRouteMeta } from '../trpc';++export const downloadDocumentMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/document/{documentId}/download-beta',+ summary: 'Download document (beta)',+ description: 'Get a pre-signed download URL for the original or signed version of a document',+ tags: ['Document'],+ },+};++export const ZDownloadDocumentRequestSchema = z.object({+ documentId: z.number().describe('The ID of the document to download.'),+ version: z+ .enum(['original', 'signed'])+ .describe(+ 'The version of the document to download. "signed" returns the completed document with signatures, "original" returns the original uploaded document.',+ )+ .default('signed'),+});++export const ZDownloadDocumentResponseSchema = z.object({+ downloadUrl: z.string().describe('Pre-signed URL for downloading the PDF file'),+ filename: z.string().describe('The filename of the PDF file'),+ contentType: z.string().describe('MIME type of the file'),+});++export type TDownloadDocumentRequest = z.infer<typeof ZDownloadDocumentRequestSchema>;+export type TDownloadDocumentResponse = z.infer<typeof ZDownloadDocumentResponseSchema>;diff --git a/packages/trpc/server/document-router/download-document.ts b/packages/trpc/server/document-router/download-document.tsindex c7e0f02c7..241479f54 100644--- a/packages/trpc/server/document-router/download-document.ts+++ b/packages/trpc/server/document-router/download-document.ts@@ -1,11 +1,3 @@-import type { DocumentData } from '@prisma/client';-import { DocumentDataType, EnvelopeType } from '@prisma/client';--import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';-import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';-import { getPresignGetUrl } from '@documenso/lib/universal/upload/server-actions';-import { isDocumentCompleted } from '@documenso/lib/utils/document';-import { authenticatedProcedure } from '../trpc';import {ZDownloadDocumentRequestSchema,@@ -17,8 +9,7 @@ export const downloadDocumentRoute = authenticatedProcedure.meta(downloadDocumentMeta).input(ZDownloadDocumentRequestSchema).output(ZDownloadDocumentResponseSchema)- .query(async ({ input, ctx }) => {- const { teamId, user } = ctx;+ .query(({ input, ctx }) => {const { documentId, version } = input;ctx.logger.info({@@ -28,69 +19,5 @@ export const downloadDocumentRoute = authenticatedProcedure},});- const envelope = await getEnvelopeById({- id: {- type: 'documentId',- id: documentId,- },- type: EnvelopeType.DOCUMENT,- userId: user.id,- teamId,- });-- // This error is done AFTER the get envelope so we can test access controls without S3.- if (process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT !== 's3') {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document downloads are only available when S3 storage is configured.',- });- }-- const documentData: DocumentData | undefined = envelope.envelopeItems[0]?.documentData;-- if (envelope.envelopeItems.length !== 1 || !documentData) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message:- 'This endpoint only supports documents with a single item. Use envelopes API instead.',- });- }-- if (documentData.type !== DocumentDataType.S3_PATH) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document is not stored in S3 and cannot be downloaded via URL.',- });- }-- if (version === 'signed' && !isDocumentCompleted(envelope.status)) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document is not completed yet.',- });- }-- try {- const data =- version === 'original' ? documentData.initialData || documentData.data : documentData.data;-- const { url } = await getPresignGetUrl(data);-- const baseTitle = envelope.title.replace(/\.pdf$/, '');- const suffix = version === 'signed' ? '_signed.pdf' : '.pdf';- const filename = `${baseTitle}${suffix}`;-- return {- downloadUrl: url,- filename,- contentType: 'application/pdf',- };- } catch (error) {- ctx.logger.error({- error,- message: 'Failed to generate download URL',- documentId,- version,- });-- throw new AppError(AppErrorCode.UNKNOWN_ERROR, {- message: 'Failed to generate download URL',- });- }+ throw new Error('NOT_IMPLEMENTED');});diff --git a/packages/trpc/server/document-router/download-document.types.ts b/packages/trpc/server/document-router/download-document.types.tsindex be4f454f8..9d4003443 100644--- a/packages/trpc/server/document-router/download-document.types.ts+++ b/packages/trpc/server/document-router/download-document.types.ts@@ -5,10 +5,12 @@ import type { TrpcRouteMeta } from '../trpc';export const downloadDocumentMeta: TrpcRouteMeta = {openapi: {method: 'GET',- path: '/document/{documentId}/download-beta',- summary: 'Download document (beta)',- description: 'Get a pre-signed download URL for the original or signed version of a document',+ path: '/document/{documentId}/download',+ summary: 'Download document',tags: ['Document'],+ responseHeaders: z.object({+ 'Content-Type': z.literal('application/pdf'),+ }),},};@@ -22,11 +24,7 @@ export const ZDownloadDocumentRequestSchema = z.object({.default('signed'),});-export const ZDownloadDocumentResponseSchema = z.object({- downloadUrl: z.string().describe('Pre-signed URL for downloading the PDF file'),- filename: z.string().describe('The filename of the PDF file'),- contentType: z.string().describe('MIME type of the file'),-});+export const ZDownloadDocumentResponseSchema = z.instanceof(Uint8Array);export type TDownloadDocumentRequest = z.infer<typeof ZDownloadDocumentRequestSchema>;export type TDownloadDocumentResponse = z.infer<typeof ZDownloadDocumentResponseSchema>;diff --git a/packages/trpc/server/document-router/find-inbox.ts b/packages/trpc/server/document-router/find-inbox.tsindex fd1177f07..9634de87e 100644--- a/packages/trpc/server/document-router/find-inbox.ts+++ b/packages/trpc/server/document-router/find-inbox.ts@@ -92,6 +92,14 @@ export const findInbox = async ({ userId, page = 1, perPage = 10, orderBy }: Finurl: true,},},+ envelopeItems: {+ select: {+ id: true,+ envelopeId: true,+ title: true,+ order: true,+ },+ },},}),prisma.envelope.count({diff --git a/packages/trpc/server/document-router/router.ts b/packages/trpc/server/document-router/router.tsindex f5d34a141..2d814827a 100644--- a/packages/trpc/server/document-router/router.ts+++ b/packages/trpc/server/document-router/router.ts@@ -5,11 +5,13 @@ import { deleteAttachmentRoute } from './attachment/delete-attachment';import { findAttachmentsRoute } from './attachment/find-attachments';import { updateAttachmentRoute } from './attachment/update-attachment';import { createDocumentRoute } from './create-document';+import { createDocumentFormDataRoute } from './create-document-formdata';import { createDocumentTemporaryRoute } from './create-document-temporary';import { deleteDocumentRoute } from './delete-document';import { distributeDocumentRoute } from './distribute-document';import { downloadDocumentRoute } from './download-document';import { downloadDocumentAuditLogsRoute } from './download-document-audit-logs';+import { downloadDocumentBetaRoute } from './download-document-beta';import { downloadDocumentCertificateRoute } from './download-document-certificate';import { duplicateDocumentRoute } from './duplicate-document';import { findDocumentAuditLogsRoute } from './find-document-audit-logs';@@ -38,8 +40,10 @@ export const documentRouter = router({share: shareDocumentRoute,// Temporary v2 beta routes to be removed once V2 is fully released.+ downloadBeta: downloadDocumentBetaRoute,download: downloadDocumentRoute,createDocumentTemporary: createDocumentTemporaryRoute,+ createDocumentFormData: createDocumentFormDataRoute,// Internal document routes for custom frontend requests.getDocumentByToken: getDocumentByTokenRoute,diff --git a/packages/trpc/server/embedding-router/_router.ts b/packages/trpc/server/embedding-router/_router.tsindex 3699e6712..a37a16923 100644--- a/packages/trpc/server/embedding-router/_router.ts+++ b/packages/trpc/server/embedding-router/_router.ts@@ -1,5 +1,4 @@import { router } from '../trpc';-import { applyMultiSignSignatureRoute } from './apply-multi-sign-signature';import { createEmbeddingDocumentRoute } from './create-embedding-document';import { createEmbeddingPresignTokenRoute } from './create-embedding-presign-token';import { createEmbeddingTemplateRoute } from './create-embedding-template';@@ -15,6 +14,6 @@ export const embeddingPresignRouter = router({createEmbeddingTemplate: createEmbeddingTemplateRoute,updateEmbeddingDocument: updateEmbeddingDocumentRoute,updateEmbeddingTemplate: updateEmbeddingTemplateRoute,- applyMultiSignSignature: applyMultiSignSignatureRoute,+ // applyMultiSignSignature: applyMultiSignSignatureRoute,getMultiSignDocument: getMultiSignDocumentRoute,});diff --git a/packages/trpc/server/embedding-router/get-multi-sign-document.types.ts b/packages/trpc/server/embedding-router/get-multi-sign-document.types.tsindex d4f7f5cc2..f54eaf026 100644--- a/packages/trpc/server/embedding-router/get-multi-sign-document.types.ts+++ b/packages/trpc/server/embedding-router/get-multi-sign-document.types.ts@@ -4,6 +4,7 @@ import { ZDocumentLiteSchema } from '@documenso/lib/types/document';import { ZRecipientLiteSchema } from '@documenso/lib/types/recipient';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 FieldSchema from '@documenso/prisma/generated/zod/modelSchema/FieldSchema';import SignatureSchema from '@documenso/prisma/generated/zod/modelSchema/SignatureSchema';@@ -40,6 +41,10 @@ export const ZGetMultiSignDocumentResponseSchema = ZDocumentLiteSchema.extend({signature: SignatureSchema.nullable(),}),),+ envelopeItems: EnvelopeItemSchema.pick({+ id: true,+ envelopeId: true,+ }).array(),});export type TGetMultiSignDocumentRequestSchema = z.infer<typeof ZGetMultiSignDocumentRequestSchema>;diff --git a/packages/trpc/server/envelope-router/attachment/create-attachment.ts b/packages/trpc/server/envelope-router/attachment/create-attachment.tsindex 239052005..f149bbe31 100644--- a/packages/trpc/server/envelope-router/attachment/create-attachment.ts+++ b/packages/trpc/server/envelope-router/attachment/create-attachment.ts@@ -4,18 +4,11 @@ import { authenticatedProcedure } from '../../trpc';import {ZCreateAttachmentRequestSchema,ZCreateAttachmentResponseSchema,+ createAttachmentMeta,} from './create-attachment.types';export const createAttachmentRoute = authenticatedProcedure- .meta({- openapi: {- method: 'POST',- path: '/envelope/attachment/create',- summary: 'Create attachment',- description: 'Create a new attachment for an envelope',- tags: ['Envelope'],- },- })+ .meta(createAttachmentMeta).input(ZCreateAttachmentRequestSchema).output(ZCreateAttachmentResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/attachment/create-attachment.types.ts b/packages/trpc/server/envelope-router/attachment/create-attachment.types.tsindex 106a6e751..661427815 100644--- a/packages/trpc/server/envelope-router/attachment/create-attachment.types.ts+++ b/packages/trpc/server/envelope-router/attachment/create-attachment.types.ts@@ -1,5 +1,17 @@import { z } from 'zod';+import type { TrpcRouteMeta } from '../../trpc';++export const createAttachmentMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/attachment/create',+ summary: 'Create attachment',+ description: 'Create a new attachment for an envelope',+ tags: ['Envelope Attachments'],+ },+};+export const ZCreateAttachmentRequestSchema = z.object({envelopeId: z.string(),data: z.object({diff --git a/packages/trpc/server/envelope-router/attachment/delete-attachment.ts b/packages/trpc/server/envelope-router/attachment/delete-attachment.tsindex 3fd82805e..f49280825 100644--- a/packages/trpc/server/envelope-router/attachment/delete-attachment.ts+++ b/packages/trpc/server/envelope-router/attachment/delete-attachment.ts@@ -4,18 +4,11 @@ import { authenticatedProcedure } from '../../trpc';import {ZDeleteAttachmentRequestSchema,ZDeleteAttachmentResponseSchema,+ deleteAttachmentMeta,} from './delete-attachment.types';export const deleteAttachmentRoute = authenticatedProcedure- .meta({- openapi: {- method: 'POST',- path: '/envelope/attachment/delete',- summary: 'Delete attachment',- description: 'Delete an attachment from an envelope',- tags: ['Envelope'],- },- })+ .meta(deleteAttachmentMeta).input(ZDeleteAttachmentRequestSchema).output(ZDeleteAttachmentResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/attachment/delete-attachment.types.ts b/packages/trpc/server/envelope-router/attachment/delete-attachment.types.tsindex 81d7c0614..b5dd8f6af 100644--- a/packages/trpc/server/envelope-router/attachment/delete-attachment.types.ts+++ b/packages/trpc/server/envelope-router/attachment/delete-attachment.types.ts@@ -1,5 +1,17 @@import { z } from 'zod';+import type { TrpcRouteMeta } from '../../trpc';++export const deleteAttachmentMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/attachment/delete',+ summary: 'Delete attachment',+ description: 'Delete an attachment from an envelope',+ tags: ['Envelope Attachments'],+ },+};+export const ZDeleteAttachmentRequestSchema = z.object({id: z.string(),});diff --git a/packages/trpc/server/envelope-router/attachment/find-attachments.ts b/packages/trpc/server/envelope-router/attachment/find-attachments.tsindex 74e81c5e1..6ee555f55 100644--- a/packages/trpc/server/envelope-router/attachment/find-attachments.ts+++ b/packages/trpc/server/envelope-router/attachment/find-attachments.ts@@ -2,22 +2,15 @@ import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { findAttachmentsByEnvelopeId } from '@documenso/lib/server-only/envelope-attachment/find-attachments-by-envelope-id';import { findAttachmentsByToken } from '@documenso/lib/server-only/envelope-attachment/find-attachments-by-token';-import { procedure } from '../../trpc';+import { maybeAuthenticatedProcedure } from '../../trpc';import {ZFindAttachmentsRequestSchema,ZFindAttachmentsResponseSchema,+ findAttachmentsMeta,} from './find-attachments.types';-export const findAttachmentsRoute = procedure- .meta({- openapi: {- method: 'GET',- path: '/envelope/attachment',- summary: 'Find attachments',- description: 'Find all attachments for an envelope',- tags: ['Envelope'],- },- })+export const findAttachmentsRoute = maybeAuthenticatedProcedure+ .meta(findAttachmentsMeta).input(ZFindAttachmentsRequestSchema).output(ZFindAttachmentsResponseSchema).query(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/attachment/find-attachments.types.ts b/packages/trpc/server/envelope-router/attachment/find-attachments.types.tsindex e61b2d2cb..5355a0ed5 100644--- a/packages/trpc/server/envelope-router/attachment/find-attachments.types.ts+++ b/packages/trpc/server/envelope-router/attachment/find-attachments.types.ts@@ -2,6 +2,18 @@ import { z } from 'zod';import { ZEnvelopeAttachmentTypeSchema } from '@documenso/lib/types/envelope-attachment';+import type { TrpcRouteMeta } from '../../trpc';++export const findAttachmentsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/envelope/attachment',+ summary: 'Find attachments',+ description: 'Find all attachments for an envelope',+ tags: ['Envelope Attachments'],+ },+};+export const ZFindAttachmentsRequestSchema = z.object({envelopeId: z.string(),token: z.string().optional(),diff --git a/packages/trpc/server/envelope-router/attachment/update-attachment.ts b/packages/trpc/server/envelope-router/attachment/update-attachment.tsindex 11a7dfa5b..dd0613cc7 100644--- a/packages/trpc/server/envelope-router/attachment/update-attachment.ts+++ b/packages/trpc/server/envelope-router/attachment/update-attachment.ts@@ -4,18 +4,11 @@ import { authenticatedProcedure } from '../../trpc';import {ZUpdateAttachmentRequestSchema,ZUpdateAttachmentResponseSchema,+ updateAttachmentMeta,} from './update-attachment.types';export const updateAttachmentRoute = authenticatedProcedure- .meta({- openapi: {- method: 'POST',- path: '/envelope/attachment/update',- summary: 'Update attachment',- description: 'Update an existing attachment',- tags: ['Envelope'],- },- })+ .meta(updateAttachmentMeta).input(ZUpdateAttachmentRequestSchema).output(ZUpdateAttachmentResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/attachment/update-attachment.types.ts b/packages/trpc/server/envelope-router/attachment/update-attachment.types.tsindex eaf12b559..d46b15251 100644--- a/packages/trpc/server/envelope-router/attachment/update-attachment.types.ts+++ b/packages/trpc/server/envelope-router/attachment/update-attachment.types.ts@@ -1,5 +1,17 @@import { z } from 'zod';+import type { TrpcRouteMeta } from '../../trpc';++export const updateAttachmentMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/attachment/update',+ summary: 'Update attachment',+ description: 'Update an existing attachment',+ tags: ['Envelope Attachments'],+ },+};+export const ZUpdateAttachmentRequestSchema = z.object({id: z.string(),data: z.object({diff --git a/packages/trpc/server/envelope-router/create-envelope-items.ts b/packages/trpc/server/envelope-router/create-envelope-items.tsindex 55ed38daf..46b15d8e4 100644--- a/packages/trpc/server/envelope-router/create-envelope-items.ts+++ b/packages/trpc/server/envelope-router/create-envelope-items.ts@@ -2,6 +2,7 @@ import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { getEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-envelope-by-id';import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';import { prefixedId } from '@documenso/lib/universal/id';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';import { canEnvelopeItemsBeModified } from '@documenso/lib/utils/envelope';import { prisma } from '@documenso/prisma';@@ -10,14 +11,17 @@ import { authenticatedProcedure } from '../trpc';import {ZCreateEnvelopeItemsRequestSchema,ZCreateEnvelopeItemsResponseSchema,+ createEnvelopeItemsMeta,} from './create-envelope-items.types';export const createEnvelopeItemsRoute = authenticatedProcedure+ .meta(createEnvelopeItemsMeta).input(ZCreateEnvelopeItemsRequestSchema).output(ZCreateEnvelopeItemsResponseSchema).mutation(async ({ input, ctx }) => {const { user, teamId, metadata } = ctx;- const { envelopeId, items } = input;+ const { payload, files } = input;+ const { envelopeId } = payload;ctx.logger.info({input: {@@ -71,7 +75,7 @@ export const createEnvelopeItemsRoute = authenticatedProcedureconst organisationClaim = envelope.team.organisation.organisationClaim;const remainingEnvelopeItems =- organisationClaim.envelopeItemCount - envelope.envelopeItems.length - items.length;+ organisationClaim.envelopeItemCount - envelope.envelopeItems.length - files.length;if (remainingEnvelopeItems < 0) {throw new AppError('ENVELOPE_ITEM_LIMIT_EXCEEDED', {@@ -80,41 +84,24 @@ export const createEnvelopeItemsRoute = authenticatedProcedure});}- const foundDocumentData = await prisma.documentData.findMany({- where: {- id: {- in: items.map((item) => item.documentDataId),- },- },- select: {- envelopeItem: {- select: {- id: true,- },- },- },- });+ // For each file, stream to s3 and create the document data.+ const envelopeItems = await Promise.all(+ files.map(async (file) => {+ const { id: documentDataId } = await putNormalizedPdfFileServerSide(file);- // Check that all the document data was found.- if (foundDocumentData.length !== items.length) {- throw new AppError(AppErrorCode.NOT_FOUND, {- message: 'Document data not found',- });- }-- // Check that it doesn't already have an envelope item.- if (foundDocumentData.some((documentData) => documentData.envelopeItem?.id)) {- throw new AppError(AppErrorCode.INVALID_REQUEST, {- message: 'Document data not found',- });- }+ return {+ title: file.name,+ documentDataId,+ };+ }),+ );const currentHighestOrderValue =envelope.envelopeItems[envelope.envelopeItems.length - 1]?.order ?? 1;const result = await prisma.$transaction(async (tx) => {const createdItems = await tx.envelopeItem.createManyAndReturn({- data: items.map((item) => ({+ data: envelopeItems.map((item) => ({id: prefixedId('envelope_item'),envelopeId,title: item.title,@@ -148,6 +135,6 @@ export const createEnvelopeItemsRoute = authenticatedProcedure});return {- createdEnvelopeItems: result,+ data: result,};});diff --git a/packages/trpc/server/envelope-router/create-envelope-items.types.ts b/packages/trpc/server/envelope-router/create-envelope-items.types.tsindex 494e562f3..12467bce9 100644--- a/packages/trpc/server/envelope-router/create-envelope-items.types.ts+++ b/packages/trpc/server/envelope-router/create-envelope-items.types.ts@@ -1,38 +1,40 @@import { z } from 'zod';+import { zfd } from 'zod-form-data';-import DocumentDataSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentDataSchema';import EnvelopeItemSchema from '@documenso/prisma/generated/zod/modelSchema/EnvelopeItemSchema';-import { ZDocumentTitleSchema } from '../document-router/schema';+import { zodFormData } from '../../utils/zod-form-data';+import type { TrpcRouteMeta } from '../trpc';-export const ZCreateEnvelopeItemsRequestSchema = z.object({+export const createEnvelopeItemsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/item/create-many',+ summary: 'Create envelope items',+ description: 'Create multiple envelope items for an envelope',+ tags: ['Envelope Items'],+ },+};++export const ZCreateEnvelopeItemsPayloadSchema = z.object({envelopeId: z.string(),- items: z- .object({- title: ZDocumentTitleSchema,- documentDataId: z.string(),- })- .array(),+ // data: z.object() // Currently not used.+});++export const ZCreateEnvelopeItemsRequestSchema = zodFormData({+ payload: zfd.json(ZCreateEnvelopeItemsPayloadSchema),+ files: zfd.repeatableOfType(zfd.file()),});export const ZCreateEnvelopeItemsResponseSchema = z.object({- createdEnvelopeItems: EnvelopeItemSchema.pick({+ data: EnvelopeItemSchema.pick({id: true,title: true,- documentDataId: true,envelopeId: true,order: true,- })- .extend({- documentData: DocumentDataSchema.pick({- type: true,- id: true,- data: true,- initialData: true,- }),- })- .array(),+ }).array(),});+export type TCreateEnvelopeItemsPayload = z.infer<typeof ZCreateEnvelopeItemsPayloadSchema>;export type TCreateEnvelopeItemsRequest = z.infer<typeof ZCreateEnvelopeItemsRequestSchema>;export type TCreateEnvelopeItemsResponse = z.infer<typeof ZCreateEnvelopeItemsResponseSchema>;diff --git a/packages/trpc/server/envelope-router/create-envelope.ts b/packages/trpc/server/envelope-router/create-envelope.tsindex 7f529362a..74b98fd42 100644--- a/packages/trpc/server/envelope-router/create-envelope.ts+++ b/packages/trpc/server/envelope-router/create-envelope.ts@@ -1,18 +1,24 @@import { getServerLimits } from '@documenso/ee/server-only/limits/server';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { createEnvelope } from '@documenso/lib/server-only/envelope/create-envelope';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';import { authenticatedProcedure } from '../trpc';import {ZCreateEnvelopeRequestSchema,ZCreateEnvelopeResponseSchema,+ createEnvelopeMeta,} from './create-envelope.types';export const createEnvelopeRoute = authenticatedProcedure+ .meta(createEnvelopeMeta).input(ZCreateEnvelopeRequestSchema).output(ZCreateEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {const { user, teamId } = ctx;++ const { payload, files } = input;+const {title,type,@@ -20,12 +26,12 @@ export const createEnvelopeRoute = authenticatedProcedurevisibility,globalAccessAuth,globalActionAuth,+ formValues,recipients,folderId,- items,meta,attachments,- } = input;+ } = payload;ctx.logger.info({input: {@@ -45,13 +51,62 @@ export const createEnvelopeRoute = authenticatedProcedure});}- if (items.length > maximumEnvelopeItemCount) {+ if (files.length > maximumEnvelopeItemCount) {throw new AppError('ENVELOPE_ITEM_LIMIT_EXCEEDED', {message: `You cannot upload more than ${maximumEnvelopeItemCount} envelope items per envelope`,statusCode: 400,});}+ // For each file, stream to s3 and create the document data.+ const envelopeItems = await Promise.all(+ files.map(async (file) => {+ const { id: documentDataId } = await putNormalizedPdfFileServerSide(file);++ return {+ title: file.name,+ documentDataId,+ };+ }),+ );++ const recipientsToCreate = recipients?.map((recipient) => ({+ email: recipient.email,+ name: recipient.name,+ role: recipient.role,+ signingOrder: recipient.signingOrder,+ accessAuth: recipient.accessAuth,+ actionAuth: recipient.actionAuth,+ fields: recipient.fields?.map((field) => {+ let documentDataId: string | undefined = undefined;++ if (typeof field.identifier === 'string') {+ documentDataId = envelopeItems.find(+ (item) => item.title === field.identifier,+ )?.documentDataId;+ }++ if (typeof field.identifier === 'number') {+ documentDataId = envelopeItems.at(field.identifier)?.documentDataId;+ }++ if (field.identifier === undefined) {+ documentDataId = envelopeItems.at(0)?.documentDataId;+ }++ if (!documentDataId) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: 'Document data not found',+ });+ }++ return {+ ...field,+ documentDataId,+ };+ }),+ }));+const envelope = await createEnvelope({userId: user.id,teamId,@@ -60,16 +115,16 @@ export const createEnvelopeRoute = authenticatedProceduretype,title,externalId,+ formValues,visibility,globalAccessAuth,globalActionAuth,- recipients,+ recipients: recipientsToCreate,folderId,- envelopeItems: items,+ envelopeItems,},attachments,meta,- normalizePdf: true,requestMetadata: ctx.metadata,});diff --git a/packages/trpc/server/envelope-router/create-envelope.types.ts b/packages/trpc/server/envelope-router/create-envelope.types.tsindex ea0fee260..222e3d80e 100644--- a/packages/trpc/server/envelope-router/create-envelope.types.ts+++ b/packages/trpc/server/envelope-router/create-envelope.types.ts@@ -1,5 +1,6 @@import { EnvelopeType } from '@prisma/client';import { z } from 'zod';+import { zfd } from 'zod-form-data';import {ZDocumentAccessAuthTypesSchema,@@ -9,32 +10,35 @@ import { ZDocumentFormValuesSchema } from '@documenso/lib/types/document-form-vaimport { ZDocumentMetaCreateSchema } from '@documenso/lib/types/document-meta';import { ZEnvelopeAttachmentTypeSchema } from '@documenso/lib/types/envelope-attachment';import {- ZFieldHeightSchema,+ ZClampedFieldHeightSchema,+ ZClampedFieldPositionXSchema,+ ZClampedFieldPositionYSchema,+ ZClampedFieldWidthSchema,ZFieldPageNumberSchema,- ZFieldPageXSchema,- ZFieldPageYSchema,- ZFieldWidthSchema,} from '@documenso/lib/types/field';import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';+import { zodFormData } from '../../utils/zod-form-data';import {ZDocumentExternalIdSchema,ZDocumentTitleSchema,ZDocumentVisibilitySchema,} from '../document-router/schema';import { ZCreateRecipientSchema } from '../recipient-router/schema';+import type { TrpcRouteMeta } from '../trpc';-// Currently not in use until we allow passthrough documents on create.-// export const createEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/envelope/create',-// summary: 'Create envelope',-// tags: ['Envelope'],-// },-// };+export const createEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/create',+ contentTypes: ['multipart/form-data'],+ summary: 'Create envelope',+ description: 'Create an envelope using form data.',+ tags: ['Envelope'],+ },+};-export const ZCreateEnvelopeRequestSchema = z.object({+export const ZCreateEnvelopePayloadSchema = z.object({title: ZDocumentTitleSchema,type: z.nativeEnum(EnvelopeType),externalId: ZDocumentExternalIdSchema.optional(),@@ -42,12 +46,6 @@ export const ZCreateEnvelopeRequestSchema = z.object({globalAccessAuth: z.array(ZDocumentAccessAuthTypesSchema).optional(),globalActionAuth: z.array(ZDocumentActionAuthTypesSchema).optional(),formValues: ZDocumentFormValuesSchema.optional(),- items: z- .object({- title: ZDocumentTitleSchema.optional(),- documentDataId: z.string(),- })- .array(),folderId: z.string().describe(@@ -59,16 +57,17 @@ export const ZCreateEnvelopeRequestSchema = z.object({ZCreateRecipientSchema.extend({fields: ZFieldAndMetaSchema.and(z.object({- documentDataId: z- .string()+ identifier: z+ .union([z.string(), z.number()]).describe(- 'The ID of the document data to create the field on. If empty, the first document data will be used.',- ),+ 'Either the filename or the index of the file that was uploaded to attach the field to.',+ )+ .optional(),page: ZFieldPageNumberSchema,- positionX: ZFieldPageXSchema,- positionY: ZFieldPageYSchema,- width: ZFieldWidthSchema,- height: ZFieldHeightSchema,+ positionX: ZClampedFieldPositionXSchema,+ positionY: ZClampedFieldPositionYSchema,+ width: ZClampedFieldWidthSchema,+ height: ZClampedFieldHeightSchema,}),).array()@@ -88,9 +87,15 @@ export const ZCreateEnvelopeRequestSchema = z.object({.optional(),});+export const ZCreateEnvelopeRequestSchema = zodFormData({+ payload: zfd.json(ZCreateEnvelopePayloadSchema),+ files: zfd.repeatableOfType(zfd.file()),+});+export const ZCreateEnvelopeResponseSchema = z.object({id: z.string(),});+export type TCreateEnvelopePayload = z.infer<typeof ZCreateEnvelopePayloadSchema>;export type TCreateEnvelopeRequest = z.infer<typeof ZCreateEnvelopeRequestSchema>;export type TCreateEnvelopeResponse = z.infer<typeof ZCreateEnvelopeResponseSchema>;diff --git a/packages/trpc/server/envelope-router/delete-envelope-item.ts b/packages/trpc/server/envelope-router/delete-envelope-item.tsindex 832322d76..b5200ebdd 100644--- a/packages/trpc/server/envelope-router/delete-envelope-item.ts+++ b/packages/trpc/server/envelope-router/delete-envelope-item.ts@@ -9,9 +9,11 @@ import { authenticatedProcedure } from '../trpc';import {ZDeleteEnvelopeItemRequestSchema,ZDeleteEnvelopeItemResponseSchema,+ deleteEnvelopeItemMeta,} from './delete-envelope-item.types';export const deleteEnvelopeItemRoute = authenticatedProcedure+ .meta(deleteEnvelopeItemMeta).input(ZDeleteEnvelopeItemRequestSchema).output(ZDeleteEnvelopeItemResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/delete-envelope-item.types.ts b/packages/trpc/server/envelope-router/delete-envelope-item.types.tsindex 7a081dbd3..392a88be2 100644--- a/packages/trpc/server/envelope-router/delete-envelope-item.types.ts+++ b/packages/trpc/server/envelope-router/delete-envelope-item.types.ts@@ -1,5 +1,17 @@import { z } from 'zod';+import type { TrpcRouteMeta } from '../trpc';++export const deleteEnvelopeItemMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/item/delete',+ summary: 'Delete envelope item',+ description: 'Delete an envelope item from an envelope',+ tags: ['Envelope Items'],+ },+};+export const ZDeleteEnvelopeItemRequestSchema = z.object({envelopeId: z.string(),envelopeItemId: z.string(),diff --git a/packages/trpc/server/envelope-router/delete-envelope.ts b/packages/trpc/server/envelope-router/delete-envelope.tsindex 4691c3f5b..d909a7fd0 100644--- a/packages/trpc/server/envelope-router/delete-envelope.ts+++ b/packages/trpc/server/envelope-router/delete-envelope.ts@@ -1,22 +1,25 @@import { EnvelopeType } from '@prisma/client';import { match } from 'ts-pattern';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { deleteDocument } from '@documenso/lib/server-only/document/delete-document';import { deleteTemplate } from '@documenso/lib/server-only/template/delete-template';+import { prisma } from '@documenso/prisma';import { authenticatedProcedure } from '../trpc';import {ZDeleteEnvelopeRequestSchema,ZDeleteEnvelopeResponseSchema,+ deleteEnvelopeMeta,} from './delete-envelope.types';export const deleteEnvelopeRoute = authenticatedProcedure- // .meta(deleteEnvelopeMeta)+ .meta(deleteEnvelopeMeta).input(ZDeleteEnvelopeRequestSchema).output(ZDeleteEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {const { teamId } = ctx;- const { envelopeId, envelopeType } = input;+ const { envelopeId } = input;ctx.logger.info({input: {@@ -24,7 +27,22 @@ export const deleteEnvelopeRoute = authenticatedProcedure},});- await match(envelopeType)+ const unsafeEnvelope = await prisma.envelope.findUnique({+ where: {+ id: envelopeId,+ },+ select: {+ type: true,+ },+ });++ if (!unsafeEnvelope) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: 'Envelope not found',+ });+ }++ await match(unsafeEnvelope.type).with(EnvelopeType.DOCUMENT, async () =>deleteDocument({userId: ctx.user.id,diff --git a/packages/trpc/server/envelope-router/delete-envelope.types.ts b/packages/trpc/server/envelope-router/delete-envelope.types.tsindex c2392d379..4f2b7aac8 100644--- a/packages/trpc/server/envelope-router/delete-envelope.types.ts+++ b/packages/trpc/server/envelope-router/delete-envelope.types.ts@@ -1,18 +1,18 @@-import { EnvelopeType } from '@prisma/client';import { z } from 'zod';-// export const deleteEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/envelope/delete',-// summary: 'Delete envelope',-// tags: ['Envelope'],-// },-// };+import type { TrpcRouteMeta } from '../trpc';++export const deleteEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/delete',+ summary: 'Delete envelope',+ tags: ['Envelope'],+ },+};export const ZDeleteEnvelopeRequestSchema = z.object({envelopeId: z.string(),- envelopeType: z.nativeEnum(EnvelopeType),});export const ZDeleteEnvelopeResponseSchema = z.void();diff --git a/packages/trpc/server/envelope-router/distribute-envelope.ts b/packages/trpc/server/envelope-router/distribute-envelope.tsindex 003727007..09436c2bc 100644--- a/packages/trpc/server/envelope-router/distribute-envelope.ts+++ b/packages/trpc/server/envelope-router/distribute-envelope.ts@@ -5,10 +5,11 @@ import { authenticatedProcedure } from '../trpc';import {ZDistributeEnvelopeRequestSchema,ZDistributeEnvelopeResponseSchema,+ distributeEnvelopeMeta,} from './distribute-envelope.types';export const distributeEnvelopeRoute = authenticatedProcedure- // .meta(distributeEnvelopeMeta)+ .meta(distributeEnvelopeMeta).input(ZDistributeEnvelopeRequestSchema).output(ZDistributeEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/distribute-envelope.types.ts b/packages/trpc/server/envelope-router/distribute-envelope.types.tsindex facee7b66..9d9acab72 100644--- a/packages/trpc/server/envelope-router/distribute-envelope.types.ts+++ b/packages/trpc/server/envelope-router/distribute-envelope.types.ts@@ -2,15 +2,17 @@ import { z } from 'zod';import { ZDocumentMetaUpdateSchema } from '@documenso/lib/types/document-meta';-// export const distributeEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/envelope/distribute',-// summary: 'Distribute envelope',-// description: 'Send the document out to recipients based on your distribution method',-// tags: ['Envelope'],-// },-// };+import type { TrpcRouteMeta } from '../trpc';++export const distributeEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/distribute',+ summary: 'Distribute envelope',+ description: 'Send the envelope to recipients based on your distribution method',+ tags: ['Envelope'],+ },+};export const ZDistributeEnvelopeRequestSchema = z.object({envelopeId: z.string().describe('The ID of the envelope to send.'),diff --git a/packages/trpc/server/envelope-router/download-envelope-item.ts b/packages/trpc/server/envelope-router/download-envelope-item.tsnew file mode 100644index 000000000..3b60c2899--- /dev/null+++ b/packages/trpc/server/envelope-router/download-envelope-item.ts@@ -0,0 +1,23 @@+import { authenticatedProcedure } from '../trpc';+import {+ ZDownloadEnvelopeItemRequestSchema,+ ZDownloadEnvelopeItemResponseSchema,+ downloadEnvelopeItemMeta,+} from './download-envelope-item.types';++export const downloadEnvelopeItemRoute = authenticatedProcedure+ .meta(downloadEnvelopeItemMeta)+ .input(ZDownloadEnvelopeItemRequestSchema)+ .output(ZDownloadEnvelopeItemResponseSchema)+ .query(({ input, ctx }) => {+ const { envelopeItemId, version } = input;++ ctx.logger.info({+ input: {+ envelopeItemId,+ version,+ },+ });++ throw new Error('NOT_IMPLEMENTED');+ });diff --git a/packages/trpc/server/envelope-router/download-envelope-item.types.ts b/packages/trpc/server/envelope-router/download-envelope-item.types.tsnew file mode 100644index 000000000..61c49b88c--- /dev/null+++ b/packages/trpc/server/envelope-router/download-envelope-item.types.ts@@ -0,0 +1,31 @@+import { z } from 'zod';++import type { TrpcRouteMeta } from '../trpc';++export const downloadEnvelopeItemMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/envelopeItem/{envelopeItemId}/download',+ summary: 'Download an envelope item',+ description: 'Download an envelope item by its ID',+ tags: ['Envelope Items'],+ responseHeaders: z.object({+ 'Content-Type': z.literal('application/pdf'),+ }),+ },+};++export const ZDownloadEnvelopeItemRequestSchema = z.object({+ envelopeItemId: z.string().describe('The ID of the envelope item to download.'),+ version: z+ .enum(['original', 'signed'])+ .describe(+ 'The version of the envelope item to download. "signed" returns the completed document with signatures, "original" returns the original uploaded document.',+ )+ .default('signed'),+});++export const ZDownloadEnvelopeItemResponseSchema = z.instanceof(Uint8Array);++export type TDownloadEnvelopeItemRequest = z.infer<typeof ZDownloadEnvelopeItemRequestSchema>;+export type TDownloadEnvelopeItemResponse = z.infer<typeof ZDownloadEnvelopeItemResponseSchema>;diff --git a/packages/trpc/server/envelope-router/duplicate-envelope.ts b/packages/trpc/server/envelope-router/duplicate-envelope.tsindex 3ed0aca7f..d7034e279 100644--- a/packages/trpc/server/envelope-router/duplicate-envelope.ts+++ b/packages/trpc/server/envelope-router/duplicate-envelope.ts@@ -4,9 +4,11 @@ import { authenticatedProcedure } from '../trpc';import {ZDuplicateEnvelopeRequestSchema,ZDuplicateEnvelopeResponseSchema,+ duplicateEnvelopeMeta,} from './duplicate-envelope.types';export const duplicateEnvelopeRoute = authenticatedProcedure+ .meta(duplicateEnvelopeMeta).input(ZDuplicateEnvelopeRequestSchema).output(ZDuplicateEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {@@ -29,6 +31,6 @@ export const duplicateEnvelopeRoute = authenticatedProcedure});return {- duplicatedEnvelopeId: duplicatedEnvelope.id,+ id: duplicatedEnvelope.id,};});diff --git a/packages/trpc/server/envelope-router/duplicate-envelope.types.ts b/packages/trpc/server/envelope-router/duplicate-envelope.types.tsindex 082003d54..348e631a6 100644--- a/packages/trpc/server/envelope-router/duplicate-envelope.types.ts+++ b/packages/trpc/server/envelope-router/duplicate-envelope.types.ts@@ -1,11 +1,23 @@import { z } from 'zod';+import type { TrpcRouteMeta } from '../trpc';++export const duplicateEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/duplicate',+ summary: 'Duplicate envelope',+ description: 'Duplicate an envelope with all its settings',+ tags: ['Envelope'],+ },+};+export const ZDuplicateEnvelopeRequestSchema = z.object({envelopeId: z.string(),});export const ZDuplicateEnvelopeResponseSchema = z.object({- duplicatedEnvelopeId: z.string(),+ id: z.string().describe('The ID of the newly created envelope.'),});export type TDuplicateEnvelopeRequest = z.infer<typeof ZDuplicateEnvelopeRequestSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.ts b/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.tsnew file mode 100644index 000000000..5f72ebb37--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.ts@@ -0,0 +1,38 @@+import { createEnvelopeFields } from '@documenso/lib/server-only/field/create-envelope-fields';++import { authenticatedProcedure } from '../../trpc';+import {+ ZCreateEnvelopeFieldsRequestSchema,+ ZCreateEnvelopeFieldsResponseSchema,+ createEnvelopeFieldsMeta,+} from './create-envelope-fields.types';++export const createEnvelopeFieldsRoute = authenticatedProcedure+ .meta(createEnvelopeFieldsMeta)+ .input(ZCreateEnvelopeFieldsRequestSchema)+ .output(ZCreateEnvelopeFieldsResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId, metadata } = ctx;+ const { envelopeId, data: fields } = input;++ ctx.logger.info({+ input: {+ envelopeId,+ },+ });++ const { fields: data } = await createEnvelopeFields({+ userId: user.id,+ teamId,+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ fields,+ requestMetadata: metadata,+ });++ return {+ data,+ };+ });diff --git a/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.types.ts b/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.types.tsnew file mode 100644index 000000000..1ae9dd172--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/create-envelope-fields.types.ts@@ -0,0 +1,53 @@+import { z } from 'zod';++import {+ ZClampedFieldHeightSchema,+ ZClampedFieldPositionXSchema,+ ZClampedFieldPositionYSchema,+ ZClampedFieldWidthSchema,+ ZFieldPageNumberSchema,+ ZFieldSchema,+} from '@documenso/lib/types/field';+import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';++import type { TrpcRouteMeta } from '../../trpc';++export const createEnvelopeFieldsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/field/create-many',+ contentTypes: ['multipart/form-data'],+ summary: 'Create envelope fields',+ description: 'Create multiple fields for an envelope',+ tags: ['Envelope Fields'],+ },+};++const ZCreateFieldSchema = ZFieldAndMetaSchema.and(+ z.object({+ recipientId: z.number().describe('The ID of the recipient to create the field for'),+ envelopeItemId: z+ .string()+ .optional()+ .describe(+ 'The ID of the envelope item to put the field on. If not provided, field will be placed on the first item.',+ ),+ page: ZFieldPageNumberSchema,+ positionX: ZClampedFieldPositionXSchema,+ positionY: ZClampedFieldPositionYSchema,+ width: ZClampedFieldWidthSchema,+ height: ZClampedFieldHeightSchema,+ }),+);++export const ZCreateEnvelopeFieldsRequestSchema = z.object({+ envelopeId: z.string(),+ data: ZCreateFieldSchema.array(),+});++export const ZCreateEnvelopeFieldsResponseSchema = z.object({+ data: z.array(ZFieldSchema),+});++export type TCreateEnvelopeFieldsRequest = z.infer<typeof ZCreateEnvelopeFieldsRequestSchema>;+export type TCreateEnvelopeFieldsResponse = z.infer<typeof ZCreateEnvelopeFieldsResponseSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.ts b/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.tsnew file mode 100644index 000000000..4b4dc35d4--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.ts@@ -0,0 +1,118 @@+import { EnvelopeType } from '@prisma/client';++import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { getEnvelopeWhereInput } from '@documenso/lib/server-only/envelope/get-envelope-by-id';+import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';+import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';+import { canRecipientFieldsBeModified } from '@documenso/lib/utils/recipients';+import { prisma } from '@documenso/prisma';++import { authenticatedProcedure } from '../../trpc';+import {+ ZDeleteEnvelopeFieldRequestSchema,+ ZDeleteEnvelopeFieldResponseSchema,+ deleteEnvelopeFieldMeta,+} from './delete-envelope-field.types';++export const deleteEnvelopeFieldRoute = authenticatedProcedure+ .meta(deleteEnvelopeFieldMeta)+ .input(ZDeleteEnvelopeFieldRequestSchema)+ .output(ZDeleteEnvelopeFieldResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId, metadata } = ctx;+ const { fieldId } = input;++ ctx.logger.info({+ input: {+ fieldId,+ },+ });++ const unsafeField = await prisma.field.findUnique({+ where: {+ id: fieldId,+ },+ select: {+ envelopeId: true,+ },+ });++ if (!unsafeField) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: 'Field not found',+ });+ }++ const { envelopeWhereInput } = await getEnvelopeWhereInput({+ id: {+ type: 'envelopeId',+ id: unsafeField.envelopeId,+ },+ type: null,+ userId: user.id,+ teamId,+ });++ const envelope = await prisma.envelope.findUnique({+ where: envelopeWhereInput,+ include: {+ recipients: {+ include: {+ fields: true,+ },+ },+ },+ });++ const recipientWithFields = envelope?.recipients.find((recipient) =>+ recipient.fields.some((field) => field.id === fieldId),+ );+ const fieldToDelete = recipientWithFields?.fields.find((field) => field.id === fieldId);++ if (!envelope || !recipientWithFields || !fieldToDelete) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: 'Field not found',+ });+ }++ if (envelope.completedAt) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Envelope already complete',+ });+ }++ // Check whether the recipient associated with the field can have new fields created.+ if (!canRecipientFieldsBeModified(recipientWithFields, recipientWithFields.fields)) {+ throw new AppError(AppErrorCode.INVALID_REQUEST, {+ message: 'Recipient has already interacted with the document.',+ });+ }++ await prisma.$transaction(async (tx) => {+ const deletedField = await tx.field.delete({+ where: {+ id: fieldToDelete.id,+ envelopeId: envelope.id,+ },+ });++ // Handle field deleted audit log.+ if (envelope.type === EnvelopeType.DOCUMENT) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.FIELD_DELETED,+ envelopeId: envelope.id,+ metadata,+ data: {+ fieldId: deletedField.secondaryId,+ fieldRecipientEmail: recipientWithFields.email,+ fieldRecipientId: deletedField.recipientId,+ fieldType: deletedField.type,+ },+ }),+ });+ }++ return deletedField;+ });+ });diff --git a/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.types.ts b/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.types.tsnew file mode 100644index 000000000..b4de27118--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/delete-envelope-field.types.ts@@ -0,0 +1,22 @@+import { z } from 'zod';++import type { TrpcRouteMeta } from '../../trpc';++export const deleteEnvelopeFieldMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/field/delete',+ summary: 'Delete envelope field',+ description: 'Delete an envelope field',+ tags: ['Envelope Fields'],+ },+};++export const ZDeleteEnvelopeFieldRequestSchema = z.object({+ fieldId: z.number(),+});++export const ZDeleteEnvelopeFieldResponseSchema = z.void();++export type TDeleteEnvelopeFieldRequest = z.infer<typeof ZDeleteEnvelopeFieldRequestSchema>;+export type TDeleteEnvelopeFieldResponse = z.infer<typeof ZDeleteEnvelopeFieldResponseSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.ts b/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.tsnew file mode 100644index 000000000..0ba40b479--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.ts@@ -0,0 +1,29 @@+import { getFieldById } from '@documenso/lib/server-only/field/get-field-by-id';++import { authenticatedProcedure } from '../../trpc';+import {+ ZGetEnvelopeFieldRequestSchema,+ ZGetEnvelopeFieldResponseSchema,+ getEnvelopeFieldMeta,+} from './get-envelope-field.types';++export const getEnvelopeFieldRoute = authenticatedProcedure+ .meta(getEnvelopeFieldMeta)+ .input(ZGetEnvelopeFieldRequestSchema)+ .output(ZGetEnvelopeFieldResponseSchema)+ .query(async ({ input, ctx }) => {+ const { teamId, user } = ctx;+ const { fieldId } = input;++ ctx.logger.info({+ input: {+ fieldId,+ },+ });++ return await getFieldById({+ userId: user.id,+ teamId,+ fieldId,+ });+ });diff --git a/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.types.ts b/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.types.tsnew file mode 100644index 000000000..6b1a735c9--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/get-envelope-field.types.ts@@ -0,0 +1,24 @@+import { z } from 'zod';++import { ZEnvelopeFieldSchema } from '@documenso/lib/types/field';++import type { TrpcRouteMeta } from '../../trpc';++export const getEnvelopeFieldMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/envelope/field/{fieldId}',+ summary: 'Get envelope field',+ description: 'Returns an envelope field given an ID',+ tags: ['Envelope Fields'],+ },+};++export const ZGetEnvelopeFieldRequestSchema = z.object({+ fieldId: z.number(),+});++export const ZGetEnvelopeFieldResponseSchema = ZEnvelopeFieldSchema;++export type TGetEnvelopeFieldRequest = z.infer<typeof ZGetEnvelopeFieldRequestSchema>;+export type TGetEnvelopeFieldResponse = z.infer<typeof ZGetEnvelopeFieldResponseSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.ts b/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.tsnew file mode 100644index 000000000..acb0c98fa--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.ts@@ -0,0 +1,39 @@+import { updateEnvelopeFields } from '@documenso/lib/server-only/field/update-envelope-fields';++import { authenticatedProcedure } from '../../trpc';+import {+ ZUpdateEnvelopeFieldsRequestSchema,+ ZUpdateEnvelopeFieldsResponseSchema,+ updateEnvelopeFieldsMeta,+} from './update-envelope-fields.types';++export const updateEnvelopeFieldsRoute = authenticatedProcedure+ .meta(updateEnvelopeFieldsMeta)+ .input(ZUpdateEnvelopeFieldsRequestSchema)+ .output(ZUpdateEnvelopeFieldsResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId } = ctx;+ const { envelopeId, data: fields } = input;++ ctx.logger.info({+ input: {+ envelopeId,+ },+ });++ const { fields: data } = await updateEnvelopeFields({+ userId: user.id,+ teamId,+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ type: null,+ fields,+ requestMetadata: ctx.metadata,+ });++ return {+ data,+ };+ });diff --git a/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.types.ts b/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.types.tsnew file mode 100644index 000000000..0bead4d95--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-fields/update-envelope-fields.types.ts@@ -0,0 +1,52 @@+import { z } from 'zod';++import {+ ZClampedFieldHeightSchema,+ ZClampedFieldPositionXSchema,+ ZClampedFieldPositionYSchema,+ ZClampedFieldWidthSchema,+ ZFieldPageNumberSchema,+ ZFieldSchema,+} from '@documenso/lib/types/field';+import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';++import type { TrpcRouteMeta } from '../../trpc';++export const updateEnvelopeFieldsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/field/update-many',+ summary: 'Update envelope fields',+ description: 'Update multiple envelope fields for an envelope',+ tags: ['Envelope Fields'],+ },+};++const ZUpdateFieldSchema = ZFieldAndMetaSchema.and(+ z.object({+ id: z.number().describe('The ID of the field to update.'),+ envelopeItemId: z+ .string()+ .optional()+ .describe(+ 'The ID of the envelope item to put the field on. If not provided, field will be placed on the first item.',+ ),+ page: ZFieldPageNumberSchema.optional(),+ positionX: ZClampedFieldPositionXSchema.optional(),+ positionY: ZClampedFieldPositionYSchema.optional(),+ width: ZClampedFieldWidthSchema.optional(),+ height: ZClampedFieldHeightSchema.optional(),+ }),+);++export const ZUpdateEnvelopeFieldsRequestSchema = z.object({+ envelopeId: z.string(),+ data: ZUpdateFieldSchema.array(),+});++export const ZUpdateEnvelopeFieldsResponseSchema = z.object({+ data: z.array(ZFieldSchema),+});++export type TUpdateEnvelopeFieldsRequest = z.infer<typeof ZUpdateEnvelopeFieldsRequestSchema>;+export type TUpdateEnvelopeFieldsResponse = z.infer<typeof ZUpdateEnvelopeFieldsResponseSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.ts b/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.tsnew file mode 100644index 000000000..549a371d8--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.ts@@ -0,0 +1,38 @@+import { createEnvelopeRecipients } from '@documenso/lib/server-only/recipient/create-envelope-recipients';++import { authenticatedProcedure } from '../../trpc';+import {+ ZCreateEnvelopeRecipientsRequestSchema,+ ZCreateEnvelopeRecipientsResponseSchema,+ createEnvelopeRecipientsMeta,+} from './create-envelope-recipients.types';++export const createEnvelopeRecipientsRoute = authenticatedProcedure+ .meta(createEnvelopeRecipientsMeta)+ .input(ZCreateEnvelopeRecipientsRequestSchema)+ .output(ZCreateEnvelopeRecipientsResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId, metadata } = ctx;+ const { envelopeId, data: recipients } = input;++ ctx.logger.info({+ input: {+ envelopeId,+ },+ });++ const { recipients: data } = await createEnvelopeRecipients({+ userId: user.id,+ teamId,+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ recipients,+ requestMetadata: metadata,+ });++ return {+ data,+ };+ });diff --git a/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.types.ts b/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.types.tsnew file mode 100644index 000000000..b5ed928f3--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/create-envelope-recipients.types.ts@@ -0,0 +1,32 @@+import { z } from 'zod';++import { ZEnvelopeRecipientLiteSchema } from '@documenso/lib/types/recipient';++import { ZCreateRecipientSchema } from '../../recipient-router/schema';+import type { TrpcRouteMeta } from '../../trpc';++export const createEnvelopeRecipientsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/recipient/create-many',+ summary: 'Create envelope recipients',+ description: 'Create multiple recipients for an envelope',+ tags: ['Envelope Recipients'],+ },+};++export const ZCreateEnvelopeRecipientsRequestSchema = z.object({+ envelopeId: z.string(),+ data: ZCreateRecipientSchema.array(),+});++export const ZCreateEnvelopeRecipientsResponseSchema = z.object({+ data: ZEnvelopeRecipientLiteSchema.array(),+});++export type TCreateEnvelopeRecipientsRequest = z.infer<+ typeof ZCreateEnvelopeRecipientsRequestSchema+>;+export type TCreateEnvelopeRecipientsResponse = z.infer<+ typeof ZCreateEnvelopeRecipientsResponseSchema+>;diff --git a/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.ts b/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.tsnew file mode 100644index 000000000..a6c63cd65--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.ts@@ -0,0 +1,30 @@+import { deleteEnvelopeRecipient } from '@documenso/lib/server-only/recipient/delete-envelope-recipient';++import { authenticatedProcedure } from '../../trpc';+import {+ ZDeleteEnvelopeRecipientRequestSchema,+ ZDeleteEnvelopeRecipientResponseSchema,+ deleteEnvelopeRecipientMeta,+} from './delete-envelope-recipient.types';++export const deleteEnvelopeRecipientRoute = authenticatedProcedure+ .meta(deleteEnvelopeRecipientMeta)+ .input(ZDeleteEnvelopeRecipientRequestSchema)+ .output(ZDeleteEnvelopeRecipientResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId, metadata } = ctx;+ const { recipientId } = input;++ ctx.logger.info({+ input: {+ recipientId,+ },+ });++ await deleteEnvelopeRecipient({+ userId: user.id,+ teamId,+ recipientId,+ requestMetadata: metadata,+ });+ });diff --git a/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.types.ts b/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.types.tsnew file mode 100644index 000000000..f82609cd2--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/delete-envelope-recipient.types.ts@@ -0,0 +1,24 @@+import { z } from 'zod';++import type { TrpcRouteMeta } from '../../trpc';++export const deleteEnvelopeRecipientMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/recipient/delete',+ summary: 'Delete envelope recipient',+ description: 'Delete an envelope recipient',+ tags: ['Envelope Recipients'],+ },+};++export const ZDeleteEnvelopeRecipientRequestSchema = z.object({+ recipientId: z.number(),+});++export const ZDeleteEnvelopeRecipientResponseSchema = z.void();++export type TDeleteEnvelopeRecipientRequest = z.infer<typeof ZDeleteEnvelopeRecipientRequestSchema>;+export type TDeleteEnvelopeRecipientResponse = z.infer<+ typeof ZDeleteEnvelopeRecipientResponseSchema+>;diff --git a/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.ts b/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.tsnew file mode 100644index 000000000..a39df2ab8--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.ts@@ -0,0 +1,45 @@+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { buildTeamWhereQuery } from '@documenso/lib/utils/teams';+import { prisma } from '@documenso/prisma';++import { authenticatedProcedure } from '../../trpc';+import {+ ZGetEnvelopeRecipientRequestSchema,+ ZGetEnvelopeRecipientResponseSchema,+ getEnvelopeRecipientMeta,+} from './get-envelope-recipient.types';++export const getEnvelopeRecipientRoute = authenticatedProcedure+ .meta(getEnvelopeRecipientMeta)+ .input(ZGetEnvelopeRecipientRequestSchema)+ .output(ZGetEnvelopeRecipientResponseSchema)+ .query(async ({ input, ctx }) => {+ const { teamId, user } = ctx;+ const { recipientId } = input;++ ctx.logger.info({+ input: {+ recipientId,+ },+ });++ const recipient = await prisma.recipient.findFirst({+ where: {+ id: recipientId,+ envelope: {+ team: buildTeamWhereQuery({ teamId, userId: user.id }),+ },+ },+ include: {+ fields: true,+ },+ });++ if (!recipient) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: 'Recipient not found',+ });+ }++ return recipient;+ });diff --git a/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.types.ts b/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.types.tsnew file mode 100644index 000000000..8742788e9--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/get-envelope-recipient.types.ts@@ -0,0 +1,24 @@+import { z } from 'zod';++import { ZEnvelopeRecipientSchema } from '@documenso/lib/types/recipient';++import type { TrpcRouteMeta } from '../../trpc';++export const getEnvelopeRecipientMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/envelope/recipient/{recipientId}',+ summary: 'Get envelope recipient',+ description: 'Returns an envelope recipient given an ID',+ tags: ['Envelope Recipients'],+ },+};++export const ZGetEnvelopeRecipientRequestSchema = z.object({+ recipientId: z.number(),+});++export const ZGetEnvelopeRecipientResponseSchema = ZEnvelopeRecipientSchema;++export type TGetEnvelopeRecipientRequest = z.infer<typeof ZGetEnvelopeRecipientRequestSchema>;+export type TGetEnvelopeRecipientResponse = z.infer<typeof ZGetEnvelopeRecipientResponseSchema>;diff --git a/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.ts b/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.tsnew file mode 100644index 000000000..f5b36cdd0--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.ts@@ -0,0 +1,38 @@+import { updateEnvelopeRecipients } from '@documenso/lib/server-only/recipient/update-envelope-recipients';++import { authenticatedProcedure } from '../../trpc';+import {+ ZUpdateEnvelopeRecipientsRequestSchema,+ ZUpdateEnvelopeRecipientsResponseSchema,+ updateEnvelopeRecipientsMeta,+} from './update-envelope-recipients.types';++export const updateEnvelopeRecipientsRoute = authenticatedProcedure+ .meta(updateEnvelopeRecipientsMeta)+ .input(ZUpdateEnvelopeRecipientsRequestSchema)+ .output(ZUpdateEnvelopeRecipientsResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId } = ctx;+ const { envelopeId, data: recipients } = input;++ ctx.logger.info({+ input: {+ envelopeId,+ },+ });++ const { recipients: data } = await updateEnvelopeRecipients({+ userId: user.id,+ teamId,+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ recipients,+ requestMetadata: ctx.metadata,+ });++ return {+ data,+ };+ });diff --git a/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.types.ts b/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.types.tsnew file mode 100644index 000000000..5b027489e--- /dev/null+++ b/packages/trpc/server/envelope-router/envelope-recipients/update-envelope-recipients.types.ts@@ -0,0 +1,32 @@+import { z } from 'zod';++import { ZRecipientLiteSchema } from '@documenso/lib/types/recipient';++import { ZUpdateRecipientSchema } from '../../recipient-router/schema';+import type { TrpcRouteMeta } from '../../trpc';++export const updateEnvelopeRecipientsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/recipient/update-many',+ summary: 'Update envelope recipients',+ description: 'Update multiple recipients for an envelope',+ tags: ['Envelope Recipients'],+ },+};++export const ZUpdateEnvelopeRecipientsRequestSchema = z.object({+ envelopeId: z.string(),+ data: ZUpdateRecipientSchema.array(),+});++export const ZUpdateEnvelopeRecipientsResponseSchema = z.object({+ data: ZRecipientLiteSchema.array(),+});++export type TUpdateEnvelopeRecipientsRequest = z.infer<+ typeof ZUpdateEnvelopeRecipientsRequestSchema+>;+export type TUpdateEnvelopeRecipientsResponse = z.infer<+ typeof ZUpdateEnvelopeRecipientsResponseSchema+>;diff --git a/packages/trpc/server/envelope-router/get-envelope-items-by-token.ts b/packages/trpc/server/envelope-router/get-envelope-items-by-token.tsindex 435e2a2ea..9c61cf4c3 100644--- a/packages/trpc/server/envelope-router/get-envelope-items-by-token.ts+++ b/packages/trpc/server/envelope-router/get-envelope-items-by-token.ts@@ -34,10 +34,25 @@ export const getEnvelopeItemsByTokenRoute = maybeAuthenticatedProcedure});}- return await handleGetEnvelopeItemsByUser({ envelopeId, userId: user.id, teamId });+ const { envelopeItems: data } = await handleGetEnvelopeItemsByUser({+ envelopeId,+ userId: user.id,+ teamId,+ });++ return {+ data,+ };}- return await handleGetEnvelopeItemsByToken({ envelopeId, token: access.token });+ const { envelopeItems: data } = await handleGetEnvelopeItemsByToken({+ envelopeId,+ token: access.token,+ });++ return {+ data,+ };});const handleGetEnvelopeItemsByToken = async ({diff --git a/packages/trpc/server/envelope-router/get-envelope-items-by-token.types.ts b/packages/trpc/server/envelope-router/get-envelope-items-by-token.types.tsindex c3bb02d5e..02fa08b26 100644--- a/packages/trpc/server/envelope-router/get-envelope-items-by-token.types.ts+++ b/packages/trpc/server/envelope-router/get-envelope-items-by-token.types.ts@@ -1,6 +1,5 @@import { z } from 'zod';-import DocumentDataSchema from '@documenso/prisma/generated/zod/modelSchema/DocumentDataSchema';import EnvelopeItemSchema from '@documenso/prisma/generated/zod/modelSchema/EnvelopeItemSchema';export const ZGetEnvelopeItemsByTokenRequestSchema = z.object({@@ -17,18 +16,10 @@ export const ZGetEnvelopeItemsByTokenRequestSchema = z.object({});export const ZGetEnvelopeItemsByTokenResponseSchema = z.object({- envelopeItems: EnvelopeItemSchema.pick({+ data: EnvelopeItemSchema.pick({id: true,+ envelopeId: true,title: true,order: true,- })- .extend({- documentData: DocumentDataSchema.pick({- type: true,- id: true,- data: true,- initialData: true,- }),- })- .array(),+ }).array(),});diff --git a/packages/trpc/server/envelope-router/get-envelope-items.ts b/packages/trpc/server/envelope-router/get-envelope-items.tsindex 475294b97..a7d06c1b5 100644--- a/packages/trpc/server/envelope-router/get-envelope-items.ts+++ b/packages/trpc/server/envelope-router/get-envelope-items.ts@@ -50,6 +50,6 @@ export const getEnvelopeItemsRoute = authenticatedProcedure}return {- envelopeItems: envelope.envelopeItems,+ data: envelope.envelopeItems,};});diff --git a/packages/trpc/server/envelope-router/get-envelope-items.types.ts b/packages/trpc/server/envelope-router/get-envelope-items.types.tsindex f59db94fa..674f895f7 100644--- a/packages/trpc/server/envelope-router/get-envelope-items.types.ts+++ b/packages/trpc/server/envelope-router/get-envelope-items.types.ts@@ -8,7 +8,7 @@ export const ZGetEnvelopeItemsRequestSchema = z.object({});export const ZGetEnvelopeItemsResponseSchema = z.object({- envelopeItems: EnvelopeItemSchema.pick({+ data: EnvelopeItemSchema.pick({id: true,title: true,order: true,diff --git a/packages/trpc/server/envelope-router/get-envelope.ts b/packages/trpc/server/envelope-router/get-envelope.tsindex 4d85974ab..0de032ce3 100644--- a/packages/trpc/server/envelope-router/get-envelope.ts+++ b/packages/trpc/server/envelope-router/get-envelope.ts@@ -1,10 +1,14 @@import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';import { authenticatedProcedure } from '../trpc';-import { ZGetEnvelopeRequestSchema, ZGetEnvelopeResponseSchema } from './get-envelope.types';+import {+ ZGetEnvelopeRequestSchema,+ ZGetEnvelopeResponseSchema,+ getEnvelopeMeta,+} from './get-envelope.types';export const getEnvelopeRoute = authenticatedProcedure- // .meta(getEnvelopeMeta)+ .meta(getEnvelopeMeta).input(ZGetEnvelopeRequestSchema).output(ZGetEnvelopeResponseSchema).query(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/get-envelope.types.ts b/packages/trpc/server/envelope-router/get-envelope.types.tsindex 44a27c94d..79f608747 100644--- a/packages/trpc/server/envelope-router/get-envelope.types.ts+++ b/packages/trpc/server/envelope-router/get-envelope.types.ts@@ -2,15 +2,17 @@ import { z } from 'zod';import { ZEnvelopeSchema } from '@documenso/lib/types/envelope';-// export const getEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'GET',-// path: '/envelope/{envelopeId}',-// summary: 'Get envelope',-// description: 'Returns a envelope given an ID',-// tags: ['Envelope'],-// },-// };+import type { TrpcRouteMeta } from '../trpc';++export const getEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'GET',+ path: '/envelope/{envelopeId}',+ summary: 'Get envelope',+ description: 'Returns an envelope given an ID',+ tags: ['Envelope'],+ },+};export const ZGetEnvelopeRequestSchema = z.object({envelopeId: z.string(),diff --git a/packages/trpc/server/envelope-router/redistribute-envelope.ts b/packages/trpc/server/envelope-router/redistribute-envelope.tsindex 2c3af6680..b38d8a26d 100644--- a/packages/trpc/server/envelope-router/redistribute-envelope.ts+++ b/packages/trpc/server/envelope-router/redistribute-envelope.ts@@ -4,10 +4,11 @@ import { authenticatedProcedure } from '../trpc';import {ZRedistributeEnvelopeRequestSchema,ZRedistributeEnvelopeResponseSchema,+ redistributeEnvelopeMeta,} from './redistribute-envelope.types';export const redistributeEnvelopeRoute = authenticatedProcedure- // .meta(redistributeEnvelopeMeta)+ .meta(redistributeEnvelopeMeta).input(ZRedistributeEnvelopeRequestSchema).output(ZRedistributeEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/redistribute-envelope.types.ts b/packages/trpc/server/envelope-router/redistribute-envelope.types.tsindex cd8610ab1..a9e499474 100644--- a/packages/trpc/server/envelope-router/redistribute-envelope.types.ts+++ b/packages/trpc/server/envelope-router/redistribute-envelope.types.ts@@ -1,15 +1,17 @@import { z } from 'zod';-// export const redistributeEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/envelope/redistribute',-// summary: 'Redistribute document',-// description:-// 'Redistribute the document to the provided recipients who have not actioned the document. Will use the distribution method set in the document',-// tags: ['Envelope'],-// },-// };+import type { TrpcRouteMeta } from '../trpc';++export const redistributeEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/redistribute',+ summary: 'Redistribute envelope',+ description:+ 'Redistribute the envelope to the provided recipients who have not actioned the envelope. Will use the distribution method set in the envelope',+ tags: ['Envelope'],+ },+};export const ZRedistributeEnvelopeRequestSchema = z.object({envelopeId: z.string(),diff --git a/packages/trpc/server/envelope-router/router.ts b/packages/trpc/server/envelope-router/router.tsindex 2e650e542..0e93520b3 100644--- a/packages/trpc/server/envelope-router/router.ts+++ b/packages/trpc/server/envelope-router/router.ts@@ -9,6 +9,14 @@ import { deleteEnvelopeRoute } from './delete-envelope';import { deleteEnvelopeItemRoute } from './delete-envelope-item';import { distributeEnvelopeRoute } from './distribute-envelope';import { duplicateEnvelopeRoute } from './duplicate-envelope';+import { createEnvelopeFieldsRoute } from './envelope-fields/create-envelope-fields';+import { deleteEnvelopeFieldRoute } from './envelope-fields/delete-envelope-field';+import { getEnvelopeFieldRoute } from './envelope-fields/get-envelope-field';+import { updateEnvelopeFieldsRoute } from './envelope-fields/update-envelope-fields';+import { createEnvelopeRecipientsRoute } from './envelope-recipients/create-envelope-recipients';+import { deleteEnvelopeRecipientRoute } from './envelope-recipients/delete-envelope-recipient';+import { getEnvelopeRecipientRoute } from './envelope-recipients/get-envelope-recipient';+import { updateEnvelopeRecipientsRoute } from './envelope-recipients/update-envelope-recipients';import { getEnvelopeRoute } from './get-envelope';import { getEnvelopeItemsRoute } from './get-envelope-items';import { getEnvelopeItemsByTokenRoute } from './get-envelope-items-by-token';@@ -18,17 +26,20 @@ import { setEnvelopeRecipientsRoute } from './set-envelope-recipients';import { signEnvelopeFieldRoute } from './sign-envelope-field';import { updateEnvelopeRoute } from './update-envelope';import { updateEnvelopeItemsRoute } from './update-envelope-items';+import { useEnvelopeRoute } from './use-envelope';+/**+ * Note: The order of the routes is important for public API routes.+ *+ * Example: GET /envelope/attachment must appear before GET /envelope/:id+ */export const envelopeRouter = router({- get: getEnvelopeRoute,- create: createEnvelopeRoute,- update: updateEnvelopeRoute,- delete: deleteEnvelopeRoute,- duplicate: duplicateEnvelopeRoute,- distribute: distributeEnvelopeRoute,- redistribute: redistributeEnvelopeRoute,- // share: shareEnvelopeRoute,-+ attachment: {+ find: findAttachmentsRoute,+ create: createAttachmentRoute,+ update: updateAttachmentRoute,+ delete: deleteAttachmentRoute,+ },item: {getMany: getEnvelopeItemsRoute,getManyByToken: getEnvelopeItemsByTokenRoute,@@ -37,16 +48,26 @@ export const envelopeRouter = router({delete: deleteEnvelopeItemRoute,},recipient: {+ get: getEnvelopeRecipientRoute,+ createMany: createEnvelopeRecipientsRoute,+ updateMany: updateEnvelopeRecipientsRoute,+ delete: deleteEnvelopeRecipientRoute,set: setEnvelopeRecipientsRoute,},field: {+ get: getEnvelopeFieldRoute,+ createMany: createEnvelopeFieldsRoute,+ updateMany: updateEnvelopeFieldsRoute,+ delete: deleteEnvelopeFieldRoute,set: setEnvelopeFieldsRoute,sign: signEnvelopeFieldRoute,},- attachment: {- find: findAttachmentsRoute,- create: createAttachmentRoute,- update: updateAttachmentRoute,- delete: deleteAttachmentRoute,- },+ get: getEnvelopeRoute,+ create: createEnvelopeRoute,+ use: useEnvelopeRoute,+ update: updateEnvelopeRoute,+ delete: deleteEnvelopeRoute,+ duplicate: duplicateEnvelopeRoute,+ distribute: distributeEnvelopeRoute,+ redistribute: redistributeEnvelopeRoute,});diff --git a/packages/trpc/server/envelope-router/set-envelope-fields.ts b/packages/trpc/server/envelope-router/set-envelope-fields.tsindex 445ec9785..243629142 100644--- a/packages/trpc/server/envelope-router/set-envelope-fields.ts+++ b/packages/trpc/server/envelope-router/set-envelope-fields.ts@@ -65,7 +65,7 @@ export const setEnvelopeFieldsRoute = authenticatedProcedure.exhaustive();return {- fields: result.fields.map((field) => ({+ data: result.fields.map((field) => ({id: field.id,formId: field.formId,})),diff --git a/packages/trpc/server/envelope-router/set-envelope-fields.types.ts b/packages/trpc/server/envelope-router/set-envelope-fields.types.tsindex ea3fb6269..4bf6a6c00 100644--- a/packages/trpc/server/envelope-router/set-envelope-fields.types.ts+++ b/packages/trpc/server/envelope-router/set-envelope-fields.types.ts@@ -1,12 +1,19 @@import { EnvelopeType, FieldType } from '@prisma/client';import { z } from 'zod';+import {+ ZClampedFieldHeightSchema,+ ZClampedFieldPositionXSchema,+ ZClampedFieldPositionYSchema,+ ZClampedFieldWidthSchema,+} from '@documenso/lib/types/field';import { ZFieldMetaSchema } from '@documenso/lib/types/field-meta';export const ZSetEnvelopeFieldsRequestSchema = z.object({envelopeId: z.string(),envelopeType: z.nativeEnum(EnvelopeType),fields: z.array(+ // Todo: Envelopes - Use strict schema for types + field meta.z.object({id: z.number()@@ -20,34 +27,17 @@ export const ZSetEnvelopeFieldsRequestSchema = z.object({.number().min(1).describe('The page number of the field on the envelope. Starts from 1.'),- // Todo: Envelopes - Extract these 0-100 schemas with better descriptions.- positionX: z- .number()- .min(0)- .max(100)- .describe('The percentage based X position of the field on the envelope.'),- positionY: z- .number()- .min(0)- .max(100)- .describe('The percentage based Y position of the field on the envelope.'),- width: z- .number()- .min(0)- .max(100)- .describe('The percentage based width of the field on the envelope.'),- height: z- .number()- .min(0)- .max(100)- .describe('The percentage based height of the field on the envelope.'),- fieldMeta: ZFieldMetaSchema, // Todo: Envelopes - Use a more strict form?+ positionX: ZClampedFieldPositionXSchema,+ positionY: ZClampedFieldPositionYSchema,+ width: ZClampedFieldWidthSchema,+ height: ZClampedFieldHeightSchema,+ fieldMeta: ZFieldMetaSchema,}),),});export const ZSetEnvelopeFieldsResponseSchema = z.object({- fields: z+ data: z.object({id: z.number(),formId: z.string().optional(),diff --git a/packages/trpc/server/envelope-router/set-envelope-recipients.ts b/packages/trpc/server/envelope-router/set-envelope-recipients.tsindex f9f6ffd98..4fca34864 100644--- a/packages/trpc/server/envelope-router/set-envelope-recipients.ts+++ b/packages/trpc/server/envelope-router/set-envelope-recipients.ts@@ -23,7 +23,7 @@ export const setEnvelopeRecipientsRoute = authenticatedProcedure},});- return await match(envelopeType)+ const { recipients: data } = await match(envelopeType).with(EnvelopeType.DOCUMENT, async () =>setDocumentRecipients({userId: ctx.user.id,@@ -48,4 +48,8 @@ export const setEnvelopeRecipientsRoute = authenticatedProcedure}),).exhaustive();++ return {+ data,+ };});diff --git a/packages/trpc/server/envelope-router/set-envelope-recipients.types.ts b/packages/trpc/server/envelope-router/set-envelope-recipients.types.tsindex c24fd6402..3e34146ad 100644--- a/packages/trpc/server/envelope-router/set-envelope-recipients.types.ts+++ b/packages/trpc/server/envelope-router/set-envelope-recipients.types.ts@@ -20,7 +20,7 @@ export const ZSetEnvelopeRecipientsRequestSchema = z.object({});export const ZSetEnvelopeRecipientsResponseSchema = z.object({- recipients: ZRecipientLiteSchema.omit({+ data: ZRecipientLiteSchema.omit({documentId: true,templateId: true,}).array(),diff --git a/packages/trpc/server/envelope-router/sign-envelope-field.ts b/packages/trpc/server/envelope-router/sign-envelope-field.tsindex 0b37cfc2e..fd9695ff7 100644--- a/packages/trpc/server/envelope-router/sign-envelope-field.ts+++ b/packages/trpc/server/envelope-router/sign-envelope-field.ts@@ -133,6 +133,49 @@ export const signEnvelopeFieldRoute = procedureconst insertionValues = extractFieldInsertionValues({ fieldValue, field, documentMeta });+ // Early return for uninserting fields.+ if (!insertionValues.inserted) {+ return await prisma.$transaction(async (tx) => {+ const updatedField = await tx.field.update({+ where: {+ id: field.id,+ },+ data: {+ customText: '',+ inserted: false,+ },+ });++ await tx.signature.deleteMany({+ where: {+ fieldId: field.id,+ },+ });++ if (recipient.role !== RecipientRole.ASSISTANT) {+ await tx.documentAuditLog.create({+ data: createDocumentAuditLogData({+ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FIELD_UNINSERTED,+ envelopeId: envelope.id,+ user: {+ name: recipient.name,+ email: recipient.email,+ },+ requestMetadata: metadata.requestMetadata,+ data: {+ field: field.type,+ fieldId: field.secondaryId,+ },+ }),+ });+ }++ return {+ signedField: updatedField,+ };+ });+ }+const derivedRecipientActionAuth = await validateFieldAuth({documentAuthOptions: envelope.authOptions,recipient,diff --git a/packages/trpc/server/envelope-router/update-envelope-items.ts b/packages/trpc/server/envelope-router/update-envelope-items.tsindex 05a75bd44..2e25ad2d9 100644--- a/packages/trpc/server/envelope-router/update-envelope-items.ts+++ b/packages/trpc/server/envelope-router/update-envelope-items.ts@@ -7,9 +7,11 @@ import { authenticatedProcedure } from '../trpc';import {ZUpdateEnvelopeItemsRequestSchema,ZUpdateEnvelopeItemsResponseSchema,+ updateEnvelopeItemsMeta,} from './update-envelope-items.types';export const updateEnvelopeItemsRoute = authenticatedProcedure+ .meta(updateEnvelopeItemsMeta).input(ZUpdateEnvelopeItemsRequestSchema).output(ZUpdateEnvelopeItemsResponseSchema).mutation(async ({ input, ctx }) => {@@ -93,6 +95,6 @@ export const updateEnvelopeItemsRoute = authenticatedProcedure// Todo: Envelope [AUDIT_LOGS]return {- updatedEnvelopeItems,+ data: updatedEnvelopeItems,};});diff --git a/packages/trpc/server/envelope-router/update-envelope-items.types.ts b/packages/trpc/server/envelope-router/update-envelope-items.types.tsindex bd023edb3..4d7a38cb0 100644--- a/packages/trpc/server/envelope-router/update-envelope-items.types.ts+++ b/packages/trpc/server/envelope-router/update-envelope-items.types.ts@@ -3,6 +3,17 @@ import { z } from 'zod';import EnvelopeItemSchema from '@documenso/prisma/generated/zod/modelSchema/EnvelopeItemSchema';import { ZDocumentTitleSchema } from '../document-router/schema';+import type { TrpcRouteMeta } from '../trpc';++export const updateEnvelopeItemsMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/item/update-many',+ summary: 'Update envelope items',+ description: 'Update multiple envelope items for an envelope',+ tags: ['Envelope Items'],+ },+};export const ZUpdateEnvelopeItemsRequestSchema = z.object({envelopeId: z.string(),@@ -17,7 +28,7 @@ export const ZUpdateEnvelopeItemsRequestSchema = z.object({});export const ZUpdateEnvelopeItemsResponseSchema = z.object({- updatedEnvelopeItems: EnvelopeItemSchema.pick({+ data: EnvelopeItemSchema.pick({id: true,order: true,title: true,diff --git a/packages/trpc/server/envelope-router/update-envelope.ts b/packages/trpc/server/envelope-router/update-envelope.tsindex 8de730be7..0887d5245 100644--- a/packages/trpc/server/envelope-router/update-envelope.ts+++ b/packages/trpc/server/envelope-router/update-envelope.ts@@ -4,10 +4,11 @@ import { authenticatedProcedure } from '../trpc';import {ZUpdateEnvelopeRequestSchema,ZUpdateEnvelopeResponseSchema,+ updateEnvelopeMeta,} from './update-envelope.types';export const updateEnvelopeRoute = authenticatedProcedure- // .meta(updateEnvelopeTrpcMeta)+ .meta(updateEnvelopeMeta).input(ZUpdateEnvelopeRequestSchema).output(ZUpdateEnvelopeResponseSchema).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/server/envelope-router/update-envelope.types.ts b/packages/trpc/server/envelope-router/update-envelope.types.tsindex a6fcc5165..17d10b434 100644--- a/packages/trpc/server/envelope-router/update-envelope.types.ts+++ b/packages/trpc/server/envelope-router/update-envelope.types.ts@@ -1,5 +1,3 @@-import { EnvelopeType } from '@prisma/client';-// import type { OpenApiMeta } from 'trpc-to-openapi';import { z } from 'zod';import {@@ -14,19 +12,19 @@ import {ZDocumentTitleSchema,ZDocumentVisibilitySchema,} from '../document-router/schema';+import type { TrpcRouteMeta } from '../trpc';-// export const updateEnvelopeMeta: TrpcRouteMeta = {-// openapi: {-// method: 'POST',-// path: '/envelope/update',-// summary: 'Update envelope',-// tags: ['Envelope'],-// },-// };+export const updateEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/update',+ summary: 'Update envelope',+ tags: ['Envelope'],+ },+};export const ZUpdateEnvelopeRequestSchema = z.object({envelopeId: z.string(),- envelopeType: z.nativeEnum(EnvelopeType),data: z.object({title: ZDocumentTitleSchema.optional(),diff --git a/packages/trpc/server/envelope-router/use-envelope.ts b/packages/trpc/server/envelope-router/use-envelope.tsnew file mode 100644index 000000000..fee863e94--- /dev/null+++ b/packages/trpc/server/envelope-router/use-envelope.ts@@ -0,0 +1,170 @@+import { EnvelopeType } from '@prisma/client';++import { getServerLimits } from '@documenso/ee/server-only/limits/server';+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';+import { sendDocument } from '@documenso/lib/server-only/document/send-document';+import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';+import { createDocumentFromTemplate } from '@documenso/lib/server-only/template/create-document-from-template';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';++import { authenticatedProcedure } from '../trpc';+import {+ ZUseEnvelopeRequestSchema,+ ZUseEnvelopeResponseSchema,+ useEnvelopeMeta,+} from './use-envelope.types';++export const useEnvelopeRoute = authenticatedProcedure+ .meta(useEnvelopeMeta)+ .input(ZUseEnvelopeRequestSchema)+ .output(ZUseEnvelopeResponseSchema)+ .mutation(async ({ input, ctx }) => {+ const { user, teamId } = ctx;++ const { payload, files = [] } = input;++ const {+ envelopeId,+ externalId,+ recipients,+ distributeDocument,+ customDocumentData = [],+ folderId,+ prefillFields,+ override,+ attachments,+ } = payload;++ ctx.logger.info({+ input: {+ envelopeId,+ folderId,+ },+ });++ const limits = await getServerLimits({ userId: user.id, teamId });++ if (limits.remaining.documents === 0) {+ throw new AppError(AppErrorCode.LIMIT_EXCEEDED, {+ message: 'You have reached your document limit.',+ });+ }++ // Verify the template exists and get envelope items+ const envelope = await getEnvelopeById({+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ type: EnvelopeType.TEMPLATE,+ userId: user.id,+ teamId,+ });++ if (files.length > envelope.envelopeItems.length) {+ throw new AppError(AppErrorCode.INVALID_BODY, {+ message: `You cannot upload more than ${envelope.envelopeItems.length} envelope items per envelope`,+ });+ }++ const filesToUpload = files.filter(+ (file, index) =>+ payload.customDocumentData &&+ payload.customDocumentData.some(+ (mapping) => mapping.identifier === file.name || mapping.identifier === index,+ ),+ );++ // Process uploaded files and create document data for them+ const uploadedFiles = await Promise.all(+ filesToUpload.map(async (file) => {+ const { id: documentDataId } = await putNormalizedPdfFileServerSide(file);++ return {+ name: file.name,+ documentDataId,+ };+ }),+ );++ // Map custom document data using identifiers+ const customDocumentDataMapped = customDocumentData?.map((mapping) => {+ let documentDataId: string | undefined;++ // Find the uploaded file by identifier+ if (typeof mapping.identifier === 'string') {+ documentDataId = uploadedFiles.find(+ (file) => file.name === mapping.identifier,+ )?.documentDataId;+ }++ if (typeof mapping.identifier === 'number') {+ documentDataId = uploadedFiles.at(mapping.identifier)?.documentDataId;+ }++ if (mapping.identifier === undefined) {+ documentDataId = uploadedFiles.at(0)?.documentDataId;+ }++ if (!documentDataId) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: `File with identifier "${mapping.identifier}" not found in uploaded files`,+ });+ }++ // Verify that the envelopeItemId exists in the template+ const envelopeItem = envelope.envelopeItems.find(+ (item) => item.id === mapping.envelopeItemId,+ );++ if (!envelopeItem) {+ throw new AppError(AppErrorCode.NOT_FOUND, {+ message: `Envelope item with ID "${mapping.envelopeItemId}" not found in template`,+ });+ }++ return {+ documentDataId,+ envelopeItemId: mapping.envelopeItemId,+ };+ });++ // Create document from template+ const createdEnvelope = await createDocumentFromTemplate({+ id: {+ type: 'envelopeId',+ id: envelopeId,+ },+ externalId,+ teamId,+ userId: user.id,+ recipients,+ customDocumentData: customDocumentDataMapped,+ requestMetadata: ctx.metadata,+ folderId,+ prefillFields,+ override,+ attachments,+ });++ // Distribute document if requested+ if (distributeDocument) {+ await sendDocument({+ id: {+ type: 'envelopeId',+ id: createdEnvelope.id,+ },+ userId: user.id,+ teamId,+ requestMetadata: ctx.metadata,+ }).catch((err) => {+ console.error(err);++ throw new AppError('DOCUMENT_SEND_FAILED');+ });+ }++ return {+ id: createdEnvelope.id,+ };+ });diff --git a/packages/trpc/server/envelope-router/use-envelope.types.ts b/packages/trpc/server/envelope-router/use-envelope.types.tsnew file mode 100644index 000000000..9150f1915--- /dev/null+++ b/packages/trpc/server/envelope-router/use-envelope.types.ts@@ -0,0 +1,121 @@+import { z } from 'zod';+import { zfd } from 'zod-form-data';++import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';+import {+ ZDocumentMetaDateFormatSchema,+ ZDocumentMetaDistributionMethodSchema,+ ZDocumentMetaDrawSignatureEnabledSchema,+ ZDocumentMetaLanguageSchema,+ ZDocumentMetaMessageSchema,+ ZDocumentMetaRedirectUrlSchema,+ ZDocumentMetaSubjectSchema,+ ZDocumentMetaTimezoneSchema,+ ZDocumentMetaTypedSignatureEnabledSchema,+ ZDocumentMetaUploadSignatureEnabledSchema,+} from '@documenso/lib/types/document-meta';+import { ZEnvelopeAttachmentTypeSchema } from '@documenso/lib/types/envelope-attachment';+import { ZFieldMetaPrefillFieldsSchema } from '@documenso/lib/types/field-meta';++import { zodFormData } from '../../utils/zod-form-data';+import type { TrpcRouteMeta } from '../trpc';++export const useEnvelopeMeta: TrpcRouteMeta = {+ openapi: {+ method: 'POST',+ path: '/envelope/use',+ contentTypes: ['multipart/form-data'],+ summary: 'Use envelope',+ description:+ 'Create a document envelope from a template envelope. Upload custom files to replace the template PDFs and map them to specific envelope items using identifiers.',+ tags: ['Envelope'],+ },+};++export const ZUseEnvelopePayloadSchema = z.object({+ envelopeId: z.string().describe('The ID of the template envelope to use.'),+ externalId: z.string().optional().describe('External ID for the created document.'),+ recipients: z+ .array(+ z.object({+ id: z.number().describe('The ID of the recipient in the template.'),+ email: z.string().email().max(254),+ name: z.string().max(255).optional(),+ signingOrder: z.number().optional(),+ }),+ )+ .describe('The information of the recipients to create the document with.'),+ distributeDocument: z+ .boolean()+ .describe('Whether to create the document as pending and distribute it to recipients.')+ .optional(),+ customDocumentData: z+ .array(+ z.object({+ identifier: z+ .union([z.string(), z.number()])+ .describe(+ 'Either the filename or the index of the file that was uploaded. This maps to which envelope item in the template should use this file.',+ ),+ envelopeItemId: z+ .string()+ .describe('The envelope item ID from the template to replace with the uploaded file.'),+ }),+ )+ .describe(+ 'Map uploaded files to specific envelope items in the template. If not provided, files will be ignored.',+ )+ .optional(),+ folderId: z+ .string()+ .describe(+ 'The ID of the folder to create the document in. If not provided, the document will be created in the root folder.',+ )+ .optional(),+ prefillFields: z+ .array(ZFieldMetaPrefillFieldsSchema)+ .describe(+ 'The fields to prefill on the document before sending it out. Useful when you want to create a document from an existing template and pre-fill the fields with specific values.',+ )+ .optional(),+ override: z+ .object({+ title: z.string().min(1).max(255).optional(),+ subject: ZDocumentMetaSubjectSchema.optional(),+ message: ZDocumentMetaMessageSchema.optional(),+ timezone: ZDocumentMetaTimezoneSchema.optional(),+ dateFormat: ZDocumentMetaDateFormatSchema.optional(),+ redirectUrl: ZDocumentMetaRedirectUrlSchema.optional(),+ distributionMethod: ZDocumentMetaDistributionMethodSchema.optional(),+ emailSettings: ZDocumentEmailSettingsSchema.optional(),+ language: ZDocumentMetaLanguageSchema.optional(),+ typedSignatureEnabled: ZDocumentMetaTypedSignatureEnabledSchema.optional(),+ uploadSignatureEnabled: ZDocumentMetaUploadSignatureEnabledSchema.optional(),+ drawSignatureEnabled: ZDocumentMetaDrawSignatureEnabledSchema.optional(),+ allowDictateNextSigner: z.boolean().optional(),+ })+ .describe('Override values from the template for the created document.')+ .optional(),+ attachments: z+ .array(+ z.object({+ label: z.string().min(1, 'Label is required'),+ data: z.string().url('Must be a valid URL'),+ type: ZEnvelopeAttachmentTypeSchema.optional().default('link'),+ }),+ )+ .optional(),+});++export const ZUseEnvelopeRequestSchema = zodFormData({+ payload: zfd.json(ZUseEnvelopePayloadSchema),+ files: zfd.repeatableOfType(zfd.file()).optional(),+});++export const ZUseEnvelopeResponseSchema = z.object({+ id: z.string().describe('The ID of the created envelope.'),+});++export type TUseEnvelopePayload = z.infer<typeof ZUseEnvelopePayloadSchema>;+export type TUseEnvelopeRequest = z.infer<typeof ZUseEnvelopeRequestSchema>;+export type TUseEnvelopeResponse = z.infer<typeof ZUseEnvelopeResponseSchema>;diff --git a/packages/trpc/server/field-router/router.ts b/packages/trpc/server/field-router/router.tsindex a739f6f24..92efab7fa 100644--- a/packages/trpc/server/field-router/router.ts+++ b/packages/trpc/server/field-router/router.ts@@ -8,8 +8,7 @@ import { removeSignedFieldWithToken } from '@documenso/lib/server-only/field/remimport { setFieldsForDocument } from '@documenso/lib/server-only/field/set-fields-for-document';import { setFieldsForTemplate } from '@documenso/lib/server-only/field/set-fields-for-template';import { signFieldWithToken } from '@documenso/lib/server-only/field/sign-field-with-token';-import { updateDocumentFields } from '@documenso/lib/server-only/field/update-document-fields';-import { updateTemplateFields } from '@documenso/lib/server-only/field/update-template-fields';+import { updateEnvelopeFields } from '@documenso/lib/server-only/field/update-envelope-fields';import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../document-router/schema';import { authenticatedProcedure, procedure, router } from '../trpc';@@ -109,7 +108,14 @@ export const fieldRouter = router({type: 'documentId',id: documentId,},- fields: [field],+ fields: [+ {+ ...field,+ page: field.pageNumber,+ positionX: field.pageX,+ positionY: field.pageY,+ },+ ],requestMetadata: ctx.metadata,});@@ -148,7 +154,12 @@ export const fieldRouter = router({type: 'documentId',id: documentId,},- fields,+ fields: fields.map((field) => ({+ ...field,+ page: field.pageNumber,+ positionX: field.pageX,+ positionY: field.pageY,+ })),requestMetadata: ctx.metadata,});}),@@ -178,10 +189,14 @@ export const fieldRouter = router({},});- const updatedFields = await updateDocumentFields({+ const updatedFields = await updateEnvelopeFields({userId: ctx.user.id,teamId,- documentId,+ id: {+ type: 'documentId',+ id: documentId,+ },+ type: EnvelopeType.DOCUMENT,fields: [field],requestMetadata: ctx.metadata,});@@ -214,10 +229,14 @@ export const fieldRouter = router({},});- return await updateDocumentFields({+ return await updateEnvelopeFields({userId: ctx.user.id,teamId,- documentId,+ id: {+ type: 'documentId',+ id: documentId,+ },+ type: EnvelopeType.DOCUMENT,fields,requestMetadata: ctx.metadata,});@@ -328,7 +347,14 @@ export const fieldRouter = router({type: 'templateId',id: templateId,},- fields: [field],+ fields: [+ {+ ...field,+ page: field.pageNumber,+ positionX: field.pageX,+ positionY: field.pageY,+ },+ ],requestMetadata: ctx.metadata,});@@ -401,7 +427,12 @@ export const fieldRouter = router({type: 'templateId',id: templateId,},- fields,+ fields: fields.map((field) => ({+ ...field,+ page: field.pageNumber,+ positionX: field.pageX,+ positionY: field.pageY,+ })),requestMetadata: ctx.metadata,});}),@@ -431,11 +462,16 @@ export const fieldRouter = router({},});- const updatedFields = await updateTemplateFields({+ const updatedFields = await updateEnvelopeFields({userId: ctx.user.id,teamId,- templateId,+ id: {+ type: 'templateId',+ id: templateId,+ },+ type: EnvelopeType.TEMPLATE,fields: [field],+ requestMetadata: ctx.metadata,});return updatedFields.fields[0];@@ -466,11 +502,16 @@ export const fieldRouter = router({},});- return await updateTemplateFields({+ return await updateEnvelopeFields({userId: ctx.user.id,teamId,- templateId,+ id: {+ type: 'templateId',+ id: templateId,+ },+ type: EnvelopeType.TEMPLATE,fields,+ requestMetadata: ctx.metadata,});}),diff --git a/packages/trpc/server/open-api.ts b/packages/trpc/server/open-api.tsindex c55042f93..678650e31 100644--- a/packages/trpc/server/open-api.ts+++ b/packages/trpc/server/open-api.ts@@ -6,10 +6,11 @@ import { appRouter } from './router';export const openApiDocument = {...generateOpenApiDocument(appRouter, {- title: 'Documenso v2 beta API',- description: 'Subject to breaking changes until v2 is fully released.',- version: '0.0.0',- baseUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta`,+ title: 'Documenso v2 API',+ description:+ 'Welcome to the Documenso v2 API.\n\nThis API provides access to our system, which you can use to integrate applications, automate workflows, or build custom tools.',+ version: '1.0.0',+ baseUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2`,securitySchemes: {apiKey: {type: 'apiKey',diff --git a/packages/trpc/server/recipient-router/router.ts b/packages/trpc/server/recipient-router/router.tsindex b8ed8bc0f..532bb2171 100644--- a/packages/trpc/server/recipient-router/router.ts+++ b/packages/trpc/server/recipient-router/router.ts@@ -2,15 +2,12 @@ import { EnvelopeType } from '@prisma/client';import { completeDocumentWithToken } from '@documenso/lib/server-only/document/complete-document-with-token';import { rejectDocumentWithToken } from '@documenso/lib/server-only/document/reject-document-with-token';-import { createDocumentRecipients } from '@documenso/lib/server-only/recipient/create-document-recipients';-import { createTemplateRecipients } from '@documenso/lib/server-only/recipient/create-template-recipients';-import { deleteDocumentRecipient } from '@documenso/lib/server-only/recipient/delete-document-recipient';-import { deleteTemplateRecipient } from '@documenso/lib/server-only/recipient/delete-template-recipient';+import { createEnvelopeRecipients } from '@documenso/lib/server-only/recipient/create-envelope-recipients';+import { deleteEnvelopeRecipient } from '@documenso/lib/server-only/recipient/delete-envelope-recipient';import { getRecipientById } from '@documenso/lib/server-only/recipient/get-recipient-by-id';import { setDocumentRecipients } from '@documenso/lib/server-only/recipient/set-document-recipients';import { setTemplateRecipients } from '@documenso/lib/server-only/recipient/set-template-recipients';-import { updateDocumentRecipients } from '@documenso/lib/server-only/recipient/update-document-recipients';-import { updateTemplateRecipients } from '@documenso/lib/server-only/recipient/update-template-recipients';+import { updateEnvelopeRecipients } from '@documenso/lib/server-only/recipient/update-envelope-recipients';import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../document-router/schema';import { authenticatedProcedure, procedure, router } from '../trpc';@@ -108,7 +105,7 @@ export const recipientRouter = router({},});- const createdRecipients = await createDocumentRecipients({+ const createdRecipients = await createEnvelopeRecipients({userId: ctx.user.id,teamId,id: {@@ -147,7 +144,7 @@ export const recipientRouter = router({},});- return await createDocumentRecipients({+ return await createEnvelopeRecipients({userId: ctx.user.id,teamId,id: {@@ -184,7 +181,7 @@ export const recipientRouter = router({},});- const updatedRecipients = await updateDocumentRecipients({+ const updatedRecipients = await updateEnvelopeRecipients({userId: ctx.user.id,teamId,id: {@@ -223,7 +220,7 @@ export const recipientRouter = router({},});- return await updateDocumentRecipients({+ return await updateEnvelopeRecipients({userId: ctx.user.id,teamId,id: {@@ -259,7 +256,7 @@ export const recipientRouter = router({},});- await deleteDocumentRecipient({+ await deleteEnvelopeRecipient({userId: ctx.user.id,teamId,recipientId,@@ -363,11 +360,15 @@ export const recipientRouter = router({},});- const createdRecipients = await createTemplateRecipients({+ const createdRecipients = await createEnvelopeRecipients({userId: ctx.user.id,teamId,- templateId,+ id: {+ id: templateId,+ type: 'templateId',+ },recipients: [recipient],+ requestMetadata: ctx.metadata,});return createdRecipients.recipients[0];@@ -398,11 +399,15 @@ export const recipientRouter = router({},});- return await createTemplateRecipients({+ return await createEnvelopeRecipients({userId: ctx.user.id,teamId,- templateId,+ id: {+ id: templateId,+ type: 'templateId',+ },recipients,+ requestMetadata: ctx.metadata,});}),@@ -431,11 +436,15 @@ export const recipientRouter = router({},});- const updatedRecipients = await updateTemplateRecipients({+ const updatedRecipients = await updateEnvelopeRecipients({userId: ctx.user.id,teamId,- templateId,+ id: {+ type: 'templateId',+ id: templateId,+ },recipients: [recipient],+ requestMetadata: ctx.metadata,});return updatedRecipients.recipients[0];@@ -466,11 +475,15 @@ export const recipientRouter = router({},});- return await updateTemplateRecipients({+ return await updateEnvelopeRecipients({userId: ctx.user.id,teamId,- templateId,+ id: {+ type: 'templateId',+ id: templateId,+ },recipients,+ requestMetadata: ctx.metadata,});}),@@ -498,10 +511,11 @@ export const recipientRouter = router({},});- await deleteTemplateRecipient({+ await deleteEnvelopeRecipient({recipientId,userId: ctx.user.id,teamId,+ requestMetadata: ctx.metadata,});return ZGenericSuccessResponse;diff --git a/packages/trpc/server/recipient-router/schema.ts b/packages/trpc/server/recipient-router/schema.tsindex dafebd196..58a2a1289 100644--- a/packages/trpc/server/recipient-router/schema.ts+++ b/packages/trpc/server/recipient-router/schema.ts@@ -28,8 +28,8 @@ export const ZCreateRecipientSchema = z.object({name: z.string().max(255),role: z.nativeEnum(RecipientRole),signingOrder: z.number().optional(),- accessAuth: z.array(ZRecipientAccessAuthTypesSchema).optional().default([]),- actionAuth: z.array(ZRecipientActionAuthTypesSchema).optional().default([]),+ accessAuth: z.array(ZRecipientAccessAuthTypesSchema).default([]).optional(),+ actionAuth: z.array(ZRecipientActionAuthTypesSchema).default([]).optional(),});export const ZUpdateRecipientSchema = z.object({@@ -38,8 +38,8 @@ export const ZUpdateRecipientSchema = z.object({name: z.string().max(255).optional(),role: z.nativeEnum(RecipientRole).optional(),signingOrder: z.number().optional(),- accessAuth: z.array(ZRecipientAccessAuthTypesSchema).optional().default([]),- actionAuth: z.array(ZRecipientActionAuthTypesSchema).optional().default([]),+ accessAuth: z.array(ZRecipientAccessAuthTypesSchema).default([]).optional(),+ actionAuth: z.array(ZRecipientActionAuthTypesSchema).default([]).optional(),});export const ZCreateDocumentRecipientRequestSchema = z.object({diff --git a/packages/trpc/server/template-router/router.ts b/packages/trpc/server/template-router/router.tsindex 0ee4669d4..4c1e62d15 100644--- a/packages/trpc/server/template-router/router.ts+++ b/packages/trpc/server/template-router/router.ts@@ -21,6 +21,7 @@ import { deleteTemplateDirectLink } from '@documenso/lib/server-only/template/deimport { findTemplates } from '@documenso/lib/server-only/template/find-templates';import { getTemplateById } from '@documenso/lib/server-only/template/get-template-by-id';import { toggleTemplateDirectLink } from '@documenso/lib/server-only/template/toggle-template-direct-link';+import { putNormalizedPdfFileServerSide } from '@documenso/lib/universal/upload/put-file.server';import { getPresignPostUrl } from '@documenso/lib/universal/upload/server-actions';import { mapSecondaryIdToTemplateId } from '@documenso/lib/utils/envelope';import { mapFieldToLegacyField } from '@documenso/lib/utils/fields';@@ -159,20 +160,26 @@ export const templateRouter = router({* @private*/createTemplate: authenticatedProcedure- // .meta({ // Note before releasing this to public, update the response schema to be correct.- // openapi: {- // method: 'POST',- // path: '/template/create',- // summary: 'Create template',- // description: 'Create a new template',- // tags: ['Template'],- // },- // })+ .meta({+ openapi: {+ method: 'POST',+ path: '/template/create',+ contentTypes: ['multipart/form-data'],+ summary: 'Create template',+ description: 'Create a new template',+ tags: ['Template'],+ },+ }).input(ZCreateTemplateMutationSchema).output(ZCreateTemplateResponseSchema).mutation(async ({ input, ctx }) => {const { teamId } = ctx;- const { title, templateDocumentDataId, folderId } = input;++ const { payload, file } = input;++ const { title, folderId } = payload;++ const { id: templateDocumentDataId } = await putNormalizedPdfFileServerSide(file);ctx.logger.info({input: {@@ -198,7 +205,8 @@ export const templateRouter = router({});return {- legacyTemplateId: mapSecondaryIdToTemplateId(envelope.secondaryId),+ envelopeId: envelope.id,+ id: mapSecondaryIdToTemplateId(envelope.secondaryId),};}),diff --git a/packages/trpc/server/template-router/schema.ts b/packages/trpc/server/template-router/schema.tsindex a199f1c1a..60b56ff3d 100644--- a/packages/trpc/server/template-router/schema.ts+++ b/packages/trpc/server/template-router/schema.ts@@ -1,5 +1,6 @@import { DocumentSigningOrder, DocumentVisibility, TemplateType } from '@prisma/client';import { z } from 'zod';+import { zfd } from 'zod-form-data';import { ZDocumentSchema } from '@documenso/lib/types/document';import {@@ -29,6 +30,7 @@ import {} from '@documenso/lib/types/template';import { LegacyTemplateDirectLinkSchema } from '@documenso/prisma/types/template-legacy-schema';+import { zodFormData } from '../../utils/zod-form-data';import { ZSignFieldWithTokenMutationSchema } from '../field-router/schema';export const MAX_TEMPLATE_PUBLIC_TITLE_LENGTH = 50;@@ -77,12 +79,16 @@ export const ZTemplateMetaUpsertSchema = z.object({allowDictateNextSigner: z.boolean().optional(),});-export const ZCreateTemplateMutationSchema = z.object({+export const ZCreateTemplatePayloadSchema = z.object({title: z.string().min(1).trim(),- templateDocumentDataId: z.string().min(1),folderId: z.string().optional(),});+export const ZCreateTemplateMutationSchema = zodFormData({+ payload: zfd.json(ZCreateTemplatePayloadSchema),+ file: zfd.file(),+});+export const ZCreateDocumentFromDirectTemplateRequestSchema = z.object({directRecipientName: z.string().max(255).optional(),directRecipientEmail: z.string().email().max(254),@@ -224,7 +230,8 @@ export const ZCreateTemplateV2ResponseSchema = z.object({});export const ZCreateTemplateResponseSchema = z.object({- legacyTemplateId: z.number(),+ envelopeId: z.string(),+ id: z.number(),});export const ZUpdateTemplateRequestSchema = z.object({@@ -273,6 +280,7 @@ export const ZBulkSendTemplateMutationSchema = z.object({sendImmediately: z.boolean(),});+export type TCreateTemplatePayloadSchema = z.infer<typeof ZCreateTemplatePayloadSchema>;export type TCreateTemplateMutationSchema = z.infer<typeof ZCreateTemplateMutationSchema>;export type TDuplicateTemplateMutationSchema = z.infer<typeof ZDuplicateTemplateMutationSchema>;export type TDeleteTemplateMutationSchema = z.infer<typeof ZDeleteTemplateMutationSchema>;diff --git a/packages/trpc/server/trpc.ts b/packages/trpc/server/trpc.tsindex 96870c246..a880dfa49 100644--- a/packages/trpc/server/trpc.ts+++ b/packages/trpc/server/trpc.ts@@ -1,5 +1,4 @@import { TRPCError, initTRPC } from '@trpc/server';-import SuperJSON from 'superjson';import type { AnyZodObject } from 'zod';import { AppError, genericErrorCodeToTrpcErrorCodeMap } from '@documenso/lib/errors/app-error';@@ -9,6 +8,7 @@ import type { ApiRequestMetadata } from '@documenso/lib/universal/extract-requesimport { alphaid } from '@documenso/lib/universal/id';import { isAdmin } from '@documenso/lib/utils/is-admin';+import { dataTransformer } from '../utils/data-transformer';import type { TrpcContext } from './context';// Can't import type from trpc-to-openapi because it breaks build, not sure why.@@ -35,7 +35,7 @@ const t = initTRPC.meta<TrpcRouteMeta>().context<TrpcContext>().create({- transformer: SuperJSON,+ transformer: dataTransformer,errorFormatter(opts) {const { shape, error } = opts;@@ -164,14 +164,62 @@ export const maybeAuthenticatedMiddleware = t.middleware(async ({ ctx, next, patnonBatchedRequestId: alphaid(),});- ctx.logger.info({+ const infoToLog: TrpcApiLog = {path,auth: ctx.metadata.auth,source: ctx.metadata.source,- userId: ctx.user?.id,- apiTokenId: null,trpcMiddleware: 'maybeAuthenticated',unverifiedTeamId: ctx.teamId,+ };++ const authorizationHeader = ctx.req.headers.get('authorization');++ // Taken from `authenticatedMiddleware` in `@documenso/api/v1/middleware/authenticated.ts`.+ if (authorizationHeader) {+ // Support for both "Authorization: Bearer api_xxx" and "Authorization: api_xxx"+ const [token] = (authorizationHeader || '').split('Bearer ').filter((s) => s.length > 0);++ if (!token) {+ throw new Error('Token was not provided for authenticated middleware');+ }++ const apiToken = await getApiTokenByToken({ token });++ ctx.logger.info({+ ...infoToLog,+ userId: apiToken.user.id,+ apiTokenId: apiToken.id,+ } satisfies TrpcApiLog);++ return await next({+ ctx: {+ ...ctx,+ user: apiToken.user,+ teamId: apiToken.teamId,+ session: null,+ metadata: {+ ...ctx.metadata,+ auditUser: apiToken.team+ ? {+ id: null,+ email: null,+ name: apiToken.team.name,+ }+ : {+ id: apiToken.user.id,+ email: apiToken.user.email,+ name: apiToken.user.name,+ },+ auth: 'api',+ } satisfies ApiRequestMetadata,+ },+ });+ }++ trpcSessionLogger.info({+ ...infoToLog,+ userId: ctx.user?.id,+ apiTokenId: null,} satisfies TrpcApiLog);return await next({diff --git a/packages/trpc/utils/data-transformer.ts b/packages/trpc/utils/data-transformer.tsnew file mode 100644index 000000000..2c632c1cc--- /dev/null+++ b/packages/trpc/utils/data-transformer.ts@@ -0,0 +1,17 @@+import type { DataTransformer } from '@trpc/server';+import SuperJSON from 'superjson';++export const dataTransformer: DataTransformer = {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ serialize: (data: any) => {+ if (data instanceof FormData) {+ return data;+ }++ return SuperJSON.serialize(data);+ },+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ deserialize: (data: any) => {+ return SuperJSON.deserialize(data);+ },+};diff --git a/packages/trpc/utils/openapi-fetch-handler.ts b/packages/trpc/utils/openapi-fetch-handler.tsnew file mode 100644index 000000000..c597a45cd--- /dev/null+++ b/packages/trpc/utils/openapi-fetch-handler.ts@@ -0,0 +1,202 @@+import { TRPCError } from '@trpc/server';+import type { FetchHandlerOptions } from '@trpc/server/adapters/fetch';+import type { ServerResponse } from 'node:http';+import { type OpenApiRouter, createOpenApiNodeHttpHandler } from 'trpc-to-openapi';++const CONTENT_TYPE_JSON = 'application/json';+const CONTENT_TYPE_URLENCODED = 'application/x-www-form-urlencoded';+const CONTENT_TYPE_MULTIPART = 'multipart/form-data';++const getUrlEncodedBody = async (req: Request) => {+ const params = new URLSearchParams(await req.text());++ const data: Record<string, unknown> = {};++ for (const key of params.keys()) {+ data[key] = params.getAll(key);+ }++ return data;+};++const getMultipartBody = async (req: Request) => {+ const formData = await req.formData();++ const data: Record<string, unknown> = {};++ for (const key of formData.keys()) {+ const values = formData.getAll(key);++ // Return array for multiple values, single value otherwise (matches URL-encoded behavior)+ data[key] = values.length > 1 ? values : values[0];+ }++ return data;+};+/**+ * Parses the request body based on its content type.+ *+ * Handles JSON, URL-encoded, and multipart/form-data requests.+ * For multipart requests, converts FormData to a plain object (similar to URL-encoded)+ * so it can be validated by tRPC schemas. The content-type header is rewritten+ * later to prevent downstream parsing issues.+ */+const getRequestBody = async (req: Request) => {+ try {+ const contentType = req.headers.get('content-type') || '';++ if (contentType.includes(CONTENT_TYPE_JSON)) {+ return {+ isValid: true,+ // Use JSON.parse instead of req.json() because req.json() does not throw on invalid JSON+ data: JSON.parse(await req.text()),+ };+ }++ if (contentType.includes(CONTENT_TYPE_URLENCODED)) {+ return {+ isValid: true,+ data: await getUrlEncodedBody(req),+ };+ }++ // Handle multipart/form-data by parsing as FormData and converting to a plain object.+ // This mirrors how URL-encoded data is structured, allowing tRPC to validate it normally.+ // The content-type header is rewritten to application/json later via the request proxy+ // because createOpenApiNodeHttpHandler aborts on any bodied request that isn't application/json.+ if (contentType.includes(CONTENT_TYPE_MULTIPART)) {+ return {+ isValid: true,+ data: await getMultipartBody(req),+ };+ }++ return {+ isValid: true,+ data: req.body,+ };+ } catch (err) {+ return {+ isValid: false,+ cause: err,+ };+ }+};++/**+ * Creates a proxy around the original Request that intercepts property access+ * to transform the request for compatibility with the Node HTTP handler.+ *+ * Key transformations:+ * - Parses and provides the body as a plain object (handles multipart/form-data conversion)+ * - Rewrites content-type header for multipart requests to application/json+ * (required because createOpenApiNodeHttpHandler aborts on non-JSON bodied requests)+ */+const createRequestProxy = async (req: Request, url?: string) => {+ const body = await getRequestBody(req);++ const originalContentType = req.headers.get('content-type') || '';++ const isMultipart = originalContentType.includes(CONTENT_TYPE_MULTIPART);++ return new Proxy(req, {+ get: (target, prop) => {+ switch (prop) {+ case 'url':+ return url ?? target.url;++ case 'body': {+ if (!body.isValid) {+ throw new TRPCError({+ code: 'PARSE_ERROR',+ message: 'Failed to parse request body',+ cause: body.cause,+ });+ }++ return body.data;+ }++ case 'headers': {+ const headers = new Headers(target.headers);++ // Rewrite content-type header for multipart requests to application/json.+ // This is necessary because `createOpenApiNodeHttpHandler` aborts on any bodied+ // request that isn't application/json. Since we've already parsed the multipart+ // data into a plain object above, this is safe to do.+ if (isMultipart) {+ headers.set('content-type', CONTENT_TYPE_JSON);+ }++ return headers;+ }++ default:+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any+ return (target as unknown as Record<string | number | symbol, unknown>)[prop];+ }+ },+ });+};++export type CreateOpenApiFetchHandlerOptions<TRouter extends OpenApiRouter> = Omit<+ FetchHandlerOptions<TRouter>,+ 'batching'+> & {+ req: Request;+ endpoint: `/${string}`;+};++export const createOpenApiFetchHandler = async <TRouter extends OpenApiRouter>(+ opts: CreateOpenApiFetchHandlerOptions<TRouter>,+): Promise<Response> => {+ const resHeaders = new Headers();+ const url = new URL(opts.req.url.replace(opts.endpoint, ''));+ const req: Request = await createRequestProxy(opts.req, url.toString());++ // @ts-expect-error Inherited from original fetch handler in `trpc-to-openapi`+ const openApiHttpHandler = createOpenApiNodeHttpHandler(opts);++ return new Promise<Response>((resolve) => {+ let statusCode: number;++ // Create a mock ServerResponse object that bridges Node HTTP APIs with Fetch API Response.+ // This allows the Node HTTP handler to work with Fetch API Request objects.+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions+ const res = {+ setHeader: (key: string, value: string | readonly string[]) => {+ if (typeof value === 'string') {+ resHeaders.set(key, value);+ } else {+ for (const v of value) {+ resHeaders.append(key, v);+ }+ }+ },+ get statusCode() {+ return statusCode;+ },+ set statusCode(code: number) {+ statusCode = code;+ },+ end: (body: string) => {+ resolve(+ new Response(body, {+ headers: resHeaders,+ status: statusCode,+ }),+ );+ },+ } as ServerResponse;++ // Type assertions are necessary here for interop between Fetch API Request/Response+ // and Node HTTP IncomingMessage/ServerResponse types.+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions+ const nodeReq = req as unknown as Parameters<typeof openApiHttpHandler>[0];++ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions+ const nodeRes = res as unknown as Parameters<typeof openApiHttpHandler>[1];++ void openApiHttpHandler(nodeReq, nodeRes);+ });+};diff --git a/packages/trpc/utils/zod-form-data.ts b/packages/trpc/utils/zod-form-data.tsnew file mode 100644index 000000000..0b78bdb82--- /dev/null+++ b/packages/trpc/utils/zod-form-data.ts@@ -0,0 +1,32 @@+import type { ZodRawShape } from 'zod';+import z from 'zod';++/**+ * This helper takes the place of the `z.object` at the root of your schema.+ * It wraps your schema in a `z.preprocess` that extracts all the data out of a `FormData`+ * and transforms it into a regular object.+ * If the `FormData` contains multiple entries with the same field name,+ * it will automatically turn that field into an array.+ *+ * This is used instead of `zfd.formData()` because it receives `undefined`+ * somewhere in the pipeline of our openapi schema generation and throws+ * an error. This provides the same functionality as `zfd.formData()` but+ * can be considered somewhat safer.+ */+export const zodFormData = <T extends ZodRawShape>(schema: T) => {+ return z.preprocess((data) => {+ if (data instanceof FormData) {+ const formData: Record<string, unknown> = {};++ for (const key of data.keys()) {+ const values = data.getAll(key);++ formData[key] = values.length > 1 ? values : values[0];+ }++ return formData;+ }++ return data;+ }, z.object(schema));+};diff --git a/packages/ui/components/document/document-dialog.tsx b/packages/ui/components/document/document-dialog.tsxdeleted file mode 100644index 5e039cbe4..000000000--- a/packages/ui/components/document/document-dialog.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { useState } from 'react';--import type { DocumentData } from '@prisma/client';-import * as DialogPrimitive from '@radix-ui/react-dialog';-import { X } from 'lucide-react';--import { cn } from '../../lib/utils';-import { Dialog, DialogOverlay, DialogPortal, DialogTrigger } from '../../primitives/dialog';-import PDFViewer from '../../primitives/pdf-viewer';--export type DocumentDialogProps = {- trigger?: React.ReactNode;- documentData: DocumentData;-} & Omit<DialogPrimitive.DialogProps, 'children'>;--/**- * A dialog which renders the provided document.- */-export default function DocumentDialog({ trigger, documentData, ...props }: DocumentDialogProps) {- const [documentLoaded, setDocumentLoaded] = useState(false);-- const onDocumentLoad = () => {- setDocumentLoaded(true);- };-- return (- <Dialog {...props}>- <DialogPortal>- <DialogOverlay className="bg-black/80" />-- {trigger && (- <DialogTrigger onClick={(e) => e.stopPropagation()} asChild={true}>- {trigger}- </DialogTrigger>- )}-- <DialogPrimitive.Content- className={cn(- 'animate-in data-[state=open]:fade-in-90 sm:zoom-in-90 pointer-events-none fixed z-50 h-screen w-screen overflow-y-auto px-2 py-14 opacity-0 transition-opacity lg:py-32',- {- 'opacity-100': documentLoaded,- },- )}- onClick={() => props.onOpenChange?.(false)}- >- <PDFViewer- className="mx-auto w-full max-w-3xl xl:max-w-5xl"- documentData={documentData}- onClick={(e) => e.stopPropagation()}- onDocumentLoad={onDocumentLoad}- />-- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none disabled:pointer-events-none">- <X className="h-6 w-6 text-white" />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- </DialogPrimitive.Content>- </DialogPortal>- </Dialog>- );-}diff --git a/packages/ui/components/document/document-download-button.tsx b/packages/ui/components/document/document-download-button.tsxdeleted file mode 100644index 51efefa96..000000000--- a/packages/ui/components/document/document-download-button.tsx+++ /dev/null@@ -1,69 +0,0 @@-import type { HTMLAttributes } from 'react';-import { useState } from 'react';--import { useLingui } from '@lingui/react';-import { Trans } from '@lingui/react/macro';-import type { DocumentData } from '@prisma/client';-import { Download } from 'lucide-react';--import { downloadPDF } from '@documenso/lib/client-only/download-pdf';-import { useToast } from '@documenso/ui/primitives/use-toast';--import { Button } from '../../primitives/button';--export type DownloadButtonProps = HTMLAttributes<HTMLButtonElement> & {- disabled?: boolean;- fileName?: string;- documentData?: DocumentData;-};--export const DocumentDownloadButton = ({- className,- fileName,- documentData,- disabled,- ...props-}: DownloadButtonProps) => {- const { _ } = useLingui();- const { toast } = useToast();-- const [isLoading, setIsLoading] = useState(false);-- const onDownloadClick = async () => {- try {- setIsLoading(true);-- if (!documentData) {- setIsLoading(false);- return;- }-- await downloadPDF({ documentData, fileName }).then(() => {- setIsLoading(false);- });- } catch (err) {- setIsLoading(false);-- toast({- title: _('Something went wrong'),- description: _('An error occurred while downloading your document.'),- variant: 'destructive',- });- }- };-- return (- <Button- type="button"- variant="outline"- className={className}- disabled={disabled || !documentData}- onClick={onDownloadClick}- loading={isLoading}- {...props}- >- {!isLoading && <Download className="mr-2 h-5 w-5" />}- <Trans>Download</Trans>- </Button>- );-};diff --git a/packages/ui/components/document/envelope-recipient-field-tooltip.tsx b/packages/ui/components/document/envelope-recipient-field-tooltip.tsxnew file mode 100644index 000000000..323f83e03--- /dev/null+++ b/packages/ui/components/document/envelope-recipient-field-tooltip.tsx@@ -0,0 +1,189 @@+import { useCallback, useEffect, useState } from 'react';++import { Trans, useLingui } from '@lingui/react/macro';+import { SigningStatus } from '@prisma/client';+import type { Field, Recipient } from '@prisma/client';+import { ClockIcon, EyeOffIcon } from 'lucide-react';++import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-client-rect';+import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';++import { isTemplateRecipientEmailPlaceholder } from '../../../lib/constants/template';+import { extractInitials } from '../../../lib/utils/recipient-formatter';+import { SignatureIcon } from '../../icons/signature';+import { cn } from '../../lib/utils';+import { Avatar, AvatarFallback } from '../../primitives/avatar';+import { Badge } from '../../primitives/badge';+import { FRIENDLY_FIELD_TYPE } from '../../primitives/document-flow/types';+import { PopoverHover } from '../../primitives/popover';++interface EnvelopeRecipientFieldTooltipProps {+ field: Pick<+ Field,+ 'id' | 'inserted' | 'positionX' | 'positionY' | 'width' | 'height' | 'page' | 'type'+ > & {+ recipient: Pick<Recipient, 'name' | 'email' | 'signingStatus'>;+ };+ showFieldStatus?: boolean;+ showRecipientTooltip?: boolean;+ showRecipientColors?: boolean;+}++const getRecipientDisplayText = (recipient: { name: string; email: string }) => {+ if (recipient.name && !isTemplateRecipientEmailPlaceholder(recipient.email)) {+ return `${recipient.name} (${recipient.email})`;+ }++ if (recipient.name && isTemplateRecipientEmailPlaceholder(recipient.email)) {+ return recipient.name;+ }++ return recipient.email;+};++/**+ * Renders a tooltip for a given field.+ */+export function EnvelopeRecipientFieldTooltip({+ field,+ showFieldStatus = false,+ showRecipientTooltip = false,+ showRecipientColors = false,+}: EnvelopeRecipientFieldTooltipProps) {+ const { t } = useLingui();++ const [hideField, setHideField] = useState<boolean>(!showRecipientTooltip);++ const [coords, setCoords] = useState({+ x: 0,+ y: 0,+ height: 0,+ width: 0,+ });++ const calculateCoords = useCallback(() => {+ const $page = document.querySelector<HTMLElement>(+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.page}"]`,+ );++ if (!$page) {+ return;+ }++ const { height, width } = getBoundingClientRect($page);++ const fieldHeight = (Number(field.height) / 100) * height;+ const fieldWidth = (Number(field.width) / 100) * width;++ const fieldX = (Number(field.positionX) / 100) * width + Number(fieldWidth);+ const fieldY = (Number(field.positionY) / 100) * height;++ setCoords({+ x: fieldX,+ y: fieldY,+ height: fieldHeight,+ width: fieldWidth,+ });+ }, [field.height, field.page, field.positionX, field.positionY, field.width]);++ useEffect(() => {+ calculateCoords();+ }, [calculateCoords]);++ useEffect(() => {+ const onResize = () => {+ calculateCoords();+ };++ window.addEventListener('resize', onResize);++ return () => {+ window.removeEventListener('resize', onResize);+ };+ }, [calculateCoords]);++ useEffect(() => {+ const $page = document.querySelector<HTMLElement>(+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.page}"]`,+ );++ if (!$page) {+ return;+ }++ const observer = new ResizeObserver(() => {+ calculateCoords();+ });++ observer.observe($page);++ return () => {+ observer.disconnect();+ };+ }, [calculateCoords, field.page]);++ if (hideField) {+ return null;+ }++ return (+ <div+ id="field-recipient-tooltip"+ className={cn('absolute z-40')}+ style={{+ top: `${coords.y}px`,+ left: `${coords.x}px`,+ }}+ >+ <PopoverHover+ trigger={+ <Avatar className="absolute -left-3 -top-3 z-50 h-6 w-6 border-2 border-solid border-gray-200/50 transition-colors hover:border-gray-200">+ <AvatarFallback className="bg-neutral-50 text-xs text-gray-400">+ {extractInitials(field.recipient.name || field.recipient.email)}+ </AvatarFallback>+ </Avatar>+ }+ contentProps={{+ className: 'relative flex mb-4 w-fit flex-col p-4 text-sm',+ }}+ >+ {showFieldStatus && (+ <Badge+ className="mx-auto mb-1 py-0.5"+ variant={+ field.recipient.signingStatus === SigningStatus.SIGNED ? 'default' : 'secondary'+ }+ >+ {field.recipient.signingStatus === SigningStatus.SIGNED ? (+ <>+ <SignatureIcon className="mr-1 h-3 w-3" />+ <Trans>Signed</Trans>+ </>+ ) : (+ <>+ <ClockIcon className="mr-1 h-3 w-3" />+ <Trans>Pending</Trans>+ </>+ )}+ </Badge>+ )}++ <p className="text-center font-semibold">+ <span>{t(FRIENDLY_FIELD_TYPE[field.type])} field</span>+ </p>++ <p className="text-muted-foreground mt-1 text-center text-xs">+ {getRecipientDisplayText(field.recipient)}+ </p>++ <button+ className="absolute right-0 top-0 my-1 p-2 focus:outline-none focus-visible:ring-0"+ onClick={() => setHideField(true)}+ title="Hide field"+ >+ <EyeOffIcon className="h-3 w-3" />+ </button>+ </PopoverHover>+ </div>+ );+}diff --git a/packages/ui/components/pdf-viewer/pdf-viewer-konva-lazy.tsx b/packages/ui/components/pdf-viewer/pdf-viewer-konva-lazy.tsxindex 954bda37e..2d5d38658 100644--- a/packages/ui/components/pdf-viewer/pdf-viewer-konva-lazy.tsx+++ b/packages/ui/components/pdf-viewer/pdf-viewer-konva-lazy.tsx@@ -2,11 +2,14 @@ import React, { Suspense, lazy } from 'react';import { type PDFDocumentProxy } from 'pdfjs-dist';+import type { PdfViewerRendererMode } from './pdf-viewer-konva';+export type LoadedPDFDocument = PDFDocumentProxy;export type PDFViewerProps = {className?: string;onDocumentLoad?: () => void;+ renderer: PdfViewerRendererMode;[key: string]: unknown;} & Omit<React.HTMLAttributes<HTMLDivElement>, 'onPageClick'>;diff --git a/packages/ui/components/pdf-viewer/pdf-viewer-konva.tsx b/packages/ui/components/pdf-viewer/pdf-viewer-konva.tsxindex 4dca7ae4c..1c0fc37a8 100644--- a/packages/ui/components/pdf-viewer/pdf-viewer-konva.tsx+++ b/packages/ui/components/pdf-viewer/pdf-viewer-konva.tsx@@ -1,6 +1,8 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Trans } from '@lingui/react/macro';+import type { MessageDescriptor } from '@lingui/core';+import { msg } from '@lingui/core/macro';+import { Trans, useLingui } from '@lingui/react/macro';import Konva from 'konva';import { Loader } from 'lucide-react';import { type PDFDocumentProxy } from 'pdfjs-dist';@@ -8,6 +10,7 @@ import { Document as PDFDocument, Page as PDFPage, pdfjs } from 'react-pdf';import { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/envelope-render-provider';import { cn } from '@documenso/ui/lib/utils';+import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';export type LoadedPDFDocument = PDFDocumentProxy;@@ -29,10 +32,31 @@ const PDFLoader = () => (</>);+export type PdfViewerRendererMode = 'editor' | 'preview' | 'signing';++const RendererErrorMessages: Record<+ PdfViewerRendererMode,+ { title: MessageDescriptor; description: MessageDescriptor }+> = {+ editor: {+ title: msg`Configuration Error`,+ description: msg`There was an issue rendering some fields, please review the fields and try again.`,+ },+ preview: {+ title: msg`Configuration Error`,+ description: msg`Something went wrong while rendering the document, some fields may be missing or corrupted.`,+ },+ signing: {+ title: msg`Configuration Error`,+ description: msg`Something went wrong while rendering the document, some fields may be missing or corrupted.`,+ },+};+export type PdfViewerKonvaProps = {className?: string;onDocumentLoad?: () => void;customPageRenderer?: React.FunctionComponent;+ renderer: PdfViewerRendererMode;[key: string]: unknown;} & Omit<React.HTMLAttributes<HTMLDivElement>, 'onPageClick'>;@@ -40,18 +64,21 @@ export const PdfViewerKonva = ({className,onDocumentLoad,customPageRenderer,+ renderer,...props}: PdfViewerKonvaProps) => {+ const { t } = useLingui();+const $el = useRef<HTMLDivElement>(null);- const { getPdfBuffer, currentEnvelopeItem } = useCurrentEnvelopeRender();+ const { getPdfBuffer, currentEnvelopeItem, renderError } = useCurrentEnvelopeRender();const [width, setWidth] = useState(0);const [numPages, setNumPages] = useState(0);const [pdfError, setPdfError] = useState(false);const envelopeItemFile = useMemo(() => {- const data = getPdfBuffer(currentEnvelopeItem?.documentDataId || '');+ const data = getPdfBuffer(currentEnvelopeItem?.id || '');if (!data || data.status !== 'loaded') {return null;@@ -60,7 +87,7 @@ export const PdfViewerKonva = ({return {data: new Uint8Array(data.file),};- }, [currentEnvelopeItem?.documentDataId, getPdfBuffer]);+ }, [currentEnvelopeItem?.id, getPdfBuffer]);const onDocumentLoaded = useCallback((doc: PDFDocumentProxy) => {@@ -92,6 +119,13 @@ export const PdfViewerKonva = ({return (<div ref={$el} className={cn('w-full max-w-[800px]', className)} {...props}>+ {renderError && (+ <Alert variant="destructive" className="mb-4 max-w-[800px]">+ <AlertTitle>{t(RendererErrorMessages[renderer].title)}</AlertTitle>+ <AlertDescription>{t(RendererErrorMessages[renderer].description)}</AlertDescription>+ </Alert>+ )}+{envelopeItemFile && Konva ? (<PDFDocumentfile={envelopeItemFile}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 880308853..a79f845e5 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -78,6 +78,6 @@"tailwind-merge": "^1.12.0","tailwindcss-animate": "^1.0.5","ts-pattern": "^5.0.5",- "zod": "3.24.1"+ "zod": "^3.25.76"}}\ No newline at end of filediff --git a/packages/ui/primitives/combobox.tsx b/packages/ui/primitives/combobox.tsxindex 2f5bb6712..038b5f48a 100644--- a/packages/ui/primitives/combobox.tsx+++ b/packages/ui/primitives/combobox.tsx@@ -58,7 +58,7 @@ const Combobox = ({</Button></PopoverTrigger>- <PopoverContent className="p-0" side="bottom" align="start">+ <PopoverContent className="z-[1001] p-0" side="bottom" align="start"><Command><CommandInput placeholder={value || placeholderValue} />diff --git a/packages/ui/primitives/document-flow/field-items-advanced-settings/constants.ts b/packages/ui/primitives/document-flow/field-items-advanced-settings/constants.tsindex ebb8f38ae..c98da7451 100644--- a/packages/ui/primitives/document-flow/field-items-advanced-settings/constants.ts+++ b/packages/ui/primitives/document-flow/field-items-advanced-settings/constants.ts@@ -16,6 +16,12 @@ export const numberFormatValues = [},];+export enum CheckboxValidationRules {+ SELECT_AT_LEAST = 'Select at least',+ SELECT_EXACTLY = 'Select exactly',+ SELECT_AT_MOST = 'Select at most',+}+export const checkboxValidationRules = ['Select at least', 'Select exactly', 'Select at most'];export const checkboxValidationLength = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];export const checkboxValidationSigns = [diff --git a/packages/ui/primitives/document-upload.tsx b/packages/ui/primitives/document-upload.tsxindex 35d1d819d..b4c7daf95 100644--- a/packages/ui/primitives/document-upload.tsx+++ b/packages/ui/primitives/document-upload.tsx@@ -66,7 +66,7 @@ export const DocumentDropzone = ({const heading = {document: msg`Upload Document`,template: msg`Upload Template Document`,- envelope: msg`Envelope (beta)`,+ envelope: msg`Upload Envelope`,};if (disabled && IS_BILLING_ENABLED()) {diff --git a/packages/ui/primitives/pdf-viewer.tsx b/packages/ui/primitives/pdf-viewer.tsxindex 3bf8f0866..37b920f41 100644--- a/packages/ui/primitives/pdf-viewer.tsx+++ b/packages/ui/primitives/pdf-viewer.tsx@@ -1,9 +1,10 @@-import React, { useEffect, useMemo, useRef, useState } from 'react';+import React, { useEffect, useRef, useState } from 'react';import { msg } from '@lingui/core/macro';import { useLingui } from '@lingui/react';import { Trans } from '@lingui/react/macro';-import type { DocumentData } from '@prisma/client';+import type { EnvelopeItem } from '@prisma/client';+import { base64 } from '@scure/base';import { Loader } from 'lucide-react';import { type PDFDocumentProxy } from 'pdfjs-dist';import { Document as PDFDocument, Page as PDFPage, pdfjs } from 'react-pdf';@@ -11,7 +12,7 @@ import 'react-pdf/dist/esm/Page/AnnotationLayer.css';import 'react-pdf/dist/esm/Page/TextLayer.css';import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';-import { getFile } from '@documenso/lib/universal/upload/get-file';+import { getEnvelopeDownloadUrl } from '@documenso/lib/utils/envelope-download';import { cn } from '../lib/utils';import { useToast } from './use-toast';@@ -48,17 +49,23 @@ const PDFLoader = () => (export type PDFViewerProps = {className?: string;- documentData: Pick<DocumentData, 'type' | 'data'>;+ envelopeItem: Pick<EnvelopeItem, 'id' | 'envelopeId'>;+ token: string | undefined;+ version: 'original' | 'signed';onDocumentLoad?: (_doc: LoadedPDFDocument) => void;onPageClick?: OnPDFViewerPageClick;+ overrideData?: string;[key: string]: unknown;} & Omit<React.HTMLAttributes<HTMLDivElement>, 'onPageClick'>;export const PDFViewer = ({className,- documentData,+ envelopeItem,+ token,+ version,onDocumentLoad,onPageClick,+ overrideData,...props}: PDFViewerProps) => {const { _ } = useLingui();@@ -67,17 +74,14 @@ export const PDFViewer = ({const $el = useRef<HTMLDivElement>(null);const [isDocumentBytesLoading, setIsDocumentBytesLoading] = useState(false);- const [documentBytes, setDocumentBytes] = useState<Uint8Array | null>(null);+ const [documentBytes, setDocumentBytes] = useState<Uint8Array | null>(+ overrideData ? base64.decode(overrideData) : null,+ );const [width, setWidth] = useState(0);const [numPages, setNumPages] = useState(0);const [pdfError, setPdfError] = useState(false);- const memoizedData = useMemo(- () => ({ type: documentData.type, data: documentData.data }),- [documentData.data, documentData.type],- );-const isLoading = isDocumentBytesLoading || !documentBytes;const onDocumentLoaded = (doc: LoadedPDFDocument) => {@@ -142,13 +146,26 @@ export const PDFViewer = ({}, []);useEffect(() => {+ if (overrideData) {+ const bytes = base64.decode(overrideData);++ setDocumentBytes(bytes);+ return;+ }+const fetchDocumentBytes = async () => {try {setIsDocumentBytesLoading(true);- const bytes = await getFile(memoizedData);+ const documentUrl = getEnvelopeDownloadUrl({+ envelopeItem: envelopeItem,+ token,+ version,+ });++ const bytes = await fetch(documentUrl).then(async (res) => await res.arrayBuffer());- setDocumentBytes(bytes);+ setDocumentBytes(new Uint8Array(bytes));setIsDocumentBytesLoading(false);} catch (err) {@@ -163,7 +180,7 @@ export const PDFViewer = ({};void fetchDocumentBytes();- }, [memoizedData, toast]);+ }, [envelopeItem.envelopeId, envelopeItem.id, token, version, toast, overrideData]);return (<div ref={$el} className={cn('overflow-hidden', className)} {...props}>