Skip to content

The Open Source DocuSign Alternative.

feat: replace template variables with values

Ephraim Atta-Duncan345343f4b583
diff --git a/packages/lib/server-only/document/send-document.tsx b/packages/lib/server-only/document/send-document.tsx
index 10e75b7ca..b3eda2077 100644
--- a/packages/lib/server-only/document/send-document.tsx
+++ b/packages/lib/server-only/document/send-document.tsx
@@ -3,6 +3,7 @@ import { createElement } from 'react';
import { mailer } from '@documenso/email/mailer';
import { render } from '@documenso/email/render';
import { DocumentInviteEmailTemplate } from '@documenso/email/templates/document-invite';
+import { renderCustomEmailTemplate } from '@documenso/lib/utils/render-custom-email-template';
import { prisma } from '@documenso/prisma';
import { DocumentStatus, SendStatus } from '@documenso/prisma/client';
@@ -47,6 +48,12 @@ export const sendDocument = async ({ documentId, userId }: SendDocumentOptions)
document.Recipient.map(async (recipient) => {
const { email, name } = recipient;
+ const customEmailTemplate = {
+ 'signer.name': name,
+ 'signer.email': email,
+ 'document.name': document.title,
+ };
+
if (recipient.sendStatus === SendStatus.SENT) {
return;
}
@@ -60,7 +67,10 @@ export const sendDocument = async ({ documentId, userId }: SendDocumentOptions)
inviterEmail: user.email,
assetBaseUrl,
signDocumentLink,
- customBody: customEmail?.customEmailBody || '',
+ customBody: renderCustomEmailTemplate(
+ customEmail?.customEmailBody || '',
+ customEmailTemplate,
+ ),
});
await mailer.sendMail({
@@ -73,7 +83,7 @@ export const sendDocument = async ({ documentId, userId }: SendDocumentOptions)
address: process.env.NEXT_PRIVATE_SMTP_FROM_ADDRESS || '[email protected]',
},
subject: customEmail?.customEmailSubject
- ? customEmail.customEmailSubject
+ ? renderCustomEmailTemplate(customEmail.customEmailSubject, customEmailTemplate)
: 'Please sign this document',
html: render(template),
text: render(template, { plainText: true }),
diff --git a/packages/lib/utils/render-custom-email-template.ts b/packages/lib/utils/render-custom-email-template.ts
new file mode 100644
index 000000000..304298c86
--- /dev/null
+++ b/packages/lib/utils/render-custom-email-template.ts
@@ -0,0 +1,20 @@
+export const renderCustomEmailTemplate = <T extends Record<string, string>>(
+ template: string,
+ variables: T,
+): string => {
+ let t = template;
+
+ Object.entries(variables).forEach((entry) => {
+ const [key, value] = entry;
+
+ const placeholder = `{${key}}`;
+
+ const re = new RegExp(placeholder, 'g');
+
+ if (Object.prototype.hasOwnProperty.call(variables, key)) {
+ t = t.replace(re, String(value));
+ }
+ });
+
+ return t;
+};