Files
sign/packages/lib/server-only/template/duplicate-template.ts

105 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-10-06 22:54:24 +00:00
import { nanoid } from '@documenso/lib/universal/id';
import { prisma } from '@documenso/prisma';
2024-02-08 12:33:20 +11:00
import type { Prisma } from '@documenso/prisma/client';
2023-12-15 22:07:27 +11:00
import type { TDuplicateTemplateMutationSchema } from '@documenso/trpc/server/template-router/schema';
2023-10-06 22:54:24 +00:00
export type DuplicateTemplateOptions = TDuplicateTemplateMutationSchema & {
userId: number;
};
2024-02-08 12:33:20 +11:00
export const duplicateTemplate = async ({
templateId,
userId,
teamId,
}: DuplicateTemplateOptions) => {
let templateWhereFilter: Prisma.TemplateWhereUniqueInput = {
id: templateId,
userId,
teamId: null,
};
if (teamId !== undefined) {
templateWhereFilter = {
id: templateId,
teamId,
team: {
members: {
some: {
userId,
},
},
},
};
}
2023-10-06 22:54:24 +00:00
const template = await prisma.template.findUnique({
2024-02-08 12:33:20 +11:00
where: templateWhereFilter,
2023-10-06 22:54:24 +00:00
include: {
Recipient: true,
Field: true,
templateDocumentData: true,
},
});
if (!template) {
throw new Error('Template not found.');
}
const documentData = await prisma.documentData.create({
data: {
type: template.templateDocumentData.type,
data: template.templateDocumentData.data,
initialData: template.templateDocumentData.initialData,
},
});
const duplicatedTemplate = await prisma.template.create({
data: {
userId,
2024-02-08 12:33:20 +11:00
teamId,
2023-10-06 22:54:24 +00:00
title: template.title + ' (copy)',
templateDocumentDataId: documentData.id,
Recipient: {
create: template.Recipient.map((recipient) => ({
email: recipient.email,
name: recipient.name,
token: nanoid(),
})),
},
},
include: {
Recipient: true,
},
});
await prisma.field.createMany({
data: template.Field.map((field) => {
const recipient = template.Recipient.find((recipient) => recipient.id === field.recipientId);
const duplicatedTemplateRecipient = duplicatedTemplate.Recipient.find(
2023-12-15 22:07:27 +11:00
(doc) => doc.email === recipient?.email,
2023-10-06 22:54:24 +00:00
);
2024-04-18 21:56:31 +07:00
if (!duplicatedTemplateRecipient) {
throw new Error('Recipient not found.');
}
2023-10-06 22:54:24 +00:00
return {
type: field.type,
page: field.page,
positionX: field.positionX,
positionY: field.positionY,
width: field.width,
height: field.height,
customText: field.customText,
inserted: field.inserted,
templateId: duplicatedTemplate.id,
2024-04-18 21:56:31 +07:00
recipientId: duplicatedTemplateRecipient.id,
2023-10-06 22:54:24 +00:00
};
}),
});
return duplicatedTemplate;
};