mirror of
https://github.com/documenso/documenso.git
synced 2026-07-10 21:15:15 +10:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 12d44e1c59 | |||
| 1b1e3d197b | |||
| a276e18e1f | |||
| 9dc66afc7b | |||
| 7a13be6bf2 | |||
| 1032028395 | |||
| 2396d0d5d0 | |||
| dac262edc9 | |||
| 25eb4ffedf | |||
| ee0ea82635 | |||
| 5f7f6698fd | |||
| 402809c809 | |||
| 733e273c05 | |||
| 7c7933c2d4 | |||
| bb120d65dd | |||
| 9c14aa6297 | |||
| 6387e809a8 | |||
| 5b2b1591a4 | |||
| e5cb4c6bfd | |||
| 8185f916d3 | |||
| c308dbf257 |
@@ -0,0 +1,222 @@
|
||||
---
|
||||
date: 2026-05-07
|
||||
title: Pdf Placeholder Selection Fields
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Extend PDF placeholders so radio and dropdown fields can be configured from the existing Documenso placeholder syntax:
|
||||
|
||||
```text
|
||||
{{FIELD_TYPE, RECIPIENT, key=value, key=value}}
|
||||
```
|
||||
|
||||
Do not introduce a new delimiter style. Existing applications may already generate placeholders in this format, so the new selection-field behavior should fit into it.
|
||||
|
||||
## Goals
|
||||
|
||||
- Keep the current placeholder grammar unchanged.
|
||||
- Support checkbox placeholders with option lists, checked values, validation, direction, required, read-only, and font size.
|
||||
- Support radio placeholders with option lists, default/preselected values, direction, required, read-only, and font size.
|
||||
- Support dropdown placeholders with option lists, default value, required, read-only, and font size.
|
||||
- Use `options` as the only public list key in PDF placeholders.
|
||||
- Convert `options` into internal `fieldMeta.values` during parsing.
|
||||
- Make generated fields usable immediately in the editor, signing UI, preview renderer, and final PDF export.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No semicolon placeholder syntax.
|
||||
- No `values` alias in PDF placeholder syntax.
|
||||
- No database migration.
|
||||
- No behavior change for existing placeholders such as `{{text, r1, required=true}}`.
|
||||
|
||||
## Placeholder Syntax
|
||||
|
||||
Use the existing comma-separated placeholder format:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, defaultValue=Check}}
|
||||
{{radio, r1, options=Basic|Pro|Enterprise, selected=Pro, direction=horizontal}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Use `|` inside `options` because `,` is already the top-level placeholder delimiter.
|
||||
|
||||
Parsing rules:
|
||||
|
||||
- Split top-level placeholder tokens on unescaped commas.
|
||||
- Split metadata tokens on the first unescaped equals sign.
|
||||
- Split `options` on unescaped pipes.
|
||||
- Trim option values and drop empty values.
|
||||
- Preserve option order.
|
||||
- Support escaped delimiters: `\,`, `\=`, and `\|`.
|
||||
- Treat field type values case-insensitively.
|
||||
|
||||
## Field Type Mapping
|
||||
|
||||
- `checkbox` maps to `FieldType.CHECKBOX`.
|
||||
- `radio` maps to `FieldType.RADIO`.
|
||||
- `dropdown` maps to `FieldType.DROPDOWN`.
|
||||
|
||||
## Metadata Mapping
|
||||
|
||||
### Checkbox
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.CHECKBOX,
|
||||
fieldMeta: {
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, value: 'Email', checked: true },
|
||||
{ id: 2, value: 'SMS', checked: false },
|
||||
{ id: 3, value: 'Phone', checked: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `checked`
|
||||
- `direction=vertical|horizontal`
|
||||
- `validationRule=atLeast|exactly|atMost`
|
||||
- `validationLength=1`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Map checkbox validation aliases internally: `atLeast` -> `Select at least`, `exactly` -> `Select exactly`, `atMost` -> `Select at most`.
|
||||
|
||||
Checkbox placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Radio
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Bank transfer}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.RADIO,
|
||||
fieldMeta: {
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, value: 'Card', checked: false },
|
||||
{ id: 2, value: 'Bank transfer', checked: true },
|
||||
{ id: 3, value: 'Check', checked: false },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `direction=vertical|horizontal`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Radio placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Dropdown
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{dropdown, r1, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.DROPDOWN,
|
||||
fieldMeta: {
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales' }, { value: 'Legal' }, { value: 'Finance' }],
|
||||
defaultValue: 'Legal',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
`defaultValue` should only be set if it matches one parsed option.
|
||||
|
||||
Dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
## Code Touchpoints
|
||||
|
||||
- `packages/lib/server-only/pdf/helpers.ts`
|
||||
- Extend `parseFieldMetaFromPlaceholder` so `options` normalizes into checkbox/radio/dropdown `fieldMeta.values`.
|
||||
- Add delimiter-aware helpers for commas, equals signs, and pipes.
|
||||
- `packages/lib/server-only/pdf/auto-place-fields.ts`
|
||||
- Replace plain comma splitting with delimiter-aware splitting.
|
||||
- Preserve the existing positional structure: field type, recipient, metadata.
|
||||
- `packages/lib/types/field-meta.ts`
|
||||
- Keep current internal schemas: checkbox/radio/dropdown still store options as `fieldMeta.values`.
|
||||
- `packages/ui/primitives/document-flow/field-content.tsx`
|
||||
- Display a radio fallback when a placeholder-created radio has no options.
|
||||
- Docs:
|
||||
- `apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx`
|
||||
- `apps/docs/content/docs/developers/api/fields.mdx`
|
||||
|
||||
## Test Plan
|
||||
|
||||
Unit tests:
|
||||
|
||||
- `options=Yes|No|Maybe` becomes stable radio values.
|
||||
- `selected=No` marks only the matching radio option checked.
|
||||
- Checkbox `options`, `checked`, `validationRule`, and `validationLength` normalize correctly.
|
||||
- Dropdown `options` and `defaultValue` normalize correctly.
|
||||
- Escaped delimiters parse correctly, for example `options=Sales\|Ops|Legal\, Compliance|A\=B`.
|
||||
|
||||
E2E/API tests:
|
||||
|
||||
- Add a PDF fixture with checkbox, radio, and dropdown placeholders using the current syntax.
|
||||
- Verify created fields have schema-compatible metadata and expected options/defaults.
|
||||
|
||||
Suggested verification:
|
||||
|
||||
```bash
|
||||
npm run test -w @documenso/lib -- server-only/pdf/helpers.test.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/auto-placing-fields/auto-place-fields-document.spec.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/envelope-editor-v2/envelope-fields.spec.ts
|
||||
npx tsc --noEmit -p packages/lib/tsconfig.json
|
||||
npx tsc --noEmit -p apps/remix/tsconfig.json
|
||||
```
|
||||
|
||||
Do not use `npm run build` for routine verification unless explicitly requested.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Keep the existing placeholder format.
|
||||
- Use only `options` publicly.
|
||||
- Keep `values` as an internal metadata field only.
|
||||
- Use `|` as the option delimiter inside `options`.
|
||||
@@ -76,6 +76,8 @@ The Enterprise Edition is required when you:
|
||||
4. Restart your Documenso instance
|
||||
5. Verify the license is active in the **Admin Panel** under the **Stats** section
|
||||
|
||||
See [Apply Your License Key](/docs/self-hosting/configuration/license) for the full walkthrough, including how to enable individual features once licensed.
|
||||
|
||||
</Accordion>
|
||||
</Accordions>
|
||||
|
||||
@@ -197,7 +199,7 @@ See [Support](/docs/policies/support) for complete support options.
|
||||
1. Sign the Enterprise license agreement
|
||||
2. Receive license key and access credentials
|
||||
3. Deploy using [self-hosting guides](/docs/self-hosting) or access Documenso Cloud
|
||||
4. Configure Enterprise features with support assistance
|
||||
4. Apply the key — see [Apply Your License Key](/docs/self-hosting/configuration/license) — and configure Enterprise features with support assistance
|
||||
|
||||
</Step>
|
||||
<Step>
|
||||
@@ -238,6 +240,7 @@ See [Support](/docs/policies/support) for complete support options.
|
||||
|
||||
## Related
|
||||
|
||||
- [Apply Your License Key](/docs/self-hosting/configuration/license) - Step-by-step license activation
|
||||
- [Community Edition](/docs/policies/community-edition) - AGPL-3.0 open-source license
|
||||
- [Licenses](/docs/policies/licenses) - Complete licensing overview and FAQ
|
||||
- [Support](/docs/policies/support) - Support channels and response times
|
||||
|
||||
@@ -443,11 +443,11 @@ Telemetry collects only: app version, installation ID, and node ID. No personal
|
||||
|
||||
## Enterprise Features
|
||||
|
||||
These variables require an active [Enterprise Edition](/docs/policies/enterprise-edition) license. Obtain a license key from [license.documenso.com](https://license.documenso.com) and set it below to unlock enterprise features such as SSO, embed editor, and 21 CFR Part 11 compliance.
|
||||
These variables require an active [Enterprise Edition](/docs/policies/enterprise-edition) license. Obtain a license key from [license.documenso.com](https://license.documenso.com) and set it below to unlock enterprise features such as SSO, embed editor, and 21 CFR Part 11 compliance. See [Apply Your License Key](/docs/self-hosting/configuration/license) for step-by-step setup.
|
||||
|
||||
| Variable | Description |
|
||||
| ------------------------------------ | ------------------------------------------------ |
|
||||
| `NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY` | License key for enterprise features |
|
||||
| `NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY` | License key for enterprise features — see [Apply Your License Key](/docs/self-hosting/configuration/license) for how to apply it |
|
||||
| `NEXT_PRIVATE_STRIPE_API_KEY` | Stripe API key for billing |
|
||||
| `NEXT_PRIVATE_STRIPE_WEBHOOK_SECRET` | Stripe webhook secret |
|
||||
| `NEXT_PRIVATE_SES_ACCESS_KEY_ID` | AWS SES access key for email domain verification |
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Apply Your License Key
|
||||
description: Activate your Enterprise license key to unlock enterprise features on your self-hosted instance.
|
||||
---
|
||||
|
||||
import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
A license key activates the Enterprise features available to your self-hosted instance, such as CSC signing, SSO, embed white-labelling, and 21 CFR Part 11 compliance.
|
||||
|
||||
<Callout type="info">
|
||||
The license key applies to your **whole instance**, not an individual user account. There's one
|
||||
key per deployment.
|
||||
</Callout>
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- An active Enterprise license key — contact [sales](https://documen.so/enterprise) to set up an
|
||||
Enterprise subscription, then copy your key from [license.documenso.com](https://license.documenso.com).
|
||||
See [Enterprise Edition](/docs/policies/enterprise-edition) for details.
|
||||
- A running self-hosted Documenso instance that you're able to restart
|
||||
|
||||
## Step 1: Set the environment variable
|
||||
|
||||
Set `NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY` to your license key.
|
||||
|
||||
<Tabs items={['Docker Compose', 'docker run', '.env']}>
|
||||
<Tab value="Docker Compose">
|
||||
|
||||
Add the variable to your `.env` file (or directly under `environment:` in `compose.yml`):
|
||||
|
||||
```bash
|
||||
NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY=your-license-key-here
|
||||
```
|
||||
|
||||
Then apply it:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="docker run">
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name documenso \
|
||||
-e NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY=your-license-key-here \
|
||||
documenso/documenso:latest
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value=".env">
|
||||
|
||||
If you're running Documenso directly (not in a container), add the variable to your `.env` file:
|
||||
|
||||
```bash
|
||||
NEXT_PRIVATE_DOCUMENSO_LICENSE_KEY=your-license-key-here
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Step 2: Restart the instance
|
||||
|
||||
The license key is only read once, at process startup. Setting the variable in a running container or shell has no effect until the process restarts.
|
||||
|
||||
```bash
|
||||
# Docker Compose
|
||||
docker compose restart documenso
|
||||
|
||||
# Docker
|
||||
docker restart documenso
|
||||
```
|
||||
|
||||
On startup, Documenso validates the key against the Documenso license server and caches the result locally for future startups, so a brief license-server outage won't lock you out.
|
||||
|
||||
## What the license enables
|
||||
|
||||
A valid license doesn't turn every enterprise feature on everywhere — activation depends on the feature:
|
||||
|
||||
- **CSC signing** activates instance-wide automatically once the license is active and CSC transport is configured. See [CSC / QES Signing](/docs/self-hosting/configuration/signing-certificate/csc-qes) for the full setup.
|
||||
- **SSO, embed white-labelling, 21 CFR Part 11, and similar** are provisioned per organisation. Follow each feature's own guide to configure it once the license is active.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<Accordions type="multiple">
|
||||
<Accordion title="Enterprise features are still unavailable after applying the key">
|
||||
- Confirm the key is present in the environment the running process actually reads — `docker
|
||||
exec` into the container and check `env | grep LICENSE` if unsure.
|
||||
- Confirm the instance was fully restarted after the variable was set, not just reloaded.
|
||||
- Re-copy the key to rule out truncation or accidental whitespace.
|
||||
</Accordion>
|
||||
<Accordion title="A specific feature still isn't working">
|
||||
Instance-wide features (like CSC signing) also need their own configuration — an active license
|
||||
alone isn't enough. Check that feature's guide to confirm the required settings are in place.
|
||||
Per-organisation features additionally need to be provisioned for the organisation that's using
|
||||
them.
|
||||
</Accordion>
|
||||
</Accordions>
|
||||
|
||||
## See Also
|
||||
|
||||
- [Environment Variables](/docs/self-hosting/configuration/environment) - Complete configuration reference
|
||||
- [Enterprise Edition](/docs/policies/enterprise-edition) - What's included and how to purchase a license
|
||||
- [CSC / QES Signing](/docs/self-hosting/configuration/signing-certificate/csc-qes) - Enable CSC-based signing
|
||||
@@ -2,6 +2,7 @@
|
||||
"title": "Configuration",
|
||||
"pages": [
|
||||
"environment",
|
||||
"license",
|
||||
"database",
|
||||
"email",
|
||||
"storage",
|
||||
|
||||
@@ -49,7 +49,7 @@ The callback URL is fixed — Documenso derives it from `NEXT_PUBLIC_WEBAPP_URL`
|
||||
|
||||
### Enterprise Edition license
|
||||
|
||||
CSC mode is gated by the `instanceCscSigning` license flag. Without a valid Enterprise license, the transport refuses to start (`CSC_UNLICENSED`).
|
||||
CSC mode is gated by the `instanceCscSigning` license flag. Without a valid Enterprise license, the transport refuses to start (`CSC_UNLICENSED`). See [Apply Your License Key](/docs/self-hosting/configuration/license) to activate one.
|
||||
|
||||
</Step>
|
||||
<Step>
|
||||
|
||||
@@ -141,7 +141,7 @@ See the [Quick Start guide](/docs/self-hosting/getting-started/quick-start) for
|
||||
|
||||
Self-hosted Documenso includes full core functionality under the AGPL-3.0 license. If you need enterprise features such as SSO, embed editor white label, or 21 CFR Part 11 compliance, you can activate them with a license key.
|
||||
|
||||
See [Enterprise Edition](/docs/policies/enterprise-edition) for details and [Licenses](/docs/policies/licenses) for a comparison.
|
||||
See [Enterprise Edition](/docs/policies/enterprise-edition) for details and [Licenses](/docs/policies/licenses) for a comparison. Already have a key? See [Apply Your License Key](/docs/self-hosting/configuration/license).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -109,6 +109,37 @@ You can customize fields by adding options after the recipient identifier:
|
||||
| `maxValue` | Number | Maximum allowed value |
|
||||
| `numberFormat` | Format string | Number display format |
|
||||
|
||||
### Selection Field Options
|
||||
|
||||
Checkbox, radio, and dropdown placeholders can define their selectable choices via the `options` property.
|
||||
Separate choices with pipe (`|`) characters.
|
||||
Checkbox, radio, and dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
| Option | Applies To | Values | Description |
|
||||
| ------------------ | ------------------------- | ------------------------ | ---------------------------------------- |
|
||||
| `options` | Checkbox, Radio, Dropdown | `Option 1|Option 2` | Selectable choices |
|
||||
| `checked` | Checkbox | `Option 1|Option 2` | Pre-checked choices |
|
||||
| `selected` | Radio, Dropdown | One option value | Pre-selected/default choice |
|
||||
| `default` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `defaultValue` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `direction` | Checkbox, Radio | `vertical`, `horizontal` | Option layout |
|
||||
| `validationRule` | Checkbox | `atLeast`, `exactly`, `atMost` | Checkbox selection validation rule |
|
||||
| `validationLength` | Checkbox | Number (e.g., `1`) | Checkbox validation option count |
|
||||
| `required` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the field must be completed |
|
||||
| `readOnly` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the pre-selected value is locked |
|
||||
| `fontSize` | Checkbox, Radio, Dropdown | Number (e.g., `12`) | Field text size |
|
||||
|
||||
For checkbox validation, `validationLength` defines the option count:
|
||||
- `atLeast` means at least that many options must be selected
|
||||
- `exactly` means exactly that many options must be selected
|
||||
- `atMost` means at most that many options must be selected
|
||||
|
||||
If an option needs a literal delimiter, escape it with a backslash:
|
||||
|
||||
```
|
||||
{{dropdown, r1, options=Sales\|Ops|Legal\, Compliance|A\=B}}
|
||||
```
|
||||
|
||||
### Examples with Options
|
||||
|
||||
```
|
||||
@@ -116,6 +147,10 @@ You can customize fields by adding options after the recipient identifier:
|
||||
{{number, r1, minValue=0, maxValue=100, value=50}}
|
||||
{{name, r1, fontSize=14}}
|
||||
{{text, r2, readOnly=true, text=Contract #12345}}
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Check}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
|
||||
@@ -1,20 +1,48 @@
|
||||
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
|
||||
import type { TDocumentAuditLog } from '@documenso/lib/types/document-audit-logs';
|
||||
import { 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';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import type { DateTimeFormatOptions } from 'luxon';
|
||||
import { DateTime } from 'luxon';
|
||||
import { match, P } from 'ts-pattern';
|
||||
import { UAParser } from 'ua-parser-js';
|
||||
|
||||
export type AuditLogDataTableProps = {
|
||||
logs: TDocumentAuditLog[];
|
||||
};
|
||||
|
||||
const dateFormat: DateTimeFormatOptions = {
|
||||
...DateTime.DATETIME_SHORT,
|
||||
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, userAgentInfo: UAParser.IResult) => {
|
||||
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;
|
||||
@@ -35,45 +63,74 @@ export const InternalAuditLogTable = ({ logs }: AuditLogDataTableProps) => {
|
||||
const parser = new UAParser();
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-border">
|
||||
<div className="space-y-4">
|
||||
{logs.map((log, index) => {
|
||||
parser.setUA(log.userAgent || '');
|
||||
const formattedAction = formatDocumentAuditLogAction(i18n, log);
|
||||
const userAgentInfo = parser.getResult();
|
||||
|
||||
const createdAt = DateTime.fromJSDate(log.createdAt).setLocale(APP_I18N_OPTIONS.defaultLocale);
|
||||
|
||||
const metaSegments = [
|
||||
log.email,
|
||||
log.ipAddress,
|
||||
log.userAgent ? _(formatUserAgent(log.userAgent, userAgentInfo)) : null,
|
||||
].filter((segment): segment is string => Boolean(segment));
|
||||
|
||||
return (
|
||||
<div
|
||||
<Card
|
||||
key={index}
|
||||
className="flex gap-5 py-2.5"
|
||||
// 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',
|
||||
}}
|
||||
>
|
||||
<div className="w-[5.5rem] shrink-0">
|
||||
<div className="text-foreground text-xs">{createdAt.toFormat('yyyy-MM-dd')}</div>
|
||||
<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 className="mt-0.5 text-[0.6875rem] text-muted-foreground">{createdAt.toFormat('hh:mm:ss a')}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-sm uppercase tracking-wide print:text-[8pt]">
|
||||
{log.type.replace(/_/g, ' ')}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-pretty text-foreground text-sm print:text-xs">{formattedAction.description}</div>
|
||||
|
||||
{metaSegments.length > 0 && (
|
||||
<div className="mt-1 break-words text-muted-foreground text-xs print:text-[0.6875rem]">
|
||||
{metaSegments.join(' · ')}
|
||||
<div className="font-medium text-foreground text-sm print:text-[8pt]">
|
||||
{formattedAction.description}
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
<div className="font-medium text-muted-foreground/70 uppercase tracking-wide">{_(msg`User`)}</div>
|
||||
|
||||
<div className="mt-1 font-mono text-foreground">{log.email || 'N/A'}</div>
|
||||
</div>
|
||||
|
||||
<div className="text-right">
|
||||
<div className="font-medium text-muted-foreground/70 uppercase tracking-wide">
|
||||
{_(msg`IP Address`)}
|
||||
</div>
|
||||
|
||||
<div className="mt-1 font-mono text-foreground">{log.ipAddress || 'N/A'}</div>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<div className="font-medium text-muted-foreground/70 uppercase tracking-wide">
|
||||
{_(msg`User Agent`)}
|
||||
</div>
|
||||
|
||||
<div className="mt-1 text-foreground">{_(formatUserAgent(log.userAgent, userAgentInfo))}</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { findDocumentAuditLogs } from '@documenso/lib/server-only/document/find-
|
||||
import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';
|
||||
import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';
|
||||
import { getTranslations } from '@documenso/lib/utils/i18n';
|
||||
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { EnvelopeType } from '@prisma/client';
|
||||
@@ -105,86 +106,82 @@ export default function AuditLog({ loaderData }: Route.ComponentProps) {
|
||||
|
||||
return (
|
||||
<div className="print-provider pointer-events-none mx-auto max-w-screen-md">
|
||||
<header>
|
||||
<h1 className="font-semibold text-lg tracking-tight">{_(msg`Audit Log`)}</h1>
|
||||
<div className="mb-6 border-b pb-4">
|
||||
<h1 className="font-semibold text-xl">{_(msg`Audit Log`)}</h1>
|
||||
</div>
|
||||
|
||||
<p className="mt-1 text-pretty text-muted-foreground text-sm">{document.title}</p>
|
||||
</header>
|
||||
<Card>
|
||||
<CardContent className="grid grid-cols-2 gap-4 p-6 text-sm print:text-xs">
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Envelope ID`)}</span>
|
||||
|
||||
<dl className="mt-6 grid grid-cols-2 gap-x-8 gap-y-5">
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Envelope ID`)}</dt>
|
||||
<span className="mt-1 block break-words">{document.envelopeId}</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 break-all text-foreground text-sm print:text-xs">{document.envelopeId}</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Enclosed Document`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Owner`)}</dt>
|
||||
<span className="mt-1 block break-words">{document.title}</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 break-words text-foreground text-sm print:text-xs">
|
||||
{document.user.name} ({document.user.email})
|
||||
</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Status`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Status`)}</dt>
|
||||
<span className="mt-1 block">
|
||||
{_(document.deletedAt ? msg`Deleted` : DOCUMENT_STATUS[document.status].description).toUpperCase()}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 text-foreground text-sm print:text-xs">
|
||||
{_(document.deletedAt ? msg`Deleted` : DOCUMENT_STATUS[document.status].description)}
|
||||
</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Owner`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Time Zone`)}</dt>
|
||||
<span className="mt-1 block break-words">
|
||||
{document.user.name} ({document.user.email})
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 break-words text-foreground text-sm print:text-xs">
|
||||
{document.documentMeta?.timezone ?? 'N/A'}
|
||||
</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Created At`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Created At`)}</dt>
|
||||
<span className="mt-1 block">
|
||||
{DateTime.fromJSDate(document.createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 text-foreground text-sm print:text-xs">
|
||||
{DateTime.fromJSDate(document.createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')}
|
||||
</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Last Updated`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Last Updated`)}</dt>
|
||||
<span className="mt-1 block">
|
||||
{DateTime.fromJSDate(document.updatedAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 text-foreground text-sm print:text-xs">
|
||||
{DateTime.fromJSDate(document.updatedAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')}
|
||||
</dd>
|
||||
</div>
|
||||
<p>
|
||||
<span className="font-medium">{_(msg`Time Zone`)}</span>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Enclosed Document`)}</dt>
|
||||
<span className="mt-1 block break-words">{document.documentMeta?.timezone ?? 'N/A'}</span>
|
||||
</p>
|
||||
|
||||
<dd className="mt-1 break-words text-foreground text-sm print:text-xs">{document.title}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{_(msg`Recipients`)}</p>
|
||||
|
||||
<div>
|
||||
<dt className="font-medium text-muted-foreground text-xs">{_(msg`Recipients`)}</dt>
|
||||
|
||||
<dd className="mt-1 text-foreground text-sm print:text-xs">
|
||||
<ul className="space-y-0.5">
|
||||
<ul className="mt-1 list-inside list-disc">
|
||||
{document.recipients.map((recipient) => (
|
||||
<li key={recipient.id} className="break-words">
|
||||
{recipient.name} ({recipient.email}) ·{' '}
|
||||
<li key={recipient.id}>
|
||||
<span className="text-muted-foreground">
|
||||
{_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}
|
||||
</span>
|
||||
[{_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}]
|
||||
</span>{' '}
|
||||
{recipient.name} ({recipient.email})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="mt-8">
|
||||
<InternalAuditLogTable logs={auditLogs} />
|
||||
|
||||
@@ -9,8 +9,11 @@ import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-log
|
||||
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
|
||||
import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';
|
||||
import { getTranslations } from '@documenso/lib/utils/i18n';
|
||||
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@documenso/ui/primitives/table';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { EnvelopeType, FieldType, SigningStatus } from '@prisma/client';
|
||||
import { DateTime } from 'luxon';
|
||||
import { redirect } from 'react-router';
|
||||
@@ -200,178 +203,165 @@ export default function SigningCertificate({ loaderData }: Route.ComponentProps)
|
||||
|
||||
return (
|
||||
<div className="print-provider pointer-events-none mx-auto max-w-screen-md">
|
||||
<header>
|
||||
<h1 className="font-semibold text-lg tracking-tight">{_(msg`Signing Certificate`)}</h1>
|
||||
<div className="flex items-center">
|
||||
<h1 className="my-8 font-bold text-2xl">{_(msg`Signing Certificate`)}</h1>
|
||||
</div>
|
||||
|
||||
<p className="mt-1 text-pretty text-muted-foreground text-sm">{document.title}</p>
|
||||
</header>
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table overflowHidden>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{_(msg`Signer Events`)}</TableHead>
|
||||
<TableHead>{_(msg`Signature`)}</TableHead>
|
||||
<TableHead>{_(msg`Details`)}</TableHead>
|
||||
{/* <TableHead>Security</TableHead> */}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
||||
<table className="mt-6 w-full">
|
||||
<thead>
|
||||
<tr className="border-border border-b">
|
||||
<th className="w-[30%] pr-4 pb-2 text-left font-medium text-muted-foreground text-xs">
|
||||
{_(msg`Signer Events`)}
|
||||
</th>
|
||||
<TableBody className="print:text-xs">
|
||||
{document.recipients.map((recipient, i) => {
|
||||
const logs = getRecipientAuditLogs(recipient.id);
|
||||
const signature = getRecipientSignatureField(recipient.id);
|
||||
|
||||
<th className="w-[30%] pr-4 pb-2 text-left font-medium text-muted-foreground text-xs">
|
||||
{_(msg`Signature`)}
|
||||
</th>
|
||||
return (
|
||||
<TableRow key={i} className="print:break-inside-avoid">
|
||||
<TableCell truncate={false} className="w-[min-content] max-w-[220px] align-top">
|
||||
<div className="hyphens-auto break-words font-medium">{recipient.name}</div>
|
||||
<div className="break-all">{recipient.email}</div>
|
||||
<p className="mt-2 text-muted-foreground text-sm print:text-xs">
|
||||
{_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}
|
||||
</p>
|
||||
|
||||
<th className="pb-2 text-left font-medium text-muted-foreground text-xs">{_(msg`Details`)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<p className="mt-2 text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Authentication Level`)}:</span>{' '}
|
||||
<span className="block">{getAuthenticationLevel(recipient.id)}</span>
|
||||
</p>
|
||||
</TableCell>
|
||||
|
||||
<tbody className="divide-y divide-border">
|
||||
{document.recipients.map((recipient, i) => {
|
||||
const logs = getRecipientAuditLogs(recipient.id);
|
||||
const signature = getRecipientSignatureField(recipient.id);
|
||||
const isRejected = Boolean(logs.DOCUMENT_RECIPIENT_REJECTED[0]);
|
||||
<TableCell truncate={false} className="w-[min-content] align-top">
|
||||
{signature ? (
|
||||
<>
|
||||
<div
|
||||
className="inline-block rounded-lg p-1"
|
||||
style={{
|
||||
boxShadow: `0px 0px 0px 4.88px rgba(122, 196, 85, 0.1), 0px 0px 0px 1.22px rgba(122, 196, 85, 0.6), 0px 0px 0px 0.61px rgba(122, 196, 85, 1)`,
|
||||
}}
|
||||
>
|
||||
{signature.signature?.signatureImageAsBase64 && (
|
||||
<img
|
||||
src={`${signature.signature?.signatureImageAsBase64}`}
|
||||
alt="Signature"
|
||||
className="max-h-12 max-w-full"
|
||||
/>
|
||||
)}
|
||||
|
||||
return (
|
||||
<tr key={i} className="align-top print:break-inside-avoid">
|
||||
<td className="py-3 pr-4">
|
||||
<div className="hyphens-auto break-words font-medium text-sm print:text-xs">{recipient.name}</div>
|
||||
{signature.signature?.typedSignature && (
|
||||
<p className="text-center font-signature text-sm">
|
||||
{signature.signature?.typedSignature}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="break-all text-muted-foreground text-xs">{recipient.email}</div>
|
||||
|
||||
<div className="mt-0.5 text-muted-foreground text-xs">
|
||||
{_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}
|
||||
</div>
|
||||
|
||||
<div className="mt-2.5">
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Authentication Level`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{getAuthenticationLevel(recipient.id)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="py-3 pr-4">
|
||||
{signature ? (
|
||||
<div className="space-y-2.5">
|
||||
{!isRejected && (
|
||||
<div
|
||||
className="inline-block rounded-lg p-1"
|
||||
style={{
|
||||
boxShadow: `0px 0px 0px 4.88px rgba(122, 196, 85, 0.1), 0px 0px 0px 1.22px rgba(122, 196, 85, 0.6), 0px 0px 0px 0.61px rgba(122, 196, 85, 1)`,
|
||||
}}
|
||||
>
|
||||
{signature.signature?.signatureImageAsBase64 && (
|
||||
<img
|
||||
src={`${signature.signature?.signatureImageAsBase64}`}
|
||||
alt="Signature"
|
||||
className="max-h-12 max-w-full"
|
||||
/>
|
||||
)}
|
||||
|
||||
{signature.signature?.typedSignature && (
|
||||
<p className="text-center font-signature text-sm">{signature.signature?.typedSignature}</p>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Signature ID`)}:</span>{' '}
|
||||
<span className="block font-mono uppercase">{signature.secondaryId}</span>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted-foreground">
|
||||
<Trans>N/A</Trans>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Signature ID`)}</div>
|
||||
<p className="mt-2 text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`IP Address`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{logs.DOCUMENT_RECIPIENT_COMPLETED[0]?.ipAddress ?? _(msg`Unknown`)}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div className="mt-0.5 break-all font-mono text-xs uppercase">{signature.secondaryId}</div>
|
||||
<p className="mt-1 text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Device`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{getDevice(logs.DOCUMENT_RECIPIENT_COMPLETED[0]?.userAgent)}
|
||||
</span>
|
||||
</p>
|
||||
</TableCell>
|
||||
|
||||
<TableCell truncate={false} className="w-[min-content] align-top">
|
||||
<div className="space-y-1">
|
||||
<p className="text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Sent`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{logs.EMAIL_SENT[0]
|
||||
? DateTime.fromJSDate(logs.EMAIL_SENT[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: logs.DOCUMENT_SENT[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_SENT[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<p className="text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Viewed`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{logs.DOCUMENT_OPENED[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_OPENED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
{logs.DOCUMENT_RECIPIENT_REJECTED[0] ? (
|
||||
<p className="text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Rejected`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{logs.DOCUMENT_RECIPIENT_REJECTED[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_RECIPIENT_REJECTED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Signed`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{logs.DOCUMENT_RECIPIENT_COMPLETED[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_RECIPIENT_COMPLETED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="text-muted-foreground text-sm print:text-xs">
|
||||
<span className="font-medium">{_(msg`Reason`)}:</span>{' '}
|
||||
<span className="inline-block">
|
||||
{recipient.signingStatus === SigningStatus.REJECTED
|
||||
? recipient.rejectionReason
|
||||
: _(
|
||||
isOwner(recipient.email)
|
||||
? FRIENDLY_SIGNING_REASONS['__OWNER__']
|
||||
: FRIENDLY_SIGNING_REASONS[recipient.role],
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm print:text-xs">{_(msg`N/A`)}</p>
|
||||
)}
|
||||
|
||||
<div className="mt-2.5">
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`IP Address`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{logs.DOCUMENT_RECIPIENT_COMPLETED[0]?.ipAddress ?? _(msg`Unknown`)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2.5">
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Device`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{getDevice(logs.DOCUMENT_RECIPIENT_COMPLETED[0]?.userAgent)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="py-3">
|
||||
<div className="space-y-2.5">
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Sent`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{logs.EMAIL_SENT[0]
|
||||
? DateTime.fromJSDate(logs.EMAIL_SENT[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: logs.DOCUMENT_SENT[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_SENT[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Viewed`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{logs.DOCUMENT_OPENED[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_OPENED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{logs.DOCUMENT_RECIPIENT_REJECTED[0] ? (
|
||||
<div>
|
||||
<div className="font-medium text-red-600 text-xs">{_(msg`Rejected`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-red-600 text-sm print:text-xs">
|
||||
{DateTime.fromJSDate(logs.DOCUMENT_RECIPIENT_REJECTED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Signed`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{logs.DOCUMENT_RECIPIENT_COMPLETED[0]
|
||||
? DateTime.fromJSDate(logs.DOCUMENT_RECIPIENT_COMPLETED[0].createdAt)
|
||||
.setLocale(APP_I18N_OPTIONS.defaultLocale)
|
||||
.toFormat('yyyy-MM-dd hh:mm:ss a (ZZZZ)')
|
||||
: _(msg`Unknown`)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div className="font-medium text-muted-foreground text-xs">{_(msg`Reason`)}</div>
|
||||
|
||||
<div className="mt-0.5 text-foreground text-sm print:text-xs">
|
||||
{recipient.signingStatus === SigningStatus.REJECTED
|
||||
? recipient.rejectionReason
|
||||
: _(
|
||||
isOwner(recipient.email)
|
||||
? FRIENDLY_SIGNING_REASONS['__OWNER__']
|
||||
: FRIENDLY_SIGNING_REASONS[recipient.role],
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{!hidePoweredBy && (
|
||||
<div className="my-8 flex-row-reverse space-y-4">
|
||||
@@ -387,7 +377,7 @@ export default function SigningCertificate({ loaderData }: Route.ComponentProps)
|
||||
</div>
|
||||
|
||||
<div className="flex items-end justify-end gap-x-4">
|
||||
<p className="flex-shrink-0 font-medium text-muted-foreground text-xs">
|
||||
<p className="flex-shrink-0 font-medium text-sm print:text-xs">
|
||||
{_(msg`Signing certificate provided by`)}:
|
||||
</p>
|
||||
<BrandingLogo className="max-h-6 print:max-h-4" />
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
"@lingui/react": "^5.6.0",
|
||||
"@oslojs/crypto": "^1.0.1",
|
||||
"@oslojs/encoding": "^1.1.0",
|
||||
"@react-router/node": "^7.12.0",
|
||||
"@react-router/serve": "^7.12.0",
|
||||
"@react-router/node": "^7.18.1",
|
||||
"@react-router/serve": "^7.18.1",
|
||||
"@simplewebauthn/browser": "^13.2.2",
|
||||
"@simplewebauthn/server": "^13.2.2",
|
||||
"@tanstack/react-query": "5.90.10",
|
||||
@@ -81,8 +81,8 @@
|
||||
"@babel/preset-typescript": "^7.28.5",
|
||||
"@lingui/babel-plugin-lingui-macro": "^5.6.0",
|
||||
"@lingui/vite-plugin": "^5.6.0",
|
||||
"@react-router/dev": "^7.12.0",
|
||||
"@react-router/remix-routes-option-adapter": "^7.12.0",
|
||||
"@react-router/dev": "^7.18.1",
|
||||
"@react-router/remix-routes-option-adapter": "^7.18.1",
|
||||
"@rollup/plugin-babel": "^6.1.0",
|
||||
"@rollup/plugin-commonjs": "^28.0.9",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
|
||||
Generated
+2048
-1264
File diff suppressed because it is too large
Load Diff
@@ -57,7 +57,10 @@ export const UNSAFE_createEnvelopeItems = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: file.name,
|
||||
});
|
||||
|
||||
const { documentData } = await putPdfFileServerSide({
|
||||
name: file.name,
|
||||
|
||||
@@ -85,7 +85,10 @@ export const UNSAFE_replaceEnvelopeItemPdf = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: data.file.name,
|
||||
});
|
||||
|
||||
// Upload the new PDF and get a new DocumentData record.
|
||||
const { documentData: newDocumentData, filePageCount } = await putPdfFileServerSide({
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { type TFieldAndMeta, ZEnvelopeFieldAndMetaSchema } from '@documenso/lib/types/field-meta';
|
||||
import { logger } from '@documenso/lib/utils/logger';
|
||||
import { PDF, rgb } from '@libpdf/core';
|
||||
import type { FieldType, Recipient } from '@prisma/client';
|
||||
|
||||
import { parseFieldMetaFromPlaceholder, parseFieldTypeFromPlaceholder } from './helpers';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const PLACEHOLDER_REGEX = /\{\{([^}]+)\}\}/g;
|
||||
const DEFAULT_FIELD_HEIGHT_PERCENT = 2;
|
||||
@@ -61,7 +68,15 @@ export type FieldToCreate = TFieldAndMeta & {
|
||||
height: number;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<PlaceholderInfo[]> => {
|
||||
type ExtractPlaceholdersLogContext = {
|
||||
envelopeId?: string;
|
||||
fileName?: string;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<PlaceholderInfo[]> => {
|
||||
const pdfDoc = await PDF.load(new Uint8Array(pdf));
|
||||
|
||||
const placeholders: PlaceholderInfo[] = [];
|
||||
@@ -85,7 +100,7 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
continue;
|
||||
}
|
||||
|
||||
const placeholderData = innerMatch[1].split(',').map((property) => property.trim());
|
||||
const placeholderData = parsePlaceholderData(innerMatch[1]);
|
||||
const [fieldTypeString, recipientOrMeta, ...fieldMetaData] = placeholderData;
|
||||
|
||||
let fieldType: FieldType;
|
||||
@@ -109,14 +124,51 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
|
||||
const recipient = recipientOrMeta;
|
||||
|
||||
const rawFieldMeta = Object.fromEntries(fieldMetaData.map((property) => property.split('=')));
|
||||
/*
|
||||
Parse and validate the field metadata. A malformed selection placeholder
|
||||
(e.g. an unknown validation rule or a default value that doesn't match an
|
||||
option) is skipped like an invalid field type rather than aborting the whole
|
||||
upload, which may contain other valid placeholders and files.
|
||||
*/
|
||||
let fieldAndMeta: TFieldAndMeta;
|
||||
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
try {
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
|
||||
const fieldAndMeta: TFieldAndMeta = ZEnvelopeFieldAndMetaSchema.parse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
const parsedFieldAndMeta = ZEnvelopeFieldAndMetaSchema.safeParse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
|
||||
/*
|
||||
Surface schema failures as INVALID_BODY (400) instead of letting the raw
|
||||
ZodError bubble up to the caller as an INTERNAL_SERVER_ERROR (500).
|
||||
*/
|
||||
if (!parsedFieldAndMeta.success) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid field metadata for placeholder "${placeholder}": ${parsedFieldAndMeta.error.message}`,
|
||||
});
|
||||
}
|
||||
|
||||
fieldAndMeta = parsedFieldAndMeta.data;
|
||||
} catch (error) {
|
||||
const appError = AppError.parseError(error);
|
||||
|
||||
logger.warn(
|
||||
{
|
||||
envelopeId: logContext?.envelopeId,
|
||||
fileName: logContext?.fileName,
|
||||
placeholder,
|
||||
page: page.index + 1,
|
||||
code: appError.code,
|
||||
message: appError.message,
|
||||
},
|
||||
'Skipping placeholder with invalid field metadata',
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
LibPDF returns bbox in points with bottom-left origin.
|
||||
@@ -182,8 +234,9 @@ export const removePlaceholdersFromPDF = async (pdf: Buffer, placeholders?: Plac
|
||||
*/
|
||||
export const extractPdfPlaceholders = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<{ cleanedPdf: Buffer; placeholders: PlaceholderInfo[] }> => {
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf);
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf, logContext);
|
||||
|
||||
if (placeholders.length === 0) {
|
||||
return { cleanedPdf: pdf, placeholders: [] };
|
||||
|
||||
@@ -137,7 +137,6 @@ export const generateCertificatePdf = async (options: GenerateCertificatePdfOpti
|
||||
}),
|
||||
envelopeOwner,
|
||||
envelopeId: envelope.id,
|
||||
envelopeTitle: envelope.title,
|
||||
qrToken: envelope.qrToken,
|
||||
hidePoweredBy: organisationClaim.flags.hidePoweredBy ?? false,
|
||||
pageWidth,
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { FieldType } from '@prisma/client';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const expectInvalidBody = (fn: () => unknown) => {
|
||||
try {
|
||||
fn();
|
||||
expect.unreachable('Expected an AppError to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AppError);
|
||||
expect((error as AppError).code).toBe(AppErrorCode.INVALID_BODY);
|
||||
}
|
||||
};
|
||||
|
||||
describe('parseFieldTypeFromPlaceholder function', () => {
|
||||
it('maps known field type strings to the FieldType enum', () => {
|
||||
expect(parseFieldTypeFromPlaceholder('signature')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('radio')).toBe(FieldType.RADIO);
|
||||
expect(parseFieldTypeFromPlaceholder('checkbox')).toBe(FieldType.CHECKBOX);
|
||||
expect(parseFieldTypeFromPlaceholder('dropdown')).toBe(FieldType.DROPDOWN);
|
||||
});
|
||||
|
||||
it('is case-insensitive and trims surrounding whitespace', () => {
|
||||
expect(parseFieldTypeFromPlaceholder(' SiGnAtUrE ')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('RADIO')).toBe(FieldType.RADIO);
|
||||
});
|
||||
|
||||
it('throws INVALID_BODY for an unknown field type', () => {
|
||||
expectInvalidBody(() => parseFieldTypeFromPlaceholder('FILE'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsePlaceholderData function', () => {
|
||||
it('splits top-level parts on commas and trims each token', () => {
|
||||
expect(parsePlaceholderData('SIGNATURE, r1, required=true')).toEqual(['SIGNATURE', 'r1', 'required=true']);
|
||||
});
|
||||
|
||||
it('does not split on escaped commas', () => {
|
||||
expect(parsePlaceholderData('dropdown, r1, options=Legal\\, Compliance|Sales')).toEqual([
|
||||
'dropdown',
|
||||
'r1',
|
||||
'options=Legal\\, Compliance|Sales',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseRawFieldMetaFromPlaceholder function', () => {
|
||||
it('splits each token into a key/value entry', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required=true', 'fontSize=12'])).toEqual({
|
||||
required: 'true',
|
||||
fontSize: '12',
|
||||
});
|
||||
});
|
||||
|
||||
it('only splits on the first unescaped equals sign', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['label=a=b'])).toEqual({ label: 'a=b' });
|
||||
});
|
||||
|
||||
it('drops tokens without a value and overwrites duplicate keys with the last', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required', 'fontSize=12', 'fontSize=14'])).toEqual({
|
||||
fontSize: '14',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseFieldMetaFromPlaceholder function', () => {
|
||||
describe('non-field-meta cases', () => {
|
||||
it('returns undefined for signature and free signature fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'true' }, FieldType.SIGNATURE)).toBeUndefined();
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.FREE_SIGNATURE)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when there is no metadata', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.TEXT)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generic metadata', () => {
|
||||
it('coerces required/readOnly to booleans (case-insensitive)', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'TRUE', readOnly: 'false' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
required: true,
|
||||
readOnly: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('coerces numeric properties to numbers', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ fontSize: '14' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
fontSize: 14,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops numeric properties that are not a number', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ fontSize: 'abc' }, FieldType.TEXT);
|
||||
|
||||
expect(parsed).toEqual({ type: 'text' });
|
||||
expect(parsed).not.toHaveProperty('fontSize');
|
||||
});
|
||||
|
||||
it('keeps label/placeholder for non-selection fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ label: 'Company Name', placeholder: 'Acme' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
label: 'Company Name',
|
||||
placeholder: 'Acme',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('radio fields', () => {
|
||||
it('builds stable values from options', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe' }, FieldType.RADIO)).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: false, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('marks only the selected option as checked', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe', selected: 'No' }, FieldType.RADIO);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: true, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when a default value is provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ selected: 'No' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'Yes|No', selected: 'Maybe' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when options is empty', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: '' }, FieldType.RADIO));
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkbox fields', () => {
|
||||
it('builds values with checked state, validation rule alias and length', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder(
|
||||
{
|
||||
options: 'Email|SMS|Phone',
|
||||
checked: 'Email|Phone',
|
||||
validationRule: 'atLeast',
|
||||
validationLength: '1',
|
||||
},
|
||||
FieldType.CHECKBOX,
|
||||
);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, checked: true, value: 'Email' },
|
||||
{ id: 2, checked: false, value: 'SMS' },
|
||||
{ id: 3, checked: true, value: 'Phone' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for an unknown validation rule', () => {
|
||||
expectInvalidBody(() =>
|
||||
parseFieldMetaFromPlaceholder({ options: 'A|B', validationRule: 'nope' }, FieldType.CHECKBOX),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when checked values are provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ checked: 'A' }, FieldType.CHECKBOX));
|
||||
});
|
||||
|
||||
it('throws when a checked value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', checked: 'C' }, FieldType.CHECKBOX));
|
||||
});
|
||||
});
|
||||
|
||||
describe('dropdown fields', () => {
|
||||
it('builds values and sets a matching default value', () => {
|
||||
expect(
|
||||
parseFieldMetaFromPlaceholder(
|
||||
{ options: 'United States|Canada|United Kingdom', defaultValue: 'Canada' },
|
||||
FieldType.DROPDOWN,
|
||||
),
|
||||
).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'United States' }, { value: 'Canada' }, { value: 'United Kingdom' }],
|
||||
defaultValue: 'Canada',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', defaultValue: 'C' }, FieldType.DROPDOWN));
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection field options parsing', () => {
|
||||
it('trims option values and drops empty entries', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: ' A || B ' }, FieldType.DROPDOWN)).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'A' }, { value: 'B' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('parses escaped delimiters through the full placeholder pipeline', () => {
|
||||
const [, , ...fieldMetaData] = parsePlaceholderData(
|
||||
'dropdown, r1, options=Sales\\|Ops|Legal\\, Compliance|A\\=B',
|
||||
);
|
||||
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsed = parseFieldMetaFromPlaceholder(rawFieldMeta, FieldType.DROPDOWN);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales|Ops' }, { value: 'Legal, Compliance' }, { value: 'A=B' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,134 @@ type RecipientPlaceholderInfo = {
|
||||
recipientIndex: number;
|
||||
};
|
||||
|
||||
const CHECKBOX_VALIDATION_RULE_BY_ALIAS: Record<string, string> = {
|
||||
atLeast: 'Select at least',
|
||||
exactly: 'Select exactly',
|
||||
atMost: 'Select at most',
|
||||
};
|
||||
|
||||
/*
|
||||
Split a string on a delimiter, treating `\` as an escape for the next character.
|
||||
Delimiters preceded by `\` are kept in the output instead of splitting (e.g. `\,`, `\=`, `\|`).
|
||||
|
||||
With delimiter ',' (top-level placeholder parts):
|
||||
'radio, r1, options=Card/Check|Bank Transfer, selected=Bank Transfer'
|
||||
-> ['radio', ' r1', ' options=Card/Check|Bank Transfer', ' selected=Bank Transfer']
|
||||
|
||||
With delimiter '=' (split one field metadata token into key + value):
|
||||
'options=Card/Check|Bank Transfer'
|
||||
-> ['options', 'Card/Check|Bank Transfer']
|
||||
|
||||
With delimiter '|' (split option list inside 'options='):
|
||||
'Card/Check|Bank Transfer'
|
||||
-> ['Card/Check', 'Bank Transfer']
|
||||
*/
|
||||
const splitPlaceholderToken = (value: string, delimiter: string): string[] => {
|
||||
const parts: string[] = [];
|
||||
let currentPart = '';
|
||||
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const char = value[index];
|
||||
const nextChar = value[index + 1];
|
||||
|
||||
if (char === '\\' && nextChar) {
|
||||
currentPart += char + nextChar;
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === delimiter) {
|
||||
parts.push(currentPart);
|
||||
currentPart = '';
|
||||
continue;
|
||||
}
|
||||
|
||||
currentPart += char;
|
||||
}
|
||||
|
||||
parts.push(currentPart);
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
/*
|
||||
Removes the escape backslashes left over after splitting, so \,=, \|, \\ become their literal characters.
|
||||
|
||||
E.g.
|
||||
'Legal\, Compliance' -> 'Legal, Compliance'
|
||||
'Card\|Check' -> 'Card|Check'
|
||||
'A\=B' -> 'A=B'
|
||||
'C\D' -> 'C\D'
|
||||
*/
|
||||
const unescapePlaceholderValue = (value: string): string => {
|
||||
return value.replace(/\\([,=|\\])/g, '$1');
|
||||
};
|
||||
|
||||
/*
|
||||
Cleans up a selection option/default after splitting:
|
||||
unescapes literal delimiters, collapses repeated whitespace, and trims the ends.
|
||||
|
||||
E.g.
|
||||
' Legal\, Compliance ' -> 'Legal, Compliance'
|
||||
*/
|
||||
const normalizePlaceholderSelectionValue = (value: string): string => {
|
||||
return unescapePlaceholderValue(value).replace(/\s+/g, ' ').trim();
|
||||
};
|
||||
|
||||
/*
|
||||
Split an options string into individual choices.
|
||||
Splits on unescaped '|', then unescapes, trims, and drops empty entries.
|
||||
|
||||
E.g.
|
||||
'Card/Check|Bank Transfer' -> ['Card/Check', 'Bank Transfer']
|
||||
'Card\\|Check|Bank Transfer' -> ['Card|Check', 'Bank Transfer']
|
||||
*/
|
||||
const parsePlaceholderOptions = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, '|')
|
||||
.map((option) => normalizePlaceholderSelectionValue(option))
|
||||
.filter((option) => option.length > 0);
|
||||
};
|
||||
|
||||
/*
|
||||
Split a placeholder string into top-level parts (field type, recipient, metadata).
|
||||
Splits on unescaped commas, then trims whitespace.
|
||||
|
||||
E.g.
|
||||
'SIGNATURE, r1, required=true'
|
||||
-> ['SIGNATURE', 'r1', 'required=true']
|
||||
*/
|
||||
export const parsePlaceholderData = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, ',').map((token) => token.trim());
|
||||
};
|
||||
|
||||
/*
|
||||
Transforms the field metadata string array into a record of key/value pairs.
|
||||
Each token is split on the first unescaped '='; tokens with no key or no '=' are dropped.
|
||||
|
||||
E.g.
|
||||
['required=true', 'fontSize=12', 'label=a=b']
|
||||
-> { required: 'true', fontSize: '12', label: 'a=b' }
|
||||
*/
|
||||
export const parseRawFieldMetaFromPlaceholder = (fieldMetaData: string[]): Record<string, string> => {
|
||||
const rawFieldMeta: Record<string, string> = {};
|
||||
|
||||
for (const fieldMeta of fieldMetaData) {
|
||||
// Split on the first '=' only; any further '=' stays part of the value (e.g. 'label=a=b').
|
||||
const [rawKey, ...valueParts] = splitPlaceholderToken(fieldMeta, '=');
|
||||
|
||||
if (!rawKey || valueParts.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = rawKey.trim();
|
||||
const value = valueParts.join('=').trim();
|
||||
|
||||
rawFieldMeta[key] = value;
|
||||
}
|
||||
|
||||
return rawFieldMeta;
|
||||
};
|
||||
|
||||
/*
|
||||
Parse field type string to FieldType enum.
|
||||
Normalizes the input (uppercase, trim) and validates it's a valid field type.
|
||||
@@ -72,6 +200,169 @@ export const parseFieldTypeFromPlaceholder = (fieldTypeString: string): FieldTyp
|
||||
});
|
||||
};
|
||||
|
||||
const getDefaultFieldMetaValue = (rawFieldMeta: Record<string, string>) => {
|
||||
const defaultValue = rawFieldMeta.defaultValue ?? rawFieldMeta.default ?? rawFieldMeta.selected;
|
||||
|
||||
return defaultValue ? normalizePlaceholderSelectionValue(defaultValue) : undefined;
|
||||
};
|
||||
|
||||
const parseCheckboxValidationRule = (value: string): string => {
|
||||
const validationRule = CHECKBOX_VALIDATION_RULE_BY_ALIAS[value];
|
||||
|
||||
if (!validationRule) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid checkbox placeholder validation rule: ${value}`,
|
||||
});
|
||||
}
|
||||
|
||||
return validationRule;
|
||||
};
|
||||
|
||||
const parseSelectionFieldOptions = (
|
||||
rawFieldMeta: Record<string, string>,
|
||||
fieldType: FieldType,
|
||||
): string[] | undefined => {
|
||||
const rawOptions = rawFieldMeta.options;
|
||||
|
||||
if (rawOptions === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedOptions = parsePlaceholderOptions(rawOptions);
|
||||
|
||||
if (parsedOptions.length === 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `${fieldType} placeholder options must contain at least one value`,
|
||||
});
|
||||
}
|
||||
|
||||
return parsedOptions;
|
||||
};
|
||||
|
||||
const applyRadioFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.RADIO);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Radio placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedOptionIndex = defaultValue ? options.findIndex((option) => option === defaultValue) : -1;
|
||||
|
||||
if (defaultValue && selectedOptionIndex === -1) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Radio placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: index === selectedOptionIndex,
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyCheckboxFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.CHECKBOX);
|
||||
const checkedValues = rawFieldMeta.checked ? parsePlaceholderOptions(rawFieldMeta.checked) : [];
|
||||
|
||||
if (!options && checkedValues.length > 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Checkbox placeholder checked values require options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unmatchedCheckedValues = checkedValues.filter((checkedValue) => !options.includes(checkedValue));
|
||||
|
||||
if (unmatchedCheckedValues.length > 0) {
|
||||
const unmatchedCheckedValue = unmatchedCheckedValues[0];
|
||||
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: [`Checkbox placeholder checked value "${unmatchedCheckedValue}"`, 'must match one of the options'].join(
|
||||
' ',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: checkedValues.includes(option),
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyDropdownFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.DROPDOWN);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Dropdown placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaultValue && !options.includes(defaultValue)) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Dropdown placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option) => ({
|
||||
value: option,
|
||||
}));
|
||||
|
||||
if (defaultValue) {
|
||||
parsedFieldMeta.defaultValue = defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Generic field metadata properties are simple properties consisting of a key and a value.
|
||||
E.g. 'required=true', 'fontSize=12', 'textAlign=left'
|
||||
They don't require special handling.
|
||||
|
||||
Special field metadata properties are complex properties consisting of a key and a value with multiple parts.
|
||||
E.g. 'options=Card/Check|Bank Transfer', 'checked=Card|Check', 'selected=Bank Transfer'
|
||||
They require special handling.
|
||||
*/
|
||||
const shouldSkipGenericFieldMetaParsing = (property: string, fieldType: FieldType): boolean => {
|
||||
if (property === 'options' || property === 'default' || property === 'selected') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const isSelectionField =
|
||||
fieldType === FieldType.CHECKBOX || fieldType === FieldType.RADIO || fieldType === FieldType.DROPDOWN;
|
||||
|
||||
if (!isSelectionField) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
property === 'label' ||
|
||||
property === 'placeholder' ||
|
||||
property === 'defaultValue' ||
|
||||
(fieldType === FieldType.CHECKBOX && property === 'checked')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/*
|
||||
Transform raw field metadata from placeholder format to schema format.
|
||||
Users should provide properly capitalized property names (e.g., readOnly, fontSize, textAlign).
|
||||
@@ -91,7 +382,7 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
|
||||
const fieldTypeString = String(fieldType).toLowerCase();
|
||||
|
||||
const parsedFieldMeta: Record<string, boolean | number | string> = {
|
||||
const parsedFieldMeta: Record<string, unknown> = {
|
||||
type: fieldTypeString,
|
||||
};
|
||||
|
||||
@@ -104,24 +395,39 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
const rawFieldMetaEntries = Object.entries(rawFieldMeta);
|
||||
|
||||
for (const [property, value] of rawFieldMetaEntries) {
|
||||
if (shouldSkipGenericFieldMetaParsing(property, fieldType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const unescapedValue = unescapePlaceholderValue(value);
|
||||
|
||||
if (property === 'readOnly' || property === 'required') {
|
||||
parsedFieldMeta[property] = value === 'true';
|
||||
parsedFieldMeta[property] = unescapedValue.toLowerCase() === 'true';
|
||||
} else if (property === 'validationRule' && fieldType === FieldType.CHECKBOX) {
|
||||
parsedFieldMeta[property] = parseCheckboxValidationRule(unescapedValue);
|
||||
} else if (
|
||||
property === 'fontSize' ||
|
||||
property === 'maxValue' ||
|
||||
property === 'minValue' ||
|
||||
property === 'characterLimit'
|
||||
property === 'characterLimit' ||
|
||||
property === 'validationLength'
|
||||
) {
|
||||
const numValue = Number(value);
|
||||
const numValue = Number(unescapedValue);
|
||||
|
||||
if (!Number.isNaN(numValue)) {
|
||||
parsedFieldMeta[property] = numValue;
|
||||
}
|
||||
} else {
|
||||
parsedFieldMeta[property] = value;
|
||||
parsedFieldMeta[property] = unescapedValue;
|
||||
}
|
||||
}
|
||||
|
||||
match(fieldType)
|
||||
.with(FieldType.RADIO, () => applyRadioFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.CHECKBOX, () => applyCheckboxFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.DROPDOWN, () => applyDropdownFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.otherwise(() => undefined);
|
||||
|
||||
return parsedFieldMeta;
|
||||
};
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -124,7 +124,9 @@ export const createEnvelopeRouteCaller = async ({
|
||||
});
|
||||
|
||||
// Todo: Embeds - Might need to add this for client-side embeds in the future.
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
fileName: file.name,
|
||||
});
|
||||
|
||||
const { documentData } = await putPdfFileServerSide({
|
||||
name: file.name,
|
||||
|
||||
Reference in New Issue
Block a user