feat: create from template

This commit is contained in:
Mythie
2024-02-20 19:46:18 +11:00
parent 4c5b910a59
commit b9e5905469
8 changed files with 242 additions and 70 deletions

View File

@ -22,9 +22,14 @@ export const getUserByApiToken = async ({ token }: { token: string }) => {
throw new Error('Invalid token');
}
const tokenObject = user.ApiToken.find((apiToken) => apiToken.token === hashedToken);
const retrievedToken = user.ApiToken.find((apiToken) => apiToken.token === hashedToken);
if (!tokenObject || new Date(tokenObject.expires) < new Date()) {
// This should be impossible but we need to satisfy TypeScript
if (!retrievedToken) {
throw new Error('Invalid token');
}
if (retrievedToken.expires && retrievedToken.expires < new Date()) {
throw new Error('Expired token');
}

View File

@ -1,14 +1,21 @@
import { nanoid } from '@documenso/lib/universal/id';
import { prisma } from '@documenso/prisma';
import type { TCreateDocumentFromTemplateMutationSchema } from '@documenso/trpc/server/template-router/schema';
import type { RecipientRole } from '@documenso/prisma/client';
export type CreateDocumentFromTemplateOptions = TCreateDocumentFromTemplateMutationSchema & {
export type CreateDocumentFromTemplateOptions = {
templateId: number;
userId: number;
recipients?: {
name?: string;
email: string;
role?: RecipientRole;
}[];
};
export const createDocumentFromTemplate = async ({
templateId,
userId,
recipients,
}: CreateDocumentFromTemplateOptions) => {
const template = await prisma.template.findUnique({
where: {
@ -63,7 +70,11 @@ export const createDocumentFromTemplate = async ({
},
include: {
Recipient: true,
Recipient: {
orderBy: {
id: 'asc',
},
},
},
});
@ -88,5 +99,34 @@ export const createDocumentFromTemplate = async ({
}),
});
if (recipients && recipients.length > 0) {
document.Recipient = await Promise.all(
recipients.map(async (recipient, index) => {
const existingRecipient = document.Recipient.at(index);
return await prisma.recipient.upsert({
where: {
documentId_email: {
documentId: document.id,
email: existingRecipient?.email ?? recipient.email,
},
},
update: {
name: recipient.name,
email: recipient.email,
role: recipient.role,
},
create: {
documentId: document.id,
email: recipient.email,
name: recipient.name,
role: recipient.role,
token: nanoid(),
},
});
}),
);
}
return document;
};