Files
sign/packages/trpc/server/document-router/router.ts

502 lines
15 KiB
TypeScript
Raw Normal View History

import { TRPCError } from '@trpc/server';
import { DateTime } from 'luxon';
2024-12-10 16:11:20 +09:00
import { z } from 'zod';
2023-10-15 20:26:32 +11:00
import { getServerLimits } from '@documenso/ee/server-only/limits/server';
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
import { DOCUMENSO_ENCRYPTION_KEY } from '@documenso/lib/constants/crypto';
2024-04-24 19:51:18 +07:00
import { AppError } from '@documenso/lib/errors/app-error';
import { encryptSecondaryData } from '@documenso/lib/server-only/crypto/encrypt';
2023-12-02 09:38:24 +11:00
import { upsertDocumentMeta } from '@documenso/lib/server-only/document-meta/upsert-document-meta';
import { createDocument } from '@documenso/lib/server-only/document/create-document';
import { deleteDocument } from '@documenso/lib/server-only/document/delete-document';
2023-11-08 09:25:44 +00:00
import { duplicateDocumentById } from '@documenso/lib/server-only/document/duplicate-document-by-id';
2024-02-15 18:20:10 +11:00
import { findDocumentAuditLogs } from '@documenso/lib/server-only/document/find-document-audit-logs';
import { findDocuments } from '@documenso/lib/server-only/document/find-documents';
import { getDocumentById } from '@documenso/lib/server-only/document/get-document-by-id';
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
import { getDocumentWithDetailsById } from '@documenso/lib/server-only/document/get-document-with-details-by-id';
import { moveDocumentToTeam } from '@documenso/lib/server-only/document/move-document-to-team';
2023-11-16 07:35:45 +05:30
import { resendDocument } from '@documenso/lib/server-only/document/resend-document';
import { searchDocumentsWithKeyword } from '@documenso/lib/server-only/document/search-documents-with-keyword';
import { sendDocument } from '@documenso/lib/server-only/document/send-document';
2024-03-28 13:13:29 +08:00
import { updateDocumentSettings } from '@documenso/lib/server-only/document/update-document-settings';
import { updateTitle } from '@documenso/lib/server-only/document/update-title';
import { symmetricEncrypt } from '@documenso/lib/universal/crypto';
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
2024-04-24 19:51:18 +07:00
import { DocumentStatus } from '@documenso/prisma/client';
import { authenticatedProcedure, procedure, router } from '../trpc';
import {
ZCreateDocumentMutationSchema,
2024-12-10 16:11:20 +09:00
ZDeleteDocumentMutationSchema,
ZDownloadAuditLogsMutationSchema,
ZDownloadCertificateMutationSchema,
2024-02-15 18:20:10 +11:00
ZFindDocumentAuditLogsQuerySchema,
ZFindDocumentsQuerySchema,
ZGetDocumentByIdQuerySchema,
ZGetDocumentByTokenQuerySchema,
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
ZGetDocumentWithDetailsByIdQuerySchema,
ZMoveDocumentsToTeamSchema,
2023-11-16 07:35:45 +05:30
ZResendDocumentMutationSchema,
ZSearchDocumentsMutationSchema,
ZSendDocumentMutationSchema,
ZSetPasswordForDocumentMutationSchema,
2024-03-28 13:13:29 +08:00
ZSetSettingsForDocumentMutationSchema,
ZSetSigningOrderForDocumentMutationSchema,
ZSetTitleForDocumentMutationSchema,
ZUpdateTypedSignatureSettingsMutationSchema,
} from './schema';
export const documentRouter = router({
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
getDocumentById: authenticatedProcedure
.input(ZGetDocumentByIdQuerySchema)
.query(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
return await getDocumentById({
...input,
userId: ctx.user.id,
});
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
2024-03-28 13:13:29 +08:00
getDocumentByToken: procedure
.input(ZGetDocumentByTokenQuerySchema)
.query(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { token } = input;
2024-12-06 16:01:24 +09:00
return await getDocumentAndSenderByToken({
token,
userId: ctx.user?.id,
});
2024-03-28 13:13:29 +08:00
}),
2024-12-10 16:11:20 +09:00
findDocuments: authenticatedProcedure
.meta({
openapi: {
method: 'GET',
path: '/document/find',
summary: 'Find documents',
description: 'Find documents based on a search criteria',
tags: ['Documents'],
},
})
.input(ZFindDocumentsQuerySchema)
.output(z.unknown())
.query(async ({ input, ctx }) => {
const { user } = ctx;
const { search, teamId, templateId, page, perPage, orderBy, source, status } = input;
const documents = await findDocuments({
userId: user.id,
teamId,
templateId,
search,
source,
status,
page,
perPage,
orderBy,
});
return documents;
}),
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
getDocumentWithDetailsById: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'GET',
path: '/document/{documentId}',
summary: 'Get document',
description: 'Returns a document given an ID',
tags: ['Documents'],
},
})
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
.input(ZGetDocumentWithDetailsByIdQuerySchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
.query(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
return await getDocumentWithDetailsById({
...input,
userId: ctx.user.id,
});
fix: update document flow fetch logic (#1039) ## Description **Fixes issues with mismatching state between document steps.** For example, editing a recipient and proceeding to the next step may not display the updated recipient. And going back will display the old recipient instead of the updated values. **This PR also improves mutation and query speeds by adding logic to bypass query invalidation.** ```ts export const trpc = createTRPCReact<AppRouter>({ unstable_overrides: { useMutation: { async onSuccess(opts) { await opts.originalFn(); // This forces mutations to wait for all the queries on the page to reload, and in // this case one of the queries is `searchDocument` for the command overlay, which // on average takes ~500ms. This means that every single mutation must wait for this. await opts.queryClient.invalidateQueries(); }, }, }, }); ``` I've added workarounds to allow us to bypass things such as batching and invalidating queries. But I think we should instead remove this and update all the mutations where a query is required for a more optimised system. ## Example benchmarks Using stg-app vs this preview there's an average 50% speed increase across mutations. **Set signer step:** Average old speed: ~1100ms Average new speed: ~550ms **Set recipient step:** Average old speed: ~1200ms Average new speed: ~600ms **Set fields step:** Average old speed: ~1200ms Average new speed: ~600ms ## Related Issue This will resolve #470 ## Changes Made - Added ability to skip batch queries - Added a state to store the required document data. - Refetch the data between steps if/when required - Optimise mutations and queries ## Checklist - [X] I have tested these changes locally and they work as expected. - [X] I have followed the project's coding style guidelines. --------- Co-authored-by: Lucas Smith <me@lucasjamessmith.me>
2024-03-26 21:12:41 +08:00
}),
createDocument: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'POST',
path: '/document/create',
summary: 'Create document',
tags: ['Documents'],
},
})
.input(ZCreateDocumentMutationSchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { title, documentDataId, teamId } = input;
2024-12-06 16:01:24 +09:00
const { remaining } = await getServerLimits({ email: ctx.user.email, teamId });
2024-12-06 16:01:24 +09:00
if (remaining.documents <= 0) {
throw new TRPCError({
code: 'BAD_REQUEST',
2024-12-06 16:01:24 +09:00
message: 'You have reached your document limit for this month. Please upgrade your plan.',
});
}
2024-12-06 16:01:24 +09:00
return await createDocument({
userId: ctx.user.id,
teamId,
title,
documentDataId,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
2024-12-10 16:11:20 +09:00
// Todo: Refactor to updateDocument.
2024-03-28 13:13:29 +08:00
setSettingsForDocument: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}',
summary: 'Update document',
tags: ['Documents'],
},
})
2024-03-28 13:13:29 +08:00
.input(ZSetSettingsForDocumentMutationSchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
2024-03-28 13:13:29 +08:00
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, teamId, data, meta } = input;
const userId = ctx.user.id;
const requestMetadata = extractNextApiRequestMetadata(ctx.req);
if (meta.timezone || meta.dateFormat || meta.redirectUrl) {
await upsertDocumentMeta({
2024-03-28 13:13:29 +08:00
documentId,
2024-12-06 16:01:24 +09:00
dateFormat: meta.dateFormat,
timezone: meta.timezone,
redirectUrl: meta.redirectUrl,
language: meta.language,
userId: ctx.user.id,
2024-03-28 13:13:29 +08:00
requestMetadata,
});
}
2024-12-06 16:01:24 +09:00
return await updateDocumentSettings({
userId,
teamId,
documentId,
data,
requestMetadata,
});
2024-03-28 13:13:29 +08:00
}),
2024-12-10 16:11:20 +09:00
deleteDocument: authenticatedProcedure
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}/delete',
summary: 'Delete document',
tags: ['Documents'],
},
})
.input(ZDeleteDocumentMutationSchema)
.output(z.unknown())
.mutation(async ({ input, ctx }) => {
const { documentId, teamId } = input;
const userId = ctx.user.id;
return await deleteDocument({
id: documentId,
userId,
teamId,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
moveDocumentToTeam: authenticatedProcedure
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}/move',
summary: 'Move document',
description: 'Move a document to a team',
tags: ['Documents'],
},
})
.input(ZMoveDocumentsToTeamSchema)
.output(z.unknown())
.mutation(async ({ input, ctx }) => {
const { documentId, teamId } = input;
const userId = ctx.user.id;
return await moveDocumentToTeam({
documentId,
teamId,
userId,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
// Internal endpoint for now.
// Should probably use `updateDocument`
setTitleForDocument: authenticatedProcedure
.input(ZSetTitleForDocumentMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-02-26 11:59:32 +11:00
const { documentId, teamId, title } = input;
2023-12-02 09:38:24 +11:00
const userId = ctx.user.id;
2024-12-06 16:01:24 +09:00
return await updateTitle({
title,
userId,
teamId,
documentId,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
2024-01-17 17:17:08 +11:00
setPasswordForDocument: authenticatedProcedure
.input(ZSetPasswordForDocumentMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, password } = input;
2024-12-06 16:01:24 +09:00
const key = DOCUMENSO_ENCRYPTION_KEY;
2024-12-06 16:01:24 +09:00
if (!key) {
throw new Error('Missing encryption key');
2024-01-17 17:17:08 +11:00
}
2024-12-06 16:01:24 +09:00
const securePassword = symmetricEncrypt({
data: password,
key,
});
await upsertDocumentMeta({
documentId,
password: securePassword,
userId: ctx.user.id,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
2024-01-17 17:17:08 +11:00
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
setSigningOrderForDocument: authenticatedProcedure
.input(ZSetSigningOrderForDocumentMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, signingOrder } = input;
return await upsertDocumentMeta({
documentId,
signingOrder,
userId: ctx.user.id,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
updateTypedSignatureSettings: authenticatedProcedure
.input(ZUpdateTypedSignatureSettingsMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, teamId, typedSignatureEnabled } = input;
2024-12-06 16:01:24 +09:00
const document = await getDocumentById({
2024-12-10 16:11:20 +09:00
documentId,
2024-12-06 16:01:24 +09:00
teamId,
userId: ctx.user.id,
}).catch(() => null);
2024-12-06 16:01:24 +09:00
if (!document) {
throw new TRPCError({
2024-12-06 16:01:24 +09:00
code: 'NOT_FOUND',
message: 'Document not found',
});
}
2024-12-06 16:01:24 +09:00
return await upsertDocumentMeta({
documentId,
typedSignatureEnabled,
userId: ctx.user.id,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
2024-12-10 16:11:20 +09:00
// Todo: Refactor to distributeDocument.
// Todo: Rework before releasing API.
sendDocument: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}/distribute',
summary: 'Distribute document',
description: 'Send the document out to recipients based on your distribution method',
tags: ['Documents'],
},
})
.input(ZSendDocumentMutationSchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, teamId, meta } = input;
if (
meta.message ||
meta.subject ||
meta.timezone ||
meta.dateFormat ||
meta.redirectUrl ||
meta.distributionMethod ||
meta.emailSettings
) {
await upsertDocumentMeta({
documentId,
2024-12-06 16:01:24 +09:00
subject: meta.subject,
message: meta.message,
dateFormat: meta.dateFormat,
timezone: meta.timezone,
redirectUrl: meta.redirectUrl,
distributionMethod: meta.distributionMethod,
userId: ctx.user.id,
emailSettings: meta.emailSettings,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}
2024-12-06 16:01:24 +09:00
return await sendDocument({
userId: ctx.user.id,
documentId,
teamId,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
}),
2023-11-08 09:25:44 +00:00
2023-11-16 07:35:45 +05:30
resendDocument: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}/resend',
summary: 'Resend document',
description:
'Resend the document to recipients who have not signed. Will use the distribution method set in the document.',
tags: ['Documents'],
},
})
2023-11-16 07:35:45 +05:30
.input(ZResendDocumentMutationSchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
2023-11-16 07:35:45 +05:30
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
return await resendDocument({
userId: ctx.user.id,
...input,
requestMetadata: extractNextApiRequestMetadata(ctx.req),
});
2023-11-16 07:35:45 +05:30
}),
2023-11-08 09:25:44 +00:00
duplicateDocument: authenticatedProcedure
2024-12-10 16:11:20 +09:00
.meta({
openapi: {
method: 'POST',
path: '/document/{documentId}/duplicate',
summary: 'Duplicate document',
tags: ['Documents'],
},
})
2023-11-08 09:25:44 +00:00
.input(ZGetDocumentByIdQuerySchema)
2024-12-10 16:11:20 +09:00
.output(z.unknown())
2023-11-08 09:25:44 +00:00
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
return await duplicateDocumentById({
userId: ctx.user.id,
...input,
});
2023-11-08 09:25:44 +00:00
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
searchDocuments: authenticatedProcedure
.input(ZSearchDocumentsMutationSchema)
.query(async ({ input, ctx }) => {
const { query } = input;
2024-12-06 16:01:24 +09:00
const documents = await searchDocumentsWithKeyword({
query,
userId: ctx.user.id,
});
2024-03-30 14:00:34 +08:00
2024-12-06 16:01:24 +09:00
return documents;
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
findDocumentAuditLogs: authenticatedProcedure
.input(ZFindDocumentAuditLogsQuerySchema)
.query(async ({ input, ctx }) => {
const { page, perPage, documentId, cursor, filterForRecentActivity, orderBy } = input;
return await findDocumentAuditLogs({
page,
perPage,
documentId,
cursor,
filterForRecentActivity,
orderBy,
userId: ctx.user.id,
});
}),
// Internal endpoint for now.
downloadAuditLogs: authenticatedProcedure
.input(ZDownloadAuditLogsMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, teamId } = input;
2024-12-06 16:01:24 +09:00
const document = await getDocumentById({
2024-12-10 16:11:20 +09:00
documentId,
2024-12-06 16:01:24 +09:00
userId: ctx.user.id,
teamId,
}).catch(() => null);
2024-12-06 16:01:24 +09:00
if (!document || (teamId && document.teamId !== teamId)) {
throw new TRPCError({
2024-12-06 16:01:24 +09:00
code: 'FORBIDDEN',
message: 'You do not have access to this document.',
});
}
2024-12-06 16:01:24 +09:00
const encrypted = encryptSecondaryData({
data: document.id.toString(),
expiresAt: DateTime.now().plus({ minutes: 5 }).toJSDate().valueOf(),
});
return {
url: `${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/audit-log?d=${encrypted}`,
};
}),
2024-12-10 16:11:20 +09:00
// Internal endpoint for now.
downloadCertificate: authenticatedProcedure
.input(ZDownloadCertificateMutationSchema)
.mutation(async ({ input, ctx }) => {
2024-12-06 16:01:24 +09:00
const { documentId, teamId } = input;
2024-12-06 16:01:24 +09:00
const document = await getDocumentById({
2024-12-10 16:11:20 +09:00
documentId,
2024-12-06 16:01:24 +09:00
userId: ctx.user.id,
teamId,
});
2024-04-24 19:51:18 +07:00
2024-12-06 16:01:24 +09:00
if (document.status !== DocumentStatus.COMPLETED) {
throw new AppError('DOCUMENT_NOT_COMPLETE');
}
2024-12-06 16:01:24 +09:00
const encrypted = encryptSecondaryData({
data: document.id.toString(),
expiresAt: DateTime.now().plus({ minutes: 5 }).toJSDate().valueOf(),
});
2024-12-06 16:01:24 +09:00
return {
url: `${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/certificate?d=${encrypted}`,
};
}),
});