mirror of
https://github.com/documenso/documenso.git
synced 2025-11-17 18:21:32 +10:00
feat: only use background job scheduling with inngest
This commit is contained in:
@ -74,7 +74,8 @@ export class JobClient<T extends ReadonlyArray<JobDefinition> = []> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await eligibleJob.handler({ payload, io });
|
const result = await eligibleJob.handler({ payload, io });
|
||||||
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Direct job execution failed for ${options.name}:`, error);
|
console.error(`Direct job execution failed for ${options.name}:`, error);
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
@ -32,16 +32,49 @@ export const run = async ({
|
|||||||
}) => {
|
}) => {
|
||||||
const { userId, documentId, recipientId, requestMetadata } = payload;
|
const { userId, documentId, recipientId, requestMetadata } = payload;
|
||||||
|
|
||||||
const [user, document, recipient] = await Promise.all([
|
try {
|
||||||
prisma.user.findFirstOrThrow({
|
// First, check if the document exists directly before performing the multi-promise
|
||||||
where: {
|
const documentExists = await prisma.document.findFirst({
|
||||||
id: userId,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
prisma.document.findFirstOrThrow({
|
|
||||||
where: {
|
where: {
|
||||||
id: documentId,
|
id: documentId,
|
||||||
status: DocumentStatus.PENDING,
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!documentExists) {
|
||||||
|
throw new Error(`No Document found with ID ${documentId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a small delay to allow any pending transactions to complete
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
resolve();
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
const [user, recipient] = await Promise.all([
|
||||||
|
prisma.user.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: userId,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
|
||||||
|
prisma.recipient.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: recipientId,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Get the document without restricting to PENDING status
|
||||||
|
const document = await prisma.document.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: documentId,
|
||||||
|
// Don't restrict to PENDING status, as it might still be in DRAFT status
|
||||||
|
// if the transaction hasn't fully completed yet
|
||||||
|
status: {
|
||||||
|
in: [DocumentStatus.DRAFT, DocumentStatus.PENDING],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
documentMeta: true,
|
documentMeta: true,
|
||||||
@ -53,160 +86,158 @@ export const run = async ({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
});
|
||||||
prisma.recipient.findFirstOrThrow({
|
|
||||||
where: {
|
|
||||||
id: recipientId,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const { documentMeta, team } = document;
|
const { documentMeta, team } = document;
|
||||||
|
|
||||||
if (recipient.role === RecipientRole.CC) {
|
if (recipient.role === RecipientRole.CC) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isRecipientSigningRequestEmailEnabled = extractDerivedDocumentEmailSettings(
|
const isRecipientSigningRequestEmailEnabled = extractDerivedDocumentEmailSettings(
|
||||||
document.documentMeta,
|
document.documentMeta,
|
||||||
).recipientSigningRequest;
|
).recipientSigningRequest;
|
||||||
|
|
||||||
if (!isRecipientSigningRequestEmailEnabled) {
|
if (!isRecipientSigningRequestEmailEnabled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const customEmail = document?.documentMeta;
|
const customEmail = document?.documentMeta;
|
||||||
const isDirectTemplate = document.source === DocumentSource.TEMPLATE_DIRECT_LINK;
|
const isDirectTemplate = document.source === DocumentSource.TEMPLATE_DIRECT_LINK;
|
||||||
const isTeamDocument = document.teamId !== null;
|
const isTeamDocument = document.teamId !== null;
|
||||||
|
|
||||||
const recipientEmailType = RECIPIENT_ROLE_TO_EMAIL_TYPE[recipient.role];
|
const recipientEmailType = RECIPIENT_ROLE_TO_EMAIL_TYPE[recipient.role];
|
||||||
|
|
||||||
const { email, name } = recipient;
|
const { email, name } = recipient;
|
||||||
const selfSigner = email === user.email;
|
const selfSigner = email === user.email;
|
||||||
|
|
||||||
const i18n = await getI18nInstance(documentMeta?.language);
|
const i18n = await getI18nInstance(documentMeta?.language);
|
||||||
|
|
||||||
const recipientActionVerb = i18n
|
const recipientActionVerb = i18n
|
||||||
._(RECIPIENT_ROLES_DESCRIPTION[recipient.role].actionVerb)
|
._(RECIPIENT_ROLES_DESCRIPTION[recipient.role].actionVerb)
|
||||||
.toLowerCase();
|
.toLowerCase();
|
||||||
|
|
||||||
let emailMessage = customEmail?.message || '';
|
let emailMessage = customEmail?.message || '';
|
||||||
let emailSubject = i18n._(msg`Please ${recipientActionVerb} this document`);
|
let emailSubject = i18n._(msg`Please ${recipientActionVerb} this document`);
|
||||||
|
|
||||||
if (selfSigner) {
|
|
||||||
emailMessage = i18n._(
|
|
||||||
msg`You have initiated the document ${`"${document.title}"`} that requires you to ${recipientActionVerb} it.`,
|
|
||||||
);
|
|
||||||
emailSubject = i18n._(msg`Please ${recipientActionVerb} your document`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isDirectTemplate) {
|
|
||||||
emailMessage = i18n._(
|
|
||||||
msg`A document was created by your direct template that requires you to ${recipientActionVerb} it.`,
|
|
||||||
);
|
|
||||||
emailSubject = i18n._(
|
|
||||||
msg`Please ${recipientActionVerb} this document created by your direct template`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isTeamDocument && team) {
|
|
||||||
emailSubject = i18n._(msg`${team.name} invited you to ${recipientActionVerb} a document`);
|
|
||||||
emailMessage = customEmail?.message ?? '';
|
|
||||||
|
|
||||||
if (!emailMessage) {
|
|
||||||
const inviterName = user.name || '';
|
|
||||||
|
|
||||||
|
if (selfSigner) {
|
||||||
emailMessage = i18n._(
|
emailMessage = i18n._(
|
||||||
team.teamGlobalSettings?.includeSenderDetails
|
msg`You have initiated the document ${`"${document.title}"`} that requires you to ${recipientActionVerb} it.`,
|
||||||
? msg`${inviterName} on behalf of "${team.name}" has invited you to ${recipientActionVerb} the document "${document.title}".`
|
);
|
||||||
: msg`${team.name} has invited you to ${recipientActionVerb} the document "${document.title}".`,
|
emailSubject = i18n._(msg`Please ${recipientActionVerb} your document`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isDirectTemplate) {
|
||||||
|
emailMessage = i18n._(
|
||||||
|
msg`A document was created by your direct template that requires you to ${recipientActionVerb} it.`,
|
||||||
|
);
|
||||||
|
emailSubject = i18n._(
|
||||||
|
msg`Please ${recipientActionVerb} this document created by your direct template`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const customEmailTemplate = {
|
if (isTeamDocument && team) {
|
||||||
'signer.name': name,
|
emailSubject = i18n._(msg`${team.name} invited you to ${recipientActionVerb} a document`);
|
||||||
'signer.email': email,
|
emailMessage = customEmail?.message ?? '';
|
||||||
'document.name': document.title,
|
|
||||||
};
|
|
||||||
|
|
||||||
const assetBaseUrl = NEXT_PUBLIC_WEBAPP_URL() || 'http://localhost:3000';
|
if (!emailMessage) {
|
||||||
const signDocumentLink = `${NEXT_PUBLIC_WEBAPP_URL()}/sign/${recipient.token}`;
|
const inviterName = user.name || '';
|
||||||
|
|
||||||
const template = createElement(DocumentInviteEmailTemplate, {
|
emailMessage = i18n._(
|
||||||
documentName: document.title,
|
team.teamGlobalSettings?.includeSenderDetails
|
||||||
inviterName: user.name || undefined,
|
? msg`${inviterName} on behalf of "${team.name}" has invited you to ${recipientActionVerb} the document "${document.title}".`
|
||||||
inviterEmail: isTeamDocument ? team?.teamEmail?.email || user.email : user.email,
|
: msg`${team.name} has invited you to ${recipientActionVerb} the document "${document.title}".`,
|
||||||
assetBaseUrl,
|
);
|
||||||
signDocumentLink,
|
}
|
||||||
customBody: renderCustomEmailTemplate(emailMessage, customEmailTemplate),
|
}
|
||||||
role: recipient.role,
|
|
||||||
selfSigner,
|
|
||||||
isTeamInvite: isTeamDocument,
|
|
||||||
teamName: team?.name,
|
|
||||||
teamEmail: team?.teamEmail?.email,
|
|
||||||
includeSenderDetails: team?.teamGlobalSettings?.includeSenderDetails,
|
|
||||||
});
|
|
||||||
|
|
||||||
await io.runTask('send-signing-email', async () => {
|
const customEmailTemplate = {
|
||||||
const branding = document.team?.teamGlobalSettings
|
'signer.name': name,
|
||||||
? teamGlobalSettingsToBranding(document.team.teamGlobalSettings)
|
'signer.email': email,
|
||||||
: undefined;
|
'document.name': document.title,
|
||||||
|
};
|
||||||
|
|
||||||
const [html, text] = await Promise.all([
|
const assetBaseUrl = NEXT_PUBLIC_WEBAPP_URL() || 'http://localhost:3000';
|
||||||
renderEmailWithI18N(template, { lang: documentMeta?.language, branding }),
|
const signDocumentLink = `${NEXT_PUBLIC_WEBAPP_URL()}/sign/${recipient.token}`;
|
||||||
renderEmailWithI18N(template, {
|
|
||||||
lang: documentMeta?.language,
|
|
||||||
branding,
|
|
||||||
plainText: true,
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
await mailer.sendMail({
|
const template = createElement(DocumentInviteEmailTemplate, {
|
||||||
to: {
|
documentName: document.title,
|
||||||
name: recipient.name,
|
inviterName: user.name || undefined,
|
||||||
address: recipient.email,
|
inviterEmail: isTeamDocument ? team?.teamEmail?.email || user.email : user.email,
|
||||||
},
|
assetBaseUrl,
|
||||||
from: {
|
signDocumentLink,
|
||||||
name: FROM_NAME,
|
customBody: renderCustomEmailTemplate(emailMessage, customEmailTemplate),
|
||||||
address: FROM_ADDRESS,
|
role: recipient.role,
|
||||||
},
|
selfSigner,
|
||||||
subject: renderCustomEmailTemplate(
|
isTeamInvite: isTeamDocument,
|
||||||
documentMeta?.subject || emailSubject,
|
teamName: team?.name,
|
||||||
customEmailTemplate,
|
teamEmail: team?.teamEmail?.email,
|
||||||
),
|
includeSenderDetails: team?.teamGlobalSettings?.includeSenderDetails,
|
||||||
html,
|
|
||||||
text,
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
await io.runTask('update-recipient', async () => {
|
await io.runTask('send-signing-email', async () => {
|
||||||
await prisma.recipient.update({
|
const branding = document.team?.teamGlobalSettings
|
||||||
where: {
|
? teamGlobalSettingsToBranding(document.team.teamGlobalSettings)
|
||||||
id: recipient.id,
|
: undefined;
|
||||||
},
|
|
||||||
data: {
|
|
||||||
sendStatus: SendStatus.SENT,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
await io.runTask('store-audit-log', async () => {
|
const [html, text] = await Promise.all([
|
||||||
await prisma.documentAuditLog.create({
|
renderEmailWithI18N(template, { lang: documentMeta?.language, branding }),
|
||||||
data: createDocumentAuditLogData({
|
renderEmailWithI18N(template, {
|
||||||
type: DOCUMENT_AUDIT_LOG_TYPE.EMAIL_SENT,
|
lang: documentMeta?.language,
|
||||||
documentId: document.id,
|
branding,
|
||||||
user,
|
plainText: true,
|
||||||
requestMetadata,
|
}),
|
||||||
data: {
|
]);
|
||||||
emailType: recipientEmailType,
|
|
||||||
recipientId: recipient.id,
|
await mailer.sendMail({
|
||||||
recipientName: recipient.name,
|
to: {
|
||||||
recipientEmail: recipient.email,
|
name: recipient.name,
|
||||||
recipientRole: recipient.role,
|
address: recipient.email,
|
||||||
isResending: false,
|
|
||||||
},
|
},
|
||||||
}),
|
from: {
|
||||||
|
name: FROM_NAME,
|
||||||
|
address: FROM_ADDRESS,
|
||||||
|
},
|
||||||
|
subject: renderCustomEmailTemplate(
|
||||||
|
documentMeta?.subject || emailSubject,
|
||||||
|
customEmailTemplate,
|
||||||
|
),
|
||||||
|
html,
|
||||||
|
text,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
await io.runTask('update-recipient', async () => {
|
||||||
|
await prisma.recipient.update({
|
||||||
|
where: {
|
||||||
|
id: recipient.id,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
sendStatus: SendStatus.SENT,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await io.runTask('store-audit-log', async () => {
|
||||||
|
await prisma.documentAuditLog.create({
|
||||||
|
data: createDocumentAuditLogData({
|
||||||
|
type: DOCUMENT_AUDIT_LOG_TYPE.EMAIL_SENT,
|
||||||
|
documentId: document.id,
|
||||||
|
user,
|
||||||
|
requestMetadata,
|
||||||
|
data: {
|
||||||
|
emailType: recipientEmailType,
|
||||||
|
recipientId: recipient.id,
|
||||||
|
recipientName: recipient.name,
|
||||||
|
recipientEmail: recipient.email,
|
||||||
|
recipientRole: recipient.role,
|
||||||
|
isResending: false,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Job failed with error:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@ -133,31 +133,6 @@ export const sendDocument = async ({
|
|||||||
Object.assign(document, result);
|
Object.assign(document, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Commented out server side checks for minimum 1 signature per signer now since we need to
|
|
||||||
// decide if we want to enforce this for API & templates.
|
|
||||||
// const fields = await getFieldsForDocument({
|
|
||||||
// documentId: documentId,
|
|
||||||
// userId: userId,
|
|
||||||
// });
|
|
||||||
|
|
||||||
// const fieldsWithSignerEmail = fields.map((field) => ({
|
|
||||||
// ...field,
|
|
||||||
// signerEmail:
|
|
||||||
// document.Recipient.find((recipient) => recipient.id === field.recipientId)?.email ?? '',
|
|
||||||
// }));
|
|
||||||
|
|
||||||
// const everySignerHasSignature = document?.Recipient.every(
|
|
||||||
// (recipient) =>
|
|
||||||
// recipient.role !== RecipientRole.SIGNER ||
|
|
||||||
// fieldsWithSignerEmail.some(
|
|
||||||
// (field) => field.type === 'SIGNATURE' && field.signerEmail === recipient.email,
|
|
||||||
// ),
|
|
||||||
// );
|
|
||||||
|
|
||||||
// if (!everySignerHasSignature) {
|
|
||||||
// throw new Error('Some signers have not been assigned a signature field.');
|
|
||||||
// }
|
|
||||||
|
|
||||||
const isRecipientSigningRequestEmailEnabled = extractDerivedDocumentEmailSettings(
|
const isRecipientSigningRequestEmailEnabled = extractDerivedDocumentEmailSettings(
|
||||||
document.documentMeta,
|
document.documentMeta,
|
||||||
).recipientSigningRequest;
|
).recipientSigningRequest;
|
||||||
@ -165,52 +140,14 @@ export const sendDocument = async ({
|
|||||||
// Only send email if one of the following is true:
|
// Only send email if one of the following is true:
|
||||||
// - It is explicitly set
|
// - It is explicitly set
|
||||||
// - The email is enabled for signing requests AND sendEmail is undefined
|
// - The email is enabled for signing requests AND sendEmail is undefined
|
||||||
if (sendEmail || (isRecipientSigningRequestEmailEnabled && sendEmail === undefined)) {
|
const shouldSendEmail =
|
||||||
await Promise.all(
|
sendEmail || (isRecipientSigningRequestEmailEnabled && sendEmail === undefined);
|
||||||
recipientsToNotify.map(async (recipient) => {
|
|
||||||
if (recipient.sendStatus === SendStatus.SENT || recipient.role === RecipientRole.CC) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await jobs.triggerJob({
|
|
||||||
name: 'send.signing.requested.email',
|
|
||||||
payload: {
|
|
||||||
userId,
|
|
||||||
documentId,
|
|
||||||
recipientId: recipient.id,
|
|
||||||
requestMetadata: requestMetadata?.requestMetadata,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const allRecipientsHaveNoActionToTake = document.recipients.every(
|
const allRecipientsHaveNoActionToTake = document.recipients.every(
|
||||||
(recipient) =>
|
(recipient) =>
|
||||||
recipient.role === RecipientRole.CC || recipient.signingStatus === SigningStatus.SIGNED,
|
recipient.role === RecipientRole.CC || recipient.signingStatus === SigningStatus.SIGNED,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (allRecipientsHaveNoActionToTake) {
|
|
||||||
await jobs.triggerJob({
|
|
||||||
name: 'internal.seal-document',
|
|
||||||
payload: {
|
|
||||||
documentId,
|
|
||||||
requestMetadata: requestMetadata?.requestMetadata,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Keep the return type the same for the `sendDocument` method
|
|
||||||
return await prisma.document.findFirstOrThrow({
|
|
||||||
where: {
|
|
||||||
id: documentId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
documentMeta: true,
|
|
||||||
recipients: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedDocument = await prisma.$transaction(async (tx) => {
|
const updatedDocument = await prisma.$transaction(async (tx) => {
|
||||||
if (document.status === DocumentStatus.DRAFT) {
|
if (document.status === DocumentStatus.DRAFT) {
|
||||||
await tx.documentAuditLog.create({
|
await tx.documentAuditLog.create({
|
||||||
@ -244,5 +181,47 @@ export const sendDocument = async ({
|
|||||||
teamId,
|
teamId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Now that the transaction is complete and document status is updated, trigger email jobs
|
||||||
|
if (shouldSendEmail) {
|
||||||
|
await Promise.all(
|
||||||
|
recipientsToNotify.map(async (recipient) => {
|
||||||
|
if (recipient.sendStatus === SendStatus.SENT || recipient.role === RecipientRole.CC) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await jobs.triggerJob({
|
||||||
|
name: 'send.signing.requested.email',
|
||||||
|
payload: {
|
||||||
|
userId,
|
||||||
|
documentId,
|
||||||
|
recipientId: recipient.id,
|
||||||
|
requestMetadata: requestMetadata?.requestMetadata,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allRecipientsHaveNoActionToTake) {
|
||||||
|
await jobs.triggerJob({
|
||||||
|
name: 'internal.seal-document',
|
||||||
|
payload: {
|
||||||
|
documentId,
|
||||||
|
requestMetadata: requestMetadata?.requestMetadata,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Keep the return type the same for the `sendDocument` method
|
||||||
|
return await prisma.document.findFirstOrThrow({
|
||||||
|
where: {
|
||||||
|
id: documentId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
documentMeta: true,
|
||||||
|
recipients: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return updatedDocument;
|
return updatedDocument;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user