Files
sign/packages/lib/server-only/template/find-templates.ts

118 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-12-14 01:23:35 +09:00
import type { z } from 'zod';
2024-02-08 12:33:20 +11:00
import { prisma } from '@documenso/prisma';
2024-06-06 14:46:48 +10:00
import type { Prisma, Template } from '@documenso/prisma/client';
2024-12-14 01:23:35 +09:00
import {
DocumentDataSchema,
FieldSchema,
RecipientSchema,
TeamSchema,
TemplateDirectLinkSchema,
TemplateMetaSchema,
TemplateSchema,
} from '@documenso/prisma/generated/zod';
2024-02-08 12:33:20 +11:00
2024-12-14 01:23:35 +09:00
import { type FindResultResponse, ZFindResultResponse } from '../../types/search-params';
2024-02-08 12:33:20 +11:00
export type FindTemplatesOptions = {
userId: number;
teamId?: number;
2024-06-06 14:46:48 +10:00
type?: Template['type'];
page?: number;
perPage?: number;
2024-02-08 12:33:20 +11:00
};
2024-12-14 01:23:35 +09:00
export const ZFindTemplatesResponseSchema = ZFindResultResponse.extend({
data: TemplateSchema.extend({
templateDocumentData: DocumentDataSchema,
team: TeamSchema.pick({
id: true,
url: true,
}).nullable(),
Field: FieldSchema.array(),
Recipient: RecipientSchema.array(),
templateMeta: TemplateMetaSchema.pick({
signingOrder: true,
distributionMethod: true,
}).nullable(),
directLink: TemplateDirectLinkSchema.pick({
token: true,
enabled: true,
}).nullable(),
}).array(), // Todo: openapi.
});
export type TFindTemplatesResponse = z.infer<typeof ZFindTemplatesResponseSchema>;
export type FindTemplateRow = TFindTemplatesResponse['data'][number];
2024-02-08 12:33:20 +11:00
export const findTemplates = async ({
userId,
teamId,
2024-06-06 14:46:48 +10:00
type,
2024-02-08 12:33:20 +11:00
page = 1,
perPage = 10,
2024-12-14 01:23:35 +09:00
}: FindTemplatesOptions): Promise<TFindTemplatesResponse> => {
2024-02-08 12:33:20 +11:00
let whereFilter: Prisma.TemplateWhereInput = {
userId,
teamId: null,
2024-06-06 14:46:48 +10:00
type,
2024-02-08 12:33:20 +11:00
};
if (teamId !== undefined) {
whereFilter = {
team: {
id: teamId,
members: {
some: {
userId,
},
},
},
};
}
const [data, count] = await Promise.all([
2024-02-08 12:33:20 +11:00
prisma.template.findMany({
where: whereFilter,
include: {
templateDocumentData: true,
team: {
select: {
id: true,
url: true,
},
},
2024-02-08 12:33:20 +11:00
Field: true,
Recipient: true,
templateMeta: {
select: {
signingOrder: true,
distributionMethod: true,
},
},
directLink: {
select: {
token: true,
enabled: true,
},
},
2024-02-08 12:33:20 +11:00
},
skip: Math.max(page - 1, 0) * perPage,
orderBy: {
createdAt: 'desc',
},
}),
prisma.template.count({
where: whereFilter,
}),
]);
return {
data,
count,
currentPage: Math.max(page, 1),
perPage,
2024-02-08 12:33:20 +11:00
totalPages: Math.ceil(count / perPage),
} satisfies FindResultResponse<typeof data>;
2024-02-08 12:33:20 +11:00
};