Skip to content

The Open Source DocuSign Alternative.

feat: include audit trail log in the completed doc (#1916)

Catalin Pitd1eb14ac16f6
diff --git a/apps/remix/app/components/forms/document-preferences-form.tsx b/apps/remix/app/components/forms/document-preferences-form.tsx
index eb91a4b84..eb3c64e06 100644
--- a/apps/remix/app/components/forms/document-preferences-form.tsx
+++ b/apps/remix/app/components/forms/document-preferences-form.tsx
@@ -55,6 +55,7 @@ export type TDocumentPreferencesFormSchema = {
documentDateFormat: TDocumentMetaDateFormat | null;
includeSenderDetails: boolean | null;
includeSigningCertificate: boolean | null;
+ includeAuditLog: boolean | null;
signatureTypes: DocumentSignatureType[];
};
@@ -66,6 +67,7 @@ type SettingsSubset = Pick<
| 'documentDateFormat'
| 'includeSenderDetails'
| 'includeSigningCertificate'
+ | 'includeAuditLog'
| 'typedSignatureEnabled'
| 'uploadSignatureEnabled'
| 'drawSignatureEnabled'
@@ -96,6 +98,7 @@ export const DocumentPreferencesForm = ({
documentDateFormat: ZDocumentMetaTimezoneSchema.nullable(),
includeSenderDetails: z.boolean().nullable(),
includeSigningCertificate: z.boolean().nullable(),
+ includeAuditLog: z.boolean().nullable(),
signatureTypes: z.array(z.nativeEnum(DocumentSignatureType)).min(canInherit ? 0 : 1, {
message: msg`At least one signature type must be enabled`.id,
}),
@@ -112,6 +115,7 @@ export const DocumentPreferencesForm = ({
documentDateFormat: settings.documentDateFormat as TDocumentMetaDateFormat | null,
includeSenderDetails: settings.includeSenderDetails,
includeSigningCertificate: settings.includeSigningCertificate,
+ includeAuditLog: settings.includeAuditLog,
signatureTypes: extractTeamSignatureSettings({ ...settings }),
},
resolver: zodResolver(ZDocumentPreferencesFormSchema),
@@ -452,6 +456,56 @@ export const DocumentPreferencesForm = ({
)}
/>
+ <FormField
+ control={form.control}
+ name="includeAuditLog"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>
+ <Trans>Include the Audit Logs in the Document</Trans>
+ </FormLabel>
+
+ <FormControl>
+ <Select
+ {...field}
+ value={field.value === null ? '-1' : field.value.toString()}
+ onValueChange={(value) =>
+ field.onChange(value === 'true' ? true : value === 'false' ? false : null)
+ }
+ >
+ <SelectTrigger className="bg-background text-muted-foreground">
+ <SelectValue />
+ </SelectTrigger>
+
+ <SelectContent>
+ <SelectItem value="true">
+ <Trans>Yes</Trans>
+ </SelectItem>
+
+ <SelectItem value="false">
+ <Trans>No</Trans>
+ </SelectItem>
+
+ {canInherit && (
+ <SelectItem value={'-1'}>
+ <Trans>Inherit from organisation</Trans>
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ </FormControl>
+
+ <FormDescription>
+ <Trans>
+ Controls whether the audit logs will be included in the document when it is
+ downloaded. The audit logs can still be downloaded from the logs page
+ separately.
+ </Trans>
+ </FormDescription>
+ </FormItem>
+ )}
+ />
+
<div className="flex flex-row justify-end space-x-4">
<Button type="submit" loading={form.formState.isSubmitting}>
<Trans>Update</Trans>
diff --git a/apps/remix/app/components/general/document/document-page-view-dropdown.tsx b/apps/remix/app/components/general/document/document-page-view-dropdown.tsx
index a57a849dd..c4043de3a 100644
--- a/apps/remix/app/components/general/document/document-page-view-dropdown.tsx
+++ b/apps/remix/app/components/general/document/document-page-view-dropdown.tsx
@@ -164,7 +164,7 @@ export const DocumentPageViewDropdown = ({ document }: DocumentPageViewDropdownP
<DropdownMenuItem asChild>
<Link to={`${documentsPath}/${document.id}/logs`}>
<ScrollTextIcon className="mr-2 h-4 w-4" />
- <Trans>Audit Log</Trans>
+ <Trans>Audit Logs</Trans>
</Link>
</DropdownMenuItem>
diff --git a/apps/remix/app/components/tables/internal-audit-log-table.tsx b/apps/remix/app/components/tables/internal-audit-log-table.tsx
index addbb4174..b3b68147a 100644
--- a/apps/remix/app/components/tables/internal-audit-log-table.tsx
+++ b/apps/remix/app/components/tables/internal-audit-log-table.tsx
@@ -1,20 +1,18 @@
import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react';
-import { DateTime } from 'luxon';
import type { DateTimeFormatOptions } from 'luxon';
+import { DateTime } from 'luxon';
+import { P, match } from 'ts-pattern';
import { UAParser } from 'ua-parser-js';
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
-import type { TDocumentAuditLog } from '@documenso/lib/types/document-audit-logs';
-import { formatDocumentAuditLogAction } from '@documenso/lib/utils/document-audit-logs';
import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from '@documenso/ui/primitives/table';
+ DOCUMENT_AUDIT_LOG_TYPE,
+ type TDocumentAuditLog,
+} from '@documenso/lib/types/document-audit-logs';
+import { formatDocumentAuditLogAction } from '@documenso/lib/utils/document-audit-logs';
+import { cn } from '@documenso/ui/lib/utils';
+import { Card, CardContent } from '@documenso/ui/primitives/card';
export type AuditLogDataTableProps = {
logs: TDocumentAuditLog[];
@@ -25,71 +23,129 @@ const dateFormat: DateTimeFormatOptions = {
hourCycle: 'h12',
};
+/**
+ * Get the color indicator for the audit log type
+ */
+
+const getAuditLogIndicatorColor = (type: string) =>
+ match(type)
+ .with(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_COMPLETED, () => 'bg-green-500')
+ .with(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_REJECTED, () => 'bg-red-500')
+ .with(DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_SENT, () => 'bg-orange-500')
+ .with(
+ P.union(
+ DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FIELD_INSERTED,
+ DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FIELD_UNINSERTED,
+ ),
+ () => 'bg-blue-500',
+ )
+ .otherwise(() => 'bg-muted');
+
/**
* DO NOT USE TRANS. YOU MUST USE _ FOR THIS FILE AND ALL CHILDREN COMPONENTS.
*/
+
+const formatUserAgent = (userAgent: string | null | undefined, userAgentInfo: UAParser.IResult) => {
+ if (!userAgent) {
+ return msg`N/A`;
+ }
+
+ const browser = userAgentInfo.browser.name;
+ const version = userAgentInfo.browser.version;
+ const os = userAgentInfo.os.name;
+
+ // If we can parse meaningful browser info, format it nicely
+ if (browser && os) {
+ const browserInfo = version ? `${browser} ${version}` : browser;
+
+ return msg`${browserInfo} on ${os}`;
+ }
+
+ return msg`${userAgent}`;
+};
+
export const InternalAuditLogTable = ({ logs }: AuditLogDataTableProps) => {
const { _ } = useLingui();
const parser = new UAParser();
- const uppercaseFistLetter = (text: string) => {
- return text.charAt(0).toUpperCase() + text.slice(1);
- };
-
return (
- <Table overflowHidden>
- <TableHeader>
- <TableRow>
- <TableHead>{_(msg`Time`)}</TableHead>
- <TableHead>{_(msg`User`)}</TableHead>
- <TableHead>{_(msg`Action`)}</TableHead>
- <TableHead>{_(msg`IP Address`)}</TableHead>
- <TableHead>{_(msg`Browser`)}</TableHead>
- </TableRow>
- </TableHeader>
-
- <TableBody className="print:text-xs">
- {logs.map((log, i) => (
- <TableRow className="break-inside-avoid" key={i}>
- <TableCell>
- {DateTime.fromJSDate(log.createdAt)
- .setLocale(APP_I18N_OPTIONS.defaultLocale)
- .toLocaleString(dateFormat)}
- </TableCell>
-
- <TableCell>
- {log.name || log.email ? (
+ <div className="space-y-4">
+ {logs.map((log, index) => {
+ parser.setUA(log.userAgent || '');
+ const formattedAction = formatDocumentAuditLogAction(_, log);
+ const userAgentInfo = parser.getResult();
+
+ return (
+ <Card
+ key={index}
+ // Add top margin for the first card to ensure it's not cut off from the 2nd page onwards
+ className={`border shadow-sm ${index > 0 ? 'print:mt-8' : ''}`}
+ style={{
+ pageBreakInside: 'avoid',
+ breakInside: 'avoid',
+ }}
+ >
+ <CardContent className="p-4">
+ {/* Header Section with indicator, event type, and timestamp */}
+ <div className="mb-3 flex items-start justify-between">
+ <div className="flex items-baseline gap-3">
+ <div
+ className={cn(`h-2 w-2 rounded-full`, getAuditLogIndicatorColor(log.type))}
+ />
+
+ <div>
+ <div className="text-muted-foreground text-sm font-medium uppercase tracking-wide print:text-[8pt]">
+ {log.type.replace(/_/g, ' ')}
+ </div>
+
+ <div className="text-foreground text-sm font-medium print:text-[8pt]">
+ {formattedAction.description}
+ </div>
+ </div>
+ </div>
+
+ <div className="text-muted-foreground text-sm print:text-[8pt]">
+ {DateTime.fromJSDate(log.createdAt)
+ .setLocale(APP_I18N_OPTIONS.defaultLocale)
+ .toLocaleString(dateFormat)}
+ </div>
+ </div>
+
+ <hr className="my-4" />
+
+ {/* Details Section - Two column layout */}
+ <div className="grid grid-cols-2 gap-x-8 gap-y-2 text-xs print:text-[6pt]">
<div>
- {log.name && (
- <p className="break-all" title={log.name}>
- {log.name}
- </p>
- )}
-
- {log.email && (
- <p className="text-muted-foreground break-all" title={log.email}>
- {log.email}
- </p>
- )}
+ <div className="text-muted-foreground/70 font-medium uppercase tracking-wide">
+ {_(msg`User`)}
+ </div>
+
+ <div className="text-foreground mt-1 font-mono">{log.email || 'N/A'}</div>
+ </div>
+
+ <div className="text-right">
+ <div className="text-muted-foreground/70 font-medium uppercase tracking-wide">
+ {_(msg`IP Address`)}
+ </div>
+
+ <div className="text-foreground mt-1 font-mono">{log.ipAddress || 'N/A'}</div>
+ </div>
+
+ <div className="col-span-2">
+ <div className="text-muted-foreground/70 font-medium uppercase tracking-wide">
+ {_(msg`User Agent`)}
+ </div>
+
+ <div className="text-foreground mt-1">
+ {_(formatUserAgent(log.userAgent, userAgentInfo))}
+ </div>
</div>
- ) : (
- <p>N/A</p>
- )}
- </TableCell>
-
- <TableCell>
- {uppercaseFistLetter(formatDocumentAuditLogAction(_, log).description)}
- </TableCell>
-
- <TableCell>{log.ipAddress}</TableCell>
-
- <TableCell>
- {log.userAgent ? parser.setUA(log.userAgent).getBrowser().name : 'N/A'}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ })}
+ </div>
);
};
diff --git a/apps/remix/app/routes/_authenticated+/o.$orgUrl.settings.document.tsx b/apps/remix/app/routes/_authenticated+/o.$orgUrl.settings.document.tsx
index 9c3cfb6ce..17969c628 100644
--- a/apps/remix/app/routes/_authenticated+/o.$orgUrl.settings.document.tsx
+++ b/apps/remix/app/routes/_authenticated+/o.$orgUrl.settings.document.tsx
@@ -46,6 +46,7 @@ export default function OrganisationSettingsDocumentPage() {
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
signatureTypes,
} = data;
@@ -54,7 +55,8 @@ export default function OrganisationSettingsDocumentPage() {
documentLanguage === null ||
documentDateFormat === null ||
includeSenderDetails === null ||
- includeSigningCertificate === null
+ includeSigningCertificate === null ||
+ includeAuditLog === null
) {
throw new Error('Should not be possible.');
}
@@ -68,6 +70,7 @@ export default function OrganisationSettingsDocumentPage() {
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
typedSignatureEnabled: signatureTypes.includes(DocumentSignatureType.TYPE),
uploadSignatureEnabled: signatureTypes.includes(DocumentSignatureType.UPLOAD),
drawSignatureEnabled: signatureTypes.includes(DocumentSignatureType.DRAW),
diff --git a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.logs.tsx b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.logs.tsx
index 754b008f3..5e89cc439 100644
--- a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.logs.tsx
+++ b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents.$id.logs.tsx
@@ -170,7 +170,7 @@ export default function DocumentsLogsPage({ loaderData }: Route.ComponentProps)
<ul className="text-muted-foreground list-inside list-disc">
{recipients.map((recipient) => (
<li key={`recipient-${recipient.id}`}>
- <span className="-ml-2">{formatRecipientText(recipient)}</span>
+ <span>{formatRecipientText(recipient)}</span>
</li>
))}
</ul>
diff --git a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/settings.document.tsx b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/settings.document.tsx
index 45c376077..c669f84f6 100644
--- a/apps/remix/app/routes/_authenticated+/t.$teamUrl+/settings.document.tsx
+++ b/apps/remix/app/routes/_authenticated+/t.$teamUrl+/settings.document.tsx
@@ -38,6 +38,7 @@ export default function TeamsSettingsPage() {
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
signatureTypes,
} = data;
@@ -50,6 +51,7 @@ export default function TeamsSettingsPage() {
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
...(signatureTypes.length === 0
? {
typedSignatureEnabled: null,
diff --git a/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.print.css b/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.print.css
new file mode 100644
index 000000000..7825a2791
--- /dev/null
+++ b/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.print.css
@@ -0,0 +1,5 @@
+@media print {
+ html {
+ font-size: 10pt;
+ }
+}
diff --git a/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.tsx b/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.tsx
index bb9d62c9a..d2f625bbc 100644
--- a/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.tsx
+++ b/apps/remix/app/routes/_internal+/[__htmltopdf]+/audit-log.tsx
@@ -12,10 +12,17 @@ import { findDocumentAuditLogs } from '@documenso/lib/server-only/document/find-
import { getTranslations } from '@documenso/lib/utils/i18n';
import { Card, CardContent } from '@documenso/ui/primitives/card';
+import appStylesheet from '~/app.css?url';
import { BrandingLogo } from '~/components/general/branding-logo';
import { InternalAuditLogTable } from '~/components/tables/internal-audit-log-table';
import type { Route } from './+types/audit-log';
+import auditLogStylesheet from './audit-log.print.css?url';
+
+export const links: Route.LinksFunction = () => [
+ { rel: 'stylesheet', href: appStylesheet },
+ { rel: 'stylesheet', href: auditLogStylesheet },
+];
export async function loader({ request }: Route.LoaderArgs) {
const d = new URL(request.url).searchParams.get('d');
@@ -76,8 +83,8 @@ export default function AuditLog({ loaderData }: Route.ComponentProps) {
return (
<div className="print-provider pointer-events-none mx-auto max-w-screen-md">
- <div className="flex items-center">
- <h1 className="my-8 text-2xl font-bold">{_(msg`Version History`)}</h1>
+ <div className="mb-6 border-b pb-4">
+ <h1 className="text-xl font-semibold">{_(msg`Audit Log`)}</h1>
</div>
<Card>
@@ -157,11 +164,9 @@ export default function AuditLog({ loaderData }: Route.ComponentProps) {
</CardContent>
</Card>
- <Card className="mt-8">
- <CardContent className="p-0">
- <InternalAuditLogTable logs={auditLogs} />
- </CardContent>
- </Card>
+ <div className="mt-8">
+ <InternalAuditLogTable logs={auditLogs} />
+ </div>
<div className="my-8 flex-row-reverse">
<div className="flex items-end justify-end gap-x-4">
diff --git a/packages/lib/jobs/definitions/internal/seal-document.handler.ts b/packages/lib/jobs/definitions/internal/seal-document.handler.ts
index edae27977..8ee0382ba 100644
--- a/packages/lib/jobs/definitions/internal/seal-document.handler.ts
+++ b/packages/lib/jobs/definitions/internal/seal-document.handler.ts
@@ -9,6 +9,7 @@ import { signPdf } from '@documenso/signing';
import { AppError, AppErrorCode } from '../../../errors/app-error';
import { sendCompletedEmail } from '../../../server-only/document/send-completed-email';
import PostHogServerClient from '../../../server-only/feature-flags/get-post-hog-server-client';
+import { getAuditLogsPdf } from '../../../server-only/htmltopdf/get-audit-logs-pdf';
import { getCertificatePdf } from '../../../server-only/htmltopdf/get-certificate-pdf';
import { addRejectionStampToPdf } from '../../../server-only/pdf/add-rejection-stamp-to-pdf';
import { flattenAnnotations } from '../../../server-only/pdf/flatten-annotations';
@@ -145,7 +146,24 @@ export const run = async ({
? await getCertificatePdf({
documentId,
language: document.documentMeta?.language,
- }).catch(() => null)
+ }).catch((e) => {
+ console.log('Failed to get certificate PDF');
+ console.error(e);
+
+ return null;
+ })
+ : null;
+
+ const auditLogData = settings.includeAuditLog
+ ? await getAuditLogsPdf({
+ documentId,
+ language: document.documentMeta?.language,
+ }).catch((e) => {
+ console.log('Failed to get audit logs PDF');
+ console.error(e);
+
+ return null;
+ })
: null;
const newDataId = await io.runTask('decorate-and-sign-pdf', async () => {
@@ -174,6 +192,16 @@ export const run = async ({
});
}
+ if (auditLogData) {
+ const auditLogDoc = await PDFDocument.load(auditLogData);
+
+ const auditLogPages = await pdfDoc.copyPages(auditLogDoc, auditLogDoc.getPageIndices());
+
+ auditLogPages.forEach((page) => {
+ pdfDoc.addPage(page);
+ });
+ }
+
for (const field of fields) {
if (field.inserted) {
document.useLegacyFieldInsertion
diff --git a/packages/lib/server-only/document/create-document-v2.ts b/packages/lib/server-only/document/create-document-v2.ts
index 419bc8935..a381fd238 100644
--- a/packages/lib/server-only/document/create-document-v2.ts
+++ b/packages/lib/server-only/document/create-document-v2.ts
@@ -212,7 +212,7 @@ export const createDocumentV2 = async ({
}),
);
- // Todo: Is it necessary to create a full audit log with all fields and recipients audit logs?
+ // Todo: Is it necessary to create a full audit logs with all fields and recipients audit logs?
await tx.documentAuditLog.create({
data: createDocumentAuditLogData({
diff --git a/packages/lib/server-only/document/seal-document.ts b/packages/lib/server-only/document/seal-document.ts
index ae7a851ee..6db44eb73 100644
--- a/packages/lib/server-only/document/seal-document.ts
+++ b/packages/lib/server-only/document/seal-document.ts
@@ -17,6 +17,7 @@ import type { RequestMetadata } from '../../universal/extract-request-metadata';
import { getFileServerSide } from '../../universal/upload/get-file.server';
import { putPdfFileServerSide } from '../../universal/upload/put-file.server';
import { fieldsContainUnsignedRequiredField } from '../../utils/advanced-fields-helpers';
+import { getAuditLogsPdf } from '../htmltopdf/get-audit-logs-pdf';
import { getCertificatePdf } from '../htmltopdf/get-certificate-pdf';
import { addRejectionStampToPdf } from '../pdf/add-rejection-stamp-to-pdf';
import { flattenAnnotations } from '../pdf/flatten-annotations';
@@ -125,6 +126,18 @@ export const sealDocument = async ({
})
: null;
+ const auditLogData = settings.includeAuditLog
+ ? await getAuditLogsPdf({
+ documentId,
+ language: document.documentMeta?.language,
+ }).catch((e) => {
+ console.log('Failed to get audit logs PDF');
+ console.error(e);
+
+ return null;
+ })
+ : null;
+
const doc = await PDFDocument.load(pdfData);
// Normalize and flatten layers that could cause issues with the signature
@@ -147,6 +160,16 @@ export const sealDocument = async ({
});
}
+ if (auditLogData) {
+ const auditLog = await PDFDocument.load(auditLogData);
+
+ const auditLogPages = await doc.copyPages(auditLog, auditLog.getPageIndices());
+
+ auditLogPages.forEach((page) => {
+ doc.addPage(page);
+ });
+ }
+
for (const field of fields) {
document.useLegacyFieldInsertion
? await legacy_insertFieldInPDF(doc, field)
diff --git a/packages/lib/server-only/htmltopdf/get-audit-logs-pdf.ts b/packages/lib/server-only/htmltopdf/get-audit-logs-pdf.ts
new file mode 100644
index 000000000..36465ff4c
--- /dev/null
+++ b/packages/lib/server-only/htmltopdf/get-audit-logs-pdf.ts
@@ -0,0 +1,83 @@
+import { DateTime } from 'luxon';
+import type { Browser } from 'playwright';
+
+import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';
+import { type SupportedLanguageCodes, isValidLanguageCode } from '../../constants/i18n';
+import { env } from '../../utils/env';
+import { encryptSecondaryData } from '../crypto/encrypt';
+
+export type GetAuditLogsPdfOptions = {
+ documentId: number;
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ language?: SupportedLanguageCodes | (string & {});
+};
+
+export const getAuditLogsPdf = async ({ documentId, language }: GetAuditLogsPdfOptions) => {
+ const { chromium } = await import('playwright');
+
+ const encryptedId = encryptSecondaryData({
+ data: documentId.toString(),
+ expiresAt: DateTime.now().plus({ minutes: 5 }).toJSDate().valueOf(),
+ });
+
+ let browser: Browser;
+
+ const browserlessUrl = env('NEXT_PRIVATE_BROWSERLESS_URL');
+
+ if (browserlessUrl) {
+ // !: Use CDP rather than the default `connect` method to avoid coupling to the playwright version.
+ // !: Previously we would have to keep the playwright version in sync with the browserless version to avoid errors.
+ browser = await chromium.connectOverCDP(browserlessUrl);
+ } else {
+ browser = await chromium.launch();
+ }
+
+ if (!browser) {
+ throw new Error(
+ 'Failed to establish a browser, please ensure you have either a Browserless.io url or chromium browser installed',
+ );
+ }
+
+ const browserContext = await browser.newContext();
+
+ const page = await browserContext.newPage();
+
+ const lang = isValidLanguageCode(language) ? language : 'en';
+
+ await page.context().addCookies([
+ {
+ name: 'language',
+ value: lang,
+ url: NEXT_PUBLIC_WEBAPP_URL(),
+ },
+ ]);
+
+ await page.goto(`${NEXT_PUBLIC_WEBAPP_URL()}/__htmltopdf/audit-log?d=${encryptedId}`, {
+ waitUntil: 'networkidle',
+ timeout: 10_000,
+ });
+
+ // !: This is a workaround to ensure the page is loaded correctly.
+ // !: It's not clear why but suddenly browserless cdp connections would
+ // !: cause the page to render blank until a reload is performed.
+ await page.reload({
+ waitUntil: 'networkidle',
+ timeout: 10_000,
+ });
+
+ await page.waitForSelector('h1', {
+ state: 'visible',
+ timeout: 10_000,
+ });
+
+ const result = await page.pdf({
+ format: 'A4',
+ printBackground: true,
+ });
+
+ await browserContext.close();
+
+ void browser.close();
+
+ return result;
+};
diff --git a/packages/lib/server-only/htmltopdf/get-certificate-pdf.ts b/packages/lib/server-only/htmltopdf/get-certificate-pdf.ts
index 09bf07232..19444e041 100644
--- a/packages/lib/server-only/htmltopdf/get-certificate-pdf.ts
+++ b/packages/lib/server-only/htmltopdf/get-certificate-pdf.ts
@@ -72,6 +72,7 @@ export const getCertificatePdf = async ({ documentId, language }: GetCertificate
const result = await page.pdf({
format: 'A4',
+ printBackground: true,
});
await browserContext.close();
diff --git a/packages/lib/utils/organisations.ts b/packages/lib/utils/organisations.ts
index f8a41c5f8..01bcc490d 100644
--- a/packages/lib/utils/organisations.ts
+++ b/packages/lib/utils/organisations.ts
@@ -120,6 +120,7 @@ export const generateDefaultOrganisationSettings = (): Omit<
includeSenderDetails: true,
includeSigningCertificate: true,
+ includeAuditLog: false,
typedSignatureEnabled: true,
uploadSignatureEnabled: true,
diff --git a/packages/lib/utils/teams.ts b/packages/lib/utils/teams.ts
index ecc8006fe..3665baf33 100644
--- a/packages/lib/utils/teams.ts
+++ b/packages/lib/utils/teams.ts
@@ -170,6 +170,7 @@ export const generateDefaultTeamSettings = (): Omit<TeamGlobalSettings, 'id' | '
includeSenderDetails: null,
includeSigningCertificate: null,
+ includeAuditLog: null,
typedSignatureEnabled: null,
uploadSignatureEnabled: null,
diff --git a/packages/prisma/migrations/20250721085125_include_audit_trail_log/migration.sql b/packages/prisma/migrations/20250721085125_include_audit_trail_log/migration.sql
new file mode 100644
index 000000000..4f3665ad3
--- /dev/null
+++ b/packages/prisma/migrations/20250721085125_include_audit_trail_log/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "OrganisationGlobalSettings" ADD COLUMN "includeAuditLog" BOOLEAN NOT NULL DEFAULT false;
+
+-- AlterTable
+ALTER TABLE "TeamGlobalSettings" ADD COLUMN "includeAuditLog" BOOLEAN;
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 0ecf9086a..14eb7f626 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -734,13 +734,13 @@ model OrganisationGlobalSettings {
id String @id
organisation Organisation?
- documentVisibility DocumentVisibility @default(EVERYONE)
- documentLanguage String @default("en")
- documentTimezone String? // Nullable to allow using local timezones if not set.
- documentDateFormat String @default("yyyy-MM-dd hh:mm a")
-
- includeSenderDetails Boolean @default(true)
- includeSigningCertificate Boolean @default(true)
+ documentVisibility DocumentVisibility @default(EVERYONE)
+ documentLanguage String @default("en")
+ includeSenderDetails Boolean @default(true)
+ includeSigningCertificate Boolean @default(true)
+ includeAuditLog Boolean @default(false)
+ documentTimezone String? // Nullable to allow using local timezones if not set.
+ documentDateFormat String @default("yyyy-MM-dd hh:mm a")
typedSignatureEnabled Boolean @default(true)
uploadSignatureEnabled Boolean @default(true)
@@ -771,6 +771,7 @@ model TeamGlobalSettings {
includeSenderDetails Boolean?
includeSigningCertificate Boolean?
+ includeAuditLog Boolean?
typedSignatureEnabled Boolean?
uploadSignatureEnabled Boolean?
diff --git a/packages/trpc/server/organisation-router/update-organisation-settings.ts b/packages/trpc/server/organisation-router/update-organisation-settings.ts
index ca347bc10..08c4dceb1 100644
--- a/packages/trpc/server/organisation-router/update-organisation-settings.ts
+++ b/packages/trpc/server/organisation-router/update-organisation-settings.ts
@@ -30,6 +30,7 @@ export const updateOrganisationSettingsRoute = authenticatedProcedure
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
@@ -117,6 +118,7 @@ export const updateOrganisationSettingsRoute = authenticatedProcedure
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
diff --git a/packages/trpc/server/organisation-router/update-organisation-settings.types.ts b/packages/trpc/server/organisation-router/update-organisation-settings.types.ts
index c7b0ac75b..6d9e79b2a 100644
--- a/packages/trpc/server/organisation-router/update-organisation-settings.types.ts
+++ b/packages/trpc/server/organisation-router/update-organisation-settings.types.ts
@@ -19,6 +19,7 @@ export const ZUpdateOrganisationSettingsRequestSchema = z.object({
documentDateFormat: ZDocumentMetaDateFormatSchema.optional(),
includeSenderDetails: z.boolean().optional(),
includeSigningCertificate: z.boolean().optional(),
+ includeAuditLog: z.boolean().optional(),
typedSignatureEnabled: z.boolean().optional(),
uploadSignatureEnabled: z.boolean().optional(),
drawSignatureEnabled: z.boolean().optional(),
diff --git a/packages/trpc/server/team-router/update-team-settings.ts b/packages/trpc/server/team-router/update-team-settings.ts
index 9cae5b330..f3805366c 100644
--- a/packages/trpc/server/team-router/update-team-settings.ts
+++ b/packages/trpc/server/team-router/update-team-settings.ts
@@ -32,6 +32,7 @@ export const updateTeamSettingsRoute = authenticatedProcedure
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
@@ -110,6 +111,7 @@ export const updateTeamSettingsRoute = authenticatedProcedure
documentDateFormat,
includeSenderDetails,
includeSigningCertificate,
+ includeAuditLog,
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
diff --git a/packages/trpc/server/team-router/update-team-settings.types.ts b/packages/trpc/server/team-router/update-team-settings.types.ts
index 9f1fee8fd..aaf5e94f1 100644
--- a/packages/trpc/server/team-router/update-team-settings.types.ts
+++ b/packages/trpc/server/team-router/update-team-settings.types.ts
@@ -23,6 +23,7 @@ export const ZUpdateTeamSettingsRequestSchema = z.object({
documentDateFormat: ZDocumentMetaDateFormatSchema.nullish(),
includeSenderDetails: z.boolean().nullish(),
includeSigningCertificate: z.boolean().nullish(),
+ includeAuditLog: z.boolean().nullish(),
typedSignatureEnabled: z.boolean().nullish(),
uploadSignatureEnabled: z.boolean().nullish(),
drawSignatureEnabled: z.boolean().nullish(),