mirror of
https://github.com/documenso/documenso.git
synced 2025-11-13 08:13:56 +10:00
feat: add document auth
This commit is contained in:
@ -161,6 +161,7 @@ export const SinglePlayerClient = () => {
|
|||||||
signingStatus: 'NOT_SIGNED',
|
signingStatus: 'NOT_SIGNED',
|
||||||
sendStatus: 'NOT_SENT',
|
sendStatus: 'NOT_SENT',
|
||||||
role: 'SIGNER',
|
role: 'SIGNER',
|
||||||
|
authOptions: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const onFileDrop = async (file: File) => {
|
const onFileDrop = async (file: File) => {
|
||||||
|
|||||||
@ -7,7 +7,6 @@ import { useRouter, useSearchParams } from 'next/navigation';
|
|||||||
import {
|
import {
|
||||||
type DocumentData,
|
type DocumentData,
|
||||||
type DocumentMeta,
|
type DocumentMeta,
|
||||||
DocumentStatus,
|
|
||||||
type Field,
|
type Field,
|
||||||
type Recipient,
|
type Recipient,
|
||||||
type User,
|
type User,
|
||||||
@ -18,12 +17,12 @@ import { cn } from '@documenso/ui/lib/utils';
|
|||||||
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
||||||
import { AddFieldsFormPartial } from '@documenso/ui/primitives/document-flow/add-fields';
|
import { AddFieldsFormPartial } from '@documenso/ui/primitives/document-flow/add-fields';
|
||||||
import type { TAddFieldsFormSchema } from '@documenso/ui/primitives/document-flow/add-fields.types';
|
import type { TAddFieldsFormSchema } from '@documenso/ui/primitives/document-flow/add-fields.types';
|
||||||
|
import { AddSettingsFormPartial } from '@documenso/ui/primitives/document-flow/add-settings';
|
||||||
|
import type { TAddSettingsFormSchema } from '@documenso/ui/primitives/document-flow/add-settings.types';
|
||||||
import { AddSignersFormPartial } from '@documenso/ui/primitives/document-flow/add-signers';
|
import { AddSignersFormPartial } from '@documenso/ui/primitives/document-flow/add-signers';
|
||||||
import type { TAddSignersFormSchema } from '@documenso/ui/primitives/document-flow/add-signers.types';
|
import type { TAddSignersFormSchema } from '@documenso/ui/primitives/document-flow/add-signers.types';
|
||||||
import { AddSubjectFormPartial } from '@documenso/ui/primitives/document-flow/add-subject';
|
import { AddSubjectFormPartial } from '@documenso/ui/primitives/document-flow/add-subject';
|
||||||
import type { TAddSubjectFormSchema } from '@documenso/ui/primitives/document-flow/add-subject.types';
|
import type { TAddSubjectFormSchema } from '@documenso/ui/primitives/document-flow/add-subject.types';
|
||||||
import { AddTitleFormPartial } from '@documenso/ui/primitives/document-flow/add-title';
|
|
||||||
import type { TAddTitleFormSchema } from '@documenso/ui/primitives/document-flow/add-title.types';
|
|
||||||
import { DocumentFlowFormContainer } from '@documenso/ui/primitives/document-flow/document-flow-root';
|
import { DocumentFlowFormContainer } from '@documenso/ui/primitives/document-flow/document-flow-root';
|
||||||
import type { DocumentFlowStep } from '@documenso/ui/primitives/document-flow/types';
|
import type { DocumentFlowStep } from '@documenso/ui/primitives/document-flow/types';
|
||||||
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
|
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
|
||||||
@ -43,8 +42,8 @@ export type EditDocumentFormProps = {
|
|||||||
documentRootPath: string;
|
documentRootPath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type EditDocumentStep = 'title' | 'signers' | 'fields' | 'subject';
|
type EditDocumentStep = 'settings' | 'signers' | 'fields' | 'subject';
|
||||||
const EditDocumentSteps: EditDocumentStep[] = ['title', 'signers', 'fields', 'subject'];
|
const EditDocumentSteps: EditDocumentStep[] = ['settings', 'signers', 'fields', 'subject'];
|
||||||
|
|
||||||
export const EditDocumentForm = ({
|
export const EditDocumentForm = ({
|
||||||
className,
|
className,
|
||||||
@ -62,7 +61,8 @@ export const EditDocumentForm = ({
|
|||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const team = useOptionalCurrentTeam();
|
const team = useOptionalCurrentTeam();
|
||||||
|
|
||||||
const { mutateAsync: addTitle } = trpc.document.setTitleForDocument.useMutation();
|
const { mutateAsync: setSettingsForDocument } =
|
||||||
|
trpc.document.setSettingsForDocument.useMutation();
|
||||||
const { mutateAsync: addFields } = trpc.field.addFields.useMutation();
|
const { mutateAsync: addFields } = trpc.field.addFields.useMutation();
|
||||||
const { mutateAsync: addSigners } = trpc.recipient.addSigners.useMutation();
|
const { mutateAsync: addSigners } = trpc.recipient.addSigners.useMutation();
|
||||||
const { mutateAsync: sendDocument } = trpc.document.sendDocument.useMutation();
|
const { mutateAsync: sendDocument } = trpc.document.sendDocument.useMutation();
|
||||||
@ -70,9 +70,9 @@ export const EditDocumentForm = ({
|
|||||||
trpc.document.setPasswordForDocument.useMutation();
|
trpc.document.setPasswordForDocument.useMutation();
|
||||||
|
|
||||||
const documentFlow: Record<EditDocumentStep, DocumentFlowStep> = {
|
const documentFlow: Record<EditDocumentStep, DocumentFlowStep> = {
|
||||||
title: {
|
settings: {
|
||||||
title: 'Add Title',
|
title: 'General',
|
||||||
description: 'Add the title to the document.',
|
description: 'Configure general settings for the document.',
|
||||||
stepIndex: 1,
|
stepIndex: 1,
|
||||||
},
|
},
|
||||||
signers: {
|
signers: {
|
||||||
@ -96,8 +96,7 @@ export const EditDocumentForm = ({
|
|||||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||||
const searchParamStep = searchParams?.get('step') as EditDocumentStep | undefined;
|
const searchParamStep = searchParams?.get('step') as EditDocumentStep | undefined;
|
||||||
|
|
||||||
let initialStep: EditDocumentStep =
|
let initialStep: EditDocumentStep = 'settings';
|
||||||
document.status === DocumentStatus.DRAFT ? 'title' : 'signers';
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
searchParamStep &&
|
searchParamStep &&
|
||||||
@ -110,13 +109,23 @@ export const EditDocumentForm = ({
|
|||||||
return initialStep;
|
return initialStep;
|
||||||
});
|
});
|
||||||
|
|
||||||
const onAddTitleFormSubmit = async (data: TAddTitleFormSchema) => {
|
const onAddSettingsFormSubmit = async (data: TAddSettingsFormSchema) => {
|
||||||
try {
|
try {
|
||||||
// Custom invocation server action
|
const { timezone, dateFormat, redirectUrl } = data.meta;
|
||||||
await addTitle({
|
|
||||||
|
await setSettingsForDocument({
|
||||||
documentId: document.id,
|
documentId: document.id,
|
||||||
teamId: team?.id,
|
teamId: team?.id,
|
||||||
title: data.title,
|
data: {
|
||||||
|
title: data.title,
|
||||||
|
globalAccessAuth: data.globalAccessAuth ?? null,
|
||||||
|
globalActionAuth: data.globalActionAuth ?? null,
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
timezone,
|
||||||
|
dateFormat,
|
||||||
|
redirectUrl,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@ -127,7 +136,7 @@ export const EditDocumentForm = ({
|
|||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: 'Error',
|
title: 'Error',
|
||||||
description: 'An error occurred while updating title.',
|
description: 'An error occurred while updating the general settings.',
|
||||||
variant: 'destructive',
|
variant: 'destructive',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -139,7 +148,11 @@ export const EditDocumentForm = ({
|
|||||||
await addSigners({
|
await addSigners({
|
||||||
documentId: document.id,
|
documentId: document.id,
|
||||||
teamId: team?.id,
|
teamId: team?.id,
|
||||||
signers: data.signers,
|
signers: data.signers.map((signer) => ({
|
||||||
|
...signer,
|
||||||
|
// Explicitly set to null to indicate we want to remove auth if required.
|
||||||
|
actionAuth: signer.actionAuth || null,
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
|
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@ -177,7 +190,7 @@ export const EditDocumentForm = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onAddSubjectFormSubmit = async (data: TAddSubjectFormSchema) => {
|
const onAddSubjectFormSubmit = async (data: TAddSubjectFormSchema) => {
|
||||||
const { subject, message, timezone, dateFormat, redirectUrl } = data.meta;
|
const { subject, message } = data.meta;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendDocument({
|
await sendDocument({
|
||||||
@ -186,9 +199,6 @@ export const EditDocumentForm = ({
|
|||||||
meta: {
|
meta: {
|
||||||
subject,
|
subject,
|
||||||
message,
|
message,
|
||||||
dateFormat,
|
|
||||||
timezone,
|
|
||||||
redirectUrl,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -245,23 +255,23 @@ export const EditDocumentForm = ({
|
|||||||
currentStep={currentDocumentFlow.stepIndex}
|
currentStep={currentDocumentFlow.stepIndex}
|
||||||
setCurrentStep={(step) => setStep(EditDocumentSteps[step - 1])}
|
setCurrentStep={(step) => setStep(EditDocumentSteps[step - 1])}
|
||||||
>
|
>
|
||||||
<AddTitleFormPartial
|
<AddSettingsFormPartial
|
||||||
key={recipients.length}
|
key={recipients.length}
|
||||||
documentFlow={documentFlow.title}
|
documentFlow={documentFlow.settings}
|
||||||
document={document}
|
document={document}
|
||||||
recipients={recipients}
|
recipients={recipients}
|
||||||
fields={fields}
|
fields={fields}
|
||||||
onSubmit={onAddTitleFormSubmit}
|
onSubmit={onAddSettingsFormSubmit}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<AddSignersFormPartial
|
<AddSignersFormPartial
|
||||||
key={recipients.length}
|
key={recipients.length}
|
||||||
documentFlow={documentFlow.signers}
|
documentFlow={documentFlow.signers}
|
||||||
document={document}
|
|
||||||
recipients={recipients}
|
recipients={recipients}
|
||||||
fields={fields}
|
fields={fields}
|
||||||
onSubmit={onAddSignersFormSubmit}
|
onSubmit={onAddSignersFormSubmit}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<AddFieldsFormPartial
|
<AddFieldsFormPartial
|
||||||
key={fields.length}
|
key={fields.length}
|
||||||
documentFlow={documentFlow.fields}
|
documentFlow={documentFlow.fields}
|
||||||
@ -269,6 +279,7 @@ export const EditDocumentForm = ({
|
|||||||
fields={fields}
|
fields={fields}
|
||||||
onSubmit={onAddFieldsFormSubmit}
|
onSubmit={onAddFieldsFormSubmit}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<AddSubjectFormPartial
|
<AddSubjectFormPartial
|
||||||
key={recipients.length}
|
key={recipients.length}
|
||||||
documentFlow={documentFlow.subject}
|
documentFlow={documentFlow.subject}
|
||||||
|
|||||||
@ -6,7 +6,9 @@ import { getServerSession } from 'next-auth';
|
|||||||
import { match } from 'ts-pattern';
|
import { match } from 'ts-pattern';
|
||||||
|
|
||||||
import signingCelebration from '@documenso/assets/images/signing-celebration.png';
|
import signingCelebration from '@documenso/assets/images/signing-celebration.png';
|
||||||
|
import { getServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
|
||||||
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
|
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
|
||||||
|
import { isRecipientAuthorized } from '@documenso/lib/server-only/document/is-recipient-authorized';
|
||||||
import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';
|
import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';
|
||||||
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
|
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
|
||||||
import { getRecipientSignatures } from '@documenso/lib/server-only/recipient/get-recipient-signatures';
|
import { getRecipientSignatures } from '@documenso/lib/server-only/recipient/get-recipient-signatures';
|
||||||
@ -17,6 +19,7 @@ import { SigningCard3D } from '@documenso/ui/components/signing-card';
|
|||||||
|
|
||||||
import { truncateTitle } from '~/helpers/truncate-title';
|
import { truncateTitle } from '~/helpers/truncate-title';
|
||||||
|
|
||||||
|
import { SigningAuthPageView } from '../signing-auth-page';
|
||||||
import { DocumentPreviewButton } from './document-preview-button';
|
import { DocumentPreviewButton } from './document-preview-button';
|
||||||
|
|
||||||
export type CompletedSigningPageProps = {
|
export type CompletedSigningPageProps = {
|
||||||
@ -32,8 +35,11 @@ export default async function CompletedSigningPage({
|
|||||||
return notFound();
|
return notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { user } = await getServerComponentSession();
|
||||||
|
|
||||||
const document = await getDocumentAndSenderByToken({
|
const document = await getDocumentAndSenderByToken({
|
||||||
token,
|
token,
|
||||||
|
requireAccessAuth: false,
|
||||||
}).catch(() => null);
|
}).catch(() => null);
|
||||||
|
|
||||||
if (!document || !document.documentData) {
|
if (!document || !document.documentData) {
|
||||||
@ -53,6 +59,17 @@ export default async function CompletedSigningPage({
|
|||||||
return notFound();
|
return notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isDocumentAccessValid = await isRecipientAuthorized({
|
||||||
|
type: 'ACCESS',
|
||||||
|
document,
|
||||||
|
recipient,
|
||||||
|
userId: user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isDocumentAccessValid) {
|
||||||
|
return <SigningAuthPageView email={recipient.email} />;
|
||||||
|
}
|
||||||
|
|
||||||
const signatures = await getRecipientSignatures({ recipientId: recipient.id });
|
const signatures = await getRecipientSignatures({ recipientId: recipient.id });
|
||||||
|
|
||||||
const recipientName =
|
const recipientName =
|
||||||
|
|||||||
@ -11,6 +11,8 @@ import {
|
|||||||
convertToLocalSystemFormat,
|
convertToLocalSystemFormat,
|
||||||
} from '@documenso/lib/constants/date-formats';
|
} from '@documenso/lib/constants/date-formats';
|
||||||
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
||||||
|
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { Recipient } from '@documenso/prisma/client';
|
import type { Recipient } from '@documenso/prisma/client';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -53,16 +55,23 @@ export const DateField = ({
|
|||||||
|
|
||||||
const tooltipText = `"${field.customText}" will appear on the document as it has a timezone of "${timezone}".`;
|
const tooltipText = `"${field.customText}" will appear on the document as it has a timezone of "${timezone}".`;
|
||||||
|
|
||||||
const onSign = async () => {
|
const onSign = async (authOptions?: TRecipientActionAuth) => {
|
||||||
try {
|
try {
|
||||||
await signFieldWithToken({
|
await signFieldWithToken({
|
||||||
token: recipient.token,
|
token: recipient.token,
|
||||||
fieldId: field.id,
|
fieldId: field.id,
|
||||||
value: dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
|
value: dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
startTransition(() => router.refresh());
|
startTransition(() => router.refresh());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const error = AppError.parseError(err);
|
||||||
|
|
||||||
|
if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
|
|||||||
@ -0,0 +1,248 @@
|
|||||||
|
/**
|
||||||
|
* Note: This file has some commented out stuff for password auth which is no longer possible.
|
||||||
|
*
|
||||||
|
* Leaving it here until after we add passkeys and 2FA since it can be reused.
|
||||||
|
*/
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
import { DateTime } from 'luxon';
|
||||||
|
import { signOut } from 'next-auth/react';
|
||||||
|
import { match } from 'ts-pattern';
|
||||||
|
|
||||||
|
import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
|
||||||
|
import {
|
||||||
|
DocumentAuth,
|
||||||
|
type TRecipientActionAuth,
|
||||||
|
type TRecipientActionAuthTypes,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
|
import { trpc } from '@documenso/trpc/react';
|
||||||
|
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||||
|
import { Button } from '@documenso/ui/primitives/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@documenso/ui/primitives/dialog';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
|
|
||||||
|
export type DocumentActionAuthDialogProps = {
|
||||||
|
title?: string;
|
||||||
|
documentAuthType: TRecipientActionAuthTypes;
|
||||||
|
description?: string;
|
||||||
|
actionTarget?: 'FIELD' | 'DOCUMENT';
|
||||||
|
isSubmitting?: boolean;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (value: boolean) => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The callback to run when the reauth form is filled out.
|
||||||
|
*/
|
||||||
|
onReauthFormSubmit: (values?: TRecipientActionAuth) => Promise<void> | void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// const ZReauthFormSchema = z.object({
|
||||||
|
// password: ZCurrentPasswordSchema,
|
||||||
|
// });
|
||||||
|
// type TReauthFormSchema = z.infer<typeof ZReauthFormSchema>;
|
||||||
|
|
||||||
|
export const DocumentActionAuthDialog = ({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
documentAuthType,
|
||||||
|
actionTarget = 'FIELD',
|
||||||
|
// onReauthFormSubmit,
|
||||||
|
isSubmitting,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: DocumentActionAuthDialogProps) => {
|
||||||
|
const { recipient } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
|
// const form = useForm({
|
||||||
|
// resolver: zodResolver(ZReauthFormSchema),
|
||||||
|
// defaultValues: {
|
||||||
|
// password: '',
|
||||||
|
// },
|
||||||
|
// });
|
||||||
|
|
||||||
|
const [isSigningOut, setIsSigningOut] = useState(false);
|
||||||
|
|
||||||
|
const isLoading = isSigningOut || isSubmitting; // || form.formState.isSubmitting;
|
||||||
|
|
||||||
|
const { mutateAsync: encryptSecondaryData } = trpc.crypto.encryptSecondaryData.useMutation();
|
||||||
|
|
||||||
|
// const [formErrorCode, setFormErrorCode] = useState<string | null>(null);
|
||||||
|
// const onFormSubmit = async (_values: TReauthFormSchema) => {
|
||||||
|
// const documentAuthValue: TRecipientActionAuth = match(documentAuthType)
|
||||||
|
// // Todo: Add passkey.
|
||||||
|
// // .with(DocumentAuthType.PASSKEY, (type) => ({
|
||||||
|
// // type,
|
||||||
|
// // value,
|
||||||
|
// // }))
|
||||||
|
// .otherwise((type) => ({
|
||||||
|
// type,
|
||||||
|
// }));
|
||||||
|
|
||||||
|
// try {
|
||||||
|
// await onReauthFormSubmit(documentAuthValue);
|
||||||
|
|
||||||
|
// onOpenChange(false);
|
||||||
|
// } catch (e) {
|
||||||
|
// const error = AppError.parseError(e);
|
||||||
|
// setFormErrorCode(error.code);
|
||||||
|
|
||||||
|
// // Suppress unauthorized errors since it's handled in this component.
|
||||||
|
// if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// throw error;
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
|
const handleChangeAccount = async (email: string) => {
|
||||||
|
try {
|
||||||
|
setIsSigningOut(true);
|
||||||
|
|
||||||
|
const encryptedEmail = await encryptSecondaryData({
|
||||||
|
data: email,
|
||||||
|
expiresAt: DateTime.now().plus({ days: 1 }).toMillis(),
|
||||||
|
});
|
||||||
|
|
||||||
|
await signOut({
|
||||||
|
callbackUrl: `/signin?email=${encodeURIComponent(encryptedEmail)}`,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
setIsSigningOut(false);
|
||||||
|
|
||||||
|
// Todo: Alert.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOnOpenChange = (value: boolean) => {
|
||||||
|
if (isLoading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onOpenChange(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
// useEffect(() => {
|
||||||
|
// form.reset();
|
||||||
|
// setFormErrorCode(null);
|
||||||
|
// }, [open, form]);
|
||||||
|
|
||||||
|
const defaultRecipientActionVerb = RECIPIENT_ROLES_DESCRIPTION[recipient.role].actionVerb;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOnOpenChange}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{title || `${defaultRecipientActionVerb} ${actionTarget.toLowerCase()}`}
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogDescription>
|
||||||
|
{description ||
|
||||||
|
`Reauthentication is required to ${defaultRecipientActionVerb.toLowerCase()} the ${actionTarget.toLowerCase()}`}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{match(documentAuthType)
|
||||||
|
.with(DocumentAuth.ACCOUNT, () => (
|
||||||
|
<fieldset disabled={isSigningOut} className="space-y-4">
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>
|
||||||
|
To {defaultRecipientActionVerb.toLowerCase()} this {actionTarget.toLowerCase()},
|
||||||
|
you need to be logged in as <strong>{recipient.email}</strong>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
onClick={async () => handleChangeAccount(recipient.email)}
|
||||||
|
loading={isSigningOut}
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</fieldset>
|
||||||
|
))
|
||||||
|
.with(DocumentAuth.EXPLICIT_NONE, () => null)
|
||||||
|
.exhaustive()}
|
||||||
|
|
||||||
|
{/* <Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onFormSubmit)}>
|
||||||
|
<fieldset className="flex h-full flex-col space-y-4" disabled={isLoading}>
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel required>Email</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Input className="bg-background" value={recipient.email} disabled />
|
||||||
|
</FormControl>
|
||||||
|
</FormItem>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="password"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel required>Password</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<PasswordInput className="bg-background" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{formErrorCode && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
{match(formErrorCode)
|
||||||
|
.with(AppErrorCode.UNAUTHORIZED, () => (
|
||||||
|
<>
|
||||||
|
<AlertTitle>Unauthorized</AlertTitle>
|
||||||
|
<AlertDescription>
|
||||||
|
We were unable to verify your details. Please ensure the details are
|
||||||
|
correct
|
||||||
|
</AlertDescription>
|
||||||
|
</>
|
||||||
|
))
|
||||||
|
.otherwise(() => (
|
||||||
|
<>
|
||||||
|
<AlertTitle>Something went wrong</AlertTitle>
|
||||||
|
<AlertDescription>
|
||||||
|
We were unable to sign this field at this time. Please try again or
|
||||||
|
contact support.
|
||||||
|
</AlertDescription>
|
||||||
|
</>
|
||||||
|
))}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button type="submit" loading={isLoading}>
|
||||||
|
Sign field
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</Form> */}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
};
|
||||||
@ -0,0 +1,168 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { createContext, useContext, useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
import { match } from 'ts-pattern';
|
||||||
|
|
||||||
|
import { DOCUMENT_AUTH_TYPES } from '@documenso/lib/constants/document-auth';
|
||||||
|
import type {
|
||||||
|
TDocumentAuthOptions,
|
||||||
|
TRecipientAccessAuthTypes,
|
||||||
|
TRecipientActionAuthTypes,
|
||||||
|
TRecipientAuthOptions,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
|
import { DocumentAuth } from '@documenso/lib/types/document-auth';
|
||||||
|
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
|
||||||
|
import type { Document, Recipient, User } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import type { DocumentActionAuthDialogProps } from './document-action-auth-dialog';
|
||||||
|
import { DocumentActionAuthDialog } from './document-action-auth-dialog';
|
||||||
|
|
||||||
|
export type DocumentAuthContextValue = {
|
||||||
|
executeActionAuthProcedure: (_value: ExecuteActionAuthProcedureOptions) => Promise<void>;
|
||||||
|
document: Document;
|
||||||
|
documentAuthOption: TDocumentAuthOptions;
|
||||||
|
setDocument: (_value: Document) => void;
|
||||||
|
recipient: Recipient;
|
||||||
|
recipientAuthOption: TRecipientAuthOptions;
|
||||||
|
setRecipient: (_value: Recipient) => void;
|
||||||
|
derivedRecipientAccessAuth: TRecipientAccessAuthTypes | null;
|
||||||
|
derivedRecipientActionAuth: TRecipientActionAuthTypes | null;
|
||||||
|
isAuthRedirectRequired: boolean;
|
||||||
|
user?: User | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DocumentAuthContext = createContext<DocumentAuthContextValue | null>(null);
|
||||||
|
|
||||||
|
export const useDocumentAuthContext = () => {
|
||||||
|
return useContext(DocumentAuthContext);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useRequiredDocumentAuthContext = () => {
|
||||||
|
const context = useDocumentAuthContext();
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('Document auth context is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
return context;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DocumentAuthProviderProps {
|
||||||
|
document: Document;
|
||||||
|
recipient: Recipient;
|
||||||
|
user?: User | null;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DocumentAuthProvider = ({
|
||||||
|
document: initialDocument,
|
||||||
|
recipient: initialRecipient,
|
||||||
|
user,
|
||||||
|
children,
|
||||||
|
}: DocumentAuthProviderProps) => {
|
||||||
|
const [document, setDocument] = useState(initialDocument);
|
||||||
|
const [recipient, setRecipient] = useState(initialRecipient);
|
||||||
|
|
||||||
|
const {
|
||||||
|
documentAuthOption,
|
||||||
|
recipientAuthOption,
|
||||||
|
derivedRecipientAccessAuth,
|
||||||
|
derivedRecipientActionAuth,
|
||||||
|
} = useMemo(
|
||||||
|
() =>
|
||||||
|
extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
recipientAuth: recipient.authOptions,
|
||||||
|
}),
|
||||||
|
[document, recipient],
|
||||||
|
);
|
||||||
|
|
||||||
|
const [documentAuthDialogPayload, setDocumentAuthDialogPayload] =
|
||||||
|
useState<ExecuteActionAuthProcedureOptions | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pre calculated auth payload if the current user is authenticated correctly
|
||||||
|
* for the `derivedRecipientActionAuth`.
|
||||||
|
*
|
||||||
|
* Will be `null` if the user still requires authentication, or if they don't need
|
||||||
|
* authentication.
|
||||||
|
*/
|
||||||
|
const preCalculatedActionAuthOptions = match(derivedRecipientActionAuth)
|
||||||
|
.with(DocumentAuth.ACCOUNT, () => {
|
||||||
|
if (recipient.email !== user?.email) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: DocumentAuth.ACCOUNT,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.with(DocumentAuth.EXPLICIT_NONE, () => ({
|
||||||
|
type: DocumentAuth.EXPLICIT_NONE,
|
||||||
|
}))
|
||||||
|
.with(null, () => null)
|
||||||
|
.exhaustive();
|
||||||
|
|
||||||
|
const executeActionAuthProcedure = async (options: ExecuteActionAuthProcedureOptions) => {
|
||||||
|
// Directly run callback if no auth required.
|
||||||
|
if (!derivedRecipientActionAuth) {
|
||||||
|
await options.onReauthFormSubmit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run callback with precalculated auth options if avaliable.
|
||||||
|
if (preCalculatedActionAuthOptions) {
|
||||||
|
setDocumentAuthDialogPayload(null);
|
||||||
|
await options.onReauthFormSubmit(preCalculatedActionAuthOptions);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request the required auth from the user.
|
||||||
|
setDocumentAuthDialogPayload({
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const isAuthRedirectRequired = Boolean(
|
||||||
|
DOCUMENT_AUTH_TYPES[derivedRecipientActionAuth || '']?.isAuthRedirectRequired &&
|
||||||
|
!preCalculatedActionAuthOptions,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DocumentAuthContext.Provider
|
||||||
|
value={{
|
||||||
|
user,
|
||||||
|
document,
|
||||||
|
setDocument,
|
||||||
|
executeActionAuthProcedure,
|
||||||
|
recipient,
|
||||||
|
setRecipient,
|
||||||
|
documentAuthOption,
|
||||||
|
recipientAuthOption,
|
||||||
|
derivedRecipientAccessAuth,
|
||||||
|
derivedRecipientActionAuth,
|
||||||
|
isAuthRedirectRequired,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
|
||||||
|
{documentAuthDialogPayload && derivedRecipientActionAuth && (
|
||||||
|
<DocumentActionAuthDialog
|
||||||
|
open={true}
|
||||||
|
onOpenChange={() => setDocumentAuthDialogPayload(null)}
|
||||||
|
onReauthFormSubmit={documentAuthDialogPayload.onReauthFormSubmit}
|
||||||
|
actionTarget={documentAuthDialogPayload.actionTarget}
|
||||||
|
documentAuthType={derivedRecipientActionAuth}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</DocumentAuthContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
type ExecuteActionAuthProcedureOptions = Omit<
|
||||||
|
DocumentActionAuthDialogProps,
|
||||||
|
'open' | 'onOpenChange' | 'documentAuthType' | 'recipientRole'
|
||||||
|
>;
|
||||||
|
|
||||||
|
DocumentAuthProvider.displayName = 'DocumentAuthProvider';
|
||||||
@ -6,6 +6,8 @@ import { useRouter } from 'next/navigation';
|
|||||||
|
|
||||||
import { Loader } from 'lucide-react';
|
import { Loader } from 'lucide-react';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { Recipient } from '@documenso/prisma/client';
|
import type { Recipient } from '@documenso/prisma/client';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -38,17 +40,24 @@ export const EmailField = ({ field, recipient }: EmailFieldProps) => {
|
|||||||
|
|
||||||
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
|
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
|
||||||
|
|
||||||
const onSign = async () => {
|
const onSign = async (authOptions?: TRecipientActionAuth) => {
|
||||||
try {
|
try {
|
||||||
await signFieldWithToken({
|
await signFieldWithToken({
|
||||||
token: recipient.token,
|
token: recipient.token,
|
||||||
fieldId: field.id,
|
fieldId: field.id,
|
||||||
value: providedEmail ?? '',
|
value: providedEmail ?? '',
|
||||||
isBase64: false,
|
isBase64: false,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
startTransition(() => router.refresh());
|
startTransition(() => router.refresh());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const error = AppError.parseError(err);
|
||||||
|
|
||||||
|
if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
|
|||||||
@ -8,6 +8,7 @@ import { useSession } from 'next-auth/react';
|
|||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import { sortFieldsByPosition, validateFieldsInserted } from '@documenso/lib/utils/fields';
|
import { sortFieldsByPosition, validateFieldsInserted } from '@documenso/lib/utils/fields';
|
||||||
import { type Document, type Field, type Recipient, RecipientRole } from '@documenso/prisma/client';
|
import { type Document, type Field, type Recipient, RecipientRole } from '@documenso/prisma/client';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -19,6 +20,7 @@ import { Input } from '@documenso/ui/primitives/input';
|
|||||||
import { Label } from '@documenso/ui/primitives/label';
|
import { Label } from '@documenso/ui/primitives/label';
|
||||||
import { SignaturePad } from '@documenso/ui/primitives/signature-pad';
|
import { SignaturePad } from '@documenso/ui/primitives/signature-pad';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
import { useRequiredSigningContext } from './provider';
|
import { useRequiredSigningContext } from './provider';
|
||||||
import { SignDialog } from './sign-dialog';
|
import { SignDialog } from './sign-dialog';
|
||||||
|
|
||||||
@ -35,6 +37,7 @@ export const SigningForm = ({ document, recipient, fields, redirectUrl }: Signin
|
|||||||
const { data: session } = useSession();
|
const { data: session } = useSession();
|
||||||
|
|
||||||
const { fullName, signature, setFullName, setSignature } = useRequiredSigningContext();
|
const { fullName, signature, setFullName, setSignature } = useRequiredSigningContext();
|
||||||
|
const { executeActionAuthProcedure } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
const [validateUninsertedFields, setValidateUninsertedFields] = useState(false);
|
const [validateUninsertedFields, setValidateUninsertedFields] = useState(false);
|
||||||
|
|
||||||
@ -64,9 +67,17 @@ export const SigningForm = ({ document, recipient, fields, redirectUrl }: Signin
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: completeDocument,
|
||||||
|
actionTarget: 'DOCUMENT',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const completeDocument = async (authOptions?: TRecipientActionAuth) => {
|
||||||
await completeDocumentWithToken({
|
await completeDocumentWithToken({
|
||||||
token: recipient.token,
|
token: recipient.token,
|
||||||
documentId: document.id,
|
documentId: document.id,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
analytics.capture('App: Recipient has completed signing', {
|
analytics.capture('App: Recipient has completed signing', {
|
||||||
|
|||||||
@ -6,6 +6,8 @@ import { useRouter } from 'next/navigation';
|
|||||||
|
|
||||||
import { Loader } from 'lucide-react';
|
import { Loader } from 'lucide-react';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { Recipient } from '@documenso/prisma/client';
|
import type { Recipient } from '@documenso/prisma/client';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -15,6 +17,7 @@ import { Input } from '@documenso/ui/primitives/input';
|
|||||||
import { Label } from '@documenso/ui/primitives/label';
|
import { Label } from '@documenso/ui/primitives/label';
|
||||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
import { useRequiredSigningContext } from './provider';
|
import { useRequiredSigningContext } from './provider';
|
||||||
import { SigningFieldContainer } from './signing-field-container';
|
import { SigningFieldContainer } from './signing-field-container';
|
||||||
|
|
||||||
@ -31,6 +34,8 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
|
|||||||
const { fullName: providedFullName, setFullName: setProvidedFullName } =
|
const { fullName: providedFullName, setFullName: setProvidedFullName } =
|
||||||
useRequiredSigningContext();
|
useRequiredSigningContext();
|
||||||
|
|
||||||
|
const { executeActionAuthProcedure } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
||||||
@ -46,9 +51,32 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
|
|||||||
const [showFullNameModal, setShowFullNameModal] = useState(false);
|
const [showFullNameModal, setShowFullNameModal] = useState(false);
|
||||||
const [localFullName, setLocalFullName] = useState('');
|
const [localFullName, setLocalFullName] = useState('');
|
||||||
|
|
||||||
const onSign = async (source: 'local' | 'provider' = 'provider') => {
|
const onPreSign = () => {
|
||||||
|
if (!providedFullName) {
|
||||||
|
setShowFullNameModal(true);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the user clicks the sign button in the dialog where they enter their full name.
|
||||||
|
*/
|
||||||
|
const onDialogSignClick = () => {
|
||||||
|
setShowFullNameModal(false);
|
||||||
|
setProvidedFullName(localFullName);
|
||||||
|
|
||||||
|
void executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: async (authOptions) => await onSign(authOptions, localFullName),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSign = async (authOptions?: TRecipientActionAuth, name?: string) => {
|
||||||
try {
|
try {
|
||||||
if (!providedFullName && !localFullName) {
|
const value = name || providedFullName;
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
setShowFullNameModal(true);
|
setShowFullNameModal(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -56,18 +84,19 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
|
|||||||
await signFieldWithToken({
|
await signFieldWithToken({
|
||||||
token: recipient.token,
|
token: recipient.token,
|
||||||
fieldId: field.id,
|
fieldId: field.id,
|
||||||
value: source === 'local' && localFullName ? localFullName : providedFullName ?? '',
|
value,
|
||||||
isBase64: false,
|
isBase64: false,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (source === 'local' && !providedFullName) {
|
|
||||||
setProvidedFullName(localFullName);
|
|
||||||
}
|
|
||||||
|
|
||||||
setLocalFullName('');
|
|
||||||
|
|
||||||
startTransition(() => router.refresh());
|
startTransition(() => router.refresh());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const error = AppError.parseError(err);
|
||||||
|
|
||||||
|
if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
@ -98,7 +127,13 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Name">
|
<SigningFieldContainer
|
||||||
|
field={field}
|
||||||
|
onPreSign={onPreSign}
|
||||||
|
onSign={onSign}
|
||||||
|
onRemove={onRemove}
|
||||||
|
type="Name"
|
||||||
|
>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
||||||
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
||||||
@ -147,10 +182,7 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
|
|||||||
type="button"
|
type="button"
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
disabled={!localFullName}
|
disabled={!localFullName}
|
||||||
onClick={() => {
|
onClick={() => onDialogSignClick()}
|
||||||
setShowFullNameModal(false);
|
|
||||||
void onSign('local');
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Sign
|
Sign
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -1,35 +1,24 @@
|
|||||||
import { headers } from 'next/headers';
|
import { headers } from 'next/headers';
|
||||||
import { notFound, redirect } from 'next/navigation';
|
import { notFound, redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { match } from 'ts-pattern';
|
|
||||||
|
|
||||||
import { DOCUMENSO_ENCRYPTION_KEY } from '@documenso/lib/constants/crypto';
|
import { DOCUMENSO_ENCRYPTION_KEY } from '@documenso/lib/constants/crypto';
|
||||||
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
|
||||||
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
|
|
||||||
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
|
||||||
import { getServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
|
import { getServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
|
||||||
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
|
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
|
||||||
|
import { isRecipientAuthorized } from '@documenso/lib/server-only/document/is-recipient-authorized';
|
||||||
import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';
|
import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';
|
||||||
import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';
|
import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';
|
||||||
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
|
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
|
||||||
import { getRecipientSignatures } from '@documenso/lib/server-only/recipient/get-recipient-signatures';
|
import { getRecipientSignatures } from '@documenso/lib/server-only/recipient/get-recipient-signatures';
|
||||||
import { symmetricDecrypt } from '@documenso/lib/universal/crypto';
|
import { symmetricDecrypt } from '@documenso/lib/universal/crypto';
|
||||||
import { extractNextHeaderRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
import { extractNextHeaderRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
||||||
import { DocumentStatus, FieldType, RecipientRole, SigningStatus } from '@documenso/prisma/client';
|
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
|
||||||
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
import { DocumentStatus, SigningStatus } from '@documenso/prisma/client';
|
||||||
import { ElementVisible } from '@documenso/ui/primitives/element-visible';
|
|
||||||
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
|
|
||||||
|
|
||||||
import { truncateTitle } from '~/helpers/truncate-title';
|
import { DocumentAuthProvider } from './document-auth-provider';
|
||||||
|
|
||||||
import { DateField } from './date-field';
|
|
||||||
import { EmailField } from './email-field';
|
|
||||||
import { SigningForm } from './form';
|
|
||||||
import { NameField } from './name-field';
|
|
||||||
import { NoLongerAvailable } from './no-longer-available';
|
import { NoLongerAvailable } from './no-longer-available';
|
||||||
import { SigningProvider } from './provider';
|
import { SigningProvider } from './provider';
|
||||||
import { SignatureField } from './signature-field';
|
import { SigningAuthPageView } from './signing-auth-page';
|
||||||
import { TextField } from './text-field';
|
import { SigningPageView } from './signing-page-view';
|
||||||
|
|
||||||
export type SigningPageProps = {
|
export type SigningPageProps = {
|
||||||
params: {
|
params: {
|
||||||
@ -42,6 +31,8 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
|
|||||||
return notFound();
|
return notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { user } = await getServerComponentSession();
|
||||||
|
|
||||||
const requestHeaders = Object.fromEntries(headers().entries());
|
const requestHeaders = Object.fromEntries(headers().entries());
|
||||||
|
|
||||||
const requestMetadata = extractNextHeaderRequestMetadata(requestHeaders);
|
const requestMetadata = extractNextHeaderRequestMetadata(requestHeaders);
|
||||||
@ -49,21 +40,40 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
|
|||||||
const [document, fields, recipient] = await Promise.all([
|
const [document, fields, recipient] = await Promise.all([
|
||||||
getDocumentAndSenderByToken({
|
getDocumentAndSenderByToken({
|
||||||
token,
|
token,
|
||||||
|
userId: user?.id,
|
||||||
|
requireAccessAuth: false,
|
||||||
}).catch(() => null),
|
}).catch(() => null),
|
||||||
getFieldsForToken({ token }),
|
getFieldsForToken({ token }),
|
||||||
getRecipientByToken({ token }).catch(() => null),
|
getRecipientByToken({ token }).catch(() => null),
|
||||||
viewedDocument({ token, requestMetadata }).catch(() => null),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!document || !document.documentData || !recipient) {
|
if (!document || !document.documentData || !recipient) {
|
||||||
return notFound();
|
return notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
const truncatedTitle = truncateTitle(document.title);
|
const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
recipientAuth: recipient.authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
const { documentData, documentMeta } = document;
|
const isDocumentAccessValid = await isRecipientAuthorized({
|
||||||
|
type: 'ACCESS',
|
||||||
|
document,
|
||||||
|
recipient,
|
||||||
|
userId: user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
const { user } = await getServerComponentSession();
|
if (!isDocumentAccessValid) {
|
||||||
|
return <SigningAuthPageView email={recipient.email} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
await viewedDocument({
|
||||||
|
token,
|
||||||
|
requestMetadata,
|
||||||
|
recipientAccessAuth: derivedRecipientAccessAuth,
|
||||||
|
}).catch(() => null);
|
||||||
|
|
||||||
|
const { documentMeta } = document;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
document.status === DocumentStatus.COMPLETED ||
|
document.status === DocumentStatus.COMPLETED ||
|
||||||
@ -109,73 +119,9 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
|
|||||||
fullName={user?.email === recipient.email ? user.name : recipient.name}
|
fullName={user?.email === recipient.email ? user.name : recipient.name}
|
||||||
signature={user?.email === recipient.email ? user.signature : undefined}
|
signature={user?.email === recipient.email ? user.signature : undefined}
|
||||||
>
|
>
|
||||||
<div className="mx-auto w-full max-w-screen-xl">
|
<DocumentAuthProvider document={document} recipient={recipient} user={user}>
|
||||||
<h1 className="mt-4 truncate text-2xl font-semibold md:text-3xl" title={document.title}>
|
<SigningPageView recipient={recipient} document={document} fields={fields} />
|
||||||
{truncatedTitle}
|
</DocumentAuthProvider>
|
||||||
</h1>
|
|
||||||
|
|
||||||
<div className="mt-2.5 flex items-center gap-x-6">
|
|
||||||
<p className="text-muted-foreground">
|
|
||||||
{document.User.name} ({document.User.email}) has invited you to{' '}
|
|
||||||
{recipient.role === RecipientRole.VIEWER && 'view'}
|
|
||||||
{recipient.role === RecipientRole.SIGNER && 'sign'}
|
|
||||||
{recipient.role === RecipientRole.APPROVER && 'approve'} this document.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-8 grid grid-cols-12 gap-y-8 lg:gap-x-8 lg:gap-y-0">
|
|
||||||
<Card
|
|
||||||
className="col-span-12 rounded-xl before:rounded-xl lg:col-span-7 xl:col-span-8"
|
|
||||||
gradient
|
|
||||||
>
|
|
||||||
<CardContent className="p-2">
|
|
||||||
<LazyPDFViewer
|
|
||||||
key={documentData.id}
|
|
||||||
documentData={documentData}
|
|
||||||
document={document}
|
|
||||||
password={documentMeta?.password}
|
|
||||||
/>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="col-span-12 lg:col-span-5 xl:col-span-4">
|
|
||||||
<SigningForm
|
|
||||||
document={document}
|
|
||||||
recipient={recipient}
|
|
||||||
fields={fields}
|
|
||||||
redirectUrl={documentMeta?.redirectUrl}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ElementVisible target={PDF_VIEWER_PAGE_SELECTOR}>
|
|
||||||
{fields.map((field) =>
|
|
||||||
match(field.type)
|
|
||||||
.with(FieldType.SIGNATURE, () => (
|
|
||||||
<SignatureField key={field.id} field={field} recipient={recipient} />
|
|
||||||
))
|
|
||||||
.with(FieldType.NAME, () => (
|
|
||||||
<NameField key={field.id} field={field} recipient={recipient} />
|
|
||||||
))
|
|
||||||
.with(FieldType.DATE, () => (
|
|
||||||
<DateField
|
|
||||||
key={field.id}
|
|
||||||
field={field}
|
|
||||||
recipient={recipient}
|
|
||||||
dateFormat={documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT}
|
|
||||||
timezone={documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
.with(FieldType.EMAIL, () => (
|
|
||||||
<EmailField key={field.id} field={field} recipient={recipient} />
|
|
||||||
))
|
|
||||||
.with(FieldType.TEXT, () => (
|
|
||||||
<TextField key={field.id} field={field} recipient={recipient} />
|
|
||||||
))
|
|
||||||
.otherwise(() => null),
|
|
||||||
)}
|
|
||||||
</ElementVisible>
|
|
||||||
</div>
|
|
||||||
</SigningProvider>
|
</SigningProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,6 +12,8 @@ import {
|
|||||||
|
|
||||||
import { truncateTitle } from '~/helpers/truncate-title';
|
import { truncateTitle } from '~/helpers/truncate-title';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
|
|
||||||
export type SignDialogProps = {
|
export type SignDialogProps = {
|
||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
document: Document;
|
document: Document;
|
||||||
@ -29,12 +31,33 @@ export const SignDialog = ({
|
|||||||
onSignatureComplete,
|
onSignatureComplete,
|
||||||
role,
|
role,
|
||||||
}: SignDialogProps) => {
|
}: SignDialogProps) => {
|
||||||
|
const { executeActionAuthProcedure, isAuthRedirectRequired } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
const [showDialog, setShowDialog] = useState(false);
|
const [showDialog, setShowDialog] = useState(false);
|
||||||
const truncatedTitle = truncateTitle(document.title);
|
const truncatedTitle = truncateTitle(document.title);
|
||||||
const isComplete = fields.every((field) => field.inserted);
|
const isComplete = fields.every((field) => field.inserted);
|
||||||
|
|
||||||
|
const handleOpenChange = async (open: boolean) => {
|
||||||
|
if (isSubmitting || !isComplete) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAuthRedirectRequired) {
|
||||||
|
await executeActionAuthProcedure({
|
||||||
|
actionTarget: 'DOCUMENT',
|
||||||
|
onReauthFormSubmit: () => {
|
||||||
|
// Do nothing since the user should be redirected.
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowDialog(open);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={showDialog && isComplete} onOpenChange={setShowDialog}>
|
<Dialog open={showDialog} onOpenChange={handleOpenChange}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
|||||||
@ -1,11 +1,13 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useMemo, useState, useTransition } from 'react';
|
import { useMemo, useState, useTransition } from 'react';
|
||||||
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { Loader } from 'lucide-react';
|
import { Loader } from 'lucide-react';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { Recipient } from '@documenso/prisma/client';
|
import type { Recipient } from '@documenso/prisma/client';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -15,6 +17,7 @@ import { Label } from '@documenso/ui/primitives/label';
|
|||||||
import { SignaturePad } from '@documenso/ui/primitives/signature-pad';
|
import { SignaturePad } from '@documenso/ui/primitives/signature-pad';
|
||||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
import { useRequiredSigningContext } from './provider';
|
import { useRequiredSigningContext } from './provider';
|
||||||
import { SigningFieldContainer } from './signing-field-container';
|
import { SigningFieldContainer } from './signing-field-container';
|
||||||
|
|
||||||
@ -29,9 +32,12 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
const { signature: providedSignature, setSignature: setProvidedSignature } =
|
const { signature: providedSignature, setSignature: setProvidedSignature } =
|
||||||
useRequiredSigningContext();
|
useRequiredSigningContext();
|
||||||
|
|
||||||
|
const { executeActionAuthProcedure } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
||||||
@ -48,7 +54,6 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
|
|
||||||
const [showSignatureModal, setShowSignatureModal] = useState(false);
|
const [showSignatureModal, setShowSignatureModal] = useState(false);
|
||||||
const [localSignature, setLocalSignature] = useState<string | null>(null);
|
const [localSignature, setLocalSignature] = useState<string | null>(null);
|
||||||
const [isLocalSignatureSet, setIsLocalSignatureSet] = useState(false);
|
|
||||||
|
|
||||||
const state = useMemo<SignatureFieldState>(() => {
|
const state = useMemo<SignatureFieldState>(() => {
|
||||||
if (!field.inserted) {
|
if (!field.inserted) {
|
||||||
@ -62,23 +67,37 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
return 'signed-text';
|
return 'signed-text';
|
||||||
}, [field.inserted, signature?.signatureImageAsBase64]);
|
}, [field.inserted, signature?.signatureImageAsBase64]);
|
||||||
|
|
||||||
useEffect(() => {
|
const onPreSign = () => {
|
||||||
if (!showSignatureModal && !isLocalSignatureSet) {
|
if (!providedSignature) {
|
||||||
setLocalSignature(null);
|
setShowSignatureModal(true);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}, [showSignatureModal, isLocalSignatureSet]);
|
|
||||||
|
|
||||||
const onSign = async (source: 'local' | 'provider' = 'provider') => {
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the user clicks the sign button in the dialog where they enter their signature.
|
||||||
|
*/
|
||||||
|
const onDialogSignClick = () => {
|
||||||
|
setShowSignatureModal(false);
|
||||||
|
setProvidedSignature(localSignature);
|
||||||
|
|
||||||
|
if (!localSignature) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: async (authOptions) => await onSign(authOptions, localSignature),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSign = async (authOptions?: TRecipientActionAuth, signature?: string) => {
|
||||||
try {
|
try {
|
||||||
if (!providedSignature && !localSignature) {
|
const value = signature || providedSignature;
|
||||||
setIsLocalSignatureSet(false);
|
|
||||||
setShowSignatureModal(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = source === 'local' && localSignature ? localSignature : providedSignature ?? '';
|
|
||||||
|
|
||||||
if (!value) {
|
if (!value) {
|
||||||
|
setShowSignatureModal(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,16 +106,17 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
fieldId: field.id,
|
fieldId: field.id,
|
||||||
value,
|
value,
|
||||||
isBase64: true,
|
isBase64: true,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (source === 'local' && !providedSignature) {
|
|
||||||
setProvidedSignature(localSignature);
|
|
||||||
}
|
|
||||||
|
|
||||||
setLocalSignature(null);
|
|
||||||
|
|
||||||
startTransition(() => router.refresh());
|
startTransition(() => router.refresh());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const error = AppError.parseError(err);
|
||||||
|
|
||||||
|
if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
@ -127,7 +147,13 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Signature">
|
<SigningFieldContainer
|
||||||
|
field={field}
|
||||||
|
onPreSign={onPreSign}
|
||||||
|
onSign={onSign}
|
||||||
|
onRemove={onRemove}
|
||||||
|
type="Signature"
|
||||||
|
>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
||||||
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
||||||
@ -190,11 +216,7 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
|
|||||||
type="button"
|
type="button"
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
disabled={!localSignature}
|
disabled={!localSignature}
|
||||||
onClick={() => {
|
onClick={() => onDialogSignClick()}
|
||||||
setShowSignatureModal(false);
|
|
||||||
setIsLocalSignatureSet(true);
|
|
||||||
void onSign('local');
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Sign
|
Sign
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -0,0 +1,67 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
import { DateTime } from 'luxon';
|
||||||
|
import { signOut } from 'next-auth/react';
|
||||||
|
|
||||||
|
import { trpc } from '@documenso/trpc/react';
|
||||||
|
import { Button } from '@documenso/ui/primitives/button';
|
||||||
|
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||||
|
|
||||||
|
export type SigningAuthPageViewProps = {
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SigningAuthPageView = ({ email }: SigningAuthPageViewProps) => {
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const [isSigningOut, setIsSigningOut] = useState(false);
|
||||||
|
|
||||||
|
const { mutateAsync: encryptSecondaryData } = trpc.crypto.encryptSecondaryData.useMutation();
|
||||||
|
|
||||||
|
const handleChangeAccount = async (email: string) => {
|
||||||
|
try {
|
||||||
|
setIsSigningOut(true);
|
||||||
|
|
||||||
|
const encryptedEmail = await encryptSecondaryData({
|
||||||
|
data: email,
|
||||||
|
expiresAt: DateTime.now().plus({ days: 1 }).toMillis(),
|
||||||
|
});
|
||||||
|
|
||||||
|
await signOut({
|
||||||
|
callbackUrl: `/signin?email=${encodeURIComponent(encryptedEmail)}`,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
toast({
|
||||||
|
title: 'Something went wrong',
|
||||||
|
description: 'We were unable to log you out at this time.',
|
||||||
|
duration: 10000,
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSigningOut(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex h-[70vh] w-full max-w-md flex-col items-center justify-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-semibold">Authentication required</h1>
|
||||||
|
|
||||||
|
<p className="text-muted-foreground mt-2 text-sm">
|
||||||
|
You need to be logged in as <strong>{email}</strong> to view this page.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
className="mt-4 w-full"
|
||||||
|
type="submit"
|
||||||
|
onClick={async () => handleChangeAccount(email)}
|
||||||
|
loading={isSigningOut}
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@ -2,15 +2,37 @@
|
|||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
|
import { type TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { FieldRootContainer } from '@documenso/ui/components/field/field';
|
import { FieldRootContainer } from '@documenso/ui/components/field/field';
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
|
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
|
|
||||||
export type SignatureFieldProps = {
|
export type SignatureFieldProps = {
|
||||||
field: FieldWithSignature;
|
field: FieldWithSignature;
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
onSign?: () => Promise<void> | void;
|
|
||||||
|
/**
|
||||||
|
* A function that is called before the field requires to be signed, or reauthed.
|
||||||
|
*
|
||||||
|
* Example, you may want to show a dialog prior to signing where they can enter a value.
|
||||||
|
*
|
||||||
|
* Once that action is complete, you will need to call `executeActionAuthProcedure` to proceed
|
||||||
|
* regardless if it requires reauth or not.
|
||||||
|
*
|
||||||
|
* If the function returns true, we will proceed with the signing process. Otherwise if
|
||||||
|
* false is returned we will not proceed.
|
||||||
|
*/
|
||||||
|
onPreSign?: () => Promise<boolean> | boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The function required to be executed to insert the field.
|
||||||
|
*
|
||||||
|
* The auth values will be passed in if avaliable.
|
||||||
|
*/
|
||||||
|
onSign?: (documentAuthValue?: TRecipientActionAuth) => Promise<void> | void;
|
||||||
onRemove?: () => Promise<void> | void;
|
onRemove?: () => Promise<void> | void;
|
||||||
type?: 'Date' | 'Email' | 'Name' | 'Signature';
|
type?: 'Date' | 'Email' | 'Name' | 'Signature';
|
||||||
tooltipText?: string | null;
|
tooltipText?: string | null;
|
||||||
@ -19,18 +41,42 @@ export type SignatureFieldProps = {
|
|||||||
export const SigningFieldContainer = ({
|
export const SigningFieldContainer = ({
|
||||||
field,
|
field,
|
||||||
loading,
|
loading,
|
||||||
|
onPreSign,
|
||||||
onSign,
|
onSign,
|
||||||
onRemove,
|
onRemove,
|
||||||
children,
|
children,
|
||||||
type,
|
type,
|
||||||
tooltipText,
|
tooltipText,
|
||||||
}: SignatureFieldProps) => {
|
}: SignatureFieldProps) => {
|
||||||
const onSignFieldClick = async () => {
|
const { executeActionAuthProcedure, isAuthRedirectRequired } = useRequiredDocumentAuthContext();
|
||||||
if (field.inserted) {
|
|
||||||
|
const handleInsertField = async () => {
|
||||||
|
if (field.inserted || !onSign) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await onSign?.();
|
if (isAuthRedirectRequired) {
|
||||||
|
await executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: () => {
|
||||||
|
// Do nothing since the user should be redirected.
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle any presign requirements, and halt if required.
|
||||||
|
if (onPreSign) {
|
||||||
|
const preSignResult = await onPreSign();
|
||||||
|
|
||||||
|
if (preSignResult === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: onSign,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onRemoveSignedFieldClick = async () => {
|
const onRemoveSignedFieldClick = async () => {
|
||||||
@ -47,7 +93,7 @@ export const SigningFieldContainer = ({
|
|||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="absolute inset-0 z-10 h-full w-full"
|
className="absolute inset-0 z-10 h-full w-full"
|
||||||
onClick={onSignFieldClick}
|
onClick={async () => handleInsertField()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
102
apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx
Normal file
102
apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
import { match } from 'ts-pattern';
|
||||||
|
|
||||||
|
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
||||||
|
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
|
||||||
|
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
||||||
|
import type { DocumentAndSender } from '@documenso/lib/server-only/document/get-document-by-token';
|
||||||
|
import type { Field, Recipient } from '@documenso/prisma/client';
|
||||||
|
import { FieldType, RecipientRole } from '@documenso/prisma/client';
|
||||||
|
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
||||||
|
import { ElementVisible } from '@documenso/ui/primitives/element-visible';
|
||||||
|
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
|
||||||
|
|
||||||
|
import { truncateTitle } from '~/helpers/truncate-title';
|
||||||
|
|
||||||
|
import { DateField } from './date-field';
|
||||||
|
import { EmailField } from './email-field';
|
||||||
|
import { SigningForm } from './form';
|
||||||
|
import { NameField } from './name-field';
|
||||||
|
import { SignatureField } from './signature-field';
|
||||||
|
import { TextField } from './text-field';
|
||||||
|
|
||||||
|
export type SigningPageViewProps = {
|
||||||
|
document: DocumentAndSender;
|
||||||
|
recipient: Recipient;
|
||||||
|
fields: Field[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SigningPageView = ({ document, recipient, fields }: SigningPageViewProps) => {
|
||||||
|
const truncatedTitle = truncateTitle(document.title);
|
||||||
|
|
||||||
|
const { documentData, documentMeta } = document;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-screen-xl">
|
||||||
|
<h1 className="mt-4 truncate text-2xl font-semibold md:text-3xl" title={document.title}>
|
||||||
|
{truncatedTitle}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div className="mt-2.5 flex items-center gap-x-6">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{document.User.name} ({document.User.email}) has invited you to{' '}
|
||||||
|
{recipient.role === RecipientRole.VIEWER && 'view'}
|
||||||
|
{recipient.role === RecipientRole.SIGNER && 'sign'}
|
||||||
|
{recipient.role === RecipientRole.APPROVER && 'approve'} this document.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-8 grid grid-cols-12 gap-y-8 lg:gap-x-8 lg:gap-y-0">
|
||||||
|
<Card
|
||||||
|
className="col-span-12 rounded-xl before:rounded-xl lg:col-span-7 xl:col-span-8"
|
||||||
|
gradient
|
||||||
|
>
|
||||||
|
<CardContent className="p-2">
|
||||||
|
<LazyPDFViewer
|
||||||
|
key={documentData.id}
|
||||||
|
documentData={documentData}
|
||||||
|
document={document}
|
||||||
|
password={documentMeta?.password}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div className="col-span-12 lg:col-span-5 xl:col-span-4">
|
||||||
|
<SigningForm
|
||||||
|
document={document}
|
||||||
|
recipient={recipient}
|
||||||
|
fields={fields}
|
||||||
|
redirectUrl={documentMeta?.redirectUrl}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ElementVisible target={PDF_VIEWER_PAGE_SELECTOR}>
|
||||||
|
{fields.map((field) =>
|
||||||
|
match(field.type)
|
||||||
|
.with(FieldType.SIGNATURE, () => (
|
||||||
|
<SignatureField key={field.id} field={field} recipient={recipient} />
|
||||||
|
))
|
||||||
|
.with(FieldType.NAME, () => (
|
||||||
|
<NameField key={field.id} field={field} recipient={recipient} />
|
||||||
|
))
|
||||||
|
.with(FieldType.DATE, () => (
|
||||||
|
<DateField
|
||||||
|
key={field.id}
|
||||||
|
field={field}
|
||||||
|
recipient={recipient}
|
||||||
|
dateFormat={documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT}
|
||||||
|
timezone={documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
.with(FieldType.EMAIL, () => (
|
||||||
|
<EmailField key={field.id} field={field} recipient={recipient} />
|
||||||
|
))
|
||||||
|
.with(FieldType.TEXT, () => (
|
||||||
|
<TextField key={field.id} field={field} recipient={recipient} />
|
||||||
|
))
|
||||||
|
.otherwise(() => null),
|
||||||
|
)}
|
||||||
|
</ElementVisible>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@ -6,6 +6,8 @@ import { useRouter } from 'next/navigation';
|
|||||||
|
|
||||||
import { Loader } from 'lucide-react';
|
import { Loader } from 'lucide-react';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
import type { Recipient } from '@documenso/prisma/client';
|
import type { Recipient } from '@documenso/prisma/client';
|
||||||
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -15,6 +17,7 @@ import { Input } from '@documenso/ui/primitives/input';
|
|||||||
import { Label } from '@documenso/ui/primitives/label';
|
import { Label } from '@documenso/ui/primitives/label';
|
||||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||||
|
|
||||||
|
import { useRequiredDocumentAuthContext } from './document-auth-provider';
|
||||||
import { SigningFieldContainer } from './signing-field-container';
|
import { SigningFieldContainer } from './signing-field-container';
|
||||||
|
|
||||||
export type TextFieldProps = {
|
export type TextFieldProps = {
|
||||||
@ -27,6 +30,8 @@ export const TextField = ({ field, recipient }: TextFieldProps) => {
|
|||||||
|
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const { executeActionAuthProcedure } = useRequiredDocumentAuthContext();
|
||||||
|
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
const { mutateAsync: signFieldWithToken, isLoading: isSignFieldWithTokenLoading } =
|
||||||
@ -41,22 +46,35 @@ export const TextField = ({ field, recipient }: TextFieldProps) => {
|
|||||||
|
|
||||||
const [showCustomTextModal, setShowCustomTextModal] = useState(false);
|
const [showCustomTextModal, setShowCustomTextModal] = useState(false);
|
||||||
const [localText, setLocalCustomText] = useState('');
|
const [localText, setLocalCustomText] = useState('');
|
||||||
const [isLocalSignatureSet, setIsLocalSignatureSet] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!showCustomTextModal && !isLocalSignatureSet) {
|
if (!showCustomTextModal) {
|
||||||
setLocalCustomText('');
|
setLocalCustomText('');
|
||||||
}
|
}
|
||||||
}, [showCustomTextModal, isLocalSignatureSet]);
|
}, [showCustomTextModal]);
|
||||||
|
|
||||||
const onSign = async () => {
|
/**
|
||||||
|
* When the user clicks the sign button in the dialog where they enter the text field.
|
||||||
|
*/
|
||||||
|
const onDialogSignClick = () => {
|
||||||
|
setShowCustomTextModal(false);
|
||||||
|
|
||||||
|
void executeActionAuthProcedure({
|
||||||
|
onReauthFormSubmit: async (authOptions) => await onSign(authOptions),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPreSign = () => {
|
||||||
|
if (!localText) {
|
||||||
|
setShowCustomTextModal(true);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSign = async (authOptions?: TRecipientActionAuth) => {
|
||||||
try {
|
try {
|
||||||
if (!localText) {
|
|
||||||
setIsLocalSignatureSet(false);
|
|
||||||
setShowCustomTextModal(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!localText) {
|
if (!localText) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -66,12 +84,19 @@ export const TextField = ({ field, recipient }: TextFieldProps) => {
|
|||||||
fieldId: field.id,
|
fieldId: field.id,
|
||||||
value: localText,
|
value: localText,
|
||||||
isBase64: true,
|
isBase64: true,
|
||||||
|
authOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
setLocalCustomText('');
|
setLocalCustomText('');
|
||||||
|
|
||||||
startTransition(() => router.refresh());
|
startTransition(() => router.refresh());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
const error = AppError.parseError(err);
|
||||||
|
|
||||||
|
if (error.code === AppErrorCode.UNAUTHORIZED) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
@ -102,7 +127,13 @@ export const TextField = ({ field, recipient }: TextFieldProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Signature">
|
<SigningFieldContainer
|
||||||
|
field={field}
|
||||||
|
onPreSign={onPreSign}
|
||||||
|
onSign={onSign}
|
||||||
|
onRemove={onRemove}
|
||||||
|
type="Signature"
|
||||||
|
>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
|
||||||
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
|
||||||
@ -149,11 +180,7 @@ export const TextField = ({ field, recipient }: TextFieldProps) => {
|
|||||||
type="button"
|
type="button"
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
disabled={!localText}
|
disabled={!localText}
|
||||||
onClick={() => {
|
onClick={() => onDialogSignClick()}
|
||||||
setShowCustomTextModal(false);
|
|
||||||
setIsLocalSignatureSet(true);
|
|
||||||
void onSign();
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Save Text
|
Save Text
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -7,6 +7,7 @@ import { match } from 'ts-pattern';
|
|||||||
import { UAParser } from 'ua-parser-js';
|
import { UAParser } from 'ua-parser-js';
|
||||||
|
|
||||||
import { DOCUMENT_AUDIT_LOG_EMAIL_FORMAT } from '@documenso/lib/constants/document-audit-logs';
|
import { DOCUMENT_AUDIT_LOG_EMAIL_FORMAT } from '@documenso/lib/constants/document-audit-logs';
|
||||||
|
import { DOCUMENT_AUTH_TYPES } from '@documenso/lib/constants/document-auth';
|
||||||
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
||||||
import { formatDocumentAuditLogActionString } from '@documenso/lib/utils/document-audit-logs';
|
import { formatDocumentAuditLogActionString } from '@documenso/lib/utils/document-audit-logs';
|
||||||
import { trpc } from '@documenso/trpc/react';
|
import { trpc } from '@documenso/trpc/react';
|
||||||
@ -79,7 +80,11 @@ export const DocumentHistorySheet = ({
|
|||||||
* @param text The text to format
|
* @param text The text to format
|
||||||
* @returns The formatted text
|
* @returns The formatted text
|
||||||
*/
|
*/
|
||||||
const formatGenericText = (text: string) => {
|
const formatGenericText = (text?: string | null) => {
|
||||||
|
if (!text) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
return (text.charAt(0).toUpperCase() + text.slice(1).toLowerCase()).replaceAll('_', ' ');
|
return (text.charAt(0).toUpperCase() + text.slice(1).toLowerCase()).replaceAll('_', ' ');
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -219,6 +224,24 @@ export const DocumentHistorySheet = ({
|
|||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
.with(
|
||||||
|
{ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED },
|
||||||
|
{ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED },
|
||||||
|
({ data }) => (
|
||||||
|
<DocumentHistorySheetChanges
|
||||||
|
values={[
|
||||||
|
{
|
||||||
|
key: 'Old',
|
||||||
|
value: DOCUMENT_AUTH_TYPES[data.from || '']?.value || 'None',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'New',
|
||||||
|
value: DOCUMENT_AUTH_TYPES[data.to || '']?.value || 'None',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
)
|
||||||
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_META_UPDATED }, ({ data }) => {
|
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_META_UPDATED }, ({ data }) => {
|
||||||
if (data.changes.length === 0) {
|
if (data.changes.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
@ -281,6 +304,7 @@ export const DocumentHistorySheet = ({
|
|||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
|
|
||||||
.exhaustive()}
|
.exhaustive()}
|
||||||
|
|
||||||
{isUserDetailsVisible && (
|
{isUserDetailsVisible && (
|
||||||
|
|||||||
@ -1,34 +0,0 @@
|
|||||||
import { AnimatePresence, motion } from 'framer-motion';
|
|
||||||
|
|
||||||
import { cn } from '@documenso/ui/lib/utils';
|
|
||||||
|
|
||||||
export type FormErrorMessageProps = {
|
|
||||||
className?: string;
|
|
||||||
error: { message?: string } | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const FormErrorMessage = ({ error, className }: FormErrorMessageProps) => {
|
|
||||||
return (
|
|
||||||
<AnimatePresence>
|
|
||||||
{error && (
|
|
||||||
<motion.p
|
|
||||||
initial={{
|
|
||||||
opacity: 0,
|
|
||||||
y: -10,
|
|
||||||
}}
|
|
||||||
animate={{
|
|
||||||
opacity: 1,
|
|
||||||
y: 0,
|
|
||||||
}}
|
|
||||||
exit={{
|
|
||||||
opacity: 0,
|
|
||||||
y: 10,
|
|
||||||
}}
|
|
||||||
className={cn('text-xs text-red-500', className)}
|
|
||||||
>
|
|
||||||
{error.message}
|
|
||||||
</motion.p>
|
|
||||||
)}
|
|
||||||
</AnimatePresence>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
31
packages/lib/constants/document-auth.ts
Normal file
31
packages/lib/constants/document-auth.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import type { TDocumentAuth } from '../types/document-auth';
|
||||||
|
import { DocumentAuth } from '../types/document-auth';
|
||||||
|
|
||||||
|
type DocumentAuthTypeData = {
|
||||||
|
key: TDocumentAuth;
|
||||||
|
value: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this authentication event will require the user to halt and
|
||||||
|
* redirect.
|
||||||
|
*
|
||||||
|
* Defaults to false.
|
||||||
|
*/
|
||||||
|
isAuthRedirectRequired?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DOCUMENT_AUTH_TYPES: Record<string, DocumentAuthTypeData> = {
|
||||||
|
[DocumentAuth.ACCOUNT]: {
|
||||||
|
key: DocumentAuth.ACCOUNT,
|
||||||
|
value: 'Require account',
|
||||||
|
isAuthRedirectRequired: true,
|
||||||
|
},
|
||||||
|
// [DocumentAuthType.PASSKEY]: {
|
||||||
|
// key: DocumentAuthType.PASSKEY,
|
||||||
|
// value: 'Require passkey',
|
||||||
|
// },
|
||||||
|
[DocumentAuth.EXPLICIT_NONE]: {
|
||||||
|
key: DocumentAuth.EXPLICIT_NONE,
|
||||||
|
value: 'None (Overrides global settings)',
|
||||||
|
},
|
||||||
|
} satisfies Record<TDocumentAuth, DocumentAuthTypeData>;
|
||||||
@ -137,12 +137,16 @@ export class AppError extends Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static parseFromJSONString(jsonString: string): AppError | null {
|
static parseFromJSONString(jsonString: string): AppError | null {
|
||||||
const parsed = ZAppErrorJsonSchema.safeParse(JSON.parse(jsonString));
|
try {
|
||||||
|
const parsed = ZAppErrorJsonSchema.safeParse(JSON.parse(jsonString));
|
||||||
|
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new AppError(parsed.data.code, parsed.data.message, parsed.data.userMessage);
|
||||||
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new AppError(parsed.data.code, parsed.data.message, parsed.data.userMessage);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,13 +7,19 @@ import { prisma } from '@documenso/prisma';
|
|||||||
import { DocumentStatus, SigningStatus } from '@documenso/prisma/client';
|
import { DocumentStatus, SigningStatus } from '@documenso/prisma/client';
|
||||||
import { WebhookTriggerEvents } from '@documenso/prisma/client';
|
import { WebhookTriggerEvents } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||||
|
import type { TRecipientActionAuth } from '../../types/document-auth';
|
||||||
|
import { extractDocumentAuthMethods } from '../../utils/document-auth';
|
||||||
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
|
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
|
||||||
|
import { isRecipientAuthorized } from './is-recipient-authorized';
|
||||||
import { sealDocument } from './seal-document';
|
import { sealDocument } from './seal-document';
|
||||||
import { sendPendingEmail } from './send-pending-email';
|
import { sendPendingEmail } from './send-pending-email';
|
||||||
|
|
||||||
export type CompleteDocumentWithTokenOptions = {
|
export type CompleteDocumentWithTokenOptions = {
|
||||||
token: string;
|
token: string;
|
||||||
documentId: number;
|
documentId: number;
|
||||||
|
userId?: number;
|
||||||
|
authOptions?: TRecipientActionAuth;
|
||||||
requestMetadata?: RequestMetadata;
|
requestMetadata?: RequestMetadata;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -40,6 +46,8 @@ const getDocument = async ({ token, documentId }: CompleteDocumentWithTokenOptio
|
|||||||
export const completeDocumentWithToken = async ({
|
export const completeDocumentWithToken = async ({
|
||||||
token,
|
token,
|
||||||
documentId,
|
documentId,
|
||||||
|
userId,
|
||||||
|
authOptions,
|
||||||
requestMetadata,
|
requestMetadata,
|
||||||
}: CompleteDocumentWithTokenOptions) => {
|
}: CompleteDocumentWithTokenOptions) => {
|
||||||
'use server';
|
'use server';
|
||||||
@ -71,32 +79,52 @@ export const completeDocumentWithToken = async ({
|
|||||||
throw new Error(`Recipient ${recipient.id} has unsigned fields`);
|
throw new Error(`Recipient ${recipient.id} has unsigned fields`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await prisma.recipient.update({
|
const { derivedRecipientActionAuth } = extractDocumentAuthMethods({
|
||||||
where: {
|
documentAuth: document.authOptions,
|
||||||
id: recipient.id,
|
recipientAuth: recipient.authOptions,
|
||||||
},
|
|
||||||
data: {
|
|
||||||
signingStatus: SigningStatus.SIGNED,
|
|
||||||
signedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await prisma.documentAuditLog.create({
|
const isValid = await isRecipientAuthorized({
|
||||||
data: createDocumentAuditLogData({
|
type: 'ACTION',
|
||||||
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_COMPLETED,
|
document: document,
|
||||||
documentId: document.id,
|
recipient: recipient,
|
||||||
user: {
|
userId,
|
||||||
name: recipient.name,
|
authOptions,
|
||||||
email: recipient.email,
|
});
|
||||||
|
|
||||||
|
if (!isValid) {
|
||||||
|
throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid authentication values');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
await tx.recipient.update({
|
||||||
|
where: {
|
||||||
|
id: recipient.id,
|
||||||
},
|
},
|
||||||
requestMetadata,
|
|
||||||
data: {
|
data: {
|
||||||
recipientEmail: recipient.email,
|
signingStatus: SigningStatus.SIGNED,
|
||||||
recipientName: recipient.name,
|
signedAt: new Date(),
|
||||||
recipientId: recipient.id,
|
|
||||||
recipientRole: recipient.role,
|
|
||||||
},
|
},
|
||||||
}),
|
});
|
||||||
|
|
||||||
|
await tx.documentAuditLog.create({
|
||||||
|
data: createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_COMPLETED,
|
||||||
|
documentId: document.id,
|
||||||
|
user: {
|
||||||
|
name: recipient.name,
|
||||||
|
email: recipient.email,
|
||||||
|
},
|
||||||
|
requestMetadata,
|
||||||
|
data: {
|
||||||
|
recipientEmail: recipient.email,
|
||||||
|
recipientName: recipient.name,
|
||||||
|
recipientId: recipient.id,
|
||||||
|
recipientRole: recipient.role,
|
||||||
|
actionAuth: derivedRecipientActionAuth || undefined,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const pendingRecipients = await prisma.recipient.count({
|
const pendingRecipients = await prisma.recipient.count({
|
||||||
|
|||||||
@ -1,16 +1,43 @@
|
|||||||
import { prisma } from '@documenso/prisma';
|
import { prisma } from '@documenso/prisma';
|
||||||
import type { DocumentWithRecipient } from '@documenso/prisma/types/document-with-recipient';
|
import type { DocumentWithRecipient } from '@documenso/prisma/types/document-with-recipient';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||||
|
import type { TDocumentAuthMethods } from '../../types/document-auth';
|
||||||
|
import { isRecipientAuthorized } from './is-recipient-authorized';
|
||||||
|
|
||||||
export interface GetDocumentAndSenderByTokenOptions {
|
export interface GetDocumentAndSenderByTokenOptions {
|
||||||
token: string;
|
token: string;
|
||||||
|
userId?: number;
|
||||||
|
accessAuth?: TDocumentAuthMethods;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether we enforce the access requirement.
|
||||||
|
*
|
||||||
|
* Defaults to true.
|
||||||
|
*/
|
||||||
|
requireAccessAuth?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GetDocumentAndRecipientByTokenOptions {
|
export interface GetDocumentAndRecipientByTokenOptions {
|
||||||
token: string;
|
token: string;
|
||||||
|
userId?: number;
|
||||||
|
accessAuth?: TDocumentAuthMethods;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether we enforce the access requirement.
|
||||||
|
*
|
||||||
|
* Defaults to true.
|
||||||
|
*/
|
||||||
|
requireAccessAuth?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type DocumentAndSender = Awaited<ReturnType<typeof getDocumentAndSenderByToken>>;
|
||||||
|
|
||||||
export const getDocumentAndSenderByToken = async ({
|
export const getDocumentAndSenderByToken = async ({
|
||||||
token,
|
token,
|
||||||
|
userId,
|
||||||
|
accessAuth,
|
||||||
|
requireAccessAuth = true,
|
||||||
}: GetDocumentAndSenderByTokenOptions) => {
|
}: GetDocumentAndSenderByTokenOptions) => {
|
||||||
if (!token) {
|
if (!token) {
|
||||||
throw new Error('Missing token');
|
throw new Error('Missing token');
|
||||||
@ -28,12 +55,40 @@ export const getDocumentAndSenderByToken = async ({
|
|||||||
User: true,
|
User: true,
|
||||||
documentData: true,
|
documentData: true,
|
||||||
documentMeta: true,
|
documentMeta: true,
|
||||||
|
Recipient: {
|
||||||
|
where: {
|
||||||
|
token,
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
||||||
const { password: _password, ...User } = result.User;
|
const { password: _password, ...User } = result.User;
|
||||||
|
|
||||||
|
const recipient = result.Recipient[0];
|
||||||
|
|
||||||
|
// Sanity check, should not be possible.
|
||||||
|
if (!recipient) {
|
||||||
|
throw new Error('Missing recipient');
|
||||||
|
}
|
||||||
|
|
||||||
|
let documentAccessValid = true;
|
||||||
|
|
||||||
|
if (requireAccessAuth) {
|
||||||
|
documentAccessValid = await isRecipientAuthorized({
|
||||||
|
type: 'ACCESS',
|
||||||
|
document: result,
|
||||||
|
recipient,
|
||||||
|
userId,
|
||||||
|
authOptions: accessAuth,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!documentAccessValid) {
|
||||||
|
throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid access values');
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
User,
|
User,
|
||||||
@ -45,6 +100,9 @@ export const getDocumentAndSenderByToken = async ({
|
|||||||
*/
|
*/
|
||||||
export const getDocumentAndRecipientByToken = async ({
|
export const getDocumentAndRecipientByToken = async ({
|
||||||
token,
|
token,
|
||||||
|
userId,
|
||||||
|
accessAuth,
|
||||||
|
requireAccessAuth = true,
|
||||||
}: GetDocumentAndRecipientByTokenOptions): Promise<DocumentWithRecipient> => {
|
}: GetDocumentAndRecipientByTokenOptions): Promise<DocumentWithRecipient> => {
|
||||||
if (!token) {
|
if (!token) {
|
||||||
throw new Error('Missing token');
|
throw new Error('Missing token');
|
||||||
@ -68,6 +126,29 @@ export const getDocumentAndRecipientByToken = async ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const recipient = result.Recipient[0];
|
||||||
|
|
||||||
|
// Sanity check, should not be possible.
|
||||||
|
if (!recipient) {
|
||||||
|
throw new Error('Missing recipient');
|
||||||
|
}
|
||||||
|
|
||||||
|
let documentAccessValid = true;
|
||||||
|
|
||||||
|
if (requireAccessAuth) {
|
||||||
|
documentAccessValid = await isRecipientAuthorized({
|
||||||
|
type: 'ACCESS',
|
||||||
|
document: result,
|
||||||
|
recipient,
|
||||||
|
userId,
|
||||||
|
authOptions: accessAuth,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!documentAccessValid) {
|
||||||
|
throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid access values');
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
Recipient: result.Recipient,
|
Recipient: result.Recipient,
|
||||||
|
|||||||
86
packages/lib/server-only/document/is-recipient-authorized.ts
Normal file
86
packages/lib/server-only/document/is-recipient-authorized.ts
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
import { match } from 'ts-pattern';
|
||||||
|
|
||||||
|
import { prisma } from '@documenso/prisma';
|
||||||
|
import type { Document, Recipient } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import type { TDocumentAuth, TDocumentAuthMethods } from '../../types/document-auth';
|
||||||
|
import { DocumentAuth } from '../../types/document-auth';
|
||||||
|
import { extractDocumentAuthMethods } from '../../utils/document-auth';
|
||||||
|
|
||||||
|
type IsRecipientAuthorizedOptions = {
|
||||||
|
type: 'ACCESS' | 'ACTION';
|
||||||
|
document: Document;
|
||||||
|
recipient: Recipient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ID of the user who initiated the request.
|
||||||
|
*/
|
||||||
|
userId?: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The auth details to check.
|
||||||
|
*
|
||||||
|
* Optional because there are scenarios where no auth options are required such as
|
||||||
|
* using the user ID.
|
||||||
|
*/
|
||||||
|
authOptions?: TDocumentAuthMethods;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRecipient = async (email: string) => {
|
||||||
|
return await prisma.user.findFirst({
|
||||||
|
where: {
|
||||||
|
email,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the recipient is authorized to perform the requested operation on a
|
||||||
|
* document, given the provided auth options.
|
||||||
|
*
|
||||||
|
* @returns True if the recipient can perform the requested operation.
|
||||||
|
*/
|
||||||
|
export const isRecipientAuthorized = async ({
|
||||||
|
type,
|
||||||
|
document,
|
||||||
|
recipient,
|
||||||
|
userId,
|
||||||
|
authOptions,
|
||||||
|
}: IsRecipientAuthorizedOptions): Promise<boolean> => {
|
||||||
|
const { derivedRecipientAccessAuth, derivedRecipientActionAuth } = extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
recipientAuth: recipient.authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
|
const authMethod: TDocumentAuth | null =
|
||||||
|
type === 'ACCESS' ? derivedRecipientAccessAuth : derivedRecipientActionAuth;
|
||||||
|
|
||||||
|
// Early true return when auth is not required.
|
||||||
|
if (!authMethod || authMethod === DocumentAuth.EXPLICIT_NONE) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authentication required does not match provided method.
|
||||||
|
if (authOptions && authOptions.type !== authMethod) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await match(authMethod)
|
||||||
|
.with(DocumentAuth.ACCOUNT, async () => {
|
||||||
|
if (userId === undefined) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const recipientUser = await getRecipient(recipient.email);
|
||||||
|
|
||||||
|
if (!recipientUser) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return recipientUser.id === userId;
|
||||||
|
})
|
||||||
|
.exhaustive();
|
||||||
|
};
|
||||||
162
packages/lib/server-only/document/update-document-settings.ts
Normal file
162
packages/lib/server-only/document/update-document-settings.ts
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
||||||
|
import type { RequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
||||||
|
import type { CreateDocumentAuditLogDataResponse } from '@documenso/lib/utils/document-audit-logs';
|
||||||
|
import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-logs';
|
||||||
|
import { prisma } from '@documenso/prisma';
|
||||||
|
import { DocumentStatus } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||||
|
import type { TDocumentAccessAuthTypes, TDocumentActionAuthTypes } from '../../types/document-auth';
|
||||||
|
import { createDocumentAuthOptions, extractDocumentAuthMethods } from '../../utils/document-auth';
|
||||||
|
|
||||||
|
export type UpdateDocumentSettingsOptions = {
|
||||||
|
userId: number;
|
||||||
|
teamId?: number;
|
||||||
|
documentId: number;
|
||||||
|
data: {
|
||||||
|
title?: string;
|
||||||
|
globalAccessAuth?: TDocumentAccessAuthTypes | null;
|
||||||
|
globalActionAuth?: TDocumentActionAuthTypes | null;
|
||||||
|
};
|
||||||
|
requestMetadata?: RequestMetadata;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateDocumentSettings = async ({
|
||||||
|
userId,
|
||||||
|
teamId,
|
||||||
|
documentId,
|
||||||
|
data,
|
||||||
|
requestMetadata,
|
||||||
|
}: UpdateDocumentSettingsOptions) => {
|
||||||
|
if (!data.title && !data.globalAccessAuth && !data.globalActionAuth) {
|
||||||
|
throw new AppError(AppErrorCode.INVALID_BODY, 'Missing data to update');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await prisma.user.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const document = await prisma.document.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: documentId,
|
||||||
|
...(teamId
|
||||||
|
? {
|
||||||
|
team: {
|
||||||
|
id: teamId,
|
||||||
|
members: {
|
||||||
|
some: {
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
userId,
|
||||||
|
teamId: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { documentAuthOption } = extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
|
const documentGlobalAccessAuth = documentAuthOption?.globalAccessAuth ?? null;
|
||||||
|
const documentGlobalActionAuth = documentAuthOption?.globalActionAuth ?? null;
|
||||||
|
|
||||||
|
// If the new global auth values aren't passed in, fallback to the current document values.
|
||||||
|
const newGlobalAccessAuth =
|
||||||
|
data?.globalAccessAuth === undefined ? documentGlobalAccessAuth : data.globalAccessAuth;
|
||||||
|
const newGlobalActionAuth =
|
||||||
|
data?.globalActionAuth === undefined ? documentGlobalActionAuth : data.globalActionAuth;
|
||||||
|
|
||||||
|
const isTitleSame = data.title === document.title;
|
||||||
|
const isGlobalAccessSame = documentGlobalAccessAuth === newGlobalAccessAuth;
|
||||||
|
const isGlobalActionSame = documentGlobalActionAuth === newGlobalActionAuth;
|
||||||
|
|
||||||
|
const auditLogs: CreateDocumentAuditLogDataResponse[] = [];
|
||||||
|
|
||||||
|
if (!isTitleSame && document.status !== DocumentStatus.DRAFT) {
|
||||||
|
throw new AppError(
|
||||||
|
AppErrorCode.INVALID_BODY,
|
||||||
|
'You cannot update the title if the document has been sent',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isTitleSame) {
|
||||||
|
auditLogs.push(
|
||||||
|
createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_TITLE_UPDATED,
|
||||||
|
documentId,
|
||||||
|
user,
|
||||||
|
requestMetadata,
|
||||||
|
data: {
|
||||||
|
from: document.title,
|
||||||
|
to: data.title || '',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isGlobalAccessSame) {
|
||||||
|
auditLogs.push(
|
||||||
|
createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED,
|
||||||
|
documentId,
|
||||||
|
user,
|
||||||
|
requestMetadata,
|
||||||
|
data: {
|
||||||
|
from: documentGlobalAccessAuth,
|
||||||
|
to: newGlobalAccessAuth,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isGlobalActionSame) {
|
||||||
|
auditLogs.push(
|
||||||
|
createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED,
|
||||||
|
documentId,
|
||||||
|
user,
|
||||||
|
requestMetadata,
|
||||||
|
data: {
|
||||||
|
from: documentGlobalActionAuth,
|
||||||
|
to: newGlobalActionAuth,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Early return if nothing is required.
|
||||||
|
if (auditLogs.length === 0) {
|
||||||
|
return document;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await prisma.$transaction(async (tx) => {
|
||||||
|
const authOptions = createDocumentAuthOptions({
|
||||||
|
globalAccessAuth: newGlobalAccessAuth,
|
||||||
|
globalActionAuth: newGlobalActionAuth,
|
||||||
|
});
|
||||||
|
|
||||||
|
const updatedDocument = await tx.document.update({
|
||||||
|
where: {
|
||||||
|
id: documentId,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
title: data.title,
|
||||||
|
authOptions,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.documentAuditLog.createMany({
|
||||||
|
data: auditLogs,
|
||||||
|
});
|
||||||
|
|
||||||
|
return updatedDocument;
|
||||||
|
});
|
||||||
|
};
|
||||||
@ -5,15 +5,21 @@ import { prisma } from '@documenso/prisma';
|
|||||||
import { ReadStatus } from '@documenso/prisma/client';
|
import { ReadStatus } from '@documenso/prisma/client';
|
||||||
import { WebhookTriggerEvents } from '@documenso/prisma/client';
|
import { WebhookTriggerEvents } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import type { TDocumentAccessAuthTypes } from '../../types/document-auth';
|
||||||
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
|
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
|
||||||
import { getDocumentAndRecipientByToken } from './get-document-by-token';
|
import { getDocumentAndRecipientByToken } from './get-document-by-token';
|
||||||
|
|
||||||
export type ViewedDocumentOptions = {
|
export type ViewedDocumentOptions = {
|
||||||
token: string;
|
token: string;
|
||||||
|
recipientAccessAuth?: TDocumentAccessAuthTypes | null;
|
||||||
requestMetadata?: RequestMetadata;
|
requestMetadata?: RequestMetadata;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const viewedDocument = async ({ token, requestMetadata }: ViewedDocumentOptions) => {
|
export const viewedDocument = async ({
|
||||||
|
token,
|
||||||
|
recipientAccessAuth,
|
||||||
|
requestMetadata,
|
||||||
|
}: ViewedDocumentOptions) => {
|
||||||
const recipient = await prisma.recipient.findFirst({
|
const recipient = await prisma.recipient.findFirst({
|
||||||
where: {
|
where: {
|
||||||
token,
|
token,
|
||||||
@ -51,12 +57,13 @@ export const viewedDocument = async ({ token, requestMetadata }: ViewedDocumentO
|
|||||||
recipientId: recipient.id,
|
recipientId: recipient.id,
|
||||||
recipientName: recipient.name,
|
recipientName: recipient.name,
|
||||||
recipientRole: recipient.role,
|
recipientRole: recipient.role,
|
||||||
|
accessAuth: recipientAccessAuth || undefined,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const document = await getDocumentAndRecipientByToken({ token });
|
const document = await getDocumentAndRecipientByToken({ token, requireAccessAuth: false });
|
||||||
|
|
||||||
await triggerWebhook({
|
await triggerWebhook({
|
||||||
event: WebhookTriggerEvents.DOCUMENT_OPENED,
|
event: WebhookTriggerEvents.DOCUMENT_OPENED,
|
||||||
|
|||||||
@ -8,15 +8,21 @@ import { DocumentStatus, FieldType, SigningStatus } from '@documenso/prisma/clie
|
|||||||
|
|
||||||
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '../../constants/date-formats';
|
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '../../constants/date-formats';
|
||||||
import { DEFAULT_DOCUMENT_TIME_ZONE } from '../../constants/time-zones';
|
import { DEFAULT_DOCUMENT_TIME_ZONE } from '../../constants/time-zones';
|
||||||
|
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||||
import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs';
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs';
|
||||||
|
import type { TRecipientActionAuth } from '../../types/document-auth';
|
||||||
import type { RequestMetadata } from '../../universal/extract-request-metadata';
|
import type { RequestMetadata } from '../../universal/extract-request-metadata';
|
||||||
import { createDocumentAuditLogData } from '../../utils/document-audit-logs';
|
import { createDocumentAuditLogData } from '../../utils/document-audit-logs';
|
||||||
|
import { extractDocumentAuthMethods } from '../../utils/document-auth';
|
||||||
|
import { isRecipientAuthorized } from '../document/is-recipient-authorized';
|
||||||
|
|
||||||
export type SignFieldWithTokenOptions = {
|
export type SignFieldWithTokenOptions = {
|
||||||
token: string;
|
token: string;
|
||||||
fieldId: number;
|
fieldId: number;
|
||||||
value: string;
|
value: string;
|
||||||
isBase64?: boolean;
|
isBase64?: boolean;
|
||||||
|
userId?: number;
|
||||||
|
authOptions?: TRecipientActionAuth;
|
||||||
requestMetadata?: RequestMetadata;
|
requestMetadata?: RequestMetadata;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -25,6 +31,8 @@ export const signFieldWithToken = async ({
|
|||||||
fieldId,
|
fieldId,
|
||||||
value,
|
value,
|
||||||
isBase64,
|
isBase64,
|
||||||
|
userId,
|
||||||
|
authOptions,
|
||||||
requestMetadata,
|
requestMetadata,
|
||||||
}: SignFieldWithTokenOptions) => {
|
}: SignFieldWithTokenOptions) => {
|
||||||
const field = await prisma.field.findFirstOrThrow({
|
const field = await prisma.field.findFirstOrThrow({
|
||||||
@ -71,6 +79,23 @@ export const signFieldWithToken = async ({
|
|||||||
throw new Error(`Field ${fieldId} has no recipientId`);
|
throw new Error(`Field ${fieldId} has no recipientId`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { derivedRecipientActionAuth } = extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
recipientAuth: recipient.authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
|
const isValid = await isRecipientAuthorized({
|
||||||
|
type: 'ACTION',
|
||||||
|
document: document,
|
||||||
|
recipient: recipient,
|
||||||
|
userId,
|
||||||
|
authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isValid) {
|
||||||
|
throw new AppError(AppErrorCode.UNAUTHORIZED, 'Invalid authentication values');
|
||||||
|
}
|
||||||
|
|
||||||
const documentMeta = await prisma.documentMeta.findFirst({
|
const documentMeta = await prisma.documentMeta.findFirst({
|
||||||
where: {
|
where: {
|
||||||
documentId: document.id,
|
documentId: document.id,
|
||||||
@ -158,9 +183,11 @@ export const signFieldWithToken = async ({
|
|||||||
data: updatedField.customText,
|
data: updatedField.customText,
|
||||||
}))
|
}))
|
||||||
.exhaustive(),
|
.exhaustive(),
|
||||||
fieldSecurity: {
|
fieldSecurity: derivedRecipientActionAuth
|
||||||
type: 'NONE',
|
? {
|
||||||
},
|
type: derivedRecipientActionAuth,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
import { prisma } from '@documenso/prisma';
|
import { prisma } from '@documenso/prisma';
|
||||||
import type { FieldType, Team } from '@documenso/prisma/client';
|
import type { FieldType, Team } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs';
|
||||||
import type { RequestMetadata } from '../../universal/extract-request-metadata';
|
import type { RequestMetadata } from '../../universal/extract-request-metadata';
|
||||||
import { createDocumentAuditLogData } from '../../utils/document-audit-logs';
|
import { createDocumentAuditLogData, diffFieldChanges } from '../../utils/document-audit-logs';
|
||||||
|
|
||||||
export type UpdateFieldOptions = {
|
export type UpdateFieldOptions = {
|
||||||
fieldId: number;
|
fieldId: number;
|
||||||
@ -33,7 +34,7 @@ export const updateField = async ({
|
|||||||
pageHeight,
|
pageHeight,
|
||||||
requestMetadata,
|
requestMetadata,
|
||||||
}: UpdateFieldOptions) => {
|
}: UpdateFieldOptions) => {
|
||||||
const field = await prisma.field.update({
|
const oldField = await prisma.field.findFirstOrThrow({
|
||||||
where: {
|
where: {
|
||||||
id: fieldId,
|
id: fieldId,
|
||||||
Document: {
|
Document: {
|
||||||
@ -55,23 +56,49 @@ export const updateField = async ({
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
data: {
|
|
||||||
recipientId,
|
|
||||||
type,
|
|
||||||
page: pageNumber,
|
|
||||||
positionX: pageX,
|
|
||||||
positionY: pageY,
|
|
||||||
width: pageWidth,
|
|
||||||
height: pageHeight,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
Recipient: true,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!field) {
|
const field = prisma.$transaction(async (tx) => {
|
||||||
throw new Error('Field not found');
|
const updatedField = await tx.field.update({
|
||||||
}
|
where: {
|
||||||
|
id: fieldId,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
recipientId,
|
||||||
|
type,
|
||||||
|
page: pageNumber,
|
||||||
|
positionX: pageX,
|
||||||
|
positionY: pageY,
|
||||||
|
width: pageWidth,
|
||||||
|
height: pageHeight,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
Recipient: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.documentAuditLog.create({
|
||||||
|
data: createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.FIELD_UPDATED,
|
||||||
|
documentId,
|
||||||
|
user: {
|
||||||
|
id: team?.id ?? user.id,
|
||||||
|
email: team?.name ?? user.email,
|
||||||
|
name: team ? '' : user.name,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
fieldId: updatedField.secondaryId,
|
||||||
|
fieldRecipientEmail: updatedField.Recipient?.email ?? '',
|
||||||
|
fieldRecipientId: recipientId ?? -1,
|
||||||
|
fieldType: updatedField.type,
|
||||||
|
changes: diffFieldChanges(oldField, updatedField),
|
||||||
|
},
|
||||||
|
requestMetadata,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return updatedField;
|
||||||
|
});
|
||||||
|
|
||||||
const user = await prisma.user.findFirstOrThrow({
|
const user = await prisma.user.findFirstOrThrow({
|
||||||
where: {
|
where: {
|
||||||
@ -99,24 +126,5 @@ export const updateField = async ({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await prisma.documentAuditLog.create({
|
|
||||||
data: createDocumentAuditLogData({
|
|
||||||
type: 'FIELD_UPDATED',
|
|
||||||
documentId,
|
|
||||||
user: {
|
|
||||||
id: team?.id ?? user.id,
|
|
||||||
email: team?.name ?? user.email,
|
|
||||||
name: team ? '' : user.name,
|
|
||||||
},
|
|
||||||
data: {
|
|
||||||
fieldId: field.secondaryId,
|
|
||||||
fieldRecipientEmail: field.Recipient?.email ?? '',
|
|
||||||
fieldRecipientId: recipientId ?? -1,
|
|
||||||
fieldType: field.type,
|
|
||||||
},
|
|
||||||
requestMetadata,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
return field;
|
return field;
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,10 +1,15 @@
|
|||||||
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
|
||||||
|
import {
|
||||||
|
type TRecipientActionAuthTypes,
|
||||||
|
ZRecipientAuthOptionsSchema,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
import type { RequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
import type { RequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
||||||
import { nanoid } from '@documenso/lib/universal/id';
|
import { nanoid } from '@documenso/lib/universal/id';
|
||||||
import {
|
import {
|
||||||
createDocumentAuditLogData,
|
createDocumentAuditLogData,
|
||||||
diffRecipientChanges,
|
diffRecipientChanges,
|
||||||
} from '@documenso/lib/utils/document-audit-logs';
|
} from '@documenso/lib/utils/document-audit-logs';
|
||||||
|
import { createRecipientAuthOptions } from '@documenso/lib/utils/document-auth';
|
||||||
import { prisma } from '@documenso/prisma';
|
import { prisma } from '@documenso/prisma';
|
||||||
import { RecipientRole } from '@documenso/prisma/client';
|
import { RecipientRole } from '@documenso/prisma/client';
|
||||||
import { SendStatus, SigningStatus } from '@documenso/prisma/client';
|
import { SendStatus, SigningStatus } from '@documenso/prisma/client';
|
||||||
@ -18,6 +23,7 @@ export interface SetRecipientsForDocumentOptions {
|
|||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
role: RecipientRole;
|
role: RecipientRole;
|
||||||
|
actionAuth?: TRecipientActionAuthTypes | null;
|
||||||
}[];
|
}[];
|
||||||
requestMetadata?: RequestMetadata;
|
requestMetadata?: RequestMetadata;
|
||||||
}
|
}
|
||||||
@ -111,6 +117,15 @@ export const setRecipientsForDocument = async ({
|
|||||||
const persistedRecipients = await prisma.$transaction(async (tx) => {
|
const persistedRecipients = await prisma.$transaction(async (tx) => {
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
linkedRecipients.map(async (recipient) => {
|
linkedRecipients.map(async (recipient) => {
|
||||||
|
let authOptions = ZRecipientAuthOptionsSchema.parse(recipient._persisted?.authOptions);
|
||||||
|
|
||||||
|
if (recipient.actionAuth !== undefined) {
|
||||||
|
authOptions = createRecipientAuthOptions({
|
||||||
|
accessAuth: authOptions.accessAuth,
|
||||||
|
actionAuth: recipient.actionAuth,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const upsertedRecipient = await tx.recipient.upsert({
|
const upsertedRecipient = await tx.recipient.upsert({
|
||||||
where: {
|
where: {
|
||||||
id: recipient._persisted?.id ?? -1,
|
id: recipient._persisted?.id ?? -1,
|
||||||
@ -124,6 +139,7 @@ export const setRecipientsForDocument = async ({
|
|||||||
sendStatus: recipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,
|
sendStatus: recipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,
|
||||||
signingStatus:
|
signingStatus:
|
||||||
recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,
|
recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,
|
||||||
|
authOptions,
|
||||||
},
|
},
|
||||||
create: {
|
create: {
|
||||||
name: recipient.name,
|
name: recipient.name,
|
||||||
@ -134,6 +150,7 @@ export const setRecipientsForDocument = async ({
|
|||||||
sendStatus: recipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,
|
sendStatus: recipient.role === RecipientRole.CC ? SendStatus.SENT : SendStatus.NOT_SENT,
|
||||||
signingStatus:
|
signingStatus:
|
||||||
recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,
|
recipient.role === RecipientRole.CC ? SigningStatus.SIGNED : SigningStatus.NOT_SIGNED,
|
||||||
|
authOptions,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -187,7 +204,10 @@ export const setRecipientsForDocument = async ({
|
|||||||
documentId: documentId,
|
documentId: documentId,
|
||||||
user,
|
user,
|
||||||
requestMetadata,
|
requestMetadata,
|
||||||
data: baseAuditLog,
|
data: {
|
||||||
|
...baseAuditLog,
|
||||||
|
actionAuth: recipient.actionAuth || undefined,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,6 +8,8 @@ import { z } from 'zod';
|
|||||||
|
|
||||||
import { FieldType } from '@documenso/prisma/client';
|
import { FieldType } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import { ZRecipientActionAuthTypesSchema } from './document-auth';
|
||||||
|
|
||||||
export const ZDocumentAuditLogTypeSchema = z.enum([
|
export const ZDocumentAuditLogTypeSchema = z.enum([
|
||||||
// Document actions.
|
// Document actions.
|
||||||
'EMAIL_SENT',
|
'EMAIL_SENT',
|
||||||
@ -26,6 +28,8 @@ export const ZDocumentAuditLogTypeSchema = z.enum([
|
|||||||
'DOCUMENT_DELETED', // When the document is soft deleted.
|
'DOCUMENT_DELETED', // When the document is soft deleted.
|
||||||
'DOCUMENT_FIELD_INSERTED', // When a field is inserted (signed/approved/etc) by a recipient.
|
'DOCUMENT_FIELD_INSERTED', // When a field is inserted (signed/approved/etc) by a recipient.
|
||||||
'DOCUMENT_FIELD_UNINSERTED', // When a field is uninserted by a recipient.
|
'DOCUMENT_FIELD_UNINSERTED', // When a field is uninserted by a recipient.
|
||||||
|
'DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED', // When the global access authentication is updated.
|
||||||
|
'DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED', // When the global action authentication is updated.
|
||||||
'DOCUMENT_META_UPDATED', // When the document meta data is updated.
|
'DOCUMENT_META_UPDATED', // When the document meta data is updated.
|
||||||
'DOCUMENT_OPENED', // When the document is opened by a recipient.
|
'DOCUMENT_OPENED', // When the document is opened by a recipient.
|
||||||
'DOCUMENT_RECIPIENT_COMPLETED', // When a recipient completes all their required tasks for the document.
|
'DOCUMENT_RECIPIENT_COMPLETED', // When a recipient completes all their required tasks for the document.
|
||||||
@ -51,7 +55,13 @@ export const ZDocumentMetaDiffTypeSchema = z.enum([
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
export const ZFieldDiffTypeSchema = z.enum(['DIMENSION', 'POSITION']);
|
export const ZFieldDiffTypeSchema = z.enum(['DIMENSION', 'POSITION']);
|
||||||
export const ZRecipientDiffTypeSchema = z.enum(['NAME', 'ROLE', 'EMAIL']);
|
export const ZRecipientDiffTypeSchema = z.enum([
|
||||||
|
'NAME',
|
||||||
|
'ROLE',
|
||||||
|
'EMAIL',
|
||||||
|
'ACCESS_AUTH',
|
||||||
|
'ACTION_AUTH',
|
||||||
|
]);
|
||||||
|
|
||||||
export const DOCUMENT_AUDIT_LOG_TYPE = ZDocumentAuditLogTypeSchema.Enum;
|
export const DOCUMENT_AUDIT_LOG_TYPE = ZDocumentAuditLogTypeSchema.Enum;
|
||||||
export const DOCUMENT_EMAIL_TYPE = ZDocumentAuditLogEmailTypeSchema.Enum;
|
export const DOCUMENT_EMAIL_TYPE = ZDocumentAuditLogEmailTypeSchema.Enum;
|
||||||
@ -107,25 +117,34 @@ export const ZDocumentAuditLogFieldDiffSchema = z.union([
|
|||||||
ZFieldDiffPositionSchema,
|
ZFieldDiffPositionSchema,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const ZRecipientDiffNameSchema = z.object({
|
export const ZGenericFromToSchema = z.object({
|
||||||
|
from: z.string().nullable(),
|
||||||
|
to: z.string().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ZRecipientDiffActionAuthSchema = ZGenericFromToSchema.extend({
|
||||||
|
type: z.literal(RECIPIENT_DIFF_TYPE.ACCESS_AUTH),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ZRecipientDiffAccessAuthSchema = ZGenericFromToSchema.extend({
|
||||||
|
type: z.literal(RECIPIENT_DIFF_TYPE.ACTION_AUTH),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ZRecipientDiffNameSchema = ZGenericFromToSchema.extend({
|
||||||
type: z.literal(RECIPIENT_DIFF_TYPE.NAME),
|
type: z.literal(RECIPIENT_DIFF_TYPE.NAME),
|
||||||
from: z.string(),
|
|
||||||
to: z.string(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ZRecipientDiffRoleSchema = z.object({
|
export const ZRecipientDiffRoleSchema = ZGenericFromToSchema.extend({
|
||||||
type: z.literal(RECIPIENT_DIFF_TYPE.ROLE),
|
type: z.literal(RECIPIENT_DIFF_TYPE.ROLE),
|
||||||
from: z.string(),
|
|
||||||
to: z.string(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ZRecipientDiffEmailSchema = z.object({
|
export const ZRecipientDiffEmailSchema = ZGenericFromToSchema.extend({
|
||||||
type: z.literal(RECIPIENT_DIFF_TYPE.EMAIL),
|
type: z.literal(RECIPIENT_DIFF_TYPE.EMAIL),
|
||||||
from: z.string(),
|
|
||||||
to: z.string(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ZDocumentAuditLogRecipientDiffSchema = z.union([
|
export const ZDocumentAuditLogRecipientDiffSchema = z.discriminatedUnion('type', [
|
||||||
|
ZRecipientDiffActionAuthSchema,
|
||||||
|
ZRecipientDiffAccessAuthSchema,
|
||||||
ZRecipientDiffNameSchema,
|
ZRecipientDiffNameSchema,
|
||||||
ZRecipientDiffRoleSchema,
|
ZRecipientDiffRoleSchema,
|
||||||
ZRecipientDiffEmailSchema,
|
ZRecipientDiffEmailSchema,
|
||||||
@ -217,11 +236,11 @@ export const ZDocumentAuditLogEventDocumentFieldInsertedSchema = z.object({
|
|||||||
data: z.string(),
|
data: z.string(),
|
||||||
}),
|
}),
|
||||||
]),
|
]),
|
||||||
|
fieldSecurity: z
|
||||||
// Todo: Replace with union once we have more field security types.
|
.object({
|
||||||
fieldSecurity: z.object({
|
type: ZRecipientActionAuthTypesSchema,
|
||||||
type: z.literal('NONE'),
|
})
|
||||||
}),
|
.optional(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -236,6 +255,22 @@ export const ZDocumentAuditLogEventDocumentFieldUninsertedSchema = z.object({
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event: Document global authentication access updated.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAuditLogEventDocumentGlobalAuthAccessUpdatedSchema = z.object({
|
||||||
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED),
|
||||||
|
data: ZGenericFromToSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event: Document global authentication action updated.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAuditLogEventDocumentGlobalAuthActionUpdatedSchema = z.object({
|
||||||
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED),
|
||||||
|
data: ZGenericFromToSchema,
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Event: Document meta updated.
|
* Event: Document meta updated.
|
||||||
*/
|
*/
|
||||||
@ -251,7 +286,9 @@ export const ZDocumentAuditLogEventDocumentMetaUpdatedSchema = z.object({
|
|||||||
*/
|
*/
|
||||||
export const ZDocumentAuditLogEventDocumentOpenedSchema = z.object({
|
export const ZDocumentAuditLogEventDocumentOpenedSchema = z.object({
|
||||||
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_OPENED),
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_OPENED),
|
||||||
data: ZBaseRecipientDataSchema,
|
data: ZBaseRecipientDataSchema.extend({
|
||||||
|
accessAuth: z.string().optional(),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -259,7 +296,9 @@ export const ZDocumentAuditLogEventDocumentOpenedSchema = z.object({
|
|||||||
*/
|
*/
|
||||||
export const ZDocumentAuditLogEventDocumentRecipientCompleteSchema = z.object({
|
export const ZDocumentAuditLogEventDocumentRecipientCompleteSchema = z.object({
|
||||||
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_COMPLETED),
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_COMPLETED),
|
||||||
data: ZBaseRecipientDataSchema,
|
data: ZBaseRecipientDataSchema.extend({
|
||||||
|
actionAuth: z.string().optional(),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -303,7 +342,9 @@ export const ZDocumentAuditLogEventFieldRemovedSchema = z.object({
|
|||||||
export const ZDocumentAuditLogEventFieldUpdatedSchema = z.object({
|
export const ZDocumentAuditLogEventFieldUpdatedSchema = z.object({
|
||||||
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.FIELD_UPDATED),
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.FIELD_UPDATED),
|
||||||
data: ZBaseFieldEventDataSchema.extend({
|
data: ZBaseFieldEventDataSchema.extend({
|
||||||
changes: z.array(ZDocumentAuditLogFieldDiffSchema),
|
// Provide an empty array as a migration workaround due to a mistake where we were
|
||||||
|
// not passing through any changes via API/v1 due to a type error.
|
||||||
|
changes: z.preprocess((x) => x || [], z.array(ZDocumentAuditLogFieldDiffSchema)),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -312,7 +353,9 @@ export const ZDocumentAuditLogEventFieldUpdatedSchema = z.object({
|
|||||||
*/
|
*/
|
||||||
export const ZDocumentAuditLogEventRecipientAddedSchema = z.object({
|
export const ZDocumentAuditLogEventRecipientAddedSchema = z.object({
|
||||||
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_CREATED),
|
type: z.literal(DOCUMENT_AUDIT_LOG_TYPE.RECIPIENT_CREATED),
|
||||||
data: ZBaseRecipientDataSchema,
|
data: ZBaseRecipientDataSchema.extend({
|
||||||
|
actionAuth: ZRecipientActionAuthTypesSchema.optional(),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -352,6 +395,8 @@ export const ZDocumentAuditLogSchema = ZDocumentAuditLogBaseSchema.and(
|
|||||||
ZDocumentAuditLogEventDocumentDeletedSchema,
|
ZDocumentAuditLogEventDocumentDeletedSchema,
|
||||||
ZDocumentAuditLogEventDocumentFieldInsertedSchema,
|
ZDocumentAuditLogEventDocumentFieldInsertedSchema,
|
||||||
ZDocumentAuditLogEventDocumentFieldUninsertedSchema,
|
ZDocumentAuditLogEventDocumentFieldUninsertedSchema,
|
||||||
|
ZDocumentAuditLogEventDocumentGlobalAuthAccessUpdatedSchema,
|
||||||
|
ZDocumentAuditLogEventDocumentGlobalAuthActionUpdatedSchema,
|
||||||
ZDocumentAuditLogEventDocumentMetaUpdatedSchema,
|
ZDocumentAuditLogEventDocumentMetaUpdatedSchema,
|
||||||
ZDocumentAuditLogEventDocumentOpenedSchema,
|
ZDocumentAuditLogEventDocumentOpenedSchema,
|
||||||
ZDocumentAuditLogEventDocumentRecipientCompleteSchema,
|
ZDocumentAuditLogEventDocumentRecipientCompleteSchema,
|
||||||
|
|||||||
121
packages/lib/types/document-auth.ts
Normal file
121
packages/lib/types/document-auth.ts
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All the available types of document authentication options for both access and action.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAuthTypesSchema = z.enum(['ACCOUNT', 'EXPLICIT_NONE']);
|
||||||
|
export const DocumentAuth = ZDocumentAuthTypesSchema.Enum;
|
||||||
|
|
||||||
|
const ZDocumentAuthAccountSchema = z.object({
|
||||||
|
type: z.literal(DocumentAuth.ACCOUNT),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ZDocumentAuthExplicitNoneSchema = z.object({
|
||||||
|
type: z.literal(DocumentAuth.EXPLICIT_NONE),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All the document auth methods for both accessing and actioning.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAuthMethodsSchema = z.discriminatedUnion('type', [
|
||||||
|
ZDocumentAuthAccountSchema,
|
||||||
|
ZDocumentAuthExplicitNoneSchema,
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The global document access auth methods.
|
||||||
|
*
|
||||||
|
* Must keep these two in sync.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAccessAuthSchema = z.discriminatedUnion('type', [ZDocumentAuthAccountSchema]);
|
||||||
|
export const ZDocumentAccessAuthTypesSchema = z.enum([DocumentAuth.ACCOUNT]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The global document action auth methods.
|
||||||
|
*
|
||||||
|
* Must keep these two in sync.
|
||||||
|
*/
|
||||||
|
export const ZDocumentActionAuthSchema = z.discriminatedUnion('type', [ZDocumentAuthAccountSchema]); // Todo: Add passkeys here.
|
||||||
|
export const ZDocumentActionAuthTypesSchema = z.enum([DocumentAuth.ACCOUNT]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The recipient access auth methods.
|
||||||
|
*
|
||||||
|
* Must keep these two in sync.
|
||||||
|
*/
|
||||||
|
export const ZRecipientAccessAuthSchema = z.discriminatedUnion('type', [
|
||||||
|
ZDocumentAuthAccountSchema,
|
||||||
|
]);
|
||||||
|
export const ZRecipientAccessAuthTypesSchema = z.enum([DocumentAuth.ACCOUNT]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The recipient action auth methods.
|
||||||
|
*
|
||||||
|
* Must keep these two in sync.
|
||||||
|
*/
|
||||||
|
export const ZRecipientActionAuthSchema = z.discriminatedUnion('type', [
|
||||||
|
ZDocumentAuthAccountSchema, // Todo: Add passkeys here.
|
||||||
|
ZDocumentAuthExplicitNoneSchema,
|
||||||
|
]);
|
||||||
|
export const ZRecipientActionAuthTypesSchema = z.enum([
|
||||||
|
DocumentAuth.ACCOUNT,
|
||||||
|
DocumentAuth.EXPLICIT_NONE,
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DocumentAccessAuth = ZDocumentAccessAuthTypesSchema.Enum;
|
||||||
|
export const DocumentActionAuth = ZDocumentActionAuthTypesSchema.Enum;
|
||||||
|
export const RecipientAccessAuth = ZRecipientAccessAuthTypesSchema.Enum;
|
||||||
|
export const RecipientActionAuth = ZRecipientActionAuthTypesSchema.Enum;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication options attached to the document.
|
||||||
|
*/
|
||||||
|
export const ZDocumentAuthOptionsSchema = z.preprocess(
|
||||||
|
(unknownValue) => {
|
||||||
|
if (unknownValue) {
|
||||||
|
return unknownValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
globalAccessAuth: null,
|
||||||
|
globalActionAuth: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
z.object({
|
||||||
|
globalAccessAuth: ZDocumentAccessAuthTypesSchema.nullable(),
|
||||||
|
globalActionAuth: ZDocumentActionAuthTypesSchema.nullable(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication options attached to the recipient.
|
||||||
|
*/
|
||||||
|
export const ZRecipientAuthOptionsSchema = z.preprocess(
|
||||||
|
(unknownValue) => {
|
||||||
|
if (unknownValue) {
|
||||||
|
return unknownValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessAuth: null,
|
||||||
|
actionAuth: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
z.object({
|
||||||
|
accessAuth: ZRecipientAccessAuthTypesSchema.nullable(),
|
||||||
|
actionAuth: ZRecipientActionAuthTypesSchema.nullable(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export type TDocumentAuth = z.infer<typeof ZDocumentAuthTypesSchema>;
|
||||||
|
export type TDocumentAuthMethods = z.infer<typeof ZDocumentAuthMethodsSchema>;
|
||||||
|
export type TDocumentAuthOptions = z.infer<typeof ZDocumentAuthOptionsSchema>;
|
||||||
|
export type TDocumentAccessAuth = z.infer<typeof ZDocumentAccessAuthSchema>;
|
||||||
|
export type TDocumentAccessAuthTypes = z.infer<typeof ZDocumentAccessAuthTypesSchema>;
|
||||||
|
export type TDocumentActionAuth = z.infer<typeof ZDocumentActionAuthSchema>;
|
||||||
|
export type TDocumentActionAuthTypes = z.infer<typeof ZDocumentActionAuthTypesSchema>;
|
||||||
|
export type TRecipientAccessAuth = z.infer<typeof ZRecipientAccessAuthSchema>;
|
||||||
|
export type TRecipientAccessAuthTypes = z.infer<typeof ZRecipientAccessAuthTypesSchema>;
|
||||||
|
export type TRecipientActionAuth = z.infer<typeof ZRecipientActionAuthSchema>;
|
||||||
|
export type TRecipientActionAuthTypes = z.infer<typeof ZRecipientActionAuthTypesSchema>;
|
||||||
|
export type TRecipientAuthOptions = z.infer<typeof ZRecipientAuthOptionsSchema>;
|
||||||
@ -22,6 +22,7 @@ import {
|
|||||||
RECIPIENT_DIFF_TYPE,
|
RECIPIENT_DIFF_TYPE,
|
||||||
ZDocumentAuditLogSchema,
|
ZDocumentAuditLogSchema,
|
||||||
} from '../types/document-audit-logs';
|
} from '../types/document-audit-logs';
|
||||||
|
import { ZRecipientAuthOptionsSchema } from '../types/document-auth';
|
||||||
import type { RequestMetadata } from '../universal/extract-request-metadata';
|
import type { RequestMetadata } from '../universal/extract-request-metadata';
|
||||||
|
|
||||||
type CreateDocumentAuditLogDataOptions<T = TDocumentAuditLog['type']> = {
|
type CreateDocumentAuditLogDataOptions<T = TDocumentAuditLog['type']> = {
|
||||||
@ -32,20 +33,20 @@ type CreateDocumentAuditLogDataOptions<T = TDocumentAuditLog['type']> = {
|
|||||||
requestMetadata?: RequestMetadata;
|
requestMetadata?: RequestMetadata;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CreateDocumentAuditLogDataResponse = Pick<
|
export type CreateDocumentAuditLogDataResponse = Pick<
|
||||||
DocumentAuditLog,
|
DocumentAuditLog,
|
||||||
'type' | 'ipAddress' | 'userAgent' | 'email' | 'userId' | 'name' | 'documentId'
|
'type' | 'ipAddress' | 'userAgent' | 'email' | 'userId' | 'name' | 'documentId'
|
||||||
> & {
|
> & {
|
||||||
data: TDocumentAuditLog['data'];
|
data: TDocumentAuditLog['data'];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createDocumentAuditLogData = ({
|
export const createDocumentAuditLogData = <T extends TDocumentAuditLog['type']>({
|
||||||
documentId,
|
documentId,
|
||||||
type,
|
type,
|
||||||
data,
|
data,
|
||||||
user,
|
user,
|
||||||
requestMetadata,
|
requestMetadata,
|
||||||
}: CreateDocumentAuditLogDataOptions): CreateDocumentAuditLogDataResponse => {
|
}: CreateDocumentAuditLogDataOptions<T>): CreateDocumentAuditLogDataResponse => {
|
||||||
return {
|
return {
|
||||||
type,
|
type,
|
||||||
data,
|
data,
|
||||||
@ -68,6 +69,7 @@ export const parseDocumentAuditLogData = (auditLog: DocumentAuditLog): TDocument
|
|||||||
|
|
||||||
// Handle any required migrations here.
|
// Handle any required migrations here.
|
||||||
if (!data.success) {
|
if (!data.success) {
|
||||||
|
// Todo: Alert us.
|
||||||
console.error(data.error);
|
console.error(data.error);
|
||||||
throw new Error('Migration required');
|
throw new Error('Migration required');
|
||||||
}
|
}
|
||||||
@ -75,7 +77,7 @@ export const parseDocumentAuditLogData = (auditLog: DocumentAuditLog): TDocument
|
|||||||
return data.data;
|
return data.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PartialRecipient = Pick<Recipient, 'email' | 'name' | 'role'>;
|
type PartialRecipient = Pick<Recipient, 'email' | 'name' | 'role' | 'authOptions'>;
|
||||||
|
|
||||||
export const diffRecipientChanges = (
|
export const diffRecipientChanges = (
|
||||||
oldRecipient: PartialRecipient,
|
oldRecipient: PartialRecipient,
|
||||||
@ -83,6 +85,32 @@ export const diffRecipientChanges = (
|
|||||||
): TDocumentAuditLogRecipientDiffSchema[] => {
|
): TDocumentAuditLogRecipientDiffSchema[] => {
|
||||||
const diffs: TDocumentAuditLogRecipientDiffSchema[] = [];
|
const diffs: TDocumentAuditLogRecipientDiffSchema[] = [];
|
||||||
|
|
||||||
|
const oldAuthOptions = ZRecipientAuthOptionsSchema.parse(oldRecipient.authOptions);
|
||||||
|
const oldAccessAuth = oldAuthOptions.accessAuth;
|
||||||
|
const oldActionAuth = oldAuthOptions.actionAuth;
|
||||||
|
|
||||||
|
const newAuthOptions = ZRecipientAuthOptionsSchema.parse(newRecipient.authOptions);
|
||||||
|
const newAccessAuth =
|
||||||
|
newAuthOptions?.accessAuth === undefined ? oldAccessAuth : newAuthOptions.accessAuth;
|
||||||
|
const newActionAuth =
|
||||||
|
newAuthOptions?.actionAuth === undefined ? oldActionAuth : newAuthOptions.actionAuth;
|
||||||
|
|
||||||
|
if (oldAccessAuth !== newAccessAuth) {
|
||||||
|
diffs.push({
|
||||||
|
type: RECIPIENT_DIFF_TYPE.ACCESS_AUTH,
|
||||||
|
from: oldAccessAuth ?? '',
|
||||||
|
to: newAccessAuth ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldActionAuth !== newActionAuth) {
|
||||||
|
diffs.push({
|
||||||
|
type: RECIPIENT_DIFF_TYPE.ACTION_AUTH,
|
||||||
|
from: oldActionAuth ?? '',
|
||||||
|
to: newActionAuth ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (oldRecipient.email !== newRecipient.email) {
|
if (oldRecipient.email !== newRecipient.email) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: RECIPIENT_DIFF_TYPE.EMAIL,
|
type: RECIPIENT_DIFF_TYPE.EMAIL,
|
||||||
@ -166,7 +194,13 @@ export const diffDocumentMetaChanges = (
|
|||||||
const oldPassword = oldData?.password ?? null;
|
const oldPassword = oldData?.password ?? null;
|
||||||
const oldRedirectUrl = oldData?.redirectUrl ?? '';
|
const oldRedirectUrl = oldData?.redirectUrl ?? '';
|
||||||
|
|
||||||
if (oldDateFormat !== newData.dateFormat) {
|
const newDateFormat = newData?.dateFormat ?? '';
|
||||||
|
const newMessage = newData?.message ?? '';
|
||||||
|
const newSubject = newData?.subject ?? '';
|
||||||
|
const newTimezone = newData?.timezone ?? '';
|
||||||
|
const newRedirectUrl = newData?.redirectUrl ?? '';
|
||||||
|
|
||||||
|
if (oldDateFormat !== newDateFormat) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: DOCUMENT_META_DIFF_TYPE.DATE_FORMAT,
|
type: DOCUMENT_META_DIFF_TYPE.DATE_FORMAT,
|
||||||
from: oldData?.dateFormat ?? '',
|
from: oldData?.dateFormat ?? '',
|
||||||
@ -174,35 +208,35 @@ export const diffDocumentMetaChanges = (
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (oldMessage !== newData.message) {
|
if (oldMessage !== newMessage) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: DOCUMENT_META_DIFF_TYPE.MESSAGE,
|
type: DOCUMENT_META_DIFF_TYPE.MESSAGE,
|
||||||
from: oldMessage,
|
from: oldMessage,
|
||||||
to: newData.message,
|
to: newMessage,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (oldSubject !== newData.subject) {
|
if (oldSubject !== newSubject) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: DOCUMENT_META_DIFF_TYPE.SUBJECT,
|
type: DOCUMENT_META_DIFF_TYPE.SUBJECT,
|
||||||
from: oldSubject,
|
from: oldSubject,
|
||||||
to: newData.subject,
|
to: newSubject,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (oldTimezone !== newData.timezone) {
|
if (oldTimezone !== newTimezone) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: DOCUMENT_META_DIFF_TYPE.TIMEZONE,
|
type: DOCUMENT_META_DIFF_TYPE.TIMEZONE,
|
||||||
from: oldTimezone,
|
from: oldTimezone,
|
||||||
to: newData.timezone,
|
to: newTimezone,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (oldRedirectUrl !== newData.redirectUrl) {
|
if (oldRedirectUrl !== newRedirectUrl) {
|
||||||
diffs.push({
|
diffs.push({
|
||||||
type: DOCUMENT_META_DIFF_TYPE.REDIRECT_URL,
|
type: DOCUMENT_META_DIFF_TYPE.REDIRECT_URL,
|
||||||
from: oldRedirectUrl,
|
from: oldRedirectUrl,
|
||||||
to: newData.redirectUrl,
|
to: newRedirectUrl,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -278,6 +312,14 @@ export const formatDocumentAuditLogAction = (auditLog: TDocumentAuditLog, userId
|
|||||||
anonymous: 'Field unsigned',
|
anonymous: 'Field unsigned',
|
||||||
identified: 'unsigned a field',
|
identified: 'unsigned a field',
|
||||||
}))
|
}))
|
||||||
|
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACCESS_UPDATED }, () => ({
|
||||||
|
anonymous: 'Document access auth updated',
|
||||||
|
identified: 'updated the document access auth requirements',
|
||||||
|
}))
|
||||||
|
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_GLOBAL_AUTH_ACTION_UPDATED }, () => ({
|
||||||
|
anonymous: 'Document signing auth updated',
|
||||||
|
identified: 'updated the document signing auth requirements',
|
||||||
|
}))
|
||||||
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_META_UPDATED }, () => ({
|
.with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_META_UPDATED }, () => ({
|
||||||
anonymous: 'Document updated',
|
anonymous: 'Document updated',
|
||||||
identified: 'updated the document',
|
identified: 'updated the document',
|
||||||
|
|||||||
72
packages/lib/utils/document-auth.ts
Normal file
72
packages/lib/utils/document-auth.ts
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
import type { Document, Recipient } from '@documenso/prisma/client';
|
||||||
|
|
||||||
|
import type {
|
||||||
|
TDocumentAuthOptions,
|
||||||
|
TRecipientAccessAuthTypes,
|
||||||
|
TRecipientActionAuthTypes,
|
||||||
|
TRecipientAuthOptions,
|
||||||
|
} from '../types/document-auth';
|
||||||
|
import { DocumentAuth } from '../types/document-auth';
|
||||||
|
import { ZDocumentAuthOptionsSchema, ZRecipientAuthOptionsSchema } from '../types/document-auth';
|
||||||
|
|
||||||
|
type ExtractDocumentAuthMethodsOptions = {
|
||||||
|
documentAuth: Document['authOptions'];
|
||||||
|
recipientAuth?: Recipient['authOptions'];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses and extracts the document and recipient authentication values.
|
||||||
|
*
|
||||||
|
* Will combine the recipient and document auth values to derive the final
|
||||||
|
* auth values for a recipient if possible.
|
||||||
|
*/
|
||||||
|
export const extractDocumentAuthMethods = ({
|
||||||
|
documentAuth,
|
||||||
|
recipientAuth,
|
||||||
|
}: ExtractDocumentAuthMethodsOptions) => {
|
||||||
|
const documentAuthOption = ZDocumentAuthOptionsSchema.parse(documentAuth);
|
||||||
|
const recipientAuthOption = ZRecipientAuthOptionsSchema.parse(recipientAuth);
|
||||||
|
|
||||||
|
const derivedRecipientAccessAuth: TRecipientAccessAuthTypes | null =
|
||||||
|
recipientAuthOption.accessAuth || documentAuthOption.globalAccessAuth;
|
||||||
|
|
||||||
|
const derivedRecipientActionAuth: TRecipientActionAuthTypes | null =
|
||||||
|
recipientAuthOption.actionAuth || documentAuthOption.globalActionAuth;
|
||||||
|
|
||||||
|
const recipientAccessAuthRequired = derivedRecipientAccessAuth !== null;
|
||||||
|
|
||||||
|
const recipientActionAuthRequired =
|
||||||
|
derivedRecipientActionAuth !== DocumentAuth.EXPLICIT_NONE &&
|
||||||
|
derivedRecipientActionAuth !== null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
derivedRecipientAccessAuth,
|
||||||
|
derivedRecipientActionAuth,
|
||||||
|
recipientAccessAuthRequired,
|
||||||
|
recipientActionAuthRequired,
|
||||||
|
documentAuthOption,
|
||||||
|
recipientAuthOption,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create document auth options in a type safe way.
|
||||||
|
*/
|
||||||
|
export const createDocumentAuthOptions = (options: TDocumentAuthOptions): TDocumentAuthOptions => {
|
||||||
|
return {
|
||||||
|
globalAccessAuth: options?.globalAccessAuth ?? null,
|
||||||
|
globalActionAuth: options?.globalActionAuth ?? null,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create recipient auth options in a type safe way.
|
||||||
|
*/
|
||||||
|
export const createRecipientAuthOptions = (
|
||||||
|
options: TRecipientAuthOptions,
|
||||||
|
): TRecipientAuthOptions => {
|
||||||
|
return {
|
||||||
|
accessAuth: options?.accessAuth ?? null,
|
||||||
|
actionAuth: options?.actionAuth ?? null,
|
||||||
|
};
|
||||||
|
};
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Document" ADD COLUMN "authOptions" JSONB;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Recipient" ADD COLUMN "authOptions" JSONB;
|
||||||
@ -226,6 +226,7 @@ model Document {
|
|||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
userId Int
|
userId Int
|
||||||
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
authOptions Json?
|
||||||
title String
|
title String
|
||||||
status DocumentStatus @default(DRAFT)
|
status DocumentStatus @default(DRAFT)
|
||||||
Recipient Recipient[]
|
Recipient Recipient[]
|
||||||
@ -323,6 +324,7 @@ model Recipient {
|
|||||||
token String
|
token String
|
||||||
expired DateTime?
|
expired DateTime?
|
||||||
signedAt DateTime?
|
signedAt DateTime?
|
||||||
|
authOptions Json?
|
||||||
role RecipientRole @default(SIGNER)
|
role RecipientRole @default(SIGNER)
|
||||||
readStatus ReadStatus @default(NOT_OPENED)
|
readStatus ReadStatus @default(NOT_OPENED)
|
||||||
signingStatus SigningStatus @default(NOT_SIGNED)
|
signingStatus SigningStatus @default(NOT_SIGNED)
|
||||||
|
|||||||
@ -12,6 +12,7 @@ import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document
|
|||||||
import { resendDocument } from '@documenso/lib/server-only/document/resend-document';
|
import { resendDocument } from '@documenso/lib/server-only/document/resend-document';
|
||||||
import { searchDocumentsWithKeyword } from '@documenso/lib/server-only/document/search-documents-with-keyword';
|
import { searchDocumentsWithKeyword } from '@documenso/lib/server-only/document/search-documents-with-keyword';
|
||||||
import { sendDocument } from '@documenso/lib/server-only/document/send-document';
|
import { sendDocument } from '@documenso/lib/server-only/document/send-document';
|
||||||
|
import { updateDocumentSettings } from '@documenso/lib/server-only/document/update-document-settings';
|
||||||
import { updateTitle } from '@documenso/lib/server-only/document/update-title';
|
import { updateTitle } from '@documenso/lib/server-only/document/update-title';
|
||||||
import { symmetricEncrypt } from '@documenso/lib/universal/crypto';
|
import { symmetricEncrypt } from '@documenso/lib/universal/crypto';
|
||||||
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
||||||
@ -27,6 +28,7 @@ import {
|
|||||||
ZSearchDocumentsMutationSchema,
|
ZSearchDocumentsMutationSchema,
|
||||||
ZSendDocumentMutationSchema,
|
ZSendDocumentMutationSchema,
|
||||||
ZSetPasswordForDocumentMutationSchema,
|
ZSetPasswordForDocumentMutationSchema,
|
||||||
|
ZSetSettingsForDocumentMutationSchema,
|
||||||
ZSetTitleForDocumentMutationSchema,
|
ZSetTitleForDocumentMutationSchema,
|
||||||
} from './schema';
|
} from './schema';
|
||||||
|
|
||||||
@ -49,22 +51,25 @@ export const documentRouter = router({
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getDocumentByToken: procedure.input(ZGetDocumentByTokenQuerySchema).query(async ({ input }) => {
|
getDocumentByToken: procedure
|
||||||
try {
|
.input(ZGetDocumentByTokenQuerySchema)
|
||||||
const { token } = input;
|
.query(async ({ input, ctx }) => {
|
||||||
|
try {
|
||||||
|
const { token } = input;
|
||||||
|
|
||||||
return await getDocumentAndSenderByToken({
|
return await getDocumentAndSenderByToken({
|
||||||
token,
|
token,
|
||||||
});
|
userId: ctx.user?.id,
|
||||||
} catch (err) {
|
});
|
||||||
console.error(err);
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
code: 'BAD_REQUEST',
|
code: 'BAD_REQUEST',
|
||||||
message: 'We were unable to find this document. Please try again later.',
|
message: 'We were unable to find this document. Please try again later.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
createDocument: authenticatedProcedure
|
createDocument: authenticatedProcedure
|
||||||
.input(ZCreateDocumentMutationSchema)
|
.input(ZCreateDocumentMutationSchema)
|
||||||
@ -150,6 +155,46 @@ export const documentRouter = router({
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
// Todo: Add API
|
||||||
|
setSettingsForDocument: authenticatedProcedure
|
||||||
|
.input(ZSetSettingsForDocumentMutationSchema)
|
||||||
|
.mutation(async ({ input, ctx }) => {
|
||||||
|
try {
|
||||||
|
const { documentId, teamId, data, meta } = input;
|
||||||
|
|
||||||
|
const userId = ctx.user.id;
|
||||||
|
|
||||||
|
const requestMetadata = extractNextApiRequestMetadata(ctx.req);
|
||||||
|
|
||||||
|
if (meta.timezone || meta.dateFormat || meta.redirectUrl) {
|
||||||
|
await upsertDocumentMeta({
|
||||||
|
documentId,
|
||||||
|
dateFormat: meta.dateFormat,
|
||||||
|
timezone: meta.timezone,
|
||||||
|
redirectUrl: meta.redirectUrl,
|
||||||
|
userId: ctx.user.id,
|
||||||
|
requestMetadata,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateDocumentSettings({
|
||||||
|
userId,
|
||||||
|
teamId,
|
||||||
|
documentId,
|
||||||
|
data,
|
||||||
|
requestMetadata,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
|
||||||
|
throw new TRPCError({
|
||||||
|
code: 'BAD_REQUEST',
|
||||||
|
message:
|
||||||
|
'We were unable to update the settings for this document. Please try again later.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
setTitleForDocument: authenticatedProcedure
|
setTitleForDocument: authenticatedProcedure
|
||||||
.input(ZSetTitleForDocumentMutationSchema)
|
.input(ZSetTitleForDocumentMutationSchema)
|
||||||
.mutation(async ({ input, ctx }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
|
|||||||
@ -1,6 +1,10 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { URL_REGEX } from '@documenso/lib/constants/url-regex';
|
import { URL_REGEX } from '@documenso/lib/constants/url-regex';
|
||||||
|
import {
|
||||||
|
ZDocumentAccessAuthTypesSchema,
|
||||||
|
ZDocumentActionAuthTypesSchema,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
import { ZBaseTableSearchParamsSchema } from '@documenso/lib/types/search-params';
|
import { ZBaseTableSearchParamsSchema } from '@documenso/lib/types/search-params';
|
||||||
import { FieldType, RecipientRole } from '@documenso/prisma/client';
|
import { FieldType, RecipientRole } from '@documenso/prisma/client';
|
||||||
|
|
||||||
@ -37,6 +41,30 @@ export const ZCreateDocumentMutationSchema = z.object({
|
|||||||
|
|
||||||
export type TCreateDocumentMutationSchema = z.infer<typeof ZCreateDocumentMutationSchema>;
|
export type TCreateDocumentMutationSchema = z.infer<typeof ZCreateDocumentMutationSchema>;
|
||||||
|
|
||||||
|
export const ZSetSettingsForDocumentMutationSchema = z.object({
|
||||||
|
documentId: z.number(),
|
||||||
|
teamId: z.number().min(1).optional(),
|
||||||
|
data: z.object({
|
||||||
|
title: z.string().min(1).optional(),
|
||||||
|
globalAccessAuth: ZDocumentAccessAuthTypesSchema.nullable().optional(),
|
||||||
|
globalActionAuth: ZDocumentActionAuthTypesSchema.nullable().optional(),
|
||||||
|
}),
|
||||||
|
meta: z.object({
|
||||||
|
timezone: z.string(),
|
||||||
|
dateFormat: z.string(),
|
||||||
|
redirectUrl: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.refine((value) => value === undefined || value === '' || URL_REGEX.test(value), {
|
||||||
|
message: 'Please enter a valid URL',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TSetGeneralSettingsForDocumentMutationSchema = z.infer<
|
||||||
|
typeof ZSetSettingsForDocumentMutationSchema
|
||||||
|
>;
|
||||||
|
|
||||||
export const ZSetTitleForDocumentMutationSchema = z.object({
|
export const ZSetTitleForDocumentMutationSchema = z.object({
|
||||||
documentId: z.number(),
|
documentId: z.number(),
|
||||||
teamId: z.number().min(1).optional(),
|
teamId: z.number().min(1).optional(),
|
||||||
@ -88,8 +116,8 @@ export const ZSendDocumentMutationSchema = z.object({
|
|||||||
meta: z.object({
|
meta: z.object({
|
||||||
subject: z.string(),
|
subject: z.string(),
|
||||||
message: z.string(),
|
message: z.string(),
|
||||||
timezone: z.string(),
|
timezone: z.string().optional(),
|
||||||
dateFormat: z.string(),
|
dateFormat: z.string().optional(),
|
||||||
redirectUrl: z
|
redirectUrl: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
|
|
||||||
|
import { AppError } from '@documenso/lib/errors/app-error';
|
||||||
import { removeSignedFieldWithToken } from '@documenso/lib/server-only/field/remove-signed-field-with-token';
|
import { removeSignedFieldWithToken } from '@documenso/lib/server-only/field/remove-signed-field-with-token';
|
||||||
import { setFieldsForDocument } from '@documenso/lib/server-only/field/set-fields-for-document';
|
import { setFieldsForDocument } from '@documenso/lib/server-only/field/set-fields-for-document';
|
||||||
import { setFieldsForTemplate } from '@documenso/lib/server-only/field/set-fields-for-template';
|
import { setFieldsForTemplate } from '@documenso/lib/server-only/field/set-fields-for-template';
|
||||||
@ -71,22 +72,21 @@ export const fieldRouter = router({
|
|||||||
.input(ZSignFieldWithTokenMutationSchema)
|
.input(ZSignFieldWithTokenMutationSchema)
|
||||||
.mutation(async ({ input, ctx }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
try {
|
try {
|
||||||
const { token, fieldId, value, isBase64 } = input;
|
const { token, fieldId, value, isBase64, authOptions } = input;
|
||||||
|
|
||||||
return await signFieldWithToken({
|
return await signFieldWithToken({
|
||||||
token,
|
token,
|
||||||
fieldId,
|
fieldId,
|
||||||
value,
|
value,
|
||||||
isBase64,
|
isBase64,
|
||||||
|
userId: ctx.user?.id,
|
||||||
|
authOptions,
|
||||||
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
||||||
throw new TRPCError({
|
throw AppError.parseErrorToTRPCError(err);
|
||||||
code: 'BAD_REQUEST',
|
|
||||||
message: 'We were unable to sign this field. Please try again later.',
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { ZRecipientActionAuthSchema } from '@documenso/lib/types/document-auth';
|
||||||
import { FieldType } from '@documenso/prisma/client';
|
import { FieldType } from '@documenso/prisma/client';
|
||||||
|
|
||||||
export const ZAddFieldsMutationSchema = z.object({
|
export const ZAddFieldsMutationSchema = z.object({
|
||||||
@ -45,6 +46,7 @@ export const ZSignFieldWithTokenMutationSchema = z.object({
|
|||||||
fieldId: z.number(),
|
fieldId: z.number(),
|
||||||
value: z.string().trim(),
|
value: z.string().trim(),
|
||||||
isBase64: z.boolean().optional(),
|
isBase64: z.boolean().optional(),
|
||||||
|
authOptions: ZRecipientActionAuthSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TSignFieldWithTokenMutationSchema = z.infer<typeof ZSignFieldWithTokenMutationSchema>;
|
export type TSignFieldWithTokenMutationSchema = z.infer<typeof ZSignFieldWithTokenMutationSchema>;
|
||||||
|
|||||||
@ -28,6 +28,7 @@ export const recipientRouter = router({
|
|||||||
email: signer.email,
|
email: signer.email,
|
||||||
name: signer.name,
|
name: signer.name,
|
||||||
role: signer.role,
|
role: signer.role,
|
||||||
|
actionAuth: signer.actionAuth,
|
||||||
})),
|
})),
|
||||||
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
||||||
});
|
});
|
||||||
@ -71,11 +72,13 @@ export const recipientRouter = router({
|
|||||||
.input(ZCompleteDocumentWithTokenMutationSchema)
|
.input(ZCompleteDocumentWithTokenMutationSchema)
|
||||||
.mutation(async ({ input, ctx }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
try {
|
try {
|
||||||
const { token, documentId } = input;
|
const { token, documentId, authOptions } = input;
|
||||||
|
|
||||||
return await completeDocumentWithToken({
|
return await completeDocumentWithToken({
|
||||||
token,
|
token,
|
||||||
documentId,
|
documentId,
|
||||||
|
authOptions,
|
||||||
|
userId: ctx.user?.id,
|
||||||
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
requestMetadata: extractNextApiRequestMetadata(ctx.req),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@ -1,5 +1,9 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import {
|
||||||
|
ZRecipientActionAuthSchema,
|
||||||
|
ZRecipientActionAuthTypesSchema,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
import { RecipientRole } from '@documenso/prisma/client';
|
import { RecipientRole } from '@documenso/prisma/client';
|
||||||
|
|
||||||
export const ZAddSignersMutationSchema = z
|
export const ZAddSignersMutationSchema = z
|
||||||
@ -12,6 +16,7 @@ export const ZAddSignersMutationSchema = z
|
|||||||
email: z.string().email().min(1),
|
email: z.string().email().min(1),
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
role: z.nativeEnum(RecipientRole),
|
role: z.nativeEnum(RecipientRole),
|
||||||
|
actionAuth: ZRecipientActionAuthTypesSchema.optional().nullable(),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
@ -54,6 +59,7 @@ export type TAddTemplateSignersMutationSchema = z.infer<typeof ZAddTemplateSigne
|
|||||||
export const ZCompleteDocumentWithTokenMutationSchema = z.object({
|
export const ZCompleteDocumentWithTokenMutationSchema = z.object({
|
||||||
token: z.string(),
|
token: z.string(),
|
||||||
documentId: z.number(),
|
documentId: z.number(),
|
||||||
|
authOptions: ZRecipientActionAuthSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TCompleteDocumentWithTokenMutationSchema = z.infer<
|
export type TCompleteDocumentWithTokenMutationSchema = z.infer<
|
||||||
|
|||||||
@ -23,7 +23,6 @@ export const authenticatedMiddleware = t.middleware(async ({ ctx, next }) => {
|
|||||||
return await next({
|
return await next({
|
||||||
ctx: {
|
ctx: {
|
||||||
...ctx,
|
...ctx,
|
||||||
|
|
||||||
user: ctx.user,
|
user: ctx.user,
|
||||||
session: ctx.session,
|
session: ctx.session,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -5,11 +5,17 @@ import { motion } from 'framer-motion';
|
|||||||
type AnimateGenericFadeInOutProps = {
|
type AnimateGenericFadeInOutProps = {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
key?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const AnimateGenericFadeInOut = ({ children, className }: AnimateGenericFadeInOutProps) => {
|
export const AnimateGenericFadeInOut = ({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
key,
|
||||||
|
}: AnimateGenericFadeInOutProps) => {
|
||||||
return (
|
return (
|
||||||
<motion.section
|
<motion.section
|
||||||
|
key={key}
|
||||||
initial={{
|
initial={{
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@ -60,7 +60,7 @@ export const DocumentDownloadButton = ({
|
|||||||
loading={isLoading}
|
loading={isLoading}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<Download className="mr-2 h-5 w-5" />
|
{!isLoading && <Download className="mr-2 h-5 w-5" />}
|
||||||
Download
|
Download
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -16,7 +16,7 @@ const Checkbox = React.forwardRef<
|
|||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
'border-input ring-offset-background focus-visible:ring-ring data-[state=checked]:border-primary peer h-4 w-4 shrink-0 rounded-sm border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
'border-input bg-background ring-offset-background focus-visible:ring-ring data-[state=checked]:border-primary peer h-4 w-4 shrink-0 rounded-sm border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
351
packages/ui/primitives/document-flow/add-settings.tsx
Normal file
351
packages/ui/primitives/document-flow/add-settings.tsx
Normal file
@ -0,0 +1,351 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { InfoIcon } from 'lucide-react';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
|
||||||
|
import { DATE_FORMATS, DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
||||||
|
import { DOCUMENT_AUTH_TYPES } from '@documenso/lib/constants/document-auth';
|
||||||
|
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
|
||||||
|
import { DocumentAccessAuth, DocumentActionAuth } from '@documenso/lib/types/document-auth';
|
||||||
|
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
|
||||||
|
import { DocumentStatus, type Field, type Recipient, SendStatus } from '@documenso/prisma/client';
|
||||||
|
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
|
||||||
|
import {
|
||||||
|
Accordion,
|
||||||
|
AccordionContent,
|
||||||
|
AccordionItem,
|
||||||
|
AccordionTrigger,
|
||||||
|
} from '@documenso/ui/primitives/accordion';
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
FormControl,
|
||||||
|
FormField,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormMessage,
|
||||||
|
} from '@documenso/ui/primitives/form/form';
|
||||||
|
|
||||||
|
import { Combobox } from '../combobox';
|
||||||
|
import { Input } from '../input';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../select';
|
||||||
|
import { useStep } from '../stepper';
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from '../tooltip';
|
||||||
|
import type { TAddSettingsFormSchema } from './add-settings.types';
|
||||||
|
import { ZAddSettingsFormSchema } from './add-settings.types';
|
||||||
|
import {
|
||||||
|
DocumentFlowFormContainerActions,
|
||||||
|
DocumentFlowFormContainerContent,
|
||||||
|
DocumentFlowFormContainerFooter,
|
||||||
|
DocumentFlowFormContainerHeader,
|
||||||
|
DocumentFlowFormContainerStep,
|
||||||
|
} from './document-flow-root';
|
||||||
|
import { ShowFieldItem } from './show-field-item';
|
||||||
|
import type { DocumentFlowStep } from './types';
|
||||||
|
|
||||||
|
export type AddSettingsFormProps = {
|
||||||
|
documentFlow: DocumentFlowStep;
|
||||||
|
recipients: Recipient[];
|
||||||
|
fields: Field[];
|
||||||
|
document: DocumentWithData;
|
||||||
|
onSubmit: (_data: TAddSettingsFormSchema) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AddSettingsFormPartial = ({
|
||||||
|
documentFlow,
|
||||||
|
recipients,
|
||||||
|
fields,
|
||||||
|
document,
|
||||||
|
onSubmit,
|
||||||
|
}: AddSettingsFormProps) => {
|
||||||
|
const { documentAuthOption } = extractDocumentAuthMethods({
|
||||||
|
documentAuth: document.authOptions,
|
||||||
|
});
|
||||||
|
|
||||||
|
const form = useForm<TAddSettingsFormSchema>({
|
||||||
|
resolver: zodResolver(ZAddSettingsFormSchema),
|
||||||
|
defaultValues: {
|
||||||
|
title: document.title,
|
||||||
|
globalAccessAuth: documentAuthOption?.globalAccessAuth || undefined,
|
||||||
|
globalActionAuth: documentAuthOption?.globalActionAuth || undefined,
|
||||||
|
meta: {
|
||||||
|
timezone: document.documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE,
|
||||||
|
dateFormat: document.documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
|
||||||
|
redirectUrl: document.documentMeta?.redirectUrl ?? '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { stepIndex, currentStep, totalSteps, previousStep } = useStep();
|
||||||
|
|
||||||
|
const documentHasBeenSent = recipients.some(
|
||||||
|
(recipient) => recipient.sendStatus === SendStatus.SENT,
|
||||||
|
);
|
||||||
|
|
||||||
|
// We almost always want to set the timezone to the user's local timezone to avoid confusion
|
||||||
|
// when the document is signed.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!form.formState.touchedFields.meta?.timezone && !documentHasBeenSent) {
|
||||||
|
form.setValue('meta.timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||||
|
}
|
||||||
|
}, [documentHasBeenSent, form, form.setValue, form.formState.touchedFields.meta?.timezone]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<DocumentFlowFormContainerHeader
|
||||||
|
title={documentFlow.title}
|
||||||
|
description={documentFlow.description}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DocumentFlowFormContainerContent>
|
||||||
|
{fields.map((field, index) => (
|
||||||
|
<ShowFieldItem key={index} field={field} recipients={recipients} />
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Form {...form}>
|
||||||
|
<fieldset
|
||||||
|
className="flex h-full flex-col space-y-6"
|
||||||
|
disabled={form.formState.isSubmitting}
|
||||||
|
>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="title"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel required>Title</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
className="bg-background"
|
||||||
|
{...field}
|
||||||
|
disabled={document.status !== DocumentStatus.DRAFT || field.disabled}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="globalAccessAuth"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel className="flex flex-row items-center">
|
||||||
|
Document access
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger>
|
||||||
|
<InfoIcon className="mx-2 h-4 w-4" />
|
||||||
|
</TooltipTrigger>
|
||||||
|
|
||||||
|
<TooltipContent className="text-foreground max-w-md space-y-2 p-4">
|
||||||
|
<p>The authentication requirement for recipients to view the document.</p>
|
||||||
|
|
||||||
|
<ul className="space-y-0.5">
|
||||||
|
<li>
|
||||||
|
<strong>Require account</strong> - The recipient must have an account,
|
||||||
|
and be signed in to view the document
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>None</strong> - The document can be accessed directly by the URL
|
||||||
|
sent to the recipient
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Select {...field} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger className="bg-background text-muted-foreground">
|
||||||
|
<SelectValue placeholder="None" />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent position="popper">
|
||||||
|
{Object.values(DocumentAccessAuth).map((authType) => (
|
||||||
|
<SelectItem key={authType} value={authType}>
|
||||||
|
{DOCUMENT_AUTH_TYPES[authType].value}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Note: -1 is remapped in the Zod schema to the required value. */}
|
||||||
|
<SelectItem value={'-1'}>None</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="globalActionAuth"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel className="flex flex-row items-center">
|
||||||
|
Recipient signing authentication
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger>
|
||||||
|
<InfoIcon className="mx-2 h-4 w-4" />
|
||||||
|
</TooltipTrigger>
|
||||||
|
|
||||||
|
<TooltipContent className="text-foreground max-w-md space-y-2 p-4">
|
||||||
|
<p>The authentication requirement for recipients to sign fields.</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
You can also override this global setting by setting the authentication
|
||||||
|
requirements directly on each recipient in the next step.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ul className="space-y-0.5">
|
||||||
|
<li>
|
||||||
|
<strong>Require account</strong> - The recipient must have an account,
|
||||||
|
and be signed in to sign fields
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>None</strong> - The recipient does not need any authentication
|
||||||
|
to sign fields
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Select {...field} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger className="bg-background text-muted-foreground">
|
||||||
|
<SelectValue placeholder="None" />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent position="popper">
|
||||||
|
{Object.values(DocumentActionAuth).map((authType) => (
|
||||||
|
<SelectItem key={authType} value={authType}>
|
||||||
|
{DOCUMENT_AUTH_TYPES[authType].value}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Note: -1 is remapped in the Zod schema to the required value. */}
|
||||||
|
<SelectItem value={'-1'}>None</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Accordion type="multiple" className="mt-6">
|
||||||
|
<AccordionItem value="advanced-options" className="border-none">
|
||||||
|
<AccordionTrigger className="text-foreground mb-2 rounded border px-3 py-2 text-left hover:bg-neutral-200/30 hover:no-underline">
|
||||||
|
Advanced Options
|
||||||
|
</AccordionTrigger>
|
||||||
|
|
||||||
|
<AccordionContent className="text-muted-foreground -mx-1 px-1 pt-2 text-sm leading-relaxed">
|
||||||
|
<div className="flex flex-col space-y-6 ">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="meta.dateFormat"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Date Format</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Select
|
||||||
|
{...field}
|
||||||
|
onValueChange={field.onChange}
|
||||||
|
disabled={documentHasBeenSent}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="bg-background">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent>
|
||||||
|
{DATE_FORMATS.map((format) => (
|
||||||
|
<SelectItem key={format.key} value={format.value}>
|
||||||
|
{format.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="meta.timezone"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Time Zone</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Combobox
|
||||||
|
className="bg-background"
|
||||||
|
options={TIME_ZONES}
|
||||||
|
{...field}
|
||||||
|
onChange={(value) => value && field.onChange(value)}
|
||||||
|
disabled={documentHasBeenSent}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="meta.redirectUrl"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel className="flex flex-row items-center">
|
||||||
|
Redirect URL{' '}
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger>
|
||||||
|
<InfoIcon className="mx-2 h-4 w-4" />
|
||||||
|
</TooltipTrigger>
|
||||||
|
|
||||||
|
<TooltipContent className="text-muted-foreground max-w-xs">
|
||||||
|
Add a URL to redirect the user to once the document is signed
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</FormLabel>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Input className="bg-background" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
</fieldset>
|
||||||
|
</Form>
|
||||||
|
</DocumentFlowFormContainerContent>
|
||||||
|
|
||||||
|
<DocumentFlowFormContainerFooter>
|
||||||
|
<DocumentFlowFormContainerStep
|
||||||
|
title={documentFlow.title}
|
||||||
|
step={currentStep}
|
||||||
|
maxStep={totalSteps}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DocumentFlowFormContainerActions
|
||||||
|
loading={form.formState.isSubmitting}
|
||||||
|
disabled={form.formState.isSubmitting}
|
||||||
|
canGoBack={stepIndex !== 0}
|
||||||
|
onGoBackClick={previousStep}
|
||||||
|
onGoNextClick={form.handleSubmit(onSubmit)}
|
||||||
|
/>
|
||||||
|
</DocumentFlowFormContainerFooter>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
42
packages/ui/primitives/document-flow/add-settings.types.ts
Normal file
42
packages/ui/primitives/document-flow/add-settings.types.ts
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
||||||
|
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
||||||
|
import { URL_REGEX } from '@documenso/lib/constants/url-regex';
|
||||||
|
import {
|
||||||
|
ZDocumentAccessAuthTypesSchema,
|
||||||
|
ZDocumentActionAuthTypesSchema,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
|
|
||||||
|
export const ZMapNegativeOneToUndefinedSchema = z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.transform((val) => {
|
||||||
|
if (val === '-1') {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return val;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ZAddSettingsFormSchema = z.object({
|
||||||
|
title: z.string().trim().min(1, { message: "Title can't be empty" }),
|
||||||
|
globalAccessAuth: ZMapNegativeOneToUndefinedSchema.pipe(
|
||||||
|
ZDocumentAccessAuthTypesSchema.optional(),
|
||||||
|
),
|
||||||
|
globalActionAuth: ZMapNegativeOneToUndefinedSchema.pipe(
|
||||||
|
ZDocumentActionAuthTypesSchema.optional(),
|
||||||
|
),
|
||||||
|
meta: z.object({
|
||||||
|
timezone: z.string().optional().default(DEFAULT_DOCUMENT_TIME_ZONE),
|
||||||
|
dateFormat: z.string().optional().default(DEFAULT_DOCUMENT_DATE_FORMAT),
|
||||||
|
redirectUrl: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.refine((value) => value === undefined || value === '' || URL_REGEX.test(value), {
|
||||||
|
message: 'Please enter a valid URL',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TAddSettingsFormSchema = z.infer<typeof ZAddSettingsFormSchema>;
|
||||||
@ -1,25 +1,33 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React, { useId } from 'react';
|
import React, { useId, useMemo, useState } from 'react';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { AnimatePresence, motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import { Plus, Trash } from 'lucide-react';
|
import { InfoIcon, Plus, Trash } from 'lucide-react';
|
||||||
import { Controller, useFieldArray, useForm } from 'react-hook-form';
|
import { useFieldArray, useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { useLimits } from '@documenso/ee/server-only/limits/provider/client';
|
import { useLimits } from '@documenso/ee/server-only/limits/provider/client';
|
||||||
|
import { DOCUMENT_AUTH_TYPES } from '@documenso/lib/constants/document-auth';
|
||||||
|
import {
|
||||||
|
RecipientActionAuth,
|
||||||
|
ZRecipientAuthOptionsSchema,
|
||||||
|
} from '@documenso/lib/types/document-auth';
|
||||||
import { nanoid } from '@documenso/lib/universal/id';
|
import { nanoid } from '@documenso/lib/universal/id';
|
||||||
import type { Field, Recipient } from '@documenso/prisma/client';
|
import type { Field, Recipient } from '@documenso/prisma/client';
|
||||||
import { DocumentStatus, RecipientRole, SendStatus } from '@documenso/prisma/client';
|
import { RecipientRole, SendStatus } from '@documenso/prisma/client';
|
||||||
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
|
import { AnimateGenericFadeInOut } from '@documenso/ui/components/animate/animate-generic-fade-in-out';
|
||||||
|
import { cn } from '@documenso/ui/lib/utils';
|
||||||
|
|
||||||
import { Button } from '../button';
|
import { Button } from '../button';
|
||||||
|
import { Checkbox } from '../checkbox';
|
||||||
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../form/form';
|
||||||
import { FormErrorMessage } from '../form/form-error-message';
|
import { FormErrorMessage } from '../form/form-error-message';
|
||||||
import { Input } from '../input';
|
import { Input } from '../input';
|
||||||
import { Label } from '../label';
|
|
||||||
import { ROLE_ICONS } from '../recipient-role-icons';
|
import { ROLE_ICONS } from '../recipient-role-icons';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger } from '../select';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../select';
|
||||||
import { useStep } from '../stepper';
|
import { useStep } from '../stepper';
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from '../tooltip';
|
||||||
import { useToast } from '../use-toast';
|
import { useToast } from '../use-toast';
|
||||||
import type { TAddSignersFormSchema } from './add-signers.types';
|
import type { TAddSignersFormSchema } from './add-signers.types';
|
||||||
import { ZAddSignersFormSchema } from './add-signers.types';
|
import { ZAddSignersFormSchema } from './add-signers.types';
|
||||||
@ -37,14 +45,12 @@ export type AddSignersFormProps = {
|
|||||||
documentFlow: DocumentFlowStep;
|
documentFlow: DocumentFlowStep;
|
||||||
recipients: Recipient[];
|
recipients: Recipient[];
|
||||||
fields: Field[];
|
fields: Field[];
|
||||||
document: DocumentWithData;
|
|
||||||
onSubmit: (_data: TAddSignersFormSchema) => void;
|
onSubmit: (_data: TAddSignersFormSchema) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const AddSignersFormPartial = ({
|
export const AddSignersFormPartial = ({
|
||||||
documentFlow,
|
documentFlow,
|
||||||
recipients,
|
recipients,
|
||||||
document,
|
|
||||||
fields,
|
fields,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
}: AddSignersFormProps) => {
|
}: AddSignersFormProps) => {
|
||||||
@ -55,11 +61,7 @@ export const AddSignersFormPartial = ({
|
|||||||
|
|
||||||
const { currentStep, totalSteps, previousStep } = useStep();
|
const { currentStep, totalSteps, previousStep } = useStep();
|
||||||
|
|
||||||
const {
|
const form = useForm<TAddSignersFormSchema>({
|
||||||
control,
|
|
||||||
handleSubmit,
|
|
||||||
formState: { errors, isSubmitting },
|
|
||||||
} = useForm<TAddSignersFormSchema>({
|
|
||||||
resolver: zodResolver(ZAddSignersFormSchema),
|
resolver: zodResolver(ZAddSignersFormSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
signers:
|
signers:
|
||||||
@ -70,6 +72,8 @@ export const AddSignersFormPartial = ({
|
|||||||
name: recipient.name,
|
name: recipient.name,
|
||||||
email: recipient.email,
|
email: recipient.email,
|
||||||
role: recipient.role,
|
role: recipient.role,
|
||||||
|
actionAuth:
|
||||||
|
ZRecipientAuthOptionsSchema.parse(recipient.authOptions)?.actionAuth ?? undefined,
|
||||||
}))
|
}))
|
||||||
: [
|
: [
|
||||||
{
|
{
|
||||||
@ -77,12 +81,33 @@ export const AddSignersFormPartial = ({
|
|||||||
name: '',
|
name: '',
|
||||||
email: '',
|
email: '',
|
||||||
role: RecipientRole.SIGNER,
|
role: RecipientRole.SIGNER,
|
||||||
|
actionAuth: undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const onFormSubmit = handleSubmit(onSubmit);
|
// Always show advanced settings if any recipient has auth options.
|
||||||
|
const alwaysShowAdvancedSettings = useMemo(() => {
|
||||||
|
const recipientHasAuthOptions = recipients.find((recipient) => {
|
||||||
|
const recipientAuthOptions = ZRecipientAuthOptionsSchema.parse(recipient.authOptions);
|
||||||
|
|
||||||
|
return recipientAuthOptions?.accessAuth || recipientAuthOptions?.actionAuth;
|
||||||
|
});
|
||||||
|
|
||||||
|
const formHasActionAuth = form.getValues('signers').find((signer) => signer.actionAuth);
|
||||||
|
|
||||||
|
return recipientHasAuthOptions !== undefined || formHasActionAuth !== undefined;
|
||||||
|
}, [recipients, form]);
|
||||||
|
|
||||||
|
const [showAdvancedSettings, setShowAdvancedSettings] = useState(alwaysShowAdvancedSettings);
|
||||||
|
|
||||||
|
const {
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
control,
|
||||||
|
} = form;
|
||||||
|
|
||||||
|
const onFormSubmit = form.handleSubmit(onSubmit);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
append: appendSigner,
|
append: appendSigner,
|
||||||
@ -112,6 +137,7 @@ export const AddSignersFormPartial = ({
|
|||||||
name: '',
|
name: '',
|
||||||
email: '',
|
email: '',
|
||||||
role: RecipientRole.SIGNER,
|
role: RecipientRole.SIGNER,
|
||||||
|
actionAuth: undefined,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -144,105 +170,190 @@ export const AddSignersFormPartial = ({
|
|||||||
description={documentFlow.description}
|
description={documentFlow.description}
|
||||||
/>
|
/>
|
||||||
<DocumentFlowFormContainerContent>
|
<DocumentFlowFormContainerContent>
|
||||||
<div className="flex w-full flex-col gap-y-4">
|
{fields.map((field, index) => (
|
||||||
{fields.map((field, index) => (
|
<ShowFieldItem key={index} field={field} recipients={recipients} />
|
||||||
<ShowFieldItem key={index} field={field} recipients={recipients} />
|
))}
|
||||||
))}
|
|
||||||
|
|
||||||
<AnimatePresence>
|
<AnimateGenericFadeInOut key={showAdvancedSettings ? 'Show' : 'Hide'}>
|
||||||
{signers.map((signer, index) => (
|
<Form {...form}>
|
||||||
<motion.div
|
<div className="flex w-full flex-col gap-y-2">
|
||||||
key={signer.id}
|
{signers.map((signer, index) => (
|
||||||
data-native-id={signer.nativeId}
|
<motion.div
|
||||||
className="flex flex-wrap items-end gap-x-4"
|
key={signer.id}
|
||||||
>
|
data-native-id={signer.nativeId}
|
||||||
<div className="flex-1">
|
className={cn('grid grid-cols-8 gap-4 pb-4', {
|
||||||
<Label htmlFor={`signer-${signer.id}-email`}>
|
'border-b pt-2': showAdvancedSettings,
|
||||||
Email
|
})}
|
||||||
<span className="text-destructive ml-1 inline-block font-medium">*</span>
|
>
|
||||||
</Label>
|
<FormField
|
||||||
|
control={form.control}
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`signers.${index}.email`}
|
name={`signers.${index}.email`}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<Input
|
<FormItem
|
||||||
id={`signer-${signer.id}-email`}
|
className={cn('relative', {
|
||||||
type="email"
|
'col-span-3': !showAdvancedSettings,
|
||||||
className="bg-background mt-2"
|
'col-span-4': showAdvancedSettings,
|
||||||
disabled={isSubmitting || hasBeenSentToRecipientId(signer.nativeId)}
|
})}
|
||||||
onKeyDown={onKeyDown}
|
>
|
||||||
{...field}
|
{!showAdvancedSettings && index === 0 && (
|
||||||
/>
|
<FormLabel required>Email</FormLabel>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
placeholder="Email"
|
||||||
|
disabled={isSubmitting || hasBeenSentToRecipientId(signer.nativeId)}
|
||||||
|
{...field}
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex-1">
|
<FormField
|
||||||
<Label htmlFor={`signer-${signer.id}-name`}>Name</Label>
|
control={form.control}
|
||||||
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`signers.${index}.name`}
|
name={`signers.${index}.name`}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<Input
|
<FormItem
|
||||||
id={`signer-${signer.id}-name`}
|
className={cn({
|
||||||
type="text"
|
'col-span-3': !showAdvancedSettings,
|
||||||
className="bg-background mt-2"
|
'col-span-4': showAdvancedSettings,
|
||||||
disabled={isSubmitting || hasBeenSentToRecipientId(signer.nativeId)}
|
})}
|
||||||
onKeyDown={onKeyDown}
|
>
|
||||||
{...field}
|
{!showAdvancedSettings && index === 0 && (
|
||||||
/>
|
<FormLabel required>Name</FormLabel>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
placeholder="Name"
|
||||||
|
disabled={isSubmitting || hasBeenSentToRecipientId(signer.nativeId)}
|
||||||
|
{...field}
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="w-[60px]">
|
{showAdvancedSettings && (
|
||||||
<Controller
|
<FormField
|
||||||
control={control}
|
control={form.control}
|
||||||
|
name={`signers.${index}.actionAuth`}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="col-span-6">
|
||||||
|
<FormControl>
|
||||||
|
<Select {...field} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger className="bg-background text-muted-foreground">
|
||||||
|
<SelectValue placeholder="Inherit authentication method" />
|
||||||
|
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger className="-mr-1 ml-auto">
|
||||||
|
<InfoIcon className="mx-2 h-4 w-4" />
|
||||||
|
</TooltipTrigger>
|
||||||
|
|
||||||
|
<TooltipContent className="text-foreground max-w-md p-4">
|
||||||
|
<p>
|
||||||
|
The authentication requirements for recipients to sign fields.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p className="mt-2">This will override any global settings.</p>
|
||||||
|
|
||||||
|
<ul className="mt-2 space-y-0.5">
|
||||||
|
<li>
|
||||||
|
<strong>Inherit authentication method</strong> - Use the
|
||||||
|
global recipient signing authentication method configured in
|
||||||
|
the "General Settings" step
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Require account</strong> - The recipient must have
|
||||||
|
an account, and be signed in to sign fields
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>None</strong> - The recipient does not need any
|
||||||
|
authentication to sign fields
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent position="popper">
|
||||||
|
{/* Note: -1 is remapped in the Zod schema to the required value. */}
|
||||||
|
<SelectItem value="-1">Inherit authentication method</SelectItem>
|
||||||
|
|
||||||
|
{Object.values(RecipientActionAuth).map((authType) => (
|
||||||
|
<SelectItem key={authType} value={authType}>
|
||||||
|
{DOCUMENT_AUTH_TYPES[authType].value}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FormField
|
||||||
name={`signers.${index}.role`}
|
name={`signers.${index}.role`}
|
||||||
render={({ field: { value, onChange } }) => (
|
render={({ field }) => (
|
||||||
<Select value={value} onValueChange={(x) => onChange(x)}>
|
<FormItem className="col-span-1 mt-auto">
|
||||||
<SelectTrigger className="bg-background">{ROLE_ICONS[value]}</SelectTrigger>
|
<FormControl>
|
||||||
|
<Select {...field} onValueChange={field.onChange}>
|
||||||
|
<SelectTrigger className="bg-background w-[60px]">
|
||||||
|
{/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions */}
|
||||||
|
{ROLE_ICONS[field.value as RecipientRole]}
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
<SelectContent className="" align="end">
|
<SelectContent align="end">
|
||||||
<SelectItem value={RecipientRole.SIGNER}>
|
<SelectItem value={RecipientRole.SIGNER}>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<span className="mr-2">{ROLE_ICONS[RecipientRole.SIGNER]}</span>
|
<span className="mr-2">{ROLE_ICONS[RecipientRole.SIGNER]}</span>
|
||||||
Signer
|
Signer
|
||||||
</div>
|
</div>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
|
||||||
<SelectItem value={RecipientRole.CC}>
|
<SelectItem value={RecipientRole.CC}>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<span className="mr-2">{ROLE_ICONS[RecipientRole.CC]}</span>
|
<span className="mr-2">{ROLE_ICONS[RecipientRole.CC]}</span>
|
||||||
Receives copy
|
Receives copy
|
||||||
</div>
|
</div>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
|
||||||
<SelectItem value={RecipientRole.APPROVER}>
|
<SelectItem value={RecipientRole.APPROVER}>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<span className="mr-2">{ROLE_ICONS[RecipientRole.APPROVER]}</span>
|
<span className="mr-2">{ROLE_ICONS[RecipientRole.APPROVER]}</span>
|
||||||
Approver
|
Approver
|
||||||
</div>
|
</div>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
|
||||||
<SelectItem value={RecipientRole.VIEWER}>
|
<SelectItem value={RecipientRole.VIEWER}>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<span className="mr-2">{ROLE_ICONS[RecipientRole.VIEWER]}</span>
|
<span className="mr-2">{ROLE_ICONS[RecipientRole.VIEWER]}</span>
|
||||||
Viewer
|
Viewer
|
||||||
</div>
|
</div>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="justify-left inline-flex h-10 w-10 items-center text-slate-500 hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
|
className="col-span-1 mt-auto inline-flex h-10 w-10 items-center justify-center text-slate-500 hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
disabled={
|
disabled={
|
||||||
isSubmitting ||
|
isSubmitting ||
|
||||||
hasBeenSentToRecipientId(signer.nativeId) ||
|
hasBeenSentToRecipientId(signer.nativeId) ||
|
||||||
@ -252,33 +363,51 @@ export const AddSignersFormPartial = ({
|
|||||||
>
|
>
|
||||||
<Trash className="h-5 w-5" />
|
<Trash className="h-5 w-5" />
|
||||||
</button>
|
</button>
|
||||||
|
</motion.div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormErrorMessage
|
||||||
|
className="mt-2"
|
||||||
|
// Dirty hack to handle errors when .root is populated for an array type
|
||||||
|
error={'signers__root' in errors && errors['signers__root']}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className={cn('mt-2 flex flex-row items-center space-x-4', {
|
||||||
|
'mt-4': showAdvancedSettings,
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
disabled={isSubmitting || signers.length >= remaining.recipients}
|
||||||
|
onClick={() => onAddSigner()}
|
||||||
|
>
|
||||||
|
<Plus className="-ml-1 mr-2 h-5 w-5" />
|
||||||
|
Add Signer
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{!alwaysShowAdvancedSettings && (
|
||||||
|
<div className="flex flex-row items-center">
|
||||||
|
<Checkbox
|
||||||
|
id="showAdvancedRecipientSettings"
|
||||||
|
className="h-5 w-5"
|
||||||
|
checkClassName="dark:text-white text-primary"
|
||||||
|
checked={showAdvancedSettings}
|
||||||
|
onCheckedChange={(value) => setShowAdvancedSettings(Boolean(value))}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<label
|
||||||
|
className="text-muted-foreground ml-2 text-sm"
|
||||||
|
htmlFor="showAdvancedRecipientSettings"
|
||||||
|
>
|
||||||
|
Show advanced settings
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
<div className="w-full">
|
</div>
|
||||||
<FormErrorMessage className="mt-2" error={errors.signers?.[index]?.email} />
|
</Form>
|
||||||
<FormErrorMessage className="mt-2" error={errors.signers?.[index]?.name} />
|
</AnimateGenericFadeInOut>
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
))}
|
|
||||||
</AnimatePresence>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<FormErrorMessage
|
|
||||||
className="mt-2"
|
|
||||||
// Dirty hack to handle errors when .root is populated for an array type
|
|
||||||
error={'signers__root' in errors && errors['signers__root']}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="mt-4">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
disabled={isSubmitting || signers.length >= remaining.recipients}
|
|
||||||
onClick={() => onAddSigner()}
|
|
||||||
>
|
|
||||||
<Plus className="-ml-1 mr-2 h-5 w-5" />
|
|
||||||
Add Signer
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</DocumentFlowFormContainerContent>
|
</DocumentFlowFormContainerContent>
|
||||||
|
|
||||||
<DocumentFlowFormContainerFooter>
|
<DocumentFlowFormContainerFooter>
|
||||||
@ -289,7 +418,6 @@ export const AddSignersFormPartial = ({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<DocumentFlowFormContainerActions
|
<DocumentFlowFormContainerActions
|
||||||
canGoBack={document.status === DocumentStatus.DRAFT}
|
|
||||||
loading={isSubmitting}
|
loading={isSubmitting}
|
||||||
disabled={isSubmitting}
|
disabled={isSubmitting}
|
||||||
onGoBackClick={previousStep}
|
onGoBackClick={previousStep}
|
||||||
|
|||||||
@ -1,5 +1,8 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { ZRecipientActionAuthTypesSchema } from '@documenso/lib/types/document-auth';
|
||||||
|
|
||||||
|
import { ZMapNegativeOneToUndefinedSchema } from './add-settings.types';
|
||||||
import { RecipientRole } from '.prisma/client';
|
import { RecipientRole } from '.prisma/client';
|
||||||
|
|
||||||
export const ZAddSignersFormSchema = z
|
export const ZAddSignersFormSchema = z
|
||||||
@ -11,6 +14,9 @@ export const ZAddSignersFormSchema = z
|
|||||||
email: z.string().email().min(1),
|
email: z.string().email().min(1),
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
role: z.nativeEnum(RecipientRole),
|
role: z.nativeEnum(RecipientRole),
|
||||||
|
actionAuth: ZMapNegativeOneToUndefinedSchema.pipe(
|
||||||
|
ZRecipientActionAuthTypesSchema.optional(),
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|||||||
@ -1,33 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { Info } from 'lucide-react';
|
import { useForm } from 'react-hook-form';
|
||||||
import { Controller, useForm } from 'react-hook-form';
|
|
||||||
|
|
||||||
import { DATE_FORMATS, DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
|
||||||
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
|
|
||||||
import type { Field, Recipient } from '@documenso/prisma/client';
|
import type { Field, Recipient } from '@documenso/prisma/client';
|
||||||
import { DocumentStatus } from '@documenso/prisma/client';
|
import { DocumentStatus } from '@documenso/prisma/client';
|
||||||
import { SendStatus } from '@documenso/prisma/client';
|
|
||||||
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
|
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
|
||||||
import {
|
|
||||||
Accordion,
|
|
||||||
AccordionContent,
|
|
||||||
AccordionItem,
|
|
||||||
AccordionTrigger,
|
|
||||||
} from '@documenso/ui/primitives/accordion';
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@documenso/ui/primitives/select';
|
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
|
|
||||||
|
|
||||||
import { Combobox } from '../combobox';
|
|
||||||
import { FormErrorMessage } from '../form/form-error-message';
|
import { FormErrorMessage } from '../form/form-error-message';
|
||||||
import { Input } from '../input';
|
import { Input } from '../input';
|
||||||
import { Label } from '../label';
|
import { Label } from '../label';
|
||||||
@ -60,19 +39,14 @@ export const AddSubjectFormPartial = ({
|
|||||||
onSubmit,
|
onSubmit,
|
||||||
}: AddSubjectFormProps) => {
|
}: AddSubjectFormProps) => {
|
||||||
const {
|
const {
|
||||||
control,
|
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
formState: { errors, isSubmitting, touchedFields },
|
formState: { errors, isSubmitting },
|
||||||
setValue,
|
|
||||||
} = useForm<TAddSubjectFormSchema>({
|
} = useForm<TAddSubjectFormSchema>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
meta: {
|
meta: {
|
||||||
subject: document.documentMeta?.subject ?? '',
|
subject: document.documentMeta?.subject ?? '',
|
||||||
message: document.documentMeta?.message ?? '',
|
message: document.documentMeta?.message ?? '',
|
||||||
timezone: document.documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE,
|
|
||||||
dateFormat: document.documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
|
|
||||||
redirectUrl: document.documentMeta?.redirectUrl ?? '',
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
resolver: zodResolver(ZAddSubjectFormSchema),
|
resolver: zodResolver(ZAddSubjectFormSchema),
|
||||||
@ -81,20 +55,6 @@ export const AddSubjectFormPartial = ({
|
|||||||
const onFormSubmit = handleSubmit(onSubmit);
|
const onFormSubmit = handleSubmit(onSubmit);
|
||||||
const { currentStep, totalSteps, previousStep } = useStep();
|
const { currentStep, totalSteps, previousStep } = useStep();
|
||||||
|
|
||||||
const hasDateField = fields.find((field) => field.type === 'DATE');
|
|
||||||
|
|
||||||
const documentHasBeenSent = recipients.some(
|
|
||||||
(recipient) => recipient.sendStatus === SendStatus.SENT,
|
|
||||||
);
|
|
||||||
|
|
||||||
// We almost always want to set the timezone to the user's local timezone to avoid confusion
|
|
||||||
// when the document is signed.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!touchedFields.meta?.timezone && !documentHasBeenSent) {
|
|
||||||
setValue('meta.timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
||||||
}
|
|
||||||
}, [documentHasBeenSent, setValue, touchedFields.meta?.timezone]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DocumentFlowFormContainerHeader
|
<DocumentFlowFormContainerHeader
|
||||||
@ -167,95 +127,6 @@ export const AddSubjectFormPartial = ({
|
|||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Accordion type="multiple" className="mt-8 border-none">
|
|
||||||
<AccordionItem value="advanced-options" className="border-none">
|
|
||||||
<AccordionTrigger className="mb-2 border-b text-left hover:no-underline">
|
|
||||||
Advanced Options
|
|
||||||
</AccordionTrigger>
|
|
||||||
|
|
||||||
<AccordionContent className="text-muted-foreground -mx-1 flex max-w-prose flex-col px-1 pt-2 text-sm leading-relaxed">
|
|
||||||
{hasDateField && (
|
|
||||||
<>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<Label htmlFor="date-format">
|
|
||||||
Date Format <span className="text-muted-foreground">(Optional)</span>
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`meta.dateFormat`}
|
|
||||||
disabled={documentHasBeenSent}
|
|
||||||
render={({ field: { value, onChange, disabled } }) => (
|
|
||||||
<Select value={value} onValueChange={onChange} disabled={disabled}>
|
|
||||||
<SelectTrigger className="bg-background mt-2">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
|
|
||||||
<SelectContent>
|
|
||||||
{DATE_FORMATS.map((format) => (
|
|
||||||
<SelectItem key={format.key} value={format.value}>
|
|
||||||
{format.label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4 flex flex-col">
|
|
||||||
<Label htmlFor="time-zone">
|
|
||||||
Time Zone <span className="text-muted-foreground">(Optional)</span>
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`meta.timezone`}
|
|
||||||
render={({ field: { value, onChange } }) => (
|
|
||||||
<Combobox
|
|
||||||
className="bg-background"
|
|
||||||
options={TIME_ZONES}
|
|
||||||
value={value}
|
|
||||||
onChange={(value) => value && onChange(value)}
|
|
||||||
disabled={documentHasBeenSent}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mt-2 flex flex-col">
|
|
||||||
<div className="flex flex-col gap-y-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="redirectUrl" className="flex items-center">
|
|
||||||
Redirect URL{' '}
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger>
|
|
||||||
<Info className="mx-2 h-4 w-4" />
|
|
||||||
</TooltipTrigger>
|
|
||||||
|
|
||||||
<TooltipContent className="text-muted-foreground max-w-xs">
|
|
||||||
Add a URL to redirect the user to once the document is signed
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
<Input
|
|
||||||
id="redirectUrl"
|
|
||||||
type="url"
|
|
||||||
className="bg-background my-2"
|
|
||||||
{...register('meta.redirectUrl')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormErrorMessage className="mt-2" error={errors.meta?.redirectUrl} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</AccordionContent>
|
|
||||||
</AccordionItem>
|
|
||||||
</Accordion>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</DocumentFlowFormContainerContent>
|
</DocumentFlowFormContainerContent>
|
||||||
|
|||||||
@ -1,21 +1,9 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
|
||||||
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
|
|
||||||
import { URL_REGEX } from '@documenso/lib/constants/url-regex';
|
|
||||||
|
|
||||||
export const ZAddSubjectFormSchema = z.object({
|
export const ZAddSubjectFormSchema = z.object({
|
||||||
meta: z.object({
|
meta: z.object({
|
||||||
subject: z.string(),
|
subject: z.string(),
|
||||||
message: z.string(),
|
message: z.string(),
|
||||||
timezone: z.string().optional().default(DEFAULT_DOCUMENT_TIME_ZONE),
|
|
||||||
dateFormat: z.string().optional().default(DEFAULT_DOCUMENT_DATE_FORMAT),
|
|
||||||
redirectUrl: z
|
|
||||||
.string()
|
|
||||||
.optional()
|
|
||||||
.refine((value) => value === undefined || value === '' || URL_REGEX.test(value), {
|
|
||||||
message: 'Please enter a valid URL',
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,103 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { useForm } from 'react-hook-form';
|
|
||||||
|
|
||||||
import type { Field, Recipient } from '@documenso/prisma/client';
|
|
||||||
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
|
|
||||||
|
|
||||||
import { FormErrorMessage } from '../form/form-error-message';
|
|
||||||
import { Input } from '../input';
|
|
||||||
import { Label } from '../label';
|
|
||||||
import { useStep } from '../stepper';
|
|
||||||
import type { TAddTitleFormSchema } from './add-title.types';
|
|
||||||
import { ZAddTitleFormSchema } from './add-title.types';
|
|
||||||
import {
|
|
||||||
DocumentFlowFormContainerActions,
|
|
||||||
DocumentFlowFormContainerContent,
|
|
||||||
DocumentFlowFormContainerFooter,
|
|
||||||
DocumentFlowFormContainerHeader,
|
|
||||||
DocumentFlowFormContainerStep,
|
|
||||||
} from './document-flow-root';
|
|
||||||
import { ShowFieldItem } from './show-field-item';
|
|
||||||
import type { DocumentFlowStep } from './types';
|
|
||||||
|
|
||||||
export type AddTitleFormProps = {
|
|
||||||
documentFlow: DocumentFlowStep;
|
|
||||||
recipients: Recipient[];
|
|
||||||
fields: Field[];
|
|
||||||
document: DocumentWithData;
|
|
||||||
onSubmit: (_data: TAddTitleFormSchema) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AddTitleFormPartial = ({
|
|
||||||
documentFlow,
|
|
||||||
recipients,
|
|
||||||
fields,
|
|
||||||
document,
|
|
||||||
onSubmit,
|
|
||||||
}: AddTitleFormProps) => {
|
|
||||||
const {
|
|
||||||
register,
|
|
||||||
handleSubmit,
|
|
||||||
formState: { errors, isSubmitting },
|
|
||||||
} = useForm<TAddTitleFormSchema>({
|
|
||||||
resolver: zodResolver(ZAddTitleFormSchema),
|
|
||||||
defaultValues: {
|
|
||||||
title: document.title,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const onFormSubmit = handleSubmit(onSubmit);
|
|
||||||
|
|
||||||
const { stepIndex, currentStep, totalSteps, previousStep } = useStep();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<DocumentFlowFormContainerHeader
|
|
||||||
title={documentFlow.title}
|
|
||||||
description={documentFlow.description}
|
|
||||||
/>
|
|
||||||
<DocumentFlowFormContainerContent>
|
|
||||||
{fields.map((field, index) => (
|
|
||||||
<ShowFieldItem key={index} field={field} recipients={recipients} />
|
|
||||||
))}
|
|
||||||
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<div className="flex flex-col gap-y-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="title">
|
|
||||||
Title<span className="text-destructive ml-1 inline-block font-medium">*</span>
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
<Input
|
|
||||||
id="title"
|
|
||||||
className="bg-background my-2"
|
|
||||||
disabled={isSubmitting}
|
|
||||||
{...register('title')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormErrorMessage className="mt-2" error={errors.title} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</DocumentFlowFormContainerContent>
|
|
||||||
|
|
||||||
<DocumentFlowFormContainerFooter>
|
|
||||||
<DocumentFlowFormContainerStep
|
|
||||||
title={documentFlow.title}
|
|
||||||
step={currentStep}
|
|
||||||
maxStep={totalSteps}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<DocumentFlowFormContainerActions
|
|
||||||
loading={isSubmitting}
|
|
||||||
disabled={isSubmitting}
|
|
||||||
canGoBack={stepIndex !== 0}
|
|
||||||
onGoBackClick={previousStep}
|
|
||||||
onGoNextClick={() => void onFormSubmit()}
|
|
||||||
/>
|
|
||||||
</DocumentFlowFormContainerFooter>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
export const ZAddTitleFormSchema = z.object({
|
|
||||||
title: z.string().trim().min(1, { message: "Title can't be empty" }),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type TAddTitleFormSchema = z.infer<typeof ZAddTitleFormSchema>;
|
|
||||||
@ -10,7 +10,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|||||||
<input
|
<input
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
className={cn(
|
||||||
'bg-background border-input ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
'bg-background border-input ring-offset-background placeholder:text-muted-foreground/40 focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
className,
|
className,
|
||||||
{
|
{
|
||||||
'ring-2 !ring-red-500 transition-all': props['aria-invalid'],
|
'ring-2 !ring-red-500 transition-all': props['aria-invalid'],
|
||||||
|
|||||||
Reference in New Issue
Block a user