chore: merged main

This commit is contained in:
Catalin Pit
2026-06-09 08:32:31 +03:00
130 changed files with 7382 additions and 1508 deletions
@@ -2,6 +2,7 @@ import type { TLicenseClaim } from '@documenso/lib/types/license';
import { trpc } from '@documenso/trpc/react';
import type { TFindSubscriptionClaimsResponse } from '@documenso/trpc/server/admin-router/find-subscription-claims.types';
import { Button } from '@documenso/ui/primitives/button';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
import {
Dialog,
DialogContent,
@@ -28,6 +29,7 @@ export const ClaimUpdateDialog = ({ claim, trigger, licenseFlags }: ClaimUpdateD
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [backportEmailTransport, setBackportEmailTransport] = useState(false);
const { mutateAsync: updateClaim, isPending } = trpc.admin.claims.update.useMutation({
onSuccess: () => {
@@ -67,19 +69,33 @@ export const ClaimUpdateDialog = ({ claim, trigger, licenseFlags }: ClaimUpdateD
await updateClaim({
id: claim.id,
data,
backportEmailTransport,
})
}
licenseFlags={licenseFlags}
formSubmitTrigger={
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={isPending}>
<Trans>Cancel</Trans>
</Button>
<>
<div className="flex items-center space-x-2">
<Checkbox
id="backport-email-transport"
checked={backportEmailTransport}
onCheckedChange={(checked) => setBackportEmailTransport(checked === true)}
/>
<label htmlFor="backport-email-transport" className="text-muted-foreground text-sm">
<Trans>Backport email transport</Trans>
</label>
</div>
<Button type="submit" loading={isPending}>
<Trans>Update Claim</Trans>
</Button>
</DialogFooter>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={isPending}>
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={isPending}>
<Trans>Update Claim</Trans>
</Button>
</DialogFooter>
</>
}
/>
</DialogContent>
@@ -1,5 +1,6 @@
import { useSession } from '@documenso/lib/client-only/providers/session';
import { getRecipientType } from '@documenso/lib/client-only/recipient-type';
import { AppError } from '@documenso/lib/errors/app-error';
import type { TRecipientLite } from '@documenso/lib/types/recipient';
import { recipientAbbreviation } from '@documenso/lib/utils/recipient-formatter';
import type { Document } from '@documenso/prisma/types/document-legacy-schema';
@@ -30,6 +31,7 @@ import { useForm, useWatch } from 'react-hook-form';
import * as z from 'zod';
import { useCurrentTeam } from '~/providers/team';
import { getDistributeErrorMessage } from '~/utils/toast-error-messages';
import { StackAvatar } from '../general/stack-avatar';
@@ -99,9 +101,12 @@ export const DocumentResendDialog = ({ document, recipients }: DocumentResendDia
setIsOpen(false);
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = getDistributeErrorMessage(error.code);
toast({
title: _(msg`Something went wrong`),
description: _(msg`This document could not be re-sent at this time. Please try again.`),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -0,0 +1,95 @@
import { trpc } from '@documenso/trpc/react';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { Trans, useLingui } from '@lingui/react/macro';
import { useState } from 'react';
import {
EmailTransportForm,
type EmailTransportFormValues,
emailTransportFormToConfig,
} from '../forms/email-transport-form';
export type EmailTransportCreateDialogProps = {
trigger?: React.ReactNode;
};
export const EmailTransportCreateDialog = ({ trigger }: EmailTransportCreateDialogProps) => {
const { t } = useLingui();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const { mutateAsync: createTransport, isPending } = trpc.admin.emailTransport.create.useMutation({
onSuccess: () => {
toast({
title: t`Transport created.`,
});
setOpen(false);
},
onError: (error) => {
toast({
title: t`Failed to create transport.`,
description: error.message,
variant: 'destructive',
});
},
});
const onFormSubmit = async (values: EmailTransportFormValues) => {
await createTransport({
name: values.name,
fromName: values.fromName,
fromAddress: values.fromAddress,
config: emailTransportFormToConfig(values),
});
};
return (
<Dialog open={open} onOpenChange={(value) => !isPending && setOpen(value)}>
<DialogTrigger onClick={(e) => e.stopPropagation()} asChild>
{trigger ?? (
<Button className="flex-shrink-0">
<Trans>Add transport</Trans>
</Button>
)}
</DialogTrigger>
<DialogContent className="scrollbar-hidden max-h-[90vh] overflow-y-auto sm:max-w-md">
<DialogHeader>
<DialogTitle>
<Trans>Add Email Transport</Trans>
</DialogTitle>
<DialogDescription>
<Trans>Fill in the details to create a new email transport.</Trans>
</DialogDescription>
</DialogHeader>
<EmailTransportForm
onFormSubmit={onFormSubmit}
formSubmitTrigger={
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={isPending}>
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={isPending}>
<Trans>Create</Trans>
</Button>
</DialogFooter>
}
/>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,114 @@
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,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { useState } from 'react';
export type EmailTransportDeleteDialogProps = {
transportId: string;
transportName: string;
subscriptionClaimCount: number;
organisationClaimCount: number;
trigger: React.ReactNode;
};
export const EmailTransportDeleteDialog = ({
transportId,
transportName,
subscriptionClaimCount,
organisationClaimCount,
trigger,
}: EmailTransportDeleteDialogProps) => {
const { t } = useLingui();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const isInUse = subscriptionClaimCount + organisationClaimCount > 0;
const { mutateAsync: deleteTransport, isPending } = trpc.admin.emailTransport.delete.useMutation({
onSuccess: () => {
toast({
title: t`Transport deleted.`,
});
setOpen(false);
},
onError: () => {
toast({
title: t`Failed to delete transport.`,
variant: 'destructive',
});
},
});
return (
<Dialog open={open} onOpenChange={(value) => !isPending && setOpen(value)}>
<DialogTrigger asChild onClick={(e) => e.stopPropagation()}>
{trigger}
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
<Trans>Delete Email Transport</Trans>
</DialogTitle>
<DialogDescription>
<Trans>Are you sure you want to delete the following transport?</Trans>
</DialogDescription>
</DialogHeader>
<Alert variant="neutral">
<AlertDescription className="text-center font-semibold">{transportName}</AlertDescription>
</Alert>
{isInUse && (
<Alert variant="destructive">
<AlertDescription>
<Trans>Warning, this email transport is currently being used by:</Trans>
<ul className="mt-2 list-disc pl-5">
{subscriptionClaimCount > 0 && (
<li>
<Plural value={subscriptionClaimCount} one="# Subscription claim" other="# Subscription claims" />
</li>
)}
{organisationClaimCount > 0 && (
<li>
<Plural value={organisationClaimCount} one="# Organisation claim" other="# Organisation claims" />
</li>
)}
</ul>
</AlertDescription>
</Alert>
)}
<DialogFooter>
<Button type="button" variant="secondary" onClick={() => setOpen(false)} disabled={isPending}>
<Trans>Cancel</Trans>
</Button>
<Button
type="submit"
variant="destructive"
loading={isPending}
onClick={async () => deleteTransport({ id: transportId })}
>
<Trans>Delete</Trans>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,126 @@
import { trpc } from '@documenso/trpc/react';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const ZSendTestEmailFormSchema = z.object({
to: z.string().email(),
});
type TSendTestEmailFormSchema = z.infer<typeof ZSendTestEmailFormSchema>;
export type EmailTransportSendTestDialogProps = {
transportId: string;
trigger: React.ReactNode;
};
export const EmailTransportSendTestDialog = ({ transportId, trigger }: EmailTransportSendTestDialogProps) => {
const { t } = useLingui();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const { mutateAsync: sendTest } = trpc.admin.emailTransport.sendTest.useMutation({
onSuccess: () => {
toast({
title: t`Test email sent.`,
});
setOpen(false);
},
onError: (error) => {
toast({
title: t`Test failed.`,
description: error.message,
variant: 'destructive',
});
},
});
const form = useForm<TSendTestEmailFormSchema>({
resolver: zodResolver(ZSendTestEmailFormSchema),
defaultValues: {
to: '',
},
});
const onFormSubmit = async ({ to }: TSendTestEmailFormSchema) => {
await sendTest({ id: transportId, to });
};
useEffect(() => {
if (!open) {
form.reset();
}
}, [open, form]);
return (
<Dialog open={open} onOpenChange={(value) => !form.formState.isSubmitting && setOpen(value)}>
<DialogTrigger asChild onClick={(e) => e.stopPropagation()}>
{trigger}
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
<Trans>Send Test Email</Trans>
</DialogTitle>
<DialogDescription>
<Trans>Send a test email using this transport to verify the configuration.</Trans>
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
<fieldset disabled={form.formState.isSubmitting} className="space-y-4">
<FormField
control={form.control}
name="to"
render={({ field }) => (
<FormItem>
<FormLabel required>
<Trans>Email</Trans>
</FormLabel>
<FormControl>
<Input type="email" placeholder={t`test@example.com`} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button
type="button"
variant="secondary"
onClick={() => setOpen(false)}
disabled={form.formState.isSubmitting}
>
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
<Trans>Send</Trans>
</Button>
</DialogFooter>
</fieldset>
</form>
</Form>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,104 @@
import { trpc } from '@documenso/trpc/react';
import type { TFindEmailTransportsResponse } from '@documenso/trpc/server/admin-router/email-transport/find-email-transports.types';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { Trans, useLingui } from '@lingui/react/macro';
import { useState } from 'react';
import {
EmailTransportForm,
type EmailTransportFormValues,
emailTransportFormToConfig,
} from '../forms/email-transport-form';
export type EmailTransportUpdateDialogProps = {
transport: TFindEmailTransportsResponse['data'][number];
trigger: React.ReactNode;
};
export const EmailTransportUpdateDialog = ({ transport, trigger }: EmailTransportUpdateDialogProps) => {
const { t } = useLingui();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const { mutateAsync: updateTransport, isPending } = trpc.admin.emailTransport.update.useMutation();
const onFormSubmit = async (values: EmailTransportFormValues) => {
try {
await updateTransport({
id: transport.id,
data: {
name: values.name,
fromName: values.fromName,
fromAddress: values.fromAddress,
config: emailTransportFormToConfig(values),
},
});
toast({
title: t`Transport updated.`,
});
setOpen(false);
} catch {
toast({
title: t`Failed to save transport.`,
variant: 'destructive',
});
}
};
return (
<Dialog open={open} onOpenChange={(value) => !isPending && setOpen(value)}>
<DialogTrigger asChild onClick={(e) => e.stopPropagation()}>
{trigger}
</DialogTrigger>
<DialogContent className="scrollbar-hidden max-h-[90vh] overflow-y-auto sm:max-w-md">
<DialogHeader>
<DialogTitle>
<Trans>Edit Email Transport</Trans>
</DialogTitle>
<DialogDescription>
<Trans>Modify the details of the email transport.</Trans>
</DialogDescription>
</DialogHeader>
<EmailTransportForm
isEdit
defaultValues={{
// Pre-fill the non-secret connection settings; secrets stay blank
// and are preserved on save unless re-entered.
...(transport.config ?? {}),
name: transport.name,
fromName: transport.fromName,
fromAddress: transport.fromAddress,
type: transport.type,
}}
onFormSubmit={onFormSubmit}
formSubmitTrigger={
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={isPending}>
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={isPending}>
<Trans>Save changes</Trans>
</Button>
</DialogFooter>
}
/>
</DialogContent>
</Dialog>
);
};
@@ -1,6 +1,7 @@
import { useCurrentEnvelopeEditor } from '@documenso/lib/client-only/providers/envelope-editor-provider';
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
import { AppError } from '@documenso/lib/errors/app-error';
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
import { getRecipientsWithMissingFields } from '@documenso/lib/utils/recipients';
import { zEmail } from '@documenso/lib/utils/zod';
@@ -37,6 +38,7 @@ import { useForm } from 'react-hook-form';
import { useNavigate } from 'react-router';
import { match } from 'ts-pattern';
import * as z from 'zod';
import { getDistributeErrorMessage } from '~/utils/toast-error-messages';
export type EnvelopeDistributeDialogProps = {
onDistribute?: () => Promise<void>;
@@ -66,7 +68,7 @@ export const EnvelopeDistributeDialog = ({
const { envelope, syncEnvelope, isAutosaving, autosaveError } = useCurrentEnvelopeEditor();
const { toast } = useToast();
const { t } = useLingui();
const { t, i18n } = useLingui();
const navigate = useNavigate();
const [isOpen, setIsOpen] = useState(false);
@@ -174,9 +176,13 @@ export const EnvelopeDistributeDialog = ({
setIsOpen(false);
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = getDistributeErrorMessage(error.code);
toast({
title: t`Something went wrong`,
description: t`This envelope could not be distributed at this time. Please try again.`,
title: i18n._(errorMessage.title),
description: i18n._(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -1,4 +1,5 @@
import { getRecipientType } from '@documenso/lib/client-only/recipient-type';
import { AppError } from '@documenso/lib/errors/app-error';
import type { TEnvelope } from '@documenso/lib/types/envelope';
import type { TEnvelopeRecipientLite } from '@documenso/lib/types/recipient';
import { recipientAbbreviation } from '@documenso/lib/utils/recipient-formatter';
@@ -25,7 +26,7 @@ import { DocumentStatus, EnvelopeType, SigningStatus } from '@prisma/client';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { getDistributeErrorMessage } from '~/utils/toast-error-messages';
import { StackAvatar } from '../general/stack-avatar';
export type EnvelopeRedistributeDialogProps = {
@@ -47,7 +48,7 @@ export const EnvelopeRedistributeDialog = ({ envelope, trigger }: EnvelopeRedist
const recipients = envelope.recipients;
const { toast } = useToast();
const { t } = useLingui();
const { t, i18n } = useLingui();
const [isOpen, setIsOpen] = useState(false);
@@ -77,9 +78,12 @@ export const EnvelopeRedistributeDialog = ({ envelope, trigger }: EnvelopeRedist
setIsOpen(false);
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = getDistributeErrorMessage(error.code);
toast({
title: t`Something went wrong`,
description: t`This envelope could not be resent at this time. Please try again.`,
title: i18n._(errorMessage.title),
description: i18n._(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -4,7 +4,7 @@ import {
TEMPLATE_RECIPIENT_NAME_PLACEHOLDER_REGEX,
} from '@documenso/lib/constants/template';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION, SKIP_QUERY_BATCH_META } from '@documenso/lib/constants/trpc';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { AppError } from '@documenso/lib/errors/app-error';
import { type TRecipientLite, ZRecipientEmailSchema } from '@documenso/lib/types/recipient';
import { putPdfFile } from '@documenso/lib/universal/upload/put-file';
import { trpc } from '@documenso/trpc/react';
@@ -35,8 +35,8 @@ import { FileTextIcon, InfoIcon, Plus, UploadCloudIcon, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router';
import { match } from 'ts-pattern';
import * as z from 'zod';
import { getTemplateUseErrorMessage } from '~/utils/toast-error-messages';
const ZAddRecipientsForNewDocumentSchema = z.object({
distributeDocument: z.boolean(),
@@ -180,22 +180,11 @@ export function TemplateUseDialog({
await navigate(documentPath);
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = match(error.code)
.with('DOCUMENT_SEND_FAILED', () => msg`The document was created but could not be sent to recipients.`)
.with(
AppErrorCode.INVALID_BODY,
AppErrorCode.INVALID_REQUEST,
() =>
msg`The document could not be created because of missing or invalid information. Please review the template's recipients and fields.`,
)
.with(AppErrorCode.NOT_FOUND, () => msg`The template or one of its recipients could not be found.`)
.with(AppErrorCode.LIMIT_EXCEEDED, () => msg`You have reached your document limit for this plan.`)
.otherwise(() => msg`An error occurred while creating document from template.`);
const errorMessage = getTemplateUseErrorMessage(error.code);
toast({
title: _(msg`Error`),
description: _(errorMessage),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
});
}
@@ -3,6 +3,7 @@ import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-form
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
import { AppError } from '@documenso/lib/errors/app-error';
import { ZDirectTemplateEmbedDataSchema } from '@documenso/lib/types/embed-direct-template-schema';
import { isFieldUnsignedAndRequired, isRequiredField } from '@documenso/lib/utils/advanced-fields-helpers';
import { getDocumentDataUrlForPdfViewer } from '@documenso/lib/utils/envelope-download';
@@ -42,6 +43,7 @@ import { useSearchParams } from 'react-router';
import { BrandingLogo } from '~/components/general/branding-logo';
import PDFViewerLazy from '~/components/general/pdf-viewer/pdf-viewer-lazy';
import { injectCss } from '~/utils/css-vars';
import { getDirectTemplateErrorMessage } from '~/utils/toast-error-messages';
import type { DirectTemplateLocalField } from '../general/direct-template/direct-template-signing-form';
import { DocumentSigningAttachmentsPopover } from '../general/document-signing/document-signing-attachments-popover';
@@ -259,9 +261,12 @@ export const EmbedDirectTemplateClientPage = ({
);
}
const error = AppError.parseError(err);
const errorMessage = getDirectTemplateErrorMessage(error.code);
toast({
title: _(msg`Something went wrong`),
description: _(msg`We were unable to submit this document at this time. Please try again later.`),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
});
}
@@ -0,0 +1,317 @@
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, useLingui } from '@lingui/react/macro';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const ZEmailTransportFormSchema = z.object({
name: z.string().min(1),
fromName: z.string().min(1),
fromAddress: z.string().email(),
type: z.enum(['SMTP_AUTH', 'SMTP_API', 'RESEND', 'MAILCHANNELS']),
host: z.string().optional(),
port: z.coerce.number().int().positive().optional(),
secure: z.boolean().optional(),
ignoreTLS: z.boolean().optional(),
username: z.string().optional(),
password: z.string().optional(),
service: z.string().optional(),
apiKey: z.string().optional(),
apiKeyUser: z.string().optional(),
endpoint: z.string().optional(),
});
export type EmailTransportFormValues = z.infer<typeof ZEmailTransportFormSchema>;
type EmailTransportFormProps = {
defaultValues?: Partial<EmailTransportFormValues>;
isEdit?: boolean;
onFormSubmit: (values: EmailTransportFormValues) => Promise<void>;
formSubmitTrigger?: React.ReactNode;
};
export const EmailTransportForm = ({
defaultValues,
isEdit = false,
onFormSubmit,
formSubmitTrigger,
}: EmailTransportFormProps) => {
const { t } = useLingui();
const form = useForm<EmailTransportFormValues>({
resolver: zodResolver(ZEmailTransportFormSchema),
defaultValues: {
name: '',
fromName: '',
fromAddress: '',
type: 'SMTP_AUTH',
secure: false,
ignoreTLS: false,
...defaultValues,
},
});
const type = form.watch('type');
const secretPlaceholder = isEdit ? t`Leave blank to keep current` : undefined;
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
<fieldset disabled={form.formState.isSubmitting} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Name</Trans>
</FormLabel>
<FormControl>
<Input placeholder={t`e.g. Resend (free plans)`} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="fromName"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>From name</Trans>
</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="fromAddress"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>From address</Trans>
</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Transport type</Trans>
</FormLabel>
<Select value={field.value} onValueChange={field.onChange} disabled={isEdit}>
<FormControl>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="SMTP_AUTH">SMTP (auth)</SelectItem>
<SelectItem value="SMTP_API">SMTP (api)</SelectItem>
<SelectItem value="RESEND">Resend</SelectItem>
<SelectItem value="MAILCHANNELS">MailChannels</SelectItem>
</SelectContent>
</Select>
{isEdit && (
<FormDescription>
<Trans>Transport type cannot be changed after creation.</Trans>
</FormDescription>
)}
<FormMessage />
</FormItem>
)}
/>
{(type === 'SMTP_AUTH' || type === 'SMTP_API') && (
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="host"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Host</Trans>
</FormLabel>
<FormControl>
<Input {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="port"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Port</Trans>
</FormLabel>
<FormControl>
<Input type="number" {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
)}
{type === 'SMTP_AUTH' && (
<>
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Username</Trans>
</FormLabel>
<FormControl>
<Input {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Password</Trans>
</FormLabel>
<FormControl>
<Input type="password" placeholder={secretPlaceholder} {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</>
)}
{type === 'SMTP_API' && (
<FormField
control={form.control}
name="apiKey"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>API key</Trans>
</FormLabel>
<FormControl>
<Input type="password" placeholder={secretPlaceholder} {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{(type === 'RESEND' || type === 'MAILCHANNELS') && (
<FormField
control={form.control}
name="apiKey"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>API key</Trans>
</FormLabel>
<FormControl>
<Input type="password" placeholder={secretPlaceholder} {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{type === 'MAILCHANNELS' && (
<FormField
control={form.control}
name="endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Endpoint (optional)</Trans>
</FormLabel>
<FormControl>
<Input {...field} value={field.value ?? ''} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{formSubmitTrigger}
</fieldset>
</form>
</Form>
);
};
/**
* Maps flat form values to the tRPC `config` discriminated union.
*/
export const emailTransportFormToConfig = (values: EmailTransportFormValues) => {
switch (values.type) {
case 'SMTP_AUTH':
return {
type: 'SMTP_AUTH' as const,
host: values.host ?? '',
port: values.port ?? 587,
secure: values.secure ?? false,
ignoreTLS: values.ignoreTLS ?? false,
username: values.username || undefined,
password: values.password || undefined,
service: values.service || undefined,
};
case 'SMTP_API':
return {
type: 'SMTP_API' as const,
host: values.host ?? '',
port: values.port ?? 587,
secure: values.secure ?? false,
apiKey: values.apiKey || '',
apiKeyUser: values.apiKeyUser || undefined,
};
case 'RESEND':
return { type: 'RESEND' as const, apiKey: values.apiKey || '' };
case 'MAILCHANNELS':
return {
type: 'MAILCHANNELS' as const,
apiKey: values.apiKey || '',
endpoint: values.endpoint || undefined,
};
}
};
@@ -1,5 +1,6 @@
import type { TLicenseClaim } from '@documenso/lib/types/license';
import { SUBSCRIPTION_CLAIM_FEATURE_FLAGS } from '@documenso/lib/types/subscription';
import { trpc } from '@documenso/trpc/react';
import { ZCreateSubscriptionClaimRequestSchema } from '@documenso/trpc/server/admin-router/create-subscription-claim.types';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
@@ -13,6 +14,7 @@ import {
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, useLingui } from '@lingui/react/macro';
import type { SubscriptionClaim } from '@prisma/client';
@@ -59,9 +61,14 @@ export const SubscriptionClaimForm = ({
emailQuota: subscriptionClaim.emailQuota,
apiRateLimits: subscriptionClaim.apiRateLimits,
apiQuota: subscriptionClaim.apiQuota,
emailTransportId: subscriptionClaim.emailTransportId ?? null,
},
});
const { data: transportsData } = trpc.admin.emailTransport.find.useQuery({ perPage: 100 });
const transports = transportsData?.data ?? [];
const NONE_VALUE = '__none__';
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
@@ -238,6 +245,40 @@ export const SubscriptionClaimForm = ({
<ClaimLimitFields control={form.control} disabled={form.formState.isSubmitting} />
<FormField
control={form.control}
name="emailTransportId"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Email transport</Trans>
</FormLabel>
<Select
value={field.value ?? NONE_VALUE}
onValueChange={(value) => field.onChange(value === NONE_VALUE ? null : value)}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t`Default (system mailer)`} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value={NONE_VALUE}>{t`Default (system mailer)`}</SelectItem>
{transports.map((transport) => (
<SelectItem key={transport.id} value={transport.id}>
{transport.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormDescription>
<Trans>Plans without a transport use the system default mailer.</Trans>
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{formSubmitTrigger}
</fieldset>
</form>
@@ -54,7 +54,6 @@ export const BillingPlans = ({ plans }: BillingPlansProps) => {
if (plan[interval] && plan[interval].isVisibleInApp) {
prices.push({
...plan[interval],
memberCount: plan.memberCount,
claim: plan.id,
});
}
@@ -120,12 +119,7 @@ export const BillingPlans = ({ plans }: BillingPlansProps) => {
<Trans>Subscribe</Trans>
</IndividualPersonalLayoutCheckoutButton>
) : (
<BillingDialog
priceId={price.id}
planName={price.product.name}
memberCount={price.memberCount}
claim={price.claim}
/>
<BillingDialog priceId={price.id} planName={price.product.name} claim={price.claim} />
)}
</CardContent>
</MotionCard>
@@ -136,16 +130,7 @@ export const BillingPlans = ({ plans }: BillingPlansProps) => {
);
};
const BillingDialog = ({
priceId,
planName,
claim,
}: {
priceId: string;
planName: string;
memberCount: number;
claim: string;
}) => {
const BillingDialog = ({ priceId, planName, claim }: { priceId: string; planName: string; claim: string }) => {
const [isOpen, setIsOpen] = useState(false);
const { t } = useLingui();
@@ -1,4 +1,5 @@
import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
import { AppError } from '@documenso/lib/errors/app-error';
import type { TTemplate } from '@documenso/lib/types/template';
import { isRequiredField } from '@documenso/lib/utils/advanced-fields-helpers';
import { getDocumentDataUrlForPdfViewer } from '@documenso/lib/utils/envelope-download';
@@ -17,6 +18,7 @@ import { useNavigate, useSearchParams } from 'react-router';
import { useRequiredDocumentSigningAuthContext } from '~/components/general/document-signing/document-signing-auth-provider';
import { useRequiredDocumentSigningContext } from '~/components/general/document-signing/document-signing-provider';
import PDFViewerLazy from '~/components/general/pdf-viewer/pdf-viewer-lazy';
import { getDirectTemplateErrorMessage } from '~/utils/toast-error-messages';
import { DirectTemplateConfigureForm, type TDirectTemplateConfigureFormSchema } from './direct-template-configure-form';
import { type DirectTemplateLocalField, DirectTemplateSigningForm } from './direct-template-signing-form';
@@ -120,9 +122,12 @@ export const DirectTemplatePageView = ({
await navigate(`/sign/${token}/complete`);
}
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = getDirectTemplateErrorMessage(error.code);
toast({
title: _(msg`Something went wrong`),
description: _(msg`We were unable to submit this document at this time. Please try again later.`),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
});
@@ -1,6 +1,7 @@
import { DocumentSignatureType } from '@documenso/lib/constants/document';
import { isValidLanguageCode } from '@documenso/lib/constants/i18n';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION, SKIP_QUERY_BATCH_META } from '@documenso/lib/constants/trpc';
import { AppError } from '@documenso/lib/errors/app-error';
import type { TDocument } from '@documenso/lib/types/document';
import { ZDocumentAccessAuthTypesSchema } from '@documenso/lib/types/document-auth';
import { getDocumentDataUrlForPdfViewer } from '@documenso/lib/utils/envelope-download';
@@ -25,9 +26,9 @@ import { DocumentDistributionMethod, DocumentStatus } from '@prisma/client';
import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { z } from 'zod';
import PDFViewerLazy from '~/components/general/pdf-viewer/pdf-viewer-lazy';
import { useCurrentTeam } from '~/providers/team';
import { getDistributeErrorMessage } from '~/utils/toast-error-messages';
export type DocumentEditFormProps = {
className?: string;
@@ -387,9 +388,12 @@ export const DocumentEditForm = ({ className, initialDocument, documentRootPath
} catch (err) {
console.error(err);
const error = AppError.parseError(err);
const errorMessage = getDistributeErrorMessage(error.code);
toast({
title: _(msg`Error`),
description: _(msg`An error occurred while sending the document.`),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
});
}
@@ -3,7 +3,7 @@ import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
import { useSession } from '@documenso/lib/client-only/providers/session';
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { AppError } from '@documenso/lib/errors/app-error';
import { formatDocumentsPath, formatTemplatesPath } from '@documenso/lib/utils/teams';
import { trpc } from '@documenso/trpc/react';
import type { TCreateDocumentPayloadSchema } from '@documenso/trpc/server/document-router/create-document.types';
@@ -20,9 +20,9 @@ import { EnvelopeType } from '@prisma/client';
import { useMemo, useState } from 'react';
import type { FileRejection } from 'react-dropzone';
import { useNavigate, useParams } from 'react-router';
import { match } from 'ts-pattern';
import { useCurrentTeam } from '~/providers/team';
import { getUploadErrorMessage } from '~/utils/toast-error-messages';
export type DocumentUploadButtonLegacyProps = {
className?: string;
@@ -130,30 +130,11 @@ export const DocumentUploadButtonLegacy = ({ className, type }: DocumentUploadBu
console.error(err);
const errorMessage = match(error.code)
.with('INVALID_DOCUMENT_FILE', () => msg`You cannot upload encrypted PDFs.`)
.with(
AppErrorCode.LIMIT_EXCEEDED,
() => msg`You have reached your document limit for this month. Please upgrade your plan.`,
)
.with(
'ENVELOPE_ITEM_LIMIT_EXCEEDED',
() => msg`You have reached the limit of the number of files per envelope.`,
)
.with('UNSUPPORTED_FILE_TYPE', () => msg`This file type isn't supported. Please upload a PDF or Word document.`)
.with(
'CONVERSION_SERVICE_UNAVAILABLE',
() => msg`Document conversion is temporarily unavailable. Please try again shortly or upload a PDF.`,
)
.with(
'CONVERSION_FAILED',
() => msg`We couldn't convert this file. Please check it's a valid Word document or upload a PDF instead.`,
)
.otherwise(() => msg`An error occurred while uploading your document.`);
const errorMessage = getUploadErrorMessage(error.code);
toast({
title: _(msg`Error`),
description: _(errorMessage),
title: _(errorMessage.title),
description: _(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -14,13 +14,22 @@ import {
import { renderField } from '@documenso/lib/universal/field-renderer/render-field';
import { getClientSideFieldTranslations } from '@documenso/lib/utils/fields';
import { canRecipientFieldsBeModified } from '@documenso/lib/utils/recipients';
import { CommandDialog } from '@documenso/ui/primitives/command';
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@documenso/ui/primitives/command';
import { FRIENDLY_FIELD_TYPE } from '@documenso/ui/primitives/document-flow/types';
import { useLingui } from '@lingui/react/macro';
import type { FieldType } from '@prisma/client';
import Konva from 'konva';
import type { KonvaEventObject } from 'konva/lib/Node';
import type { Transformer } from 'konva/lib/shapes/Transformer';
import { CopyPlusIcon, SquareStackIcon, TrashIcon, UserCircleIcon } from 'lucide-react';
import { CopyPlusIcon, ShapesIcon, SquareStackIcon, TrashIcon, UserCircleIcon } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { fieldButtonList } from './envelope-editor-fields-drag-drop';
@@ -470,6 +479,22 @@ export const EnvelopeEditorFieldsPageRenderer = ({ pageData }: { pageData: PageR
}
};
const changeSelectedFieldsType = (type: FieldType) => {
const fields = selectedKonvaFieldGroups
.map((field) => editorFields.getFieldByFormId(field.id()))
.filter((field) => field !== undefined);
for (const field of fields) {
if (field.type !== type) {
editorFields.updateFieldByFormId(field.formId, {
type,
fieldMeta: structuredClone(FIELD_META_DEFAULT_VALUES[type]),
id: undefined,
});
}
}
};
const duplicatedSelectedFields = () => {
const fields = selectedKonvaFieldGroups
.map((field) => editorFields.getFieldByFormId(field.id()))
@@ -554,6 +579,7 @@ export const EnvelopeEditorFieldsPageRenderer = ({ pageData }: { pageData: PageR
handleDuplicateSelectedFieldsOnAllPages={duplicatedSelectedFieldsOnAllPages}
handleDeleteSelectedFields={deletedSelectedFields}
handleChangeRecipient={changeSelectedFieldsRecipients}
handleChangeFieldType={changeSelectedFieldsType}
selectedFieldFormId={selectedKonvaFieldGroups.map((field) => field.id())}
style={{
position: 'absolute',
@@ -602,6 +628,7 @@ type FieldActionButtonsProps = React.HTMLAttributes<HTMLDivElement> & {
handleDuplicateSelectedFieldsOnAllPages: () => void;
handleDeleteSelectedFields: () => void;
handleChangeRecipient: (recipientId: number) => void;
handleChangeFieldType: (type: FieldType) => void;
selectedFieldFormId: string[];
};
@@ -610,15 +637,40 @@ const FieldActionButtons = ({
handleDuplicateSelectedFieldsOnAllPages,
handleDeleteSelectedFields,
handleChangeRecipient,
handleChangeFieldType,
selectedFieldFormId,
...props
}: FieldActionButtonsProps) => {
const { t } = useLingui();
const [showRecipientSelector, setShowRecipientSelector] = useState(false);
const [showFieldTypeSelector, setShowFieldTypeSelector] = useState(false);
const { editorFields, envelope } = useCurrentEnvelopeEditor();
/**
* Decide the preselected field type in the command input.
*
* If all fields share the same type, use that as the default selection.
* Otherwise show no preselection.
*/
const preselectedFieldType = useMemo(() => {
if (selectedFieldFormId.length === 0) {
return null;
}
const fields = editorFields.localFields.filter((field) => selectedFieldFormId.includes(field.formId));
if (fields.length === 0) {
return null;
}
const firstType = fields[0].type;
const isTypesSame = fields.every((field) => field.type === firstType);
return isTypesSame ? firstType : null;
}, [editorFields.localFields, selectedFieldFormId]);
/**
* Decide the preselected recipient in the command input.
*
@@ -656,6 +708,7 @@ const FieldActionButtons = ({
<div className="flex flex-col items-center" {...props}>
<div className="group flex w-fit items-center justify-evenly gap-x-1 rounded-md border bg-gray-900 p-0.5">
<button
type="button"
title={t`Change Recipient`}
className="rounded-sm p-1.5 text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-100"
onClick={() => setShowRecipientSelector(true)}
@@ -665,6 +718,17 @@ const FieldActionButtons = ({
</button>
<button
type="button"
title={t`Change Field Type`}
className="rounded-sm p-1.5 text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-100"
onClick={() => setShowFieldTypeSelector(true)}
onTouchEnd={() => setShowFieldTypeSelector(true)}
>
<ShapesIcon className="h-3 w-3" />
</button>
<button
type="button"
title={t`Duplicate`}
className="rounded-sm p-1.5 text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-100"
onClick={handleDuplicateSelectedFields}
@@ -674,6 +738,7 @@ const FieldActionButtons = ({
</button>
<button
type="button"
title={t`Duplicate on all pages`}
className="rounded-sm p-1.5 text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-100"
onClick={handleDuplicateSelectedFieldsOnAllPages}
@@ -683,6 +748,7 @@ const FieldActionButtons = ({
</button>
<button
type="button"
title={t`Remove`}
className="rounded-sm p-1.5 text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-100"
onClick={handleDeleteSelectedFields}
@@ -705,6 +771,41 @@ const FieldActionButtons = ({
fields={envelope.fields}
/>
</CommandDialog>
<CommandDialog position="start" open={showFieldTypeSelector} onOpenChange={setShowFieldTypeSelector}>
<Command defaultValue={preselectedFieldType ? t(FRIENDLY_FIELD_TYPE[preselectedFieldType]) : undefined}>
<CommandInput placeholder={t`Select a field type`} />
<CommandList>
<CommandEmpty>
<span className="inline-block px-4 text-muted-foreground">
{t`No field type matching this description was found.`}
</span>
</CommandEmpty>
<CommandGroup>
{fieldButtonList.map((field) => {
const FieldIcon = field.icon;
const label = t(FRIENDLY_FIELD_TYPE[field.type]);
return (
<CommandItem
key={field.type}
className="px-2"
onSelect={() => {
handleChangeFieldType(field.type);
setShowFieldTypeSelector(false);
}}
>
<FieldIcon className="mr-2 h-4 w-4" />
<span className="truncate">{label}</span>
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</CommandDialog>
</div>
);
};
@@ -21,6 +21,7 @@ import {
} from '@documenso/ui/components/recipient/recipient-autocomplete-input';
import { RecipientRoleSelect } from '@documenso/ui/components/recipient/recipient-role-select';
import { cn } from '@documenso/ui/lib/utils';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
@@ -586,6 +587,9 @@ export const EnvelopeEditorRecipientForm = () => {
}
}, [formValues]);
const recipientCountLimit = organisation.organisationClaim.recipientCount;
const isOverRecipientLimit = recipientCountLimit > 0 && signers.length > recipientCountLimit;
return (
<Card backdropBlur={false} className="border">
<CardHeader className="flex flex-row justify-between">
@@ -650,6 +654,17 @@ export const EnvelopeEditorRecipientForm = () => {
</CardHeader>
<CardContent>
{isOverRecipientLimit && (
<Alert variant="destructive" className="mb-4">
<AlertDescription>
<Trans>
This envelope cannot have more than {recipientCountLimit} recipients. Please contact support if you need
more.
</Trans>
</AlertDescription>
</Alert>
)}
<Form {...form}>
<div
className={cn('-mt-2 mb-2 space-y-4 rounded-md bg-accent/50 p-4', {
@@ -9,7 +9,7 @@ import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
import { AppError } from '@documenso/lib/errors/app-error';
import { ZDocumentAccessAuthTypesSchema, ZDocumentActionAuthTypesSchema } from '@documenso/lib/types/document-auth';
import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
import { DocumentEmailEvents, ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
import {
type TDocumentMetaDateFormat,
ZDocumentMetaDateFormatSchema,
@@ -39,6 +39,7 @@ import { ExpirationPeriodPicker } from '@documenso/ui/components/document/expira
import { ReminderSettingsPicker } from '@documenso/ui/components/document/reminder-settings-picker';
import { TemplateTypeSelect, TemplateTypeTooltip } from '@documenso/ui/components/template/template-type-select';
import { cn } from '@documenso/ui/lib/utils';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import { CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
import { Combobox } from '@documenso/ui/primitives/combobox';
@@ -114,7 +115,7 @@ export const ZAddSettingsFormSchema = z.object({
}),
});
type EnvelopeEditorSettingsTabType = 'general' | 'reminders' | 'email' | 'security';
type EnvelopeEditorSettingsTabType = 'general' | 'reminders' | 'notifications' | 'security';
const tabs = [
{
@@ -130,10 +131,10 @@ const tabs = [
description: msg`Configure signing reminder settings for the document.`,
},
{
id: 'email',
title: msg`Email`,
id: 'notifications',
title: msg`Notifications`,
icon: MailIcon,
description: msg`Configure email settings for the document.`,
description: msg`Configure notification settings for the document.`,
},
{
id: 'security',
@@ -143,6 +144,18 @@ const tabs = [
},
] as const;
// Recipient-facing notification events. These are suppressed at send time
// when distributionMethod is not EMAIL (see extractDerivedDocumentEmailSettings),
// so the UI mirrors that by disabling the matching checkboxes.
const RECIPIENT_EMAIL_EVENTS = [
DocumentEmailEvents.RecipientSigningRequest,
DocumentEmailEvents.RecipientRemoved,
DocumentEmailEvents.RecipientSigned,
DocumentEmailEvents.DocumentPending,
DocumentEmailEvents.DocumentCompleted,
DocumentEmailEvents.DocumentDeleted,
] as const;
type TAddSettingsFormSchema = z.infer<typeof ZAddSettingsFormSchema>;
type EnvelopeEditorSettingsDialogProps = {
@@ -205,6 +218,8 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
);
const emailSettings = form.watch('meta.emailSettings');
const distributionMethod = form.watch('meta.distributionMethod');
const isEmailDistribution = distributionMethod === DocumentDistributionMethod.EMAIL;
const { data: emailData, isLoading: isLoadingEmails } = trpc.enterprise.organisation.email.find.useQuery(
{
@@ -334,7 +349,7 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
<nav className="col-span-12 mb-8 flex flex-wrap items-center justify-start gap-x-2 gap-y-4 px-4 md:col-span-3 md:w-full md:flex-col md:items-start md:gap-y-2">
{tabs.map((tab) => {
if (tab.id === 'email' && !settings.allowConfigureDistribution) {
if (tab.id === 'notifications' && !settings.allowConfigureDistribution) {
return null;
}
@@ -730,7 +745,7 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
)}
/>
))
.with({ activeTab: 'email', settings: { allowConfigureDistribution: true } }, () => (
.with({ activeTab: 'notifications', settings: { allowConfigureDistribution: true } }, () => (
<>
{settings.allowConfigureEmailSender && organisation.organisationClaim.flags.emailDomains && (
<FormField
@@ -747,6 +762,7 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
{...field}
value={field.value === null ? '-1' : field.value}
onValueChange={(value) => field.onChange(value === '-1' ? null : value)}
disabled={!isEmailDistribution}
>
<SelectTrigger loading={isLoadingEmails} className="bg-background">
<SelectValue />
@@ -783,7 +799,7 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
</FormLabel>
<FormControl>
<Input {...field} />
<Input {...field} disabled={!isEmailDistribution} />
</FormControl>
<FormMessage />
@@ -804,7 +820,7 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
</FormLabel>
<FormControl>
<Input {...field} />
<Input {...field} disabled={!isEmailDistribution} />
</FormControl>
<FormMessage />
@@ -832,7 +848,11 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
</FormLabel>
<FormControl>
<Textarea className="h-16 resize-none bg-background" {...field} />
<Textarea
className="h-16 resize-none bg-background"
{...field}
disabled={!isEmailDistribution}
/>
</FormControl>
<FormMessage />
@@ -843,7 +863,19 @@ export const EnvelopeEditorSettingsDialog = ({ trigger, ...props }: EnvelopeEdit
<DocumentEmailCheckboxes
value={emailSettings}
onChange={(value) => form.setValue('meta.emailSettings', value)}
hiddenEvents={isEmailDistribution ? undefined : RECIPIENT_EMAIL_EVENTS}
/>
{!isEmailDistribution && (
<Alert variant="warning">
<AlertDescription>
<Trans>
Email distribution needs to be enabled in the general settings tab to configure recipient
email related settings.
</Trans>
</AlertDescription>
</Alert>
)}
</>
))
.with({ activeTab: 'security' }, () => (
@@ -9,6 +9,10 @@ import { isBase64Image } from '@documenso/lib/constants/signatures';
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import type { TEnvelope } from '@documenso/lib/types/envelope';
import { ZFullFieldSchema } from '@documenso/lib/types/field';
import {
createFieldCanvasStyleCache,
type FieldCanvasStyleCache,
} from '@documenso/lib/universal/field-renderer/field-canvas-style';
import { createSpinner } from '@documenso/lib/universal/field-renderer/field-generic-items';
import { renderField } from '@documenso/lib/universal/field-renderer/render-field';
import { isFieldUnsignedAndRequired } from '@documenso/lib/utils/advanced-fields-helpers';
@@ -135,7 +139,10 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
});
}, [envelope.recipients, pageNumber, currentEnvelopeItem?.id]);
const unsafeRenderFieldOnLayer = (unparsedField: Field & { signature?: Signature | null }) => {
const unsafeRenderFieldOnLayer = (
unparsedField: Field & { signature?: Signature | null },
fieldCanvasStyleCache: FieldCanvasStyleCache,
) => {
if (!pageLayer.current) {
console.error('Layer not loaded yet');
return;
@@ -143,11 +150,9 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
const fieldToRender = ZFullFieldSchema.parse(unparsedField);
const color = fieldToRender.fieldMeta?.readOnly
? 'readOnly'
: showPendingFieldTooltip && isFieldUnsignedAndRequired(fieldToRender)
? 'orange'
: 'green';
const isValidating = showPendingFieldTooltip && isFieldUnsignedAndRequired(fieldToRender);
const color = fieldToRender.fieldMeta?.readOnly ? 'readOnly' : isValidating ? 'orange' : 'green';
const { fieldGroup } = renderField({
scale,
@@ -159,6 +164,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
height: Number(fieldToRender.height),
positionX: Number(fieldToRender.positionX),
positionY: Number(fieldToRender.positionY),
isValidating,
signature: unparsedField.signature,
},
translations: getClientSideFieldTranslations(i18n),
@@ -166,6 +172,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
pageHeight: unscaledViewport.height,
color,
mode: 'sign',
fieldCanvasStyleCache,
});
const handleFieldGroupClick = (e: KonvaEventObject<Event>) => {
@@ -411,9 +418,12 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
fieldGroup.on('pointerdown', handleFieldGroupClick);
};
const renderFieldOnLayer = (unparsedField: Field & { signature?: Signature | null }) => {
const renderFieldOnLayer = (
unparsedField: Field & { signature?: Signature | null },
fieldCanvasStyleCache: FieldCanvasStyleCache,
) => {
try {
unsafeRenderFieldOnLayer(unparsedField);
unsafeRenderFieldOnLayer(unparsedField, fieldCanvasStyleCache);
} catch (err) {
console.error(err);
setRenderError(true);
@@ -426,6 +436,8 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
return;
}
const fieldCanvasStyleCache = createFieldCanvasStyleCache();
// Render current recipient fields which have changed or are not currently rendered.
for (const field of localPageFields) {
const existingCachedField = cachedRenderFields.current.get(field.id);
@@ -437,7 +449,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
existingCachedField.inserted !== field.inserted ||
existingCachedField.customText !== field.customText
) {
renderFieldOnLayer(field);
renderFieldOnLayer(field, fieldCanvasStyleCache);
cachedRenderFields.current.set(field.id, field);
}
}
@@ -463,6 +475,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
color: 'readOnly',
editable: false,
mode: 'sign',
fieldCanvasStyleCache,
});
// Other-recipient fields are display-only — they have no click handlers
@@ -5,7 +5,7 @@ import { useSession } from '@documenso/lib/client-only/providers/session';
import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT, IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
import { getAllowedUploadMimeTypes } from '@documenso/lib/constants/document-conversion';
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { AppError } from '@documenso/lib/errors/app-error';
import { megabytesToBytes } from '@documenso/lib/universal/unit-convertions';
import { formatDocumentsPath, formatTemplatesPath } from '@documenso/lib/utils/teams';
import { trpc } from '@documenso/trpc/react';
@@ -20,9 +20,9 @@ import { Loader } from 'lucide-react';
import { type ReactNode, useState } from 'react';
import { ErrorCode as DropzoneErrorCode, type FileRejection, useDropzone } from 'react-dropzone';
import { Link, useNavigate, useParams } from 'react-router';
import { match } from 'ts-pattern';
import { useCurrentTeam } from '~/providers/team';
import { getUploadErrorMessage } from '~/utils/toast-error-messages';
export interface EnvelopeDropZoneWrapperProps {
children: ReactNode;
@@ -109,27 +109,11 @@ export const EnvelopeDropZoneWrapper = ({ children, type, className }: EnvelopeD
} catch (err) {
const error = AppError.parseError(err);
const errorMessage = match(error.code)
.with('INVALID_DOCUMENT_FILE', () => t`You cannot upload encrypted PDFs.`)
.with(
AppErrorCode.LIMIT_EXCEEDED,
() => t`You have reached your document limit for this month. Please upgrade your plan.`,
)
.with('ENVELOPE_ITEM_LIMIT_EXCEEDED', () => t`You have reached the limit of the number of files per envelope.`)
.with('UNSUPPORTED_FILE_TYPE', () => t`This file type isn't supported. Please upload a PDF or Word document.`)
.with(
'CONVERSION_SERVICE_UNAVAILABLE',
() => t`Document conversion is temporarily unavailable. Please try again shortly or upload a PDF.`,
)
.with(
'CONVERSION_FAILED',
() => t`We couldn't convert this file. Please check it's a valid Word document or upload a PDF instead.`,
)
.otherwise(() => t`An error occurred during upload.`);
const errorMessage = getUploadErrorMessage(error.code);
toast({
title: t`Error`,
description: errorMessage,
title: i18n._(errorMessage.title),
description: i18n._(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -2,7 +2,7 @@ import { useLimits } from '@documenso/ee/server-only/limits/provider/client';
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
import { useSession } from '@documenso/lib/client-only/providers/session';
import { TIME_ZONES } from '@documenso/lib/constants/time-zones';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { AppError } from '@documenso/lib/errors/app-error';
import { formatDocumentsPath, formatTemplatesPath } from '@documenso/lib/utils/teams';
import { trpc } from '@documenso/trpc/react';
import type { TCreateEnvelopePayload } from '@documenso/trpc/server/envelope-router/create-envelope.types';
@@ -17,9 +17,9 @@ import { EnvelopeType } from '@prisma/client';
import { useMemo, useState } from 'react';
import { ErrorCode as DropzoneErrorCode, type FileRejection } from 'react-dropzone';
import { useNavigate } from 'react-router';
import { match } from 'ts-pattern';
import { useCurrentTeam } from '~/providers/team';
import { getUploadErrorMessage } from '~/utils/toast-error-messages';
export type EnvelopeUploadButtonProps = {
className?: string;
@@ -112,27 +112,11 @@ export const EnvelopeUploadButton = ({ className, type, folderId }: EnvelopeUplo
console.error(err);
const errorMessage = match(error.code)
.with('INVALID_DOCUMENT_FILE', () => t`You cannot upload encrypted PDFs.`)
.with(
AppErrorCode.LIMIT_EXCEEDED,
() => t`You have reached your document limit for this month. Please upgrade your plan.`,
)
.with('ENVELOPE_ITEM_LIMIT_EXCEEDED', () => t`You have reached the limit of the number of files per envelope.`)
.with('UNSUPPORTED_FILE_TYPE', () => t`This file type isn't supported. Please upload a PDF or Word document.`)
.with(
'CONVERSION_SERVICE_UNAVAILABLE',
() => t`Document conversion is temporarily unavailable. Please try again shortly or upload a PDF.`,
)
.with(
'CONVERSION_FAILED',
() => t`We couldn't convert this file. Please check it's a valid Word document or upload a PDF instead.`,
)
.otherwise(() => t`An error occurred while uploading your document.`);
const errorMessage = getUploadErrorMessage(error.code);
toast({
title: t`Error`,
description: errorMessage,
title: i18n._(errorMessage.title),
description: i18n._(errorMessage.description),
variant: 'destructive',
duration: 7500,
});
@@ -0,0 +1,124 @@
import { useOptionalCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
import { SUPPORT_EMAIL } from '@documenso/lib/constants/app';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION, SKIP_QUERY_BATCH_META } from '@documenso/lib/constants/trpc';
import { INTERNAL_CLAIM_ID } from '@documenso/lib/types/subscription';
import { trpc } from '@documenso/trpc/react';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@documenso/ui/primitives/dialog';
import { Trans } from '@lingui/react/macro';
import { AlertTriangle } from 'lucide-react';
import { useState } from 'react';
export const OrganisationQuotaBanner = () => {
const [isOpen, setIsOpen] = useState(false);
const organisation = useOptionalCurrentOrganisation();
const { data: quotaFlags } = trpc.organisation.getQuotaFlags.useQuery(
{ organisationId: organisation?.id ?? '' },
{
enabled: Boolean(organisation),
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
...SKIP_QUERY_BATCH_META,
refetchInterval: 1000 * 60,
refetchIntervalInBackground: false,
},
);
const isAnyQuotaExceeded = Boolean(
quotaFlags?.isDocumentQuotaExceeded || quotaFlags?.isEmailQuotaExceeded || quotaFlags?.isApiQuotaExceeded,
);
// Every member of the organisation sees the banner when a quota is exhausted.
// Note: Skipping free plan banner for now because their quota can incorrectly show as exceeded.
if (
!organisation ||
!quotaFlags ||
!isAnyQuotaExceeded ||
organisation.organisationClaim.originalSubscriptionClaimId === INTERNAL_CLAIM_ID.FREE
) {
return null;
}
return (
<>
<div className="bg-yellow-200 text-yellow-900 dark:bg-yellow-400">
<div className="mx-auto flex max-w-screen-xl items-center justify-center gap-x-4 px-4 py-2 font-medium text-sm">
<div className="flex items-center">
<AlertTriangle className="mr-2.5 h-5 w-5" />
<Trans>Your organisation has exceeded a fair use limit</Trans>
</div>
<Button
variant="outline"
className="text-yellow-900 hover:bg-yellow-100 dark:hover:bg-yellow-500"
onClick={() => setIsOpen(true)}
size="sm"
>
<Trans>Learn more</Trans>
</Button>
</div>
</div>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>
<Trans>Fair use limit exceeded</Trans>
</DialogTitle>
<DialogDescription>
<Trans>
Your organisation has exceeded a fair use limit. Please contact{' '}
<a className="text-primary" href={`mailto:${SUPPORT_EMAIL}`}>
support
</a>{' '}
to review your plan's limits.
</Trans>
</DialogDescription>
</DialogHeader>
<Alert variant="neutral">
<AlertDescription>
<ul className="list-inside list-disc text-sm">
{quotaFlags.isDocumentQuotaExceeded && (
<li className="list-disc">
<Trans>Document creation has been temporarily paused</Trans>
</li>
)}
{quotaFlags.isEmailQuotaExceeded && (
<li className="list-disc">
<Trans>Email sending has been temporarily paused</Trans>
</li>
)}
{quotaFlags.isApiQuotaExceeded && (
<li className="list-disc">
<Trans>API requests have been temporarily paused</Trans>
</li>
)}
</ul>
</AlertDescription>
</Alert>
<DialogFooter>
<DialogClose asChild>
<Button variant="secondary">
<Trans>Close</Trans>
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
};
@@ -0,0 +1,179 @@
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
import { ZUrlSearchParamsSchema } from '@documenso/lib/types/search-params';
import { trpc } from '@documenso/trpc/react';
import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table';
import { DataTable } from '@documenso/ui/primitives/data-table';
import { DataTablePagination } from '@documenso/ui/primitives/data-table-pagination';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@documenso/ui/primitives/dropdown-menu';
import { Skeleton } from '@documenso/ui/primitives/skeleton';
import { TableCell } from '@documenso/ui/primitives/table';
import { Trans, useLingui } from '@lingui/react/macro';
import { EditIcon, MoreHorizontalIcon, SendIcon, Trash2Icon } from 'lucide-react';
import { useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { EmailTransportDeleteDialog } from '../dialogs/email-transport-delete-dialog';
import { EmailTransportSendTestDialog } from '../dialogs/email-transport-send-test-dialog';
import { EmailTransportUpdateDialog } from '../dialogs/email-transport-update-dialog';
export const AdminEmailTransportsTable = () => {
const { t, i18n } = useLingui();
const [searchParams] = useSearchParams();
const updateSearchParams = useUpdateSearchParams();
const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? []));
const { data, isLoading, isLoadingError } = trpc.admin.emailTransport.find.useQuery({
query: parsedSearchParams.query,
page: parsedSearchParams.page,
perPage: parsedSearchParams.perPage,
});
const onPaginationChange = (page: number, perPage: number) => {
updateSearchParams({
page,
perPage,
});
};
const results = data ?? {
data: [],
perPage: 20,
currentPage: 1,
totalPages: 1,
};
const columns = useMemo(() => {
return [
{
header: t`Name`,
accessorKey: 'name',
},
{
header: t`Type`,
accessorKey: 'type',
},
{
header: t`From`,
cell: ({ row }) => `${row.original.fromName} <${row.original.fromAddress}>`,
},
{
header: t`Used by claims`,
cell: ({ row }) => row.original._count.subscriptionClaims + row.original._count.organisationClaims,
},
{
header: t`Created`,
accessorKey: 'createdAt',
cell: ({ row }) => i18n.date(row.original.createdAt),
},
{
id: 'actions',
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger>
<MoreHorizontalIcon className="h-5 w-5 text-muted-foreground" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-52" align="start" forceMount>
<DropdownMenuLabel>
<Trans>Actions</Trans>
</DropdownMenuLabel>
<EmailTransportUpdateDialog
transport={row.original}
trigger={
<DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
<div>
<EditIcon className="mr-2 h-4 w-4" />
<Trans>Edit</Trans>
</div>
</DropdownMenuItem>
}
/>
<EmailTransportSendTestDialog
transportId={row.original.id}
trigger={
<DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
<div>
<SendIcon className="mr-2 h-4 w-4" />
<Trans>Send test</Trans>
</div>
</DropdownMenuItem>
}
/>
<EmailTransportDeleteDialog
transportId={row.original.id}
transportName={row.original.name}
subscriptionClaimCount={row.original._count.subscriptionClaims}
organisationClaimCount={row.original._count.organisationClaims}
trigger={
<DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
<div>
<Trash2Icon className="mr-2 h-4 w-4" />
<Trans>Delete</Trans>
</div>
</DropdownMenuItem>
}
/>
</DropdownMenuContent>
</DropdownMenu>
),
},
] satisfies DataTableColumnDef<(typeof results)['data'][number]>[];
}, []);
return (
<div>
<DataTable
columns={columns}
data={results.data}
perPage={results.perPage}
currentPage={results.currentPage}
totalPages={results.totalPages}
onPaginationChange={onPaginationChange}
error={{
enable: isLoadingError,
}}
skeleton={{
enable: isLoading,
rows: 3,
component: (
<>
<TableCell className="py-4 pr-4">
<Skeleton className="h-4 w-24 rounded-full" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-16 rounded-full" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-40 rounded-full" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-12 rounded-full" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-20 rounded-full" />
</TableCell>
<TableCell>
<div className="flex flex-row justify-end space-x-2">
<Skeleton className="h-2 w-6 rounded" />
</div>
</TableCell>
</>
),
}}
>
{(table) => <DataTablePagination additionalInformation="VisibleCount" table={table} />}
</DataTable>
</div>
);
};
@@ -13,6 +13,7 @@ import { AppBanner } from '~/components/general/app-banner';
import { Header } from '~/components/general/app-header';
import { GenericErrorLayout } from '~/components/general/generic-error-layout';
import { OrganisationBillingBanner } from '~/components/general/organisations/organisation-billing-banner';
import { OrganisationQuotaBanner } from '~/components/general/organisations/organisation-quota-banner';
import { VerifyEmailBanner } from '~/components/general/verify-email-banner';
import { TeamProvider } from '~/providers/team';
@@ -109,6 +110,8 @@ export default function Layout({ loaderData, params, matches }: Route.ComponentP
<TeamProvider team={currentTeam || null}>
<OrganisationBillingBanner />
<OrganisationQuotaBanner />
{!user.emailVerified && <VerifyEmailBanner email={user.email} />}
{banner && !hideHeader && <AppBanner banner={banner} />}
@@ -129,6 +129,17 @@ export default function AdminLayout({ loaderData }: Route.ComponentProps) {
</Link>
</Button>
<Button
variant="ghost"
className={cn('justify-start md:w-full', pathname?.startsWith('/admin/email-transports') && 'bg-secondary')}
asChild
>
<Link to="/admin/email-transports">
<MailIcon className="mr-2 h-5 w-5" />
<Trans>Email Transports</Trans>
</Link>
</Button>
<Button
variant="ghost"
className={cn('justify-start md:w-full', pathname?.startsWith('/admin/email-domains') && 'bg-secondary')}
@@ -0,0 +1,59 @@
import { useDebouncedValue } from '@documenso/lib/client-only/hooks/use-debounced-value';
import { Input } from '@documenso/ui/primitives/input';
import { useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
import { useLocation, useSearchParams } from 'react-router';
import { EmailTransportCreateDialog } from '~/components/dialogs/email-transport-create-dialog';
import { SettingsHeader } from '~/components/general/settings-header';
import { AdminEmailTransportsTable } from '~/components/tables/admin-email-transports-table';
export default function AdminEmailTransportsPage() {
const { t } = useLingui();
const [searchParams, setSearchParams] = useSearchParams();
const { pathname } = useLocation();
const [searchQuery, setSearchQuery] = useState(() => searchParams?.get('query') ?? '');
const debouncedSearchQuery = useDebouncedValue(searchQuery, 500);
/**
* Handle debouncing the search query.
*/
useEffect(() => {
const params = new URLSearchParams(searchParams?.toString());
params.set('query', debouncedSearchQuery);
if (debouncedSearchQuery === '') {
params.delete('query');
}
// If nothing to change then do nothing.
if (params.toString() === searchParams?.toString()) {
return;
}
setSearchParams(params);
}, [debouncedSearchQuery, pathname, searchParams]);
return (
<div>
<SettingsHeader title={t`Email Transports`} subtitle={t`Manage all email transports`} hideDivider>
<EmailTransportCreateDialog />
</SettingsHeader>
<div className="mt-4">
<Input
defaultValue={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t`Search by name or from address`}
className="mb-4"
/>
<AdminEmailTransportsTable />
</div>
</div>
);
}
@@ -24,6 +24,7 @@ import {
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { zodResolver } from '@hookform/resolvers/zod';
@@ -572,6 +573,10 @@ const OrganisationAdminForm = ({ organisation, licenseFlags }: OrganisationAdmin
const { mutateAsync: updateOrganisation } = trpc.admin.organisation.update.useMutation();
const { data: transportsData } = trpc.admin.emailTransport.find.useQuery({ perPage: 100 });
const transports = transportsData?.data ?? [];
const NONE_VALUE = '__none__';
const hasRestrictedEnterpriseFeatures = Object.values(SUBSCRIPTION_CLAIM_FEATURE_FLAGS).some(
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
(flag) => flag.isEnterprise && !licenseFlags?.[flag.key as keyof TLicenseClaim],
@@ -602,6 +607,7 @@ const OrganisationAdminForm = ({ organisation, licenseFlags }: OrganisationAdmin
TUpdateOrganisationBillingFormSchema['claims']
>['apiRateLimits'],
apiQuota: organisation.organisationClaim.apiQuota,
emailTransportId: organisation.organisationClaim.emailTransportId ?? null,
},
originalSubscriptionClaimId: organisation.organisationClaim.originalSubscriptionClaimId || '',
},
@@ -865,6 +871,40 @@ const OrganisationAdminForm = ({ organisation, licenseFlags }: OrganisationAdmin
<ClaimLimitFields control={form.control} prefix="claims." />
<FormField
control={form.control}
name="claims.emailTransportId"
render={({ field }) => (
<FormItem>
<FormLabel>
<Trans>Email transport</Trans>
</FormLabel>
<Select
value={field.value ?? NONE_VALUE}
onValueChange={(value) => field.onChange(value === NONE_VALUE ? null : value)}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t`Default (system mailer)`} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value={NONE_VALUE}>{t`Default (system mailer)`}</SelectItem>
{transports.map((transport) => (
<SelectItem key={transport.id} value={transport.id}>
{transport.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormDescription>
<Trans>Organisations without a transport use the system default mailer.</Trans>
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<Button type="submit" loading={form.formState.isSubmitting}>
<Trans>Update</Trans>
@@ -0,0 +1,97 @@
import { AppErrorCode } from '@documenso/lib/errors/app-error';
import type { MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
import { match } from 'ts-pattern';
export type ToastMessageDescriptor = {
title: MessageDescriptor;
description: MessageDescriptor;
};
export const RECIPIENT_LIMIT_EXCEEDED_ERROR_MESSAGE = {
title: msg`Too many recipients`,
description: msg`This document has too many recipients. Please remove some recipients or contact support if you need more.`,
};
export const FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE = {
title: msg`Fair use limit exceeded`,
description: msg`Your organisation has reached its plan's fair use limit. Please contact your organisation administrator or support to continue.`,
};
export const getDistributeErrorMessage = (code: string): ToastMessageDescriptor => {
return match(code)
.with('RECIPIENT_LIMIT_EXCEEDED', () => RECIPIENT_LIMIT_EXCEEDED_ERROR_MESSAGE)
.with(AppErrorCode.TOO_MANY_REQUESTS, () => FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE)
.otherwise(() => ({
title: msg`Something went wrong`,
description: msg`An error occurred while distributing the document.`,
}));
};
export const getDirectTemplateErrorMessage = (code: string): ToastMessageDescriptor => {
return match(code)
.with('RECIPIENT_LIMIT_EXCEEDED', () => RECIPIENT_LIMIT_EXCEEDED_ERROR_MESSAGE)
.with(AppErrorCode.TOO_MANY_REQUESTS, () => FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE)
.otherwise(() => ({
title: msg`Something went wrong`,
description: msg`We were unable to submit this document at this time. Please try again later.`,
}));
};
export const getUploadErrorMessage = (code: string): ToastMessageDescriptor => {
return match(code)
.with(AppErrorCode.TOO_MANY_REQUESTS, () => FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE)
.with('INVALID_DOCUMENT_FILE', () => ({
title: msg`Error`,
description: msg`You cannot upload encrypted PDFs.`,
}))
.with(AppErrorCode.LIMIT_EXCEEDED, () => ({
title: msg`Error`,
description: msg`You have reached your document limit for this month. Please upgrade your plan.`,
}))
.with('ENVELOPE_ITEM_LIMIT_EXCEEDED', () => ({
title: msg`Error`,
description: msg`You have reached the limit of the number of files per envelope.`,
}))
.with('UNSUPPORTED_FILE_TYPE', () => ({
title: msg`Error`,
description: msg`This file type isn't supported. Please upload a PDF or Word document.`,
}))
.with('CONVERSION_SERVICE_UNAVAILABLE', () => ({
title: msg`Error`,
description: msg`Document conversion is temporarily unavailable. Please try again shortly or upload a PDF.`,
}))
.with('CONVERSION_FAILED', () => ({
title: msg`Error`,
description: msg`We couldn't convert this file. Please check it's a valid Word document or upload a PDF instead.`,
}))
.otherwise(() => ({
title: msg`Error`,
description: msg`An error occurred while uploading your document.`,
}));
};
export const getTemplateUseErrorMessage = (code: string): ToastMessageDescriptor => {
return match(code)
.with('DOCUMENT_SEND_FAILED', () => ({
title: msg`Error`,
description: msg`The document was created but could not be sent to recipients.`,
}))
.with(AppErrorCode.INVALID_BODY, AppErrorCode.INVALID_REQUEST, () => ({
title: msg`Error`,
description: msg`The document could not be created because of missing or invalid information. Please review the template's recipients and fields.`,
}))
.with(AppErrorCode.NOT_FOUND, () => ({
title: msg`Error`,
description: msg`The template or one of its recipients could not be found.`,
}))
.with(AppErrorCode.LIMIT_EXCEEDED, () => ({
title: msg`Error`,
description: msg`You have reached your document limit for this plan. Please upgrade your plan.`,
}))
.with(AppErrorCode.TOO_MANY_REQUESTS, () => FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE)
.otherwise(() => ({
title: msg`Error`,
description: msg`An error occurred while creating document from template.`,
}));
};