mirror of
https://github.com/documenso/documenso.git
synced 2026-07-05 18:44:54 +10:00
141 lines
2.8 KiB
TypeScript
141 lines
2.8 KiB
TypeScript
import { prisma } from '@documenso/prisma';
|
|
import { EnvelopeType, type Prisma } from '@prisma/client';
|
|
import { z } from 'zod';
|
|
|
|
import type { FindResultResponse } from '../../types/search-params';
|
|
|
|
export interface AdminFindDocumentsOptions {
|
|
query?: string;
|
|
page?: number;
|
|
perPage?: number;
|
|
}
|
|
|
|
const ZPositiveIntegerSchema = z.coerce.number().int().positive();
|
|
|
|
const emptyResponse = {
|
|
data: [],
|
|
count: 0,
|
|
currentPage: 1,
|
|
perPage: 10,
|
|
totalPages: 0,
|
|
};
|
|
|
|
export const adminFindDocuments = async ({ query, page = 1, perPage = 10 }: AdminFindDocumentsOptions) => {
|
|
let termFilters: Prisma.EnvelopeWhereInput | undefined = !query
|
|
? undefined
|
|
: {
|
|
title: {
|
|
contains: query,
|
|
mode: 'insensitive',
|
|
},
|
|
};
|
|
|
|
if (query?.startsWith('user:')) {
|
|
const parsedUserId = ZPositiveIntegerSchema.safeParse(query.slice('user:'.length));
|
|
|
|
if (parsedUserId.success) {
|
|
termFilters = {
|
|
userId: {
|
|
equals: parsedUserId.data,
|
|
},
|
|
};
|
|
} else {
|
|
return emptyResponse;
|
|
}
|
|
}
|
|
|
|
if (query?.startsWith('team:')) {
|
|
const parsedTeamId = ZPositiveIntegerSchema.safeParse(query.slice('team:'.length));
|
|
|
|
if (parsedTeamId.success) {
|
|
termFilters = {
|
|
teamId: {
|
|
equals: parsedTeamId.data,
|
|
},
|
|
};
|
|
} else {
|
|
return emptyResponse;
|
|
}
|
|
}
|
|
|
|
if (query && query?.startsWith('envelope_')) {
|
|
termFilters = {
|
|
id: {
|
|
equals: query,
|
|
},
|
|
};
|
|
}
|
|
|
|
if (query && query?.startsWith('document_')) {
|
|
termFilters = {
|
|
secondaryId: {
|
|
equals: query,
|
|
},
|
|
};
|
|
}
|
|
|
|
if (query) {
|
|
const isQueryAnInteger = !isNaN(parseInt(query));
|
|
|
|
if (isQueryAnInteger) {
|
|
termFilters = {
|
|
secondaryId: {
|
|
equals: `document_${query}`,
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
const [data, count] = await Promise.all([
|
|
prisma.envelope.findMany({
|
|
where: {
|
|
type: EnvelopeType.DOCUMENT,
|
|
...termFilters,
|
|
},
|
|
skip: Math.max(page - 1, 0) * perPage,
|
|
take: perPage,
|
|
orderBy: {
|
|
createdAt: 'desc',
|
|
},
|
|
include: {
|
|
user: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
email: true,
|
|
},
|
|
},
|
|
recipients: true,
|
|
team: {
|
|
select: {
|
|
id: true,
|
|
url: true,
|
|
},
|
|
},
|
|
envelopeItems: {
|
|
select: {
|
|
id: true,
|
|
envelopeId: true,
|
|
title: true,
|
|
order: true,
|
|
},
|
|
},
|
|
},
|
|
}),
|
|
prisma.envelope.count({
|
|
where: {
|
|
type: EnvelopeType.DOCUMENT,
|
|
...termFilters,
|
|
},
|
|
}),
|
|
]);
|
|
|
|
return {
|
|
data,
|
|
count,
|
|
currentPage: Math.max(page, 1),
|
|
perPage,
|
|
totalPages: Math.ceil(count / perPage),
|
|
} satisfies FindResultResponse<typeof data>;
|
|
};
|