mirror of
https://github.com/documenso/documenso.git
synced 2026-07-27 10:25:00 +10:00
feat: add signing reminder
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import { JobClient } from './client/client';
|
||||
import { TEST_CRON_JOB_DEFINITION } from './definitions/cron/test-cron';
|
||||
import { SEND_CONFIRMATION_EMAIL_JOB_DEFINITION } from './definitions/emails/send-confirmation-email';
|
||||
import { SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION } from './definitions/emails/send-rejection-emails';
|
||||
import { SEND_SIGNING_EMAIL_JOB_DEFINITION } from './definitions/emails/send-signing-email';
|
||||
import { SEND_SIGNING_REMINDER_EMAIL_JOB } from './definitions/emails/send-signing-reminder-email';
|
||||
import { SEND_TEAM_DELETED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-deleted-email';
|
||||
import { SEND_TEAM_MEMBER_JOINED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-member-joined-email';
|
||||
import { SEND_TEAM_MEMBER_LEFT_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-member-left-email';
|
||||
@@ -20,7 +20,7 @@ export const jobsClient = new JobClient([
|
||||
SEND_TEAM_DELETED_EMAIL_JOB_DEFINITION,
|
||||
SEAL_DOCUMENT_JOB_DEFINITION,
|
||||
SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION,
|
||||
TEST_CRON_JOB_DEFINITION,
|
||||
SEND_SIGNING_REMINDER_EMAIL_JOB,
|
||||
] as const);
|
||||
|
||||
export const jobs = jobsClient;
|
||||
|
||||
@@ -26,10 +26,10 @@ export type TriggerJobOptions<Definitions extends ReadonlyArray<JobDefinition> =
|
||||
};
|
||||
}[number];
|
||||
|
||||
export type CronTrigger = {
|
||||
export type CronTrigger<N extends string = string> = {
|
||||
type: 'cron';
|
||||
schedule: string;
|
||||
name?: string;
|
||||
name: N;
|
||||
};
|
||||
|
||||
export type EventTrigger<N extends string = string> = {
|
||||
@@ -45,7 +45,7 @@ export type JobDefinition<Name extends string = string, Schema = any> = {
|
||||
enabled?: boolean;
|
||||
trigger:
|
||||
| (EventTrigger<Name> & { schema?: z.ZodType<Schema> })
|
||||
| (CronTrigger & { schema?: z.ZodType<Schema> });
|
||||
| (CronTrigger<Name> & { schema?: z.ZodType<Schema> });
|
||||
handler: (options: { payload: Schema; io: JobRunIO }) => Promise<Json | void>;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
|
||||
import type { JobDefinition } from '../../client/_internal/job';
|
||||
|
||||
const TEST_CRON_JOB_DEFINITION_ID = 'test.cron';
|
||||
|
||||
export const TEST_CRON_JOB_DEFINITION = {
|
||||
id: TEST_CRON_JOB_DEFINITION_ID,
|
||||
name: 'Test Cron Job',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
type: 'cron',
|
||||
schedule: '* * * * *',
|
||||
},
|
||||
handler: async ({ io }) => {
|
||||
// send a mail to all recipients of all documents
|
||||
const documents = await prisma.document.findMany({});
|
||||
|
||||
console.log(`Found ${documents.length} unsigned documents`);
|
||||
|
||||
for (const document of documents) {
|
||||
// eslint-disable-next-line @typescript-eslint/require-await
|
||||
await io.runTask(`send-reminder-${document.id}-${document.id}`, async () => {
|
||||
console.log(`Sent reminder for document ${document.id} to recipient ${document.id}`);
|
||||
});
|
||||
}
|
||||
},
|
||||
} as const satisfies JobDefinition<typeof TEST_CRON_JOB_DEFINITION_ID>;
|
||||
@@ -0,0 +1,169 @@
|
||||
import { createElement } from 'react';
|
||||
|
||||
import { msg } from '@lingui/macro';
|
||||
|
||||
import { mailer } from '@documenso/email/mailer';
|
||||
import DocumentInviteEmailTemplate from '@documenso/email/templates/document-invite';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { DocumentStatus, RecipientRole, SendStatus } from '@documenso/prisma/client';
|
||||
import { ReminderInterval, SigningStatus } from '@documenso/prisma/generated/types';
|
||||
|
||||
import { getI18nInstance } from '../../../client-only/providers/i18n.server';
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '../../../constants/app';
|
||||
import { FROM_ADDRESS, FROM_NAME } from '../../../constants/email';
|
||||
import { RECIPIENT_ROLES_DESCRIPTION } from '../../../constants/recipient-roles';
|
||||
import { extractDerivedDocumentEmailSettings } from '../../../types/document-email';
|
||||
import { renderEmailWithI18N } from '../../../utils/render-email-with-i18n';
|
||||
import { shouldSendReminder } from '../../../utils/should-send-reminder';
|
||||
import type { JobDefinition, JobRunIO } from '../../client/_internal/job';
|
||||
|
||||
export type SendSigningReminderEmailHandlerOptions = {
|
||||
io: JobRunIO;
|
||||
};
|
||||
|
||||
const SEND_SIGNING_REMINDER_EMAIL_JOB_ID = 'send.signing.reminder.email';
|
||||
|
||||
export const SEND_SIGNING_REMINDER_EMAIL_JOB = {
|
||||
id: SEND_SIGNING_REMINDER_EMAIL_JOB_ID,
|
||||
name: 'Send Signing Reminder Email',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
type: 'cron',
|
||||
schedule: '*/5 * * * *',
|
||||
name: SEND_SIGNING_REMINDER_EMAIL_JOB_ID,
|
||||
},
|
||||
handler: async ({ io }) => {
|
||||
const now = new Date();
|
||||
|
||||
const documentWithReminders = await prisma.document.findMany({
|
||||
where: {
|
||||
status: DocumentStatus.PENDING,
|
||||
documentMeta: {
|
||||
reminderInterval: {
|
||||
not: ReminderInterval.NONE,
|
||||
},
|
||||
},
|
||||
deletedAt: null,
|
||||
},
|
||||
|
||||
include: {
|
||||
documentMeta: true,
|
||||
User: true,
|
||||
Recipient: {
|
||||
where: {
|
||||
signingStatus: SigningStatus.NOT_SIGNED,
|
||||
role: {
|
||||
not: RecipientRole.CC,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(documentWithReminders);
|
||||
|
||||
for (const document of documentWithReminders) {
|
||||
if (!extractDerivedDocumentEmailSettings(document.documentMeta).recipientSigningRequest) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const { documentMeta } = document;
|
||||
if (!documentMeta) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { reminderInterval, lastReminderSentAt } = documentMeta;
|
||||
if (
|
||||
!shouldSendReminder({
|
||||
reminderInterval,
|
||||
lastReminderSentAt,
|
||||
now,
|
||||
})
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const recipient of document.Recipient) {
|
||||
const i18n = await getI18nInstance(document.documentMeta?.language);
|
||||
const recipientActionVerb = i18n
|
||||
._(RECIPIENT_ROLES_DESCRIPTION[recipient.role].actionVerb)
|
||||
.toLowerCase();
|
||||
|
||||
const emailSubject = i18n._(
|
||||
msg`Reminder: Please ${recipientActionVerb} the document "${document.title}"`,
|
||||
);
|
||||
const emailMessage = i18n._(
|
||||
msg`This is a reminder to ${recipientActionVerb} the document "${document.title}". Please complete this at your earliest convenience.`,
|
||||
);
|
||||
|
||||
const signDocumentLink = `${NEXT_PUBLIC_WEBAPP_URL()}/sign/${recipient.token}`;
|
||||
const assetBaseUrl = NEXT_PUBLIC_WEBAPP_URL() || 'http://localhost:3000';
|
||||
|
||||
const template = createElement(DocumentInviteEmailTemplate, {
|
||||
documentName: document.title,
|
||||
inviterName: document.User.name || undefined,
|
||||
inviterEmail: document.User.email,
|
||||
assetBaseUrl,
|
||||
signDocumentLink,
|
||||
customBody: emailMessage,
|
||||
role: recipient.role,
|
||||
selfSigner: recipient.email === document.User.email,
|
||||
});
|
||||
|
||||
await io.runTask('send-reminder-email', async () => {
|
||||
const [html, text] = await Promise.all([
|
||||
renderEmailWithI18N(template, { lang: document.documentMeta?.language }),
|
||||
renderEmailWithI18N(template, {
|
||||
lang: document.documentMeta?.language,
|
||||
plainText: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
await mailer.sendMail({
|
||||
to: {
|
||||
name: recipient.name,
|
||||
address: recipient.email,
|
||||
},
|
||||
from: {
|
||||
name: FROM_NAME,
|
||||
address: FROM_ADDRESS,
|
||||
},
|
||||
subject: emailSubject,
|
||||
html,
|
||||
text,
|
||||
});
|
||||
});
|
||||
|
||||
await io.runTask('update-recipient-status', async () => {
|
||||
await prisma.recipient.update({
|
||||
where: { id: recipient.id },
|
||||
data: { sendStatus: SendStatus.SENT },
|
||||
});
|
||||
});
|
||||
|
||||
// TODO: Duncan == Audit log
|
||||
// await io.runTask('store-reminder-audit-log', async () => {
|
||||
// await prisma.documentAuditLog.create({
|
||||
// data: createDocumentAuditLogData({
|
||||
// type: DOCUMENT_AUDIT_LOG_TYPE.REMINDER_SENT,
|
||||
// documentId: document.id,
|
||||
// user,
|
||||
// requestMetadata,
|
||||
// data: {
|
||||
// recipientId: recipient.id,
|
||||
// recipientName: recipient.name,
|
||||
// recipientEmail: recipient.email,
|
||||
// recipientRole: recipient.role,
|
||||
// },
|
||||
// }),
|
||||
// });
|
||||
// });
|
||||
}
|
||||
|
||||
await prisma.documentMeta.update({
|
||||
where: { id: document.documentMeta?.id },
|
||||
data: { lastReminderSentAt: now },
|
||||
});
|
||||
}
|
||||
},
|
||||
} as const satisfies JobDefinition<typeof SEND_SIGNING_REMINDER_EMAIL_JOB_ID>;
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
diffDocumentMetaChanges,
|
||||
} from '@documenso/lib/utils/document-audit-logs';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import type { DocumentDistributionMethod, DocumentSigningOrder } from '@documenso/prisma/client';
|
||||
import type {
|
||||
DocumentDistributionMethod,
|
||||
DocumentSigningOrder,
|
||||
ReminderInterval,
|
||||
} from '@documenso/prisma/client';
|
||||
|
||||
import type { SupportedLanguageCodes } from '../../constants/i18n';
|
||||
import type { TDocumentEmailSettings } from '../../types/document-email';
|
||||
@@ -24,7 +28,7 @@ export type CreateDocumentMetaOptions = {
|
||||
signingOrder?: DocumentSigningOrder;
|
||||
distributionMethod?: DocumentDistributionMethod;
|
||||
typedSignatureEnabled?: boolean;
|
||||
reminderDays?: number;
|
||||
reminderInterval?: ReminderInterval;
|
||||
language?: SupportedLanguageCodes;
|
||||
userId: number;
|
||||
requestMetadata: RequestMetadata;
|
||||
@@ -43,7 +47,7 @@ export const upsertDocumentMeta = async ({
|
||||
emailSettings,
|
||||
distributionMethod,
|
||||
typedSignatureEnabled,
|
||||
reminderDays,
|
||||
reminderInterval,
|
||||
language,
|
||||
requestMetadata,
|
||||
}: CreateDocumentMetaOptions) => {
|
||||
@@ -98,7 +102,7 @@ export const upsertDocumentMeta = async ({
|
||||
emailSettings,
|
||||
distributionMethod,
|
||||
typedSignatureEnabled,
|
||||
reminderDays,
|
||||
reminderInterval,
|
||||
language,
|
||||
},
|
||||
update: {
|
||||
@@ -112,7 +116,7 @@ export const upsertDocumentMeta = async ({
|
||||
emailSettings,
|
||||
distributionMethod,
|
||||
typedSignatureEnabled,
|
||||
reminderDays,
|
||||
reminderInterval,
|
||||
language,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -178,6 +178,10 @@ export const completeDocumentWithToken = async ({
|
||||
requestMetadata,
|
||||
},
|
||||
});
|
||||
|
||||
// TODO: Duncan -- trigger cron job to send reminder email
|
||||
// TODO: Duncan -- audit log
|
||||
// TODO: Trigger cron job if cron is activated
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
import { ReminderInterval } from '@documenso/prisma/client';
|
||||
|
||||
export type ShouldSendReminderOptions = {
|
||||
reminderInterval: ReminderInterval;
|
||||
lastReminderSentAt: Date | null;
|
||||
now: Date;
|
||||
};
|
||||
|
||||
export const shouldSendReminder = ({
|
||||
lastReminderSentAt,
|
||||
now = new Date(),
|
||||
reminderInterval,
|
||||
}: ShouldSendReminderOptions): boolean => {
|
||||
if (!lastReminderSentAt) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hoursSinceLastReminder = DateTime.fromJSDate(now).diff(
|
||||
DateTime.fromJSDate(lastReminderSentAt),
|
||||
'hours',
|
||||
).hours;
|
||||
const monthsSinceLastReminder = DateTime.fromJSDate(now).diff(
|
||||
DateTime.fromJSDate(lastReminderSentAt),
|
||||
'months',
|
||||
).months;
|
||||
|
||||
switch (reminderInterval) {
|
||||
case ReminderInterval.EVERY_1_HOUR:
|
||||
return hoursSinceLastReminder >= 1;
|
||||
case ReminderInterval.EVERY_6_HOURS:
|
||||
return hoursSinceLastReminder >= 6;
|
||||
case ReminderInterval.EVERY_12_HOURS:
|
||||
return hoursSinceLastReminder >= 12;
|
||||
case ReminderInterval.DAILY:
|
||||
return hoursSinceLastReminder >= 24;
|
||||
case ReminderInterval.EVERY_3_DAYS:
|
||||
return hoursSinceLastReminder >= 72;
|
||||
case ReminderInterval.WEEKLY:
|
||||
return hoursSinceLastReminder >= 168;
|
||||
case ReminderInterval.EVERY_2_WEEKS:
|
||||
return hoursSinceLastReminder >= 336;
|
||||
case ReminderInterval.MONTHLY:
|
||||
return monthsSinceLastReminder >= 1;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user