mirror of
https://github.com/documenso/documenso.git
synced 2026-09-30 00:34:35 +10:00
Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
586b1f5cb5 | ||
|
|
a1d4bec143 | ||
|
|
39ae85483a | ||
|
|
638e92d534 | ||
|
|
c81bc72c4c | ||
|
|
1164d9578e | ||
|
|
e658cc5818 | ||
|
|
0c6249744a | ||
|
|
cf326f825d | ||
|
|
da934c01a6 | ||
|
|
0693a4195b | ||
|
|
2618d4d4be | ||
|
|
c5a6ff42ee | ||
|
|
132c4b08c5 | ||
|
|
9542512ce9 | ||
|
|
0f71a8b67d | ||
|
|
b795883fc7 | ||
|
|
643954ddd1 | ||
|
|
a20e8a2376 | ||
|
|
e73450dd08 | ||
|
|
5603a9e59d | ||
|
|
20ae849a1a | ||
|
|
6a99b40cba | ||
|
|
e1ad4a2c55 | ||
|
|
82918163c5 | ||
|
|
b97c22a607 | ||
|
|
389390c884 | ||
|
|
c5acba538e | ||
|
|
f5ab8a8ae3 | ||
|
|
3b20c2f960 | ||
|
|
5e8a434141 | ||
|
|
6a8bb4be04 | ||
|
|
2cac63a000 | ||
|
|
4aa3583e89 | ||
|
|
30a6b19b47 | ||
|
|
dabb7b7a0d | ||
|
|
cbb1cf7bef | ||
|
|
3ec877a68b | ||
|
|
bf406aa943 | ||
|
|
a2745ed3c2 | ||
|
|
937e9376d8 | ||
|
|
eba71d9be4 | ||
|
|
5082b475a0 | ||
|
|
4285c88f12 | ||
|
|
ae4b56dd88 | ||
|
|
ee8360585b | ||
|
|
9dc83bdb06 | ||
|
|
e532843aa6 | ||
|
|
dd08da7ea7 | ||
|
|
10f2b80025 | ||
|
|
73d58bdf31 | ||
|
|
1de57a9e43 | ||
|
|
7f11c163fe | ||
|
|
5beb57dbf0 | ||
|
|
ead3104896 | ||
|
|
75330166cc | ||
|
|
d42254ff52 | ||
|
|
914e325486 | ||
|
|
05f646b326 | ||
|
|
0099dd672a | ||
|
|
871c2a6f0e | ||
|
|
9bab1cddb3 | ||
|
|
3e0c1c444a | ||
|
|
6a8fe6f1ad | ||
|
|
779de01fe8 | ||
|
|
283c6d274b | ||
|
|
688ef2fdf3 | ||
|
|
a5e37af3e8 | ||
|
|
617f8cc204 | ||
|
|
1bd09480e6 | ||
|
|
962cffc9f5 | ||
|
|
820b319474 | ||
|
|
797f5c0e79 | ||
|
|
fc95ee9ead | ||
|
|
d6cf3fec4b | ||
|
|
f0ab7c112e | ||
|
|
8bfcec8ee6 | ||
|
|
9c27ce6d18 | ||
|
|
b3c609a549 | ||
|
|
29020bcbed | ||
|
|
6ec67d1c4d | ||
|
|
a457e1ef7d | ||
|
|
e4897fa686 | ||
|
|
c02dfaba1a | ||
|
|
54befb5962 | ||
|
|
26f0c4c5b7 | ||
|
|
7f85388eb7 | ||
|
|
3cf2963cd0 | ||
|
|
cc5ef3df16 | ||
|
|
4b72e7d546 | ||
|
|
ba0dead96f |
@@ -0,0 +1,146 @@
|
||||
---
|
||||
date: 2026-05-28
|
||||
title: Rejected Expired Recipient Filters
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Customers need to find (a) envelopes/documents in the `REJECTED` state and (b) envelopes
|
||||
with at least one recipient whose signing link has **expired**. Today the UI only exposes
|
||||
`INBOX / PENDING / COMPLETED / DRAFT / ALL` tabs, and the public API has no way to filter by
|
||||
expired recipient links — forcing a fetch-all-`PENDING`-then-inspect-each-recipient workaround.
|
||||
|
||||
Two key facts from exploration shaped this plan:
|
||||
|
||||
- **`REJECTED` is already fully wired in the backend** — the where-clause (`find-documents.ts`),
|
||||
stats counts (`get-stats.ts`), tRPC response schema, `ExtendedDocumentStatus` enum, and the
|
||||
`FRIENDLY_STATUS_MAP` display all handle it. It is simply absent from the UI tab array.
|
||||
- **Renewing expired links already works.** `resendDocument` refreshes `expiresAt` and clears
|
||||
`expirationNotifiedAt` for unsigned, non-CC recipients (`resend-document.ts:98-121`), exposed
|
||||
publicly via `POST /api/v2/document/redistribute` and `/api/v2/envelope/redistribute` and via the
|
||||
resend/redistribute UI dialogs. No new renew mechanism is needed — only documentation/wording.
|
||||
|
||||
Expiration is a per-recipient condition (not an envelope status). The approved design models it
|
||||
in the UI as an `EXPIRED` **pseudo-status tab** (reusing the existing tab machinery, mirroring how
|
||||
`REJECTED` works) and in the public API as an orthogonal boolean `hasExpiredRecipients`. Both share
|
||||
one EXISTS predicate.
|
||||
|
||||
Definition of "expired recipient" (matches `isRecipientExpired`, `packages/lib/utils/recipients.ts:118`):
|
||||
a `Recipient` with `expiresAt IS NOT NULL AND expiresAt <= now() AND signingStatus = NOT_SIGNED AND role != CC`.
|
||||
|
||||
## Approach
|
||||
|
||||
### A. Shared EXISTS predicate (reused 4x, justified)
|
||||
Add a local `hasExpiredRecipient(eb)` helper — modeled on the existing per-file `recipientExists` /
|
||||
`senderEmailIs` helpers — to `find-documents.ts`, `get-stats.ts`, and `find-envelopes.ts`. It is the
|
||||
single source of truth for the expired condition above (using `new Date()` for `now`, matching the
|
||||
`period` filter's `.toJSDate()` style).
|
||||
|
||||
### B. REJECTED tab (UI only — backend already done)
|
||||
- `apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents._index.tsx`: add
|
||||
`ExtendedDocumentStatus.REJECTED` to the tab array (lines 149-155). Count badge, highlight, and
|
||||
`?status=REJECTED` filtering already work via existing machinery.
|
||||
|
||||
### C. EXPIRED pseudo-status (UI + internal stats)
|
||||
1. `packages/prisma/types/extended-document-status.ts`: add `EXPIRED: 'EXPIRED'`. Internal-only —
|
||||
the public `DocumentStatus` enum is unaffected. This intentionally surfaces TS errors at the three
|
||||
exhaustive/`Record<ExtendedDocumentStatus>` sites below, forcing them to be handled.
|
||||
2. `packages/lib/server-only/document/find-documents.ts`:
|
||||
- Add `.with(ExtendedDocumentStatus.EXPIRED, ...)` to **both** `applyPersonalFilters` and
|
||||
`applyTeamFilters`, mirroring the `COMPLETED` branch's access control (deleted + visibility +
|
||||
owner/recipient access) with `hasExpiredRecipient(eb)` AND-ed in. Do **not** constrain
|
||||
`Envelope.status` — the EXISTS already restricts to unsigned recipients.
|
||||
3. `packages/lib/server-only/document/get-stats.ts`:
|
||||
- Add an `expiredQuery` mirroring `pendingQuery`'s access control + `hasExpiredRecipient(eb)`.
|
||||
- Add it to the `Promise.all`, add `[ExtendedDocumentStatus.EXPIRED]: expired` to the `stats`
|
||||
record. **Do not** add `expired` to the `all` sum (it overlaps `PENDING`).
|
||||
4. `packages/trpc/server/document-router/find-documents-internal.types.ts`: add
|
||||
`[ExtendedDocumentStatus.EXPIRED]: z.number()` to the `stats` response object. (`status` already
|
||||
accepts the extended enum via `z.nativeEnum(ExtendedDocumentStatus)`.)
|
||||
5. `apps/remix/app/components/general/document/document-status.tsx`: add an `EXPIRED` entry to
|
||||
`FRIENDLY_STATUS_MAP` — `label: msg` Expired, an icon (e.g. lucide `TimerOff`, matching the
|
||||
`/sign/$token/expired` page), and a distinct color (e.g. `text-orange-500`) to differentiate from
|
||||
`REJECTED` (red).
|
||||
6. `documents._index.tsx`: add `[ExtendedDocumentStatus.EXPIRED]: 0` to the `stats` `useState`
|
||||
initializer and `ExtendedDocumentStatus.EXPIRED` to the tab array. Final order:
|
||||
`INBOX, PENDING, COMPLETED, DRAFT, REJECTED, EXPIRED, ALL`.
|
||||
7. (Optional, recommended) `apps/remix/app/components/tables/documents-table-empty-state.tsx`: add
|
||||
tailored `EXPIRED` and `REJECTED` empty-state copy (currently both fall through to `.otherwise()`).
|
||||
|
||||
### D. Public API boolean `hasExpiredRecipients` (document + envelope, v2)
|
||||
1. `packages/lib/server-only/document/find-documents.ts`: add `hasExpiredRecipients?: boolean` to
|
||||
`FindDocumentsOptions`; when true, apply `.where((eb) => hasExpiredRecipient(eb))` inside
|
||||
`buildBaseQuery` (orthogonal/additive to any `status`).
|
||||
2. `packages/trpc/server/document-router/find-documents.types.ts`: add a query-safe boolean
|
||||
`hasExpiredRecipients` to `ZFindDocumentsRequestSchema` with a `.describe(...)`. Mirror the
|
||||
existing boolean-query-param handling in `find-document-audit-logs.types.ts`
|
||||
(`filterForRecentActivity`) — avoid raw `z.coerce.boolean()` (the "false" -> true footgun); use a
|
||||
string transform if needed. Pass it through in `find-documents.ts` (public handler).
|
||||
3. `packages/lib/server-only/envelope/find-envelopes.ts`: add `hasExpiredRecipients?: boolean` to
|
||||
`FindEnvelopesOptions` + the `hasExpiredRecipient(eb)` helper + the additive `.where`.
|
||||
4. `packages/trpc/server/envelope-router/find-envelopes.types.ts`: add the same param to
|
||||
`ZFindEnvelopesRequestSchema`; pass it through in the envelope-router find handler.
|
||||
The param auto-appears in the generated `/api/v2/openapi.json`.
|
||||
|
||||
Note: REST v1 `GET /api/v1/documents` is deprecated and lacks status filtering — left unchanged.
|
||||
`REJECTED` is already a valid public `status` value (`DocumentStatus.REJECTED`), so no API change is
|
||||
needed for rejected filtering.
|
||||
|
||||
### E. Renew expired links — documentation only
|
||||
No functional change. Document that resending renews expired links:
|
||||
- Update the `.description` in `packages/trpc/server/document-router/redistribute-document.types.ts`
|
||||
and `packages/trpc/server/envelope-router/redistribute-envelope.types.ts` to state that
|
||||
redistributing refreshes the signing-link expiration for unsigned recipients.
|
||||
- Optionally adjust resend/redistribute dialog copy
|
||||
(`apps/remix/app/components/dialogs/document-resend-dialog.tsx`,
|
||||
`envelope-redistribute-dialog.tsx`) to mention it renews expired links.
|
||||
|
||||
## Files To Modify (summary)
|
||||
|
||||
| Area | File |
|
||||
|------|------|
|
||||
| Enum | `packages/prisma/types/extended-document-status.ts` |
|
||||
| Where-clause + API option | `packages/lib/server-only/document/find-documents.ts` |
|
||||
| Stats counts | `packages/lib/server-only/document/get-stats.ts` |
|
||||
| Envelope find (API) | `packages/lib/server-only/envelope/find-envelopes.ts` |
|
||||
| Internal tRPC stats schema | `packages/trpc/server/document-router/find-documents-internal.types.ts` |
|
||||
| Public doc API schema + handler | `packages/trpc/server/document-router/find-documents.types.ts`, `find-documents.ts` |
|
||||
| Public envelope API schema + handler | `packages/trpc/server/envelope-router/find-envelopes.types.ts`, `find-envelopes.ts` |
|
||||
| Status display | `apps/remix/app/components/general/document/document-status.tsx` |
|
||||
| Tabs + stats init | `apps/remix/app/routes/_authenticated+/t.$teamUrl+/documents._index.tsx` |
|
||||
| Empty state (optional) | `apps/remix/app/components/tables/documents-table-empty-state.tsx` |
|
||||
| Renew docs | `redistribute-document.types.ts`, `redistribute-envelope.types.ts` (+ resend dialogs, optional) |
|
||||
|
||||
## Reused Utilities / Patterns
|
||||
- `recipientExists` / `senderEmailIs` (per-file Kysely EXISTS helpers) — the template for the new
|
||||
`hasExpiredRecipient` helper.
|
||||
- `REJECTED` branches in `find-documents.ts` (lines 279, 416) and `rejectedQuery` in `get-stats.ts`
|
||||
(line 227) — the template for the `EXPIRED` branches / `expiredQuery`.
|
||||
- `isRecipientExpired` (`packages/lib/utils/recipients.ts:118`) — defines the `expiresAt <= now`
|
||||
semantics to match.
|
||||
- Existing tab machinery in `documents._index.tsx` (`getTabHref`, count badge, personal-org `.filter`)
|
||||
— works unchanged for the new tabs.
|
||||
- `resendDocument` / `trpc.document.redistribute` / `trpc.envelope.redistribute` — existing renew path.
|
||||
|
||||
## Verification
|
||||
1. **Typecheck** (the enum change forces all exhaustive/Record sites): `npm run typecheck -w @documenso/remix`.
|
||||
2. **Seed + UI** (dev server already running): seed a team via `seedTeam`, send a document, then:
|
||||
- Reject one as a recipient -> it appears under the new **Rejected** tab with a count.
|
||||
- Force expiry (set a recipient `expiresAt` in the past, e.g. via Prisma Studio or a short
|
||||
`envelopeExpirationPeriod`) -> the doc appears under the new **Expired** tab with a count, and the
|
||||
count excludes signed/CC recipients.
|
||||
3. **Public API**: `GET /api/v2/document?hasExpiredRecipients=true` and
|
||||
`GET /api/v2/envelope?hasExpiredRecipients=true` (Bearer API token) return only envelopes with >=1
|
||||
expired unsigned recipient; confirm `GET /api/v2/document?status=REJECTED` works. Verify the param
|
||||
appears in `/api/v2/openapi.json`.
|
||||
4. **Renew**: on an expired doc, run resend/redistribute (UI dialog or
|
||||
`POST /api/v2/document/redistribute`) -> recipient `expiresAt` is refreshed, the doc leaves the
|
||||
Expired tab, and the signing link no longer redirects to `/sign/$token/expired`.
|
||||
5. **E2E** (optional): extend `packages/app-tests/e2e/envelopes/envelope-expiration-send.spec.ts`
|
||||
with an Expired-tab assertion.
|
||||
6. Do **not** modify/commit `packages/lib/translations/*.po`; run `npm run translate` only if needed
|
||||
for new `msg`/`Trans` strings, and keep generated `.po` files out of the branch.
|
||||
|
||||
## Open Questions
|
||||
- Exact icon/color for the `EXPIRED` tab (proposed: `TimerOff`, `text-orange-500`).
|
||||
- Whether to add the optional tailored empty-state copy now or defer.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
name: create-justification
|
||||
description: Create a new justification file in .agents/justifications/ with a unique three-word ID, frontmatter, and formatted title
|
||||
license: MIT
|
||||
compatibility: opencode
|
||||
metadata:
|
||||
audience: agents
|
||||
workflow: decision-making
|
||||
---
|
||||
|
||||
## What I do
|
||||
|
||||
I help you create new justification files in the `.agents/justifications/` directory. Each justification file gets:
|
||||
|
||||
- A unique three-word identifier (e.g., `swift-emerald-river`)
|
||||
- Frontmatter with the current date and formatted title
|
||||
- Content you provide
|
||||
|
||||
## How to use
|
||||
|
||||
Run the script with a slug and content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-justification.ts "decision-name" "Justification content here"
|
||||
```
|
||||
|
||||
Or use heredoc for multi-line content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-justification.ts "decision-name" << HEREDOC
|
||||
Multi-line
|
||||
justification content
|
||||
goes here
|
||||
HEREDOC
|
||||
```
|
||||
|
||||
## File format
|
||||
|
||||
Files are created as: `{three-word-id}-{slug}.md`
|
||||
|
||||
Example: `swift-emerald-river-decision-name.md`
|
||||
|
||||
The file includes frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
date: 2026-01-13
|
||||
title: Decision Name
|
||||
---
|
||||
|
||||
Your content here
|
||||
```
|
||||
|
||||
## When to use me
|
||||
|
||||
Use this skill when you need to document the reasoning or justification for a decision, approach, or architectural choice. The unique ID ensures no filename conflicts, and the frontmatter provides metadata for organization.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
name: create-plan
|
||||
description: Create a new plan file in .agents/plans/ with a unique three-word ID, frontmatter, and formatted title
|
||||
license: MIT
|
||||
compatibility: opencode
|
||||
metadata:
|
||||
audience: agents
|
||||
workflow: planning
|
||||
---
|
||||
|
||||
## What I do
|
||||
|
||||
I help you create new plan files in the `.agents/plans/` directory. Each plan file gets:
|
||||
|
||||
- A unique three-word identifier (e.g., `happy-blue-moon`)
|
||||
- Frontmatter with the current date and formatted title
|
||||
- Content you provide
|
||||
|
||||
## How to use
|
||||
|
||||
Run the script with a slug and content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-plan.ts "feature-name" "Plan content here"
|
||||
```
|
||||
|
||||
Or use heredoc for multi-line content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-plan.ts "feature-name" << HEREDOC
|
||||
Multi-line
|
||||
plan content
|
||||
goes here
|
||||
HEREDOC
|
||||
```
|
||||
|
||||
## File format
|
||||
|
||||
Files are created as: `{three-word-id}-{slug}.md`
|
||||
|
||||
Example: `happy-blue-moon-feature-name.md`
|
||||
|
||||
The file includes frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
date: 2026-01-13
|
||||
title: Feature Name
|
||||
---
|
||||
|
||||
Your content here
|
||||
```
|
||||
|
||||
## When to use me
|
||||
|
||||
Use this skill when you need to create a new plan document for a feature, task, or project. The unique ID ensures no filename conflicts, and the frontmatter provides metadata for organization.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
name: create-scratch
|
||||
description: Create a new scratch file in .agents/scratches/ with a unique three-word ID, frontmatter, and formatted title
|
||||
license: MIT
|
||||
compatibility: opencode
|
||||
metadata:
|
||||
audience: agents
|
||||
workflow: exploration
|
||||
---
|
||||
|
||||
## What I do
|
||||
|
||||
I help you create new scratch files in the `.agents/scratches/` directory. Each scratch file gets:
|
||||
|
||||
- A unique three-word identifier (e.g., `calm-teal-cloud`)
|
||||
- Frontmatter with the current date and formatted title
|
||||
- Content you provide
|
||||
|
||||
## How to use
|
||||
|
||||
Run the script with a slug and content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-scratch.ts "note-name" "Scratch content here"
|
||||
```
|
||||
|
||||
Or use heredoc for multi-line content:
|
||||
|
||||
```bash
|
||||
npx tsx scripts/create-scratch.ts "note-name" << HEREDOC
|
||||
Multi-line
|
||||
scratch content
|
||||
goes here
|
||||
HEREDOC
|
||||
```
|
||||
|
||||
## File format
|
||||
|
||||
Files are created as: `{three-word-id}-{slug}.md`
|
||||
|
||||
Example: `calm-teal-cloud-note-name.md`
|
||||
|
||||
The file includes frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
date: 2026-01-13
|
||||
title: Note Name
|
||||
---
|
||||
|
||||
Your content here
|
||||
```
|
||||
|
||||
## When to use me
|
||||
|
||||
Use this skill when you need to create a temporary note, exploration document, or scratch pad for ideas. The unique ID ensures no filename conflicts, and the frontmatter provides metadata for organization.
|
||||
@@ -80,6 +80,8 @@ NEXT_PRIVATE_SIGNING_CSC_OAUTH_CLIENT_SECRET=
|
||||
NEXT_PRIVATE_SIGNING_CSC_SIGNATURE_LEVEL=
|
||||
# OPTIONAL: Comma-separated list of timestamp authority URLs for PDF signing (enables LTV and archival timestamps).
|
||||
NEXT_PRIVATE_SIGNING_TIMESTAMP_AUTHORITY=
|
||||
# OPTIONAL: Reason to embed in PDF signatures. Defaults to "Signed by Documenso".
|
||||
NEXT_PRIVATE_SIGNING_REASON=
|
||||
# OPTIONAL: Contact info to embed in PDF signatures. Defaults to the webapp URL.
|
||||
NEXT_PUBLIC_SIGNING_CONTACT_INFO=
|
||||
# OPTIONAL: Set to "true" to use the legacy adbe.pkcs7.detached subfilter instead of ETSI.CAdES.detached.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
name: 'One-Click Deploy Provider Request'
|
||||
description: Request a new one-click deployment provider (Railway, Render, etc.) to be added to our README
|
||||
title: 'One-Click Deploy Provider Request: [Provider Name]'
|
||||
labels: ['deploy-provider-request']
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for your interest in adding a one-click deploy option for Documenso!
|
||||
|
||||
Each provider we list requires us to create, test, and maintain a deployment template, which is ongoing work on top of everything else. To keep this manageable, we ask that providers (or users) **open an issue instead of a PR** so the community can signal interest.
|
||||
|
||||
**How this works:**
|
||||
|
||||
- 👍 this issue if you'd like to see Documenso deployable on this provider.
|
||||
- If community interest is high enough, we'll consider adding it to the README.
|
||||
- Opening an issue is not a guarantee of inclusion. PRs adding badges without a prior issue and demonstrated interest will be closed.
|
||||
- type: input
|
||||
attributes:
|
||||
label: Provider Name
|
||||
placeholder: e.g. Railway
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Provider Website
|
||||
placeholder: e.g. https://railway.com
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Deploy/Template URL
|
||||
description: A link to an existing deployment template or deploy button URL, if one exists.
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Who creates and maintains the deployment template?
|
||||
options:
|
||||
- The provider
|
||||
- Me / the community
|
||||
- Nobody yet
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Testing & Maintenance
|
||||
description: Has the template been tested against the current Documenso release? How are updates handled when Documenso ships breaking changes (env vars, migrations, Docker changes)?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Why this provider?
|
||||
description: Tell us why Documenso users would benefit — existing user base, region coverage, free tier, etc.
|
||||
validations:
|
||||
required: true
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Please check the boxes that apply to this request.
|
||||
options:
|
||||
- label: I have searched existing issues to make sure this provider has not already been requested.
|
||||
- label: I understand that inclusion depends on community interest and is not guaranteed.
|
||||
- label: I understand that PRs adding deploy badges without a prior issue will be closed.
|
||||
@@ -2,7 +2,7 @@ name: 'Setup node'
|
||||
inputs:
|
||||
node_version:
|
||||
required: false
|
||||
default: v22.x
|
||||
default: v24.x
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
|
||||
@@ -15,6 +15,7 @@ jobs:
|
||||
build_app:
|
||||
name: Build App
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -32,6 +33,7 @@ jobs:
|
||||
build_docker:
|
||||
name: Build Docker Image
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -11,6 +11,7 @@ jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
@@ -8,6 +8,7 @@ on:
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
jobs:
|
||||
label-when-assigned:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Label issue
|
||||
uses: actions/github-script@v6
|
||||
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
jobs:
|
||||
label_issues:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
|
||||
@@ -13,6 +13,7 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/labeler@v4
|
||||
with:
|
||||
|
||||
@@ -14,6 +14,7 @@ jobs:
|
||||
build_and_publish_platform_containers:
|
||||
name: Build and publish platform containers
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -78,6 +79,7 @@ jobs:
|
||||
create_and_publish_manifest:
|
||||
name: Create and publish manifest
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
needs: build_and_publish_platform_containers
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
@@ -15,6 +15,7 @@ jobs:
|
||||
validate-pr:
|
||||
name: Validate PR title
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: amannn/action-semantic-pull-request@v5
|
||||
id: lint_pr_title
|
||||
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
@@ -18,6 +18,7 @@ jobs:
|
||||
pull_translations:
|
||||
name: Force pull translations
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
environment: Translations
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -16,6 +16,7 @@ jobs:
|
||||
pull_translations:
|
||||
name: Pull translations
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
environment: Translations
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -14,6 +14,7 @@ jobs:
|
||||
extract_translations:
|
||||
name: Extract and upload translations
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
environment: Translations
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
legacy-peer-deps = true
|
||||
prefer-dedupe = true
|
||||
# min-release-age = 7
|
||||
min-release-age = 7
|
||||
|
||||
+1
-1
@@ -42,8 +42,8 @@ Documenso is an open-source document signing platform built as a **monorepo** us
|
||||
| Package | Description | Port |
|
||||
| -------------------------- | -------------------------------------------------------- | ---- |
|
||||
| `@documenso/remix` | Main application - React Router (Remix) with Hono server | 3000 |
|
||||
| `@documenso/documentation` | Documentation site (Next.js + Nextra) | 3002 |
|
||||
| `@documenso/openpage-api` | Public analytics API | 3003 |
|
||||
| `@documenso/docs` | Documentation site | 3004 |
|
||||
|
||||
### Core Packages (`packages/`)
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ Contact us if you are interested in our Enterprise plan for large organizations
|
||||
|
||||
To run Documenso locally, you will need
|
||||
|
||||
- Node.js (v22 or above)
|
||||
- Node.js (v24 or above)
|
||||
- Postgres SQL Database
|
||||
- Docker (optional)
|
||||
|
||||
@@ -186,21 +186,37 @@ For full instructions, requirements, and configuration details, see the [Self Ho
|
||||
|
||||
### One-Click Deploys
|
||||
|
||||
#### Railway
|
||||
> [!NOTE]
|
||||
> Want to see another provider listed here? Please [open a provider request](https://github.com/documenso/documenso/issues/new?template=deploy-provider-request.yml) instead of a PR so the community can signal interest. PRs adding deploy badges without a prior issue will be closed.
|
||||
|
||||
[](https://railway.com/deploy/DjrRRX?referralCode=EZR3s0&utm_medium=integration&utm_source=template&utm_campaign=generic)
|
||||
|
||||
#### Render
|
||||
|
||||
[](https://render.com/deploy?repo=https://github.com/documenso/documenso)
|
||||
|
||||
#### Koyeb
|
||||
|
||||
[](https://app.koyeb.com/deploy?type=git&repository=github.com/documenso/documenso&branch=main&name=documenso-app&builder=dockerfile&dockerfile=/docker/Dockerfile)
|
||||
|
||||
#### Elestio
|
||||
|
||||
[](https://elest.io/open-source/documenso)
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="200">
|
||||
<a href="https://railway.com/deploy/DjrRRX?referralCode=EZR3s0&utm_medium=integration&utm_source=template&utm_campaign=generic">
|
||||
<img src="https://railway.com/button.svg" alt="Deploy on Railway" height="40" />
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="200">
|
||||
<a href="https://render.com/deploy?repo=https://github.com/documenso/documenso">
|
||||
<img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Render" height="40" />
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="200">
|
||||
<a href="https://app.koyeb.com/deploy?type=git&repository=github.com/documenso/documenso&branch=main&name=documenso-app&builder=dockerfile&dockerfile=/docker/Dockerfile">
|
||||
<img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="40" />
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="200">
|
||||
<a href="https://elest.io/open-source/documenso">
|
||||
<img src="https://elest.io/images/logos/deploy-to-elestio-btn.png" alt="Deploy on Elestio" height="40" />
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="200"></td>
|
||||
<td align="center" width="200"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Security
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ This guide provides a comprehensive troubleshooting matrix for the standard erro
|
||||
| `INVALID_REQUEST` | The overall request is malformed or invalid. | Review your API call parameters, including the URL, query parameters, and headers. Correct the request syntax. |
|
||||
| `RECIPIENT_EXPIRED` | The signing link or recipient access has expired. | Generate and resend a new invitation to the affected recipient. |
|
||||
| `LIMIT_EXCEEDED` | Your account usage quota has been exceeded. | Check your current plan limits. Upgrade your subscription or wait until your billing cycle renews. |
|
||||
| `MISSING_ENV_VAR` | A required environment variable is not configured on the server (500). | Primarily affects self-hosted instances: set the environment variable named in the error message and restart. On Documenso Cloud, contact support. |
|
||||
| `MISSING_SIGNATURE_FIELD` | A signer has no signature field placed on the document (400). Returned when distributing an envelope. | Add at least one signature field for every recipient with a signing role before calling `/envelope/distribute`. |
|
||||
| `NOT_FOUND` | The requested resource could not be found (404). | Verify the resource ID (envelope, document, webhook) passed in the URL. Ensure the resource has not been deleted. |
|
||||
| `NOT_IMPLEMENTED` | The requested feature is not currently supported by the server. | Consult the API documentation to verify available methods. Do not use this endpoint at this time. |
|
||||
| `NOT_SETUP` | The required configuration for this action is incomplete. | Access your account or integration settings and complete the necessary configuration before retrying. |
|
||||
@@ -37,7 +39,28 @@ The following errors occur when attempting to perform actions on an envelope tha
|
||||
| `ENVELOPE_DRAFT` | The action cannot be performed because the envelope is still in a draft state. | Finalize the envelope configuration and transition it to the `PENDING` (sent) state before attempting this operation. |
|
||||
| `ENVELOPE_COMPLETED` | The action cannot be performed because the envelope is already completed. | No further modifications (e.g., adding signers, modifying documents) can be made to an envelope once the signing process is finished. |
|
||||
| `ENVELOPE_REJECTED` | The action cannot be performed because the envelope was rejected by a recipient. | The signing flow is permanently halted. Create a new envelope if you wish to resubmit the document. |
|
||||
| `ENVELOPE_CANCELLED` | The action cannot be performed because the envelope was cancelled (400). | Create a new envelope if you need to restart the signing process. |
|
||||
| `ENVELOPE_LEGACY` | The action cannot be performed because the envelope uses an obsolete format. | This envelope was created with a legacy version of the system. Recreate the envelope using the current API version to interact with it. |
|
||||
| `ENVELOPE_TSP_LOCKED` | An AES/QES envelope cannot be modified after it leaves the draft state (400). | Make changes while the envelope is in `DRAFT`, or create a new envelope. |
|
||||
|
||||
## CSC Signing Errors
|
||||
|
||||
These errors apply to Cloud Signature Consortium (CSC) signing flows.
|
||||
|
||||
| Error Code | Description | Recommended Action |
|
||||
| :--- | :--- | :--- |
|
||||
| `CSC_INSTANCE_MODE_MISMATCH` | The requested signature level does not match the instance's CSC mode (400). | Use the signature level supported by the instance's signing configuration. |
|
||||
| `CSC_UNLICENSED` | CSC signing is not licensed for this instance (403). | Enable the CSC signing license before retrying. |
|
||||
| `CSC_PROVIDER_INFO_FAILED` | The CSC provider's discovery request failed or returned unusable information (500). | Check the provider URL, availability, and OAuth configuration. |
|
||||
| `CSC_PROVIDER_NO_TSA` | A timestamp authority is unavailable or unusable for CSC signing (500). | Configure `NEXT_PRIVATE_SIGNING_TIMESTAMP_AUTHORITY` and verify provider timestamp access. |
|
||||
| `CSC_CREDENTIAL_LIST_EMPTY` | The CSC provider returned no signing credentials for the authenticated user (400). | Enrol a signing credential with the provider, then authenticate again. |
|
||||
| `CSC_CERT_INVALID` | The selected signing certificate is missing, invalid, or outside its validity period (400). | Select or renew a valid certificate, then authenticate again. |
|
||||
| `CSC_ALGORITHM_REFUSED` | The signing credential uses an unsupported key or digest algorithm (400). | Select a credential that satisfies the instance's CSC algorithm policy. |
|
||||
| `CSC_SAD_EXPIRED_PRE_SIGN` | The signature activation data is missing, expired, or unreadable before signing (400). | Repeat the credential authorization flow. |
|
||||
| `CSC_TSP_TIMEOUT` | The trust service provider did not complete the signing request before the timeout (408). | Retry the signing request after checking provider availability. |
|
||||
| `CSC_EMBED_FAILED` | The returned CSC signature could not be embedded into the envelope items (400). | Restart the signing attempt. If it fails again, contact support. |
|
||||
| `CSC_BASE_DOCUMENT_MUTATED` | The document changed between signature preparation and signing (500). | Restart signing from the current envelope state. |
|
||||
| `CSC_REQUEST_FAILED` | A CSC provider request failed without a more specific CSC error (500). | Check provider availability and configuration, then retry. |
|
||||
|
||||
## See Also
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ description: Create, manage, and send documents for signing via the API.
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
This guide may not reflect the latest endpoints or parameters. For an always up-to-date reference,
|
||||
see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
@@ -26,35 +28,62 @@ Each document contains one or more PDF files, a list of recipients, and the fiel
|
||||
|
||||
A document object contains the following properties:
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------------- | -------------- | -------------------------------------------------------------- |
|
||||
| `id` | string | Unique identifier (e.g., `envelope_abc123`) |
|
||||
| `type` | string | `DOCUMENT` or `TEMPLATE` |
|
||||
| `status` | string | Current status: `DRAFT`, `PENDING`, `COMPLETED`, or `REJECTED` |
|
||||
| `title` | string | Document title |
|
||||
| `source` | string | How the document was created: `DOCUMENT`, `TEMPLATE`, `API` |
|
||||
| `visibility` | string | Who can view: `EVERYONE`, `ADMIN`, `MANAGER_AND_ABOVE` |
|
||||
| `externalId` | string \| null | Your custom identifier for the document |
|
||||
| `createdAt` | string | ISO 8601 timestamp |
|
||||
| `updatedAt` | string | ISO 8601 timestamp |
|
||||
| `completedAt` | string \| null | Timestamp when all recipients completed signing |
|
||||
| `deletedAt` | string \| null | Timestamp if soft-deleted |
|
||||
| `recipients` | array | List of recipients and their signing status |
|
||||
| `fields` | array | Signature and form fields on the document |
|
||||
| `envelopeItems` | array | PDF files attached to the document |
|
||||
| `documentMeta` | object | Email settings, redirect URL, signing options |
|
||||
| Property | Type | Description |
|
||||
| ------------------- | -------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `id` | string | Unique identifier (e.g., `envelope_abc123`) |
|
||||
| `secondaryId` | string | Legacy identifier in prefixed form (`document_123` for documents, `template_123` for templates) |
|
||||
| `internalVersion` | number | Internal envelope schema version |
|
||||
| `type` | string | `DOCUMENT` or `TEMPLATE` |
|
||||
| `status` | string | Current status: `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED`, or `CANCELLED` |
|
||||
| `title` | string | Document title |
|
||||
| `source` | string | How the document was created: `DOCUMENT`, `TEMPLATE`, `TEMPLATE_DIRECT_LINK` |
|
||||
| `visibility` | string | Who can view: `EVERYONE`, `ADMIN`, `MANAGER_AND_ABOVE` |
|
||||
| `templateType` | string | Template visibility: `PUBLIC`, `PRIVATE`, or `ORGANISATION` (only meaningful for templates) |
|
||||
| `externalId` | string \| null | Your custom identifier for the document |
|
||||
| `userId` | number | ID of the user who owns the document |
|
||||
| `teamId` | number | ID of the team the document belongs to |
|
||||
| `folderId` | string \| null | ID of the folder containing the document |
|
||||
| `templateId` | number \| null | Legacy ID of the template this document was created from |
|
||||
| `authOptions` | object \| null | Access and action authentication requirements |
|
||||
| `formValues` | object \| null | Pre-filled form values |
|
||||
| `publicTitle` | string | Public title shown on profile and direct-link pages |
|
||||
| `publicDescription` | string | Public description shown on profile and direct-link pages |
|
||||
| `createdAt` | string | ISO 8601 timestamp |
|
||||
| `updatedAt` | string | ISO 8601 timestamp |
|
||||
| `completedAt` | string \| null | Timestamp when all recipients completed signing |
|
||||
| `deletedAt` | string \| null | Timestamp if soft-deleted |
|
||||
| `recipients` | array | List of recipients and their signing status |
|
||||
| `fields` | array | Signature and form fields on the document |
|
||||
| `envelopeItems` | array | PDF files attached to the document |
|
||||
| `directLink` | object \| null | Direct-link signing configuration (`id`, `token`, `enabled`, `directTemplateRecipientId`) |
|
||||
| `team` | object | Owning team (`id`, `url`) |
|
||||
| `user` | object | Document owner (`id`, `name`, `email`) |
|
||||
| `documentMeta` | object | Email settings, redirect URL, signing options |
|
||||
|
||||
Documents created through the API have `source: "DOCUMENT"` — there is no separate `API` source value. To tag documents created by your integration, set `externalId` when creating them.
|
||||
|
||||
### Example Document Object
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "envelope_abc123xyz",
|
||||
"secondaryId": "document_123",
|
||||
"internalVersion": 2,
|
||||
"type": "DOCUMENT",
|
||||
"status": "PENDING",
|
||||
"source": "API",
|
||||
"source": "DOCUMENT",
|
||||
"visibility": "EVERYONE",
|
||||
"templateType": "PRIVATE",
|
||||
"title": "Service Agreement",
|
||||
"externalId": "contract-2025-001",
|
||||
"userId": 1,
|
||||
"teamId": 1,
|
||||
"folderId": null,
|
||||
"templateId": null,
|
||||
"authOptions": null,
|
||||
"formValues": null,
|
||||
"publicTitle": "",
|
||||
"publicDescription": "",
|
||||
"createdAt": "2025-01-15T10:30:00.000Z",
|
||||
"updatedAt": "2025-01-15T10:35:00.000Z",
|
||||
"completedAt": null,
|
||||
@@ -71,23 +100,41 @@ A document object contains the following properties:
|
||||
],
|
||||
"fields": [
|
||||
{
|
||||
"id": "field_123",
|
||||
"id": 123,
|
||||
"secondaryId": "field_abc123",
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 1,
|
||||
"envelopeId": "envelope_abc123xyz",
|
||||
"envelopeItemId": "envelope_item_xyz",
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 80,
|
||||
"width": 30,
|
||||
"height": 5,
|
||||
"recipientId": 1
|
||||
"positionX": "10",
|
||||
"positionY": "80",
|
||||
"width": "30",
|
||||
"height": "5",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": null
|
||||
}
|
||||
],
|
||||
"envelopeItems": [
|
||||
{
|
||||
"id": "envelope_item_xyz",
|
||||
"envelopeId": "envelope_abc123xyz",
|
||||
"documentDataId": "doc_data_abc123",
|
||||
"title": "contract.pdf",
|
||||
"order": 1
|
||||
}
|
||||
],
|
||||
"directLink": null,
|
||||
"team": {
|
||||
"id": 1,
|
||||
"url": "your-team"
|
||||
},
|
||||
"user": {
|
||||
"id": 1,
|
||||
"name": "Jane Smith",
|
||||
"email": "jane@example.com"
|
||||
},
|
||||
"documentMeta": {
|
||||
"subject": "Please sign this document",
|
||||
"message": "Hi, please review and sign this agreement.",
|
||||
@@ -97,6 +144,8 @@ A document object contains the following properties:
|
||||
}
|
||||
```
|
||||
|
||||
Field position and size values are stored as decimals and serialized as strings in API responses.
|
||||
|
||||
## List Documents
|
||||
|
||||
Retrieve a paginated list of documents.
|
||||
@@ -112,7 +161,7 @@ GET /envelope
|
||||
| `page` | integer | Page number (default: 1) |
|
||||
| `perPage` | integer | Results per page (default: 10, max: 100) |
|
||||
| `type` | string | Filter by `DOCUMENT` or `TEMPLATE` |
|
||||
| `status` | string | Filter by status: `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED` |
|
||||
| `status` | string | Filter by status: `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED`, `CANCELLED` |
|
||||
| `source` | string | Filter by creation source |
|
||||
| `folderId` | string | Filter by folder ID |
|
||||
| `orderByColumn` | string | Sort field (only `createdAt` supported) |
|
||||
@@ -152,8 +201,8 @@ const response = await fetch(`${BASE_URL}/envelope`, {
|
||||
},
|
||||
});
|
||||
|
||||
const { data, pagination } = await response.json();
|
||||
console.log(`Found ${pagination.totalItems} documents`);
|
||||
const { data, count } = await response.json();
|
||||
console.log(`Found ${count} documents`);
|
||||
|
||||
// Filter by status
|
||||
const pendingResponse = await fetch(
|
||||
@@ -195,12 +244,10 @@ const pendingDocs = await pendingResponse.json();
|
||||
]
|
||||
}
|
||||
],
|
||||
"pagination": {
|
||||
"page": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 5,
|
||||
"totalItems": 42
|
||||
}
|
||||
"count": 42,
|
||||
"currentPage": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 5
|
||||
}
|
||||
```
|
||||
|
||||
@@ -626,6 +673,72 @@ The response includes signing URLs for each recipient:
|
||||
|
||||
---
|
||||
|
||||
## Cancel Document
|
||||
|
||||
Cancel a pending document. This changes its status from `PENDING` to `CANCELLED`.
|
||||
|
||||
```
|
||||
POST /envelope/cancel
|
||||
```
|
||||
|
||||
### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------ | ------ | -------- | ----------------------------------- |
|
||||
| `envelopeId` | string | Yes | Document ID |
|
||||
| `reason` | string | No | Reason for cancelling the document |
|
||||
|
||||
### Code Examples
|
||||
|
||||
<Tabs items={['curl', 'TypeScript']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/cancel" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"envelopeId": "envelope_abc123",
|
||||
"reason": "The agreement is no longer needed."
|
||||
}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope/cancel', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'api_xxxxxxxxxxxxxxxx',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: 'envelope_abc123',
|
||||
reason: 'The agreement is no longer needed.',
|
||||
}),
|
||||
});
|
||||
|
||||
const { success } = await response.json();
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
### Behavior
|
||||
|
||||
- Only documents in `PENDING` status can be cancelled. Other statuses return `400`.
|
||||
- Cancellation is not idempotent. Cancelling the same document again returns `400`.
|
||||
- The document owner and team members with `MANAGER` or higher permissions can cancel it. Requests for documents you cannot view return `404`; requests for visible documents without sufficient permissions return `401`.
|
||||
- A successful cancellation fires the `DOCUMENT_CANCELLED` webhook.
|
||||
- Cancellation emails are sent only to eligible non-CC, non-rejected recipients who were sent or opened the document.
|
||||
|
||||
---
|
||||
|
||||
## Delete Document
|
||||
|
||||
Delete a document. Completed documents cannot be deleted.
|
||||
@@ -668,7 +781,7 @@ const response = await fetch('https://app.documenso.com/api/v2/envelope/delete',
|
||||
|
||||
const { success } = await response.json();
|
||||
|
||||
````
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
@@ -678,7 +791,7 @@ const { success } = await response.json();
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
````
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -692,9 +805,11 @@ POST /envelope/get-many
|
||||
|
||||
### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------- | ----- | -------- | --------------------- |
|
||||
| `envelopeIds` | array | Yes | Array of document IDs |
|
||||
| Field | Type | Required | Description |
|
||||
| ---------- | ------ | -------- | ---------------------------------------------------------------------------- |
|
||||
| `ids` | object | Yes | ID selector containing `type` and `ids` |
|
||||
| `ids.type` | string | Yes | `envelopeId`, `documentId`, or `templateId` |
|
||||
| `ids.ids` | array | Yes | 1-20 IDs: strings for `envelopeId`; numbers for `documentId` or `templateId` |
|
||||
|
||||
### Code Examples
|
||||
|
||||
@@ -705,12 +820,17 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/get-many" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"envelopeIds": ["envelope_abc123", "envelope_def456", "envelope_ghi789"]
|
||||
"ids": {
|
||||
"type": "envelopeId",
|
||||
"ids": ["envelope_abc123", "envelope_def456", "envelope_ghi789"]
|
||||
}
|
||||
}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const requestedIds = ['envelope_abc123', 'envelope_def456', 'envelope_ghi789'];
|
||||
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope/get-many', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -718,16 +838,36 @@ const response = await fetch('https://app.documenso.com/api/v2/envelope/get-many
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeIds: ['envelope_abc123', 'envelope_def456', 'envelope_ghi789'],
|
||||
ids: {
|
||||
type: 'envelopeId',
|
||||
ids: requestedIds,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const documents = await response.json();
|
||||
const { data } = await response.json();
|
||||
|
||||
````
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "envelope_abc123",
|
||||
"type": "DOCUMENT",
|
||||
"status": "PENDING",
|
||||
"title": "Service Agreement"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The endpoint silently omits envelopes you cannot access instead of returning `404`. Compare `data.length` with `requestedIds.length` to detect omissions.
|
||||
|
||||
---
|
||||
|
||||
## Document Statuses
|
||||
@@ -738,6 +878,7 @@ const documents = await response.json();
|
||||
| `PENDING` | Document has been sent. Waiting for recipients to sign. |
|
||||
| `COMPLETED` | All recipients have signed. Document is sealed. |
|
||||
| `REJECTED` | A recipient rejected the document. |
|
||||
| `CANCELLED` | The document was cancelled by its owner or a team member with `MANAGER` or higher permissions. |
|
||||
|
||||
### Status Transitions
|
||||
|
||||
@@ -745,11 +886,13 @@ const documents = await response.json();
|
||||
flowchart LR
|
||||
DRAFT --> PENDING --> COMPLETED
|
||||
PENDING --> REJECTED
|
||||
PENDING --> CANCELLED
|
||||
```
|
||||
|
||||
- **DRAFT to PENDING**: Call the distribute endpoint
|
||||
- **PENDING to COMPLETED**: All recipients complete their signing
|
||||
- **PENDING to REJECTED**: A recipient rejects the document
|
||||
- **PENDING to CANCELLED**: The document owner or a team member with `MANAGER` or higher permissions cancels the document
|
||||
|
||||
<Callout type="warn">
|
||||
You cannot modify recipients or fields after a document moves to `PENDING` status.
|
||||
@@ -771,8 +914,8 @@ flowchart LR
|
||||
| Parameter | Values | Description |
|
||||
| ---------- | ------------------------------------------- | ------------------------- |
|
||||
| `type` | `DOCUMENT`, `TEMPLATE` | Filter by envelope type |
|
||||
| `status` | `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED` | Filter by status |
|
||||
| `source` | `DOCUMENT`, `TEMPLATE`, `API` | Filter by creation source |
|
||||
| `status` | `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED`, `CANCELLED` | Filter by status |
|
||||
| `source` | `DOCUMENT`, `TEMPLATE`, `TEMPLATE_DIRECT_LINK` | Filter by creation source |
|
||||
| `folderId` | string | Filter by folder |
|
||||
|
||||
### Sorting
|
||||
@@ -798,10 +941,10 @@ async function getAllPendingDocuments() {
|
||||
},
|
||||
);
|
||||
|
||||
const { data, pagination } = await response.json();
|
||||
const { data, currentPage, totalPages } = await response.json();
|
||||
documents.push(...data);
|
||||
|
||||
hasMore = page < pagination.totalPages;
|
||||
hasMore = currentPage < totalPages;
|
||||
page++;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ description: Add signature and form fields to documents via API.
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
This guide may not reflect the latest endpoints or parameters. For an always up-to-date reference,
|
||||
see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
@@ -19,13 +21,13 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
| `secondaryId` | string | Secondary identifier for audit logs |
|
||||
| `type` | string | Field type (see [Field Types](#field-types)) |
|
||||
| `recipientId` | number | ID of the recipient assigned to this field |
|
||||
| `envelopeId` | number | ID of the parent envelope |
|
||||
| `envelopeId` | string | ID of the parent envelope |
|
||||
| `envelopeItemId` | string | ID of the PDF item the field is placed on |
|
||||
| `page` | number | Page number (1-indexed) |
|
||||
| `positionX` | number | X coordinate as percentage (0-100) |
|
||||
| `positionY` | number | Y coordinate as percentage (0-100) |
|
||||
| `width` | number | Width as percentage of page (0-100) |
|
||||
| `height` | number | Height as percentage of page (0-100) |
|
||||
| `positionX` | string | X coordinate as percentage (0-100), a decimal serialized as a string |
|
||||
| `positionY` | string | Y coordinate as percentage (0-100), a decimal serialized as a string |
|
||||
| `width` | string | Width as percentage of page (0-100), a decimal serialized as a string |
|
||||
| `height` | string | Height as percentage of page (0-100), a decimal serialized as a string |
|
||||
| `customText` | string | Value entered by the recipient |
|
||||
| `inserted` | boolean | Whether the field has been completed |
|
||||
| `fieldMeta` | object \| null | Type-specific configuration options |
|
||||
@@ -38,18 +40,19 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
"secondaryId": "field_abc123",
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 123,
|
||||
"envelopeId": 789,
|
||||
"envelopeItemId": "envelope_item_xyz",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 80,
|
||||
"width": 30,
|
||||
"height": 5,
|
||||
"positionX": "10",
|
||||
"positionY": "80",
|
||||
"width": "30",
|
||||
"height": "5",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "signature",
|
||||
"required": true
|
||||
"required": true,
|
||||
"overflow": "auto"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -61,7 +64,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
| Type | Description | Auto-filled |
|
||||
| ---------------- | ----------------------------------------- | ----------- |
|
||||
| `SIGNATURE` | Drawn, typed, or uploaded signature | No |
|
||||
| `FREE_SIGNATURE` | Unrestricted signature without validation | No |
|
||||
| `FREE_SIGNATURE` | Legacy free-form signature. Accepted by the v2 create schema but rejected by the v1 API and unsupported in the signing UI — avoid in new integrations | No |
|
||||
| `INITIALS` | Recipient's initials | No |
|
||||
| `NAME` | Recipient's full name | Yes |
|
||||
| `EMAIL` | Recipient's email address | Yes |
|
||||
@@ -134,10 +137,12 @@ POST /envelope/field/create-many
|
||||
|
||||
### Request Body
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ----------- | ------ | -------- | ------------------------------- |
|
||||
| `documentId`| number | Yes | The document ID |
|
||||
| `fields` | array | Yes | Array of field configurations |
|
||||
| Field | Type | Required | Description |
|
||||
| ------------ | ------ | -------- | ------------------------------- |
|
||||
| `envelopeId` | string | Yes | The envelope ID |
|
||||
| `data` | array | Yes | Array of field configurations |
|
||||
|
||||
Each entry in `data` requires a `type`, a `recipientId`, and a position — either explicit coordinates (`page`, `positionX`, `positionY`, `width`, `height`) or a [text placeholder](#placeholder-based-field-positioning) (`placeholder` with optional `width`, `height`, and `matchAll`). Optional per-entry properties: `envelopeItemId` (which PDF in the envelope to place the field on; defaults to the first item) and `fieldMeta`.
|
||||
|
||||
### Code Examples
|
||||
|
||||
@@ -148,32 +153,32 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/field/create-many" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"documentId": 123,
|
||||
"fields": [
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"data": [
|
||||
{
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 456,
|
||||
"pageNumber": 1,
|
||||
"pageX": 10,
|
||||
"pageY": 80,
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 80,
|
||||
"width": 30,
|
||||
"height": 5
|
||||
},
|
||||
{
|
||||
"type": "DATE",
|
||||
"recipientId": 456,
|
||||
"pageNumber": 1,
|
||||
"pageX": 50,
|
||||
"pageY": 80,
|
||||
"page": 1,
|
||||
"positionX": 50,
|
||||
"positionY": 80,
|
||||
"width": 20,
|
||||
"height": 3
|
||||
},
|
||||
{
|
||||
"type": "TEXT",
|
||||
"recipientId": 456,
|
||||
"pageNumber": 1,
|
||||
"pageX": 10,
|
||||
"pageY": 70,
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 70,
|
||||
"width": 40,
|
||||
"height": 4,
|
||||
"fieldMeta": {
|
||||
@@ -199,32 +204,32 @@ const response = await fetch(
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
documentId: 123,
|
||||
fields: [
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{
|
||||
type: 'SIGNATURE',
|
||||
recipientId: 456,
|
||||
pageNumber: 1,
|
||||
pageX: 10,
|
||||
pageY: 80,
|
||||
page: 1,
|
||||
positionX: 10,
|
||||
positionY: 80,
|
||||
width: 30,
|
||||
height: 5,
|
||||
},
|
||||
{
|
||||
type: 'DATE',
|
||||
recipientId: 456,
|
||||
pageNumber: 1,
|
||||
pageX: 50,
|
||||
pageY: 80,
|
||||
page: 1,
|
||||
positionX: 50,
|
||||
positionY: 80,
|
||||
width: 20,
|
||||
height: 3,
|
||||
},
|
||||
{
|
||||
type: 'TEXT',
|
||||
recipientId: 456,
|
||||
pageNumber: 1,
|
||||
pageX: 10,
|
||||
pageY: 70,
|
||||
page: 1,
|
||||
positionX: 10,
|
||||
positionY: 70,
|
||||
width: 40,
|
||||
height: 4,
|
||||
fieldMeta: {
|
||||
@@ -239,8 +244,8 @@ const response = await fetch(
|
||||
}
|
||||
);
|
||||
|
||||
const { fields } = await response.json();
|
||||
console.log(`Created ${fields.length} fields`);
|
||||
const { data } = await response.json();
|
||||
console.log(`Created ${data.length} fields`);
|
||||
|
||||
````
|
||||
</Tab>
|
||||
@@ -250,36 +255,68 @@ console.log(`Created ${fields.length} fields`);
|
||||
|
||||
```json
|
||||
{
|
||||
"fields": [
|
||||
"data": [
|
||||
{
|
||||
"id": 101,
|
||||
"secondaryId": "field_abc123",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 456,
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 80,
|
||||
"width": 30,
|
||||
"height": 5
|
||||
"positionX": "10",
|
||||
"positionY": "80",
|
||||
"width": "30",
|
||||
"height": "5",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "signature",
|
||||
"fontSize": 18,
|
||||
"overflow": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"secondaryId": "field_def456",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"type": "DATE",
|
||||
"recipientId": 456,
|
||||
"page": 1,
|
||||
"positionX": 50,
|
||||
"positionY": 80,
|
||||
"width": 20,
|
||||
"height": 3
|
||||
"positionX": "50",
|
||||
"positionY": "80",
|
||||
"width": "20",
|
||||
"height": "3",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "date",
|
||||
"fontSize": 12,
|
||||
"textAlign": "left",
|
||||
"overflow": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 103,
|
||||
"secondaryId": "field_ghi789",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"type": "TEXT",
|
||||
"recipientId": 456,
|
||||
"page": 1,
|
||||
"positionX": 10,
|
||||
"positionY": 70,
|
||||
"width": 40,
|
||||
"height": 4
|
||||
"positionX": "10",
|
||||
"positionY": "70",
|
||||
"width": "40",
|
||||
"height": "4",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "text",
|
||||
"label": "Job Title",
|
||||
"placeholder": "Enter your job title",
|
||||
"required": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -299,8 +336,10 @@ POST /envelope/field/update-many
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------ | ------ | -------- | ----------------------------- |
|
||||
| `documentId` | number | Yes | The document ID |
|
||||
| `fields` | array | Yes | Array of field update objects |
|
||||
| `envelopeId` | string | Yes | The envelope ID |
|
||||
| `data` | array | Yes | Array of field update objects |
|
||||
|
||||
Each entry in `data` requires the field `id` and `type`. Position properties (`page`, `positionX`, `positionY`, `width`, `height`), `envelopeItemId`, and `fieldMeta` are optional — only supplied values are updated. Placeholder positioning is not supported when updating; use coordinates.
|
||||
|
||||
### Code Examples
|
||||
|
||||
@@ -311,17 +350,17 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/field/update-many" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"documentId": 123,
|
||||
"fields": [
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"data": [
|
||||
{
|
||||
"id": 101,
|
||||
"type": "SIGNATURE",
|
||||
"pageY": 85
|
||||
"positionY": 85
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"type": "DATE",
|
||||
"pageY": 85
|
||||
"positionY": 85
|
||||
}
|
||||
]
|
||||
}'
|
||||
@@ -338,16 +377,16 @@ const response = await fetch(
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
documentId: 123,
|
||||
fields: [
|
||||
{ id: 101, type: 'SIGNATURE', pageY: 85 },
|
||||
{ id: 102, type: 'DATE', pageY: 85 },
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{ id: 101, type: 'SIGNATURE', positionY: 85 },
|
||||
{ id: 102, type: 'DATE', positionY: 85 },
|
||||
],
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
const { fields } = await response.json();
|
||||
const { data } = await response.json();
|
||||
|
||||
````
|
||||
</Tab>
|
||||
@@ -357,9 +396,48 @@ const { fields } = await response.json();
|
||||
|
||||
```json
|
||||
{
|
||||
"fields": [
|
||||
{ "id": 101, "type": "SIGNATURE", "positionY": 85 },
|
||||
{ "id": 102, "type": "DATE", "positionY": 85 }
|
||||
"data": [
|
||||
{
|
||||
"id": 101,
|
||||
"secondaryId": "field_abc123",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 456,
|
||||
"page": 1,
|
||||
"positionX": "10",
|
||||
"positionY": "85",
|
||||
"width": "30",
|
||||
"height": "5",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "signature",
|
||||
"fontSize": 18,
|
||||
"overflow": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"secondaryId": "field_def456",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"envelopeItemId": "envelope_item_abcdefhiklmnorst",
|
||||
"type": "DATE",
|
||||
"recipientId": 456,
|
||||
"page": 1,
|
||||
"positionX": "50",
|
||||
"positionY": "85",
|
||||
"width": "20",
|
||||
"height": "3",
|
||||
"customText": "",
|
||||
"inserted": false,
|
||||
"fieldMeta": {
|
||||
"type": "date",
|
||||
"fontSize": 12,
|
||||
"textAlign": "left",
|
||||
"overflow": "auto"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
````
|
||||
@@ -443,8 +521,8 @@ Fields use percentage-based coordinates relative to the PDF page dimensions.
|
||||
(0,0) ─────────────────────────── (100,0)
|
||||
│ │
|
||||
│ ┌─────────┐ │
|
||||
│ │ Field │ (pageX: 10, │
|
||||
│ │ │ pageY: 20, │
|
||||
│ │ Field │ (positionX: 10, │
|
||||
│ │ │ positionY: 20, │
|
||||
│ └─────────┘ width: 30, │
|
||||
│ height: 5) │
|
||||
│ │
|
||||
@@ -457,9 +535,9 @@ Fields use percentage-based coordinates relative to the PDF page dimensions.
|
||||
const field = {
|
||||
type: 'SIGNATURE',
|
||||
recipientId: 123,
|
||||
pageNumber: 1,
|
||||
pageX: 60, // 60% from left
|
||||
pageY: 85, // 85% from top (near bottom)
|
||||
page: 1,
|
||||
positionX: 60, // 60% from left
|
||||
positionY: 85, // 85% from top (near bottom)
|
||||
width: 30, // 30% of page width
|
||||
height: 8, // 8% of page height
|
||||
};
|
||||
@@ -479,6 +557,33 @@ This approach is useful when generating PDFs programmatically or using templates
|
||||
|
||||
See the [PDF Placeholders](/docs/users/documents/advanced/pdf-placeholders) guide for the full placeholder format reference, including supported field types, recipient identifiers, and field options.
|
||||
|
||||
### Placeholder Positioning via the API
|
||||
|
||||
`POST /envelope/field/create-many` accepts a placeholder position in place of coordinates. Instead of `page`, `positionX`, `positionY`, `width`, and `height`, pass:
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `placeholder` | string | Yes | Text to search for in the PDF (e.g. `{{name}}`). The field is placed at the bounding box of the first match. |
|
||||
| `width` | number | No | Override the field width. Defaults to the width of the matched text. |
|
||||
| `height` | number | No | Override the field height. Defaults to the height of the matched text. |
|
||||
| `matchAll` | boolean | No | Create a field at every occurrence of the placeholder instead of only the first. |
|
||||
|
||||
```json
|
||||
{
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"data": [
|
||||
{
|
||||
"type": "SIGNATURE",
|
||||
"recipientId": 456,
|
||||
"placeholder": "{{signature}}",
|
||||
"matchAll": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`POST /envelope/field/update-many` does not accept placeholders — field updates are coordinate-only.
|
||||
|
||||
---
|
||||
|
||||
## Field Meta Options
|
||||
@@ -643,15 +748,15 @@ All field types support these base options:
|
||||
Create a document with a signature block containing multiple field types:
|
||||
|
||||
```typescript
|
||||
async function addSignatureBlock(documentId: number, recipientId: number) {
|
||||
const fields = [
|
||||
async function addSignatureBlock(envelopeId: string, recipientId: number) {
|
||||
const data = [
|
||||
// Signature
|
||||
{
|
||||
type: 'SIGNATURE',
|
||||
recipientId,
|
||||
pageNumber: 1,
|
||||
pageX: 10,
|
||||
pageY: 80,
|
||||
page: 1,
|
||||
positionX: 10,
|
||||
positionY: 80,
|
||||
width: 30,
|
||||
height: 8,
|
||||
fieldMeta: {
|
||||
@@ -663,9 +768,9 @@ async function addSignatureBlock(documentId: number, recipientId: number) {
|
||||
{
|
||||
type: 'NAME',
|
||||
recipientId,
|
||||
pageNumber: 1,
|
||||
pageX: 10,
|
||||
pageY: 90,
|
||||
page: 1,
|
||||
positionX: 10,
|
||||
positionY: 90,
|
||||
width: 30,
|
||||
height: 4,
|
||||
fieldMeta: {
|
||||
@@ -677,9 +782,9 @@ async function addSignatureBlock(documentId: number, recipientId: number) {
|
||||
{
|
||||
type: 'DATE',
|
||||
recipientId,
|
||||
pageNumber: 1,
|
||||
pageX: 50,
|
||||
pageY: 80,
|
||||
page: 1,
|
||||
positionX: 50,
|
||||
positionY: 80,
|
||||
width: 20,
|
||||
height: 4,
|
||||
fieldMeta: {
|
||||
@@ -691,9 +796,9 @@ async function addSignatureBlock(documentId: number, recipientId: number) {
|
||||
{
|
||||
type: 'TEXT',
|
||||
recipientId,
|
||||
pageNumber: 1,
|
||||
pageX: 50,
|
||||
pageY: 90,
|
||||
page: 1,
|
||||
positionX: 50,
|
||||
positionY: 90,
|
||||
width: 30,
|
||||
height: 4,
|
||||
fieldMeta: {
|
||||
@@ -710,7 +815,7 @@ async function addSignatureBlock(documentId: number, recipientId: number) {
|
||||
Authorization: 'api_xxxxxxxxxxxxxxxx',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ documentId, fields }),
|
||||
body: JSON.stringify({ envelopeId, data }),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
|
||||
@@ -5,6 +5,8 @@ description: Complete reference for the Documenso REST API.
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
The guides below cover common API patterns but may not reflect the latest endpoints or parameters.
|
||||
For an always up-to-date reference, see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
@@ -58,8 +60,8 @@ Authorization: api_xxxxxxxxxxxxxxxx
|
||||
href="/docs/developers/api/templates"
|
||||
/>
|
||||
<Card
|
||||
title="Teams"
|
||||
description="Manage teams and team members."
|
||||
title="Team-scoped access"
|
||||
description="Use team-scoped API tokens with envelope endpoints."
|
||||
href="/docs/developers/api/teams"
|
||||
/>
|
||||
</Cards>
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"teams",
|
||||
"rate-limits",
|
||||
"versioning",
|
||||
"migrate-to-envelopes",
|
||||
"developer-mode",
|
||||
"common-errors"
|
||||
]
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
---
|
||||
title: Migrating to Envelopes
|
||||
description: Why Documenso unified documents and templates into envelopes, and how to migrate from the deprecated document and template create endpoints.
|
||||
---
|
||||
|
||||
import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
## Summary
|
||||
|
||||
The following items have been deprecated and will be removed on the <strong>1st of March 2027</strong>:
|
||||
|
||||
- <strong>API V1</strong>
|
||||
- <strong>A subset of SDK/API V2 endpoints</strong>
|
||||
- <strong>Legacy documents and templates</strong>
|
||||
- <strong>EmbedCreateDocumentV1</strong>
|
||||
- <strong>EmbedCreateTemplateV1</strong>
|
||||
- <strong>EmbedUpdateDocumentV1</strong>
|
||||
- <strong>EmbedUpdateTemplateV1</strong>
|
||||
|
||||
The beta endpoint `/api/v2-beta` will also be removed. Use `/api/v2` instead, which is a drop-in replacement.
|
||||
|
||||
Nothing breaks before 1st of March 2027, so you can migrate at your own pace.
|
||||
|
||||
## What are legacy documents and templates
|
||||
|
||||
These are documents and templates created by the following endpoints:
|
||||
|
||||
- `POST /api/v2/document/create`
|
||||
- `POST /api/v2/document/create/beta`
|
||||
- `POST /api/v2/template/create`
|
||||
- `POST /api/v2/template/create/beta`
|
||||
- `POST /api/v1/documents`
|
||||
- `POST /api/v1/templates`
|
||||
- `POST /api/v1/templates/create-document`
|
||||
- `POST /api/v1/templates/generate-document`
|
||||
|
||||
## What replaces legacy documents and templates
|
||||
|
||||
At the end of 2025 we introduced a unified system for documents and templates, called <strong>envelopes</strong>.
|
||||
|
||||
We still reference documents and templates throughout the documentation and application to distinguish them, but internally they are envelopes.
|
||||
|
||||
Moving to the envelope system gives you:
|
||||
|
||||
- **Multiple PDFs in one envelope.** Send several documents to sign in a single request.
|
||||
- **One API for documents and templates.** Learn one set of endpoints instead of two misaligned ones.
|
||||
- **A better editor and signing experience** for you and your recipients.
|
||||
|
||||
## How to migrate
|
||||
|
||||
{/* prettier-ignore */}
|
||||
<Steps>
|
||||
<Step>
|
||||
### Switch to the envelope endpoints
|
||||
|
||||
Replace each deprecated endpoint with its `/api/v2/envelope/*` equivalent from the [mapping tables](#endpoint-mapping-reference) below.
|
||||
</Step>
|
||||
<Step>
|
||||
### Set the envelope `type` on create
|
||||
|
||||
A single endpoint, `POST /api/v2/envelope/create`, can create both documents and templates. Set `type` to `DOCUMENT` or `TEMPLATE`. You can now upload more than one PDF using the `files` field.
|
||||
</Step>
|
||||
<Step>
|
||||
### Update how you store IDs
|
||||
|
||||
Envelope IDs are **strings** (for example `envelope_abc123`), not numbers. Update any code that stores, parses, or compares IDs.
|
||||
</Step>
|
||||
<Step>
|
||||
### Test, then remove the old calls
|
||||
|
||||
Verify the new flow against your account, then delete the deprecated calls.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
The main data differences are as follows:
|
||||
- ID format changed from number to string (e.g. `42` to `envelope_abc123`)
|
||||
- pageNumber becomes page
|
||||
- pageX becomes positionX
|
||||
- pageY becomes positionY
|
||||
|
||||
See the [Documents API](/docs/developers/api/documents) and [Templates API](/docs/developers/api/templates) for the full envelope reference.
|
||||
|
||||
### Deprecated V1 API Endpoints
|
||||
|
||||
Full reference in the [V1 OpenAPI reference](https://openapi-v1.documenso.com).
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| -------------------------------------------------------- | ----------------------------------------------------- |
|
||||
| `GET /api/v1/documents` | `GET /api/v2/envelope` |
|
||||
| `GET /api/v1/documents/{id}` | `GET /api/v2/envelope/{envelopeId}` |
|
||||
| `POST /api/v1/documents` | `POST /api/v2/envelope/create` |
|
||||
| `POST /api/v1/documents/{id}/send` | `POST /api/v2/envelope/distribute` |
|
||||
| `POST /api/v1/documents/{id}/resend` | `POST /api/v2/envelope/redistribute` |
|
||||
| `DELETE /api/v1/documents/{id}` | `POST /api/v2/envelope/delete` |
|
||||
| `GET /api/v1/documents/{id}/download` | `GET /api/v2/envelope/item/{envelopeItemId}/download` |
|
||||
| `POST /api/v1/documents/{id}/recipients` | `POST /api/v2/envelope/recipient/create-many` |
|
||||
| `PATCH /api/v1/documents/{id}/recipients/{recipientId}` | `POST /api/v2/envelope/recipient/update-many` |
|
||||
| `DELETE /api/v1/documents/{id}/recipients/{recipientId}` | `POST /api/v2/envelope/recipient/delete` |
|
||||
| `POST /api/v1/documents/{id}/fields` | `POST /api/v2/envelope/field/create-many` |
|
||||
| `PATCH /api/v1/documents/{id}/fields/{fieldId}` | `POST /api/v2/envelope/field/update-many` |
|
||||
| `DELETE /api/v1/documents/{id}/fields/{fieldId}` | `POST /api/v2/envelope/field/delete` |
|
||||
| `GET /api/v1/templates` | `GET /api/v2/envelope` (with `type=TEMPLATE`) |
|
||||
| `GET /api/v1/templates/{id}` | `GET /api/v2/envelope/{envelopeId}` |
|
||||
| `POST /api/v1/templates` | `POST /api/v2/envelope/create` (`type=TEMPLATE`) |
|
||||
| `DELETE /api/v1/templates/{id}` | `POST /api/v2/envelope/delete` |
|
||||
| `POST /api/v1/templates/{templateId}/create-document` | `POST /api/v2/envelope/use` |
|
||||
| `POST /api/v1/templates/{templateId}/generate-document` | `POST /api/v2/envelope/use` |
|
||||
|
||||
### Deprecated V2 API Endpoints
|
||||
|
||||
Full reference in the [V2 OpenAPI reference](https://openapi.documenso.com).
|
||||
|
||||
#### Documents
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ------------------------------------------------- | ----------------------------------------------------- |
|
||||
| `GET /api/v2/document` | `GET /api/v2/envelope` |
|
||||
| `GET /api/v2/document/{documentId}` | `GET /api/v2/envelope/{envelopeId}` |
|
||||
| `POST /api/v2/document/get-many` | `POST /api/v2/envelope/get-many` (body changes from `documentIds: number[]` to `ids: { type: "documentId"; ids: number[] }`) |
|
||||
| `POST /api/v2/document/create` | `POST /api/v2/envelope/create` |
|
||||
| `POST /api/v2/document/create/beta` | `POST /api/v2/envelope/create` |
|
||||
| `POST /api/v2/document/update` | `POST /api/v2/envelope/update` |
|
||||
| `POST /api/v2/document/delete` | `POST /api/v2/envelope/delete` |
|
||||
| `POST /api/v2/document/duplicate` | `POST /api/v2/envelope/duplicate` |
|
||||
| `POST /api/v2/document/distribute` | `POST /api/v2/envelope/distribute` |
|
||||
| `POST /api/v2/document/redistribute` | `POST /api/v2/envelope/redistribute` |
|
||||
| `GET /api/v2/document/attachment` | `GET /api/v2/envelope/attachment` |
|
||||
| `POST /api/v2/document/attachment/create` | `POST /api/v2/envelope/attachment/create` |
|
||||
| `POST /api/v2/document/attachment/update` | `POST /api/v2/envelope/attachment/update` |
|
||||
| `POST /api/v2/document/attachment/delete` | `POST /api/v2/envelope/attachment/delete` |
|
||||
| `GET /api/v2/document/{documentId}/download` | `GET /api/v2/envelope/item/{envelopeItemId}/download` |
|
||||
| `GET /api/v2/document/{documentId}/download-beta` | `GET /api/v2/envelope/item/{envelopeItemId}/download` |
|
||||
|
||||
#### Templates
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ------------------------------------- | ------------------------------------------------ |
|
||||
| `GET /api/v2/template` | `GET /api/v2/envelope` (with `type=TEMPLATE`) |
|
||||
| `GET /api/v2/template/{templateId}` | `GET /api/v2/envelope/{envelopeId}` |
|
||||
| `POST /api/v2/template/get-many` | `POST /api/v2/envelope/get-many` (body changes from `templateIds: number[]` to `ids: { type: "templateId"; ids: number[] }`) |
|
||||
| `POST /api/v2/template/create` | `POST /api/v2/envelope/create` (`type=TEMPLATE`) |
|
||||
| `POST /api/v2/template/create/beta` | `POST /api/v2/envelope/create` (`type=TEMPLATE`) |
|
||||
| `POST /api/v2/template/update` | `POST /api/v2/envelope/update` |
|
||||
| `POST /api/v2/template/duplicate` | `POST /api/v2/envelope/duplicate` |
|
||||
| `POST /api/v2/template/delete` | `POST /api/v2/envelope/delete` |
|
||||
| `POST /api/v2/template/use` | `POST /api/v2/envelope/use` |
|
||||
| `POST /api/v2/template/direct/create` | **Pending replacement** |
|
||||
| `POST /api/v2/template/direct/delete` | **Pending replacement** |
|
||||
| `POST /api/v2/template/direct/toggle` | **Pending replacement** |
|
||||
|
||||
#### Document fields
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ----------------------------------------- | ----------------------------------------- |
|
||||
| `GET /api/v2/document/field/{fieldId}` | `GET /api/v2/envelope/field/{fieldId}` |
|
||||
| `POST /api/v2/document/field/create` | `POST /api/v2/envelope/field/create-many` |
|
||||
| `POST /api/v2/document/field/create-many` | `POST /api/v2/envelope/field/create-many` |
|
||||
| `POST /api/v2/document/field/update` | `POST /api/v2/envelope/field/update-many` |
|
||||
| `POST /api/v2/document/field/update-many` | `POST /api/v2/envelope/field/update-many` |
|
||||
| `POST /api/v2/document/field/delete` | `POST /api/v2/envelope/field/delete` |
|
||||
|
||||
#### Template fields
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ----------------------------------------- | ----------------------------------------- |
|
||||
| `GET /api/v2/template/field/{fieldId}` | `GET /api/v2/envelope/field/{fieldId}` |
|
||||
| `POST /api/v2/template/field/create` | `POST /api/v2/envelope/field/create-many` |
|
||||
| `POST /api/v2/template/field/create-many` | `POST /api/v2/envelope/field/create-many` |
|
||||
| `POST /api/v2/template/field/update` | `POST /api/v2/envelope/field/update-many` |
|
||||
| `POST /api/v2/template/field/update-many` | `POST /api/v2/envelope/field/update-many` |
|
||||
| `POST /api/v2/template/field/delete` | `POST /api/v2/envelope/field/delete` |
|
||||
|
||||
#### Document recipients
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ---------------------------------------------- | ---------------------------------------------- |
|
||||
| `GET /api/v2/document/recipient/{recipientId}` | `GET /api/v2/envelope/recipient/{recipientId}` |
|
||||
| `POST /api/v2/document/recipient/create` | `POST /api/v2/envelope/recipient/create-many` |
|
||||
| `POST /api/v2/document/recipient/create-many` | `POST /api/v2/envelope/recipient/create-many` |
|
||||
| `POST /api/v2/document/recipient/update` | `POST /api/v2/envelope/recipient/update-many` |
|
||||
| `POST /api/v2/document/recipient/update-many` | `POST /api/v2/envelope/recipient/update-many` |
|
||||
| `POST /api/v2/document/recipient/delete` | `POST /api/v2/envelope/recipient/delete` |
|
||||
|
||||
#### Template recipients
|
||||
|
||||
| Deprecated endpoint | Replacement |
|
||||
| ---------------------------------------------- | ---------------------------------------------- |
|
||||
| `GET /api/v2/template/recipient/{recipientId}` | `GET /api/v2/envelope/recipient/{recipientId}` |
|
||||
| `POST /api/v2/template/recipient/create` | `POST /api/v2/envelope/recipient/create-many` |
|
||||
| `POST /api/v2/template/recipient/create-many` | `POST /api/v2/envelope/recipient/create-many` |
|
||||
| `POST /api/v2/template/recipient/update` | `POST /api/v2/envelope/recipient/update-many` |
|
||||
| `POST /api/v2/template/recipient/update-many` | `POST /api/v2/envelope/recipient/update-many` |
|
||||
| `POST /api/v2/template/recipient/delete` | `POST /api/v2/envelope/recipient/delete` |
|
||||
|
||||
### Embedding components
|
||||
|
||||
| Deprecated component | Replacement |
|
||||
| ----------------------- | --------------------- |
|
||||
| `EmbedCreateDocumentV1` | `EmbedCreateEnvelope` |
|
||||
| `EmbedCreateTemplateV1` | `EmbedCreateEnvelope` |
|
||||
| `EmbedUpdateDocumentV1` | `EmbedUpdateEnvelope` |
|
||||
| `EmbedUpdateTemplateV1` | `EmbedUpdateEnvelope` |
|
||||
|
||||
See the [embedding guide](/docs/developers/embedding) for the envelope components.
|
||||
|
||||
## FAQ
|
||||
|
||||
<Accordions>
|
||||
<Accordion title="What happens on 1 March 2027?">
|
||||
The deprecated V1 API, the V2 endpoints listed above, and the V1 embedding components are removed.
|
||||
Requests to them will fail, so migrate to the envelope API before that date.
|
||||
</Accordion>
|
||||
<Accordion title="Will my existing documents and templates keep working?">
|
||||
Yes. Documents and templates you already created remain in your account and continue to work. They will automatically be converted to envelopes. Only
|
||||
the deprecated endpoints you call are going away. Your data is not deleted.
|
||||
</Accordion>
|
||||
<Accordion title="Do I need a new API token?">
|
||||
No. Authentication is unchanged. The same API token works for the envelope endpoints under
|
||||
`https://app.documenso.com/api/v2`.
|
||||
</Accordion>
|
||||
<Accordion title="What is the difference between a document and a template now?">
|
||||
Both are envelopes, distinguished by a `type` field of `DOCUMENT` or `TEMPLATE`. They share the same
|
||||
endpoints, recipients, fields, and attachments.
|
||||
</Accordion>
|
||||
<Accordion title="I use an official SDK, what should I do?">
|
||||
The function calls to the legacy endpoints will break on the 1st of March 2027. Update to the latest SDK version and switch to its envelope methods.
|
||||
The deprecated document and template methods map to the envelope endpoints in the tables above.
|
||||
</Accordion>
|
||||
<Accordion title="I need more time or help migrating">
|
||||
Reach out to [support@documenso.com](mailto:support@documenso.com) with your use case and we will
|
||||
help you plan the migration.
|
||||
</Accordion>
|
||||
</Accordions>
|
||||
|
||||
## Getting help
|
||||
|
||||
- [V2 OpenAPI reference](https://openapi.documenso.com): the up-to-date envelope API.
|
||||
- [V1 OpenAPI reference](https://openapi-v1.documenso.com): the deprecated V1 API.
|
||||
- [support@documenso.com](mailto:support@documenso.com): migration questions and extensions.
|
||||
|
||||
## See also
|
||||
|
||||
- [Documents API](/docs/developers/api/documents): create and manage envelopes
|
||||
- [Templates API](/docs/developers/api/templates): work with templates and direct links
|
||||
- [Fields API](/docs/developers/api/fields) and [Recipients API](/docs/developers/api/recipients)
|
||||
- [API Versioning](/docs/developers/api/versioning): how Documenso versions the public API
|
||||
@@ -11,10 +11,21 @@ Documenso enforces rate limits on all API endpoints to ensure service stability.
|
||||
|
||||
## HTTP Rate Limits
|
||||
|
||||
**Limit:** 100 requests per minute per IP address
|
||||
The rate limit applies to:
|
||||
|
||||
- `/api/v1/*`
|
||||
- `/api/v2/*`
|
||||
- `/api/v2-beta/*`
|
||||
|
||||
**Limit:** 1000 requests per minute per IP address
|
||||
**Response:** 429 Too Many Requests
|
||||
|
||||
### Rate Limit Response
|
||||
<Callout type="info">
|
||||
This is the global per-IP ceiling. Your organisation may have its own rate limits configured below
|
||||
this value, in which case you can be rate-limited before reaching the global limit.
|
||||
</Callout>
|
||||
|
||||
### Global per-IP 429 Response
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -22,10 +33,22 @@ Documenso enforces rate limits on all API endpoints to ensure service stability.
|
||||
}
|
||||
```
|
||||
|
||||
<Callout type="warn">
|
||||
No rate limit headers are currently provided. When you receive a 429 response, wait at least 60
|
||||
seconds before retrying.
|
||||
</Callout>
|
||||
### Rate Limit Headers
|
||||
|
||||
Responses from `/api/v1/*`, `/api/v2/*`, and `/api/v2-beta/*` include these headers. The only
|
||||
exception is CORS preflight (`OPTIONS`) requests, which are answered before the rate limiter runs
|
||||
and carry no rate limit headers:
|
||||
|
||||
| Header | Description |
|
||||
| ----------------------- | ---------------------------------------------------------------------- |
|
||||
| `X-RateLimit-Limit` | Maximum requests allowed in the current global window |
|
||||
| `X-RateLimit-Remaining` | Requests remaining in the current global window |
|
||||
| `X-RateLimit-Reset` | End of the current global window, as a Unix epoch timestamp in seconds |
|
||||
|
||||
A 429 response from a windowed limiter also includes `Retry-After`, in seconds, with a minimum
|
||||
value of `1`. The global API limit uses fixed, epoch-aligned one-minute buckets, so the actual wait
|
||||
until the next window is between 1 and 60 seconds. Honor `Retry-After` exactly instead of sleeping
|
||||
for a fixed 60 seconds. See the [Retry-After handling example](/docs/developers/examples/common-workflows#error-handling-patterns).
|
||||
|
||||
## Resource Limits
|
||||
|
||||
@@ -39,24 +62,55 @@ Beyond HTTP rate limits, your account has usage limits based on your subscriptio
|
||||
| Total Recipients | 10 | Unlimited | Unlimited | Unlimited |
|
||||
| Direct Templates | 3 | Unlimited | Unlimited | Unlimited |
|
||||
|
||||
### Error Response
|
||||
### Organisation Limit 429 Responses
|
||||
|
||||
When you exceed a resource limit:
|
||||
Organisation windowed limits and organisation monthly quotas produce 429 responses whose body
|
||||
shape depends on the API version, and neither matches the global per-IP limiter's
|
||||
`{ "error": "..." }` body.
|
||||
|
||||
On `/api/v1/*`, the body contains only a message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "You have reached your document limit for this month. Please upgrade your plan.",
|
||||
"code": "LIMIT_EXCEEDED",
|
||||
"statusCode": 400
|
||||
"message": "Too many requests, please try again later. Contact support if you require higher limits."
|
||||
}
|
||||
```
|
||||
|
||||
On `/api/v2/*` and `/api/v2-beta/*`, the body is a structured error object:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Too many requests, please try again later. Contact support if you require higher limits.",
|
||||
"code": "TOO_MANY_REQUESTS",
|
||||
"data": {
|
||||
"code": "TOO_MANY_REQUESTS",
|
||||
"httpStatus": 429,
|
||||
"appError": {
|
||||
"code": "TOO_MANY_REQUESTS",
|
||||
"message": "Too many requests, please try again later. Contact support if you require higher limits."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Organisation windowed limit responses include the `X-RateLimit-*` headers and `Retry-After` for
|
||||
their own window. Monthly quota responses carry no quota-specific rate limit headers or
|
||||
`Retry-After` because the quota is not a time window; rely on the status code and message instead.
|
||||
|
||||
## Error Codes
|
||||
|
||||
| Code | Status | Description |
|
||||
| ------------------- | ------ | ----------------------------- |
|
||||
| `TOO_MANY_REQUESTS` | 429 | HTTP rate limit exceeded |
|
||||
| `LIMIT_EXCEEDED` | 400 | Resource usage limit exceeded |
|
||||
| Code | Status | Description |
|
||||
| ------------------- | ------ | ------------------------------------------------------------------ |
|
||||
| `TOO_MANY_REQUESTS` | 429 | Global per-IP, organisation windowed, or monthly quota exceeded |
|
||||
| `LIMIT_EXCEEDED` | 400 | Resource usage limit exceeded |
|
||||
|
||||
There are three sources of `TOO_MANY_REQUESTS` responses:
|
||||
|
||||
1. The global per-IP limit, returning the `{ "error": "..." }` body shown above.
|
||||
2. Organisation windowed rate limits for the `api`, `document`, and `email` counters.
|
||||
3. Organisation monthly quotas for the same three counters. Every authenticated API request
|
||||
consumes the `api` counter, so any endpoint can return this 429 once the monthly API quota is
|
||||
exhausted — not just envelope-related ones.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ description: Add and manage envelope recipients via API.
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
This guide may not reflect the latest endpoints or parameters. For an always up-to-date reference,
|
||||
see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
@@ -16,7 +18,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
```json
|
||||
{
|
||||
"id": 123,
|
||||
"envelopeId": "clu1abc2def3ghi4jkl",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -134,7 +136,7 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/recipient/create-many" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"envelopeId": "clu1abc2def3ghi4jkl",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"data": [
|
||||
{
|
||||
"email": "signer@example.com",
|
||||
@@ -164,7 +166,7 @@ const response = await fetch(
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: 'clu1abc2def3ghi4jkl',
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{
|
||||
email: 'signer@example.com',
|
||||
@@ -196,7 +198,7 @@ const { data: recipients } = await response.json();
|
||||
"data": [
|
||||
{
|
||||
"id": 789,
|
||||
"envelopeId": "clu1abc2def3ghi4jkl",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -209,7 +211,7 @@ const { data: recipients } = await response.json();
|
||||
},
|
||||
{
|
||||
"id": 790,
|
||||
"envelopeId": "clu1abc2def3ghi4jkl",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "approver@example.com",
|
||||
"name": "Jane Smith",
|
||||
"role": "APPROVER",
|
||||
@@ -262,7 +264,7 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/recipient/update-many" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"envelopeId": "clu1abc2def3ghi4jkl",
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"data": [
|
||||
{
|
||||
"id": 789,
|
||||
@@ -284,7 +286,7 @@ const response = await fetch(
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: 'clu1abc2def3ghi4jkl',
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{
|
||||
id: 789,
|
||||
@@ -387,7 +389,7 @@ const response = await fetch('https://app.documenso.com/api/v2/envelope/recipien
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: 'clu1abc2def3ghi4jkl',
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{
|
||||
email: 'approver@example.com',
|
||||
@@ -462,7 +464,7 @@ const response = await fetch('https://app.documenso.com/api/v2/envelope/recipien
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: 'clu1abc2def3ghi4jkl',
|
||||
envelopeId: 'envelope_abcdefhiklmnorst',
|
||||
data: [
|
||||
{
|
||||
email: 'signer@example.com',
|
||||
|
||||
@@ -1,44 +1,29 @@
|
||||
---
|
||||
title: Teams API
|
||||
description: Manage team resources, documents, and templates with team-scoped API tokens.
|
||||
title: Team-Scoped API Access
|
||||
description: Use team-scoped API tokens with document and template envelopes.
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
This guide may not reflect the latest endpoints or parameters. For an always up-to-date reference,
|
||||
see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
</Callout>
|
||||
|
||||
## Team Object
|
||||
## Team Context
|
||||
|
||||
A team object contains the following properties:
|
||||
<Callout type="info">
|
||||
The V2 REST API does not expose `/team/*` endpoints. Create and manage teams, members, and team
|
||||
settings in the Documenso web application. This page explains how a team-scoped token applies
|
||||
that team context to supported API resources.
|
||||
</Callout>
|
||||
|
||||
| Property | Type | Description |
|
||||
| ----------------- | -------------- | --------------------------------------------------- |
|
||||
| `id` | number | Unique team identifier |
|
||||
| `name` | string | Team display name |
|
||||
| `url` | string | Unique team URL slug |
|
||||
| `createdAt` | string | ISO 8601 timestamp |
|
||||
| `avatarImageId` | string \| null | ID of the team's avatar image |
|
||||
| `organisationId` | string | ID of the parent organisation |
|
||||
| `currentTeamRole` | string | Your role in the team: `ADMIN`, `MANAGER`, `MEMBER` |
|
||||
|
||||
### Example Team Object
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 123,
|
||||
"name": "Engineering",
|
||||
"url": "engineering",
|
||||
"createdAt": "2025-01-15T10:30:00.000Z",
|
||||
"avatarImageId": null,
|
||||
"organisationId": "org_abc123",
|
||||
"currentTeamRole": "ADMIN"
|
||||
}
|
||||
```
|
||||
The API resolves the team from your token. You do not pass a team ID when creating, listing, or
|
||||
using envelopes. The token's team ID determines which resources the request can access.
|
||||
|
||||
## Team-Scoped API Tokens
|
||||
|
||||
@@ -95,7 +80,7 @@ Documents created with a team token belong to that team:
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/create" \
|
||||
-H "Authorization: api_team_xxxxxxxxxxxxxxxx" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: multipart/form-data" \
|
||||
-F 'payload={
|
||||
"type": "DOCUMENT",
|
||||
@@ -156,26 +141,26 @@ Retrieve all documents belonging to the team:
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
# List all team documents
|
||||
curl -X GET "https://app.documenso.com/api/v2/envelope" \
|
||||
-H "Authorization: api_team_xxxxxxxxxxxxxxxx"
|
||||
curl -X GET "https://app.documenso.com/api/v2/envelope?type=DOCUMENT" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx"
|
||||
|
||||
# Filter by status
|
||||
curl -X GET "https://app.documenso.com/api/v2/envelope?status=PENDING" \
|
||||
-H "Authorization: api_team_xxxxxxxxxxxxxxxx"
|
||||
curl -X GET "https://app.documenso.com/api/v2/envelope?type=DOCUMENT&status=PENDING" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx"
|
||||
````
|
||||
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope', {
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope?type=DOCUMENT', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: TEAM_API_TOKEN,
|
||||
},
|
||||
});
|
||||
|
||||
const { data, pagination } = await response.json();
|
||||
console.log(`Found ${pagination.totalItems} team documents`);
|
||||
const { data, count } = await response.json();
|
||||
console.log(`Found ${count} team documents`);
|
||||
|
||||
````
|
||||
</Tab>
|
||||
@@ -190,10 +175,11 @@ Templates created with a team token are shared across the team.
|
||||
<Tabs items={['curl', 'TypeScript']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST "https://app.documenso.com/api/v2/template/create" \
|
||||
-H "Authorization: api_team_xxxxxxxxxxxxxxxx" \
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/create" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-H "Content-Type: multipart/form-data" \
|
||||
-F 'payload={
|
||||
"type": "TEMPLATE",
|
||||
"title": "NDA Template",
|
||||
"recipients": [
|
||||
{
|
||||
@@ -223,6 +209,7 @@ curl -X POST "https://app.documenso.com/api/v2/template/create" \
|
||||
const form = new FormData();
|
||||
|
||||
const payload = {
|
||||
type: 'TEMPLATE',
|
||||
title: 'NDA Template',
|
||||
recipients: [
|
||||
{
|
||||
@@ -249,7 +236,7 @@ form.append('files', fs.createReadStream('./nda-template.pdf'), {
|
||||
contentType: 'application/pdf',
|
||||
});
|
||||
|
||||
const response = await fetch('https://app.documenso.com/api/v2/template/create', {
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope/create', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: TEAM_API_TOKEN,
|
||||
@@ -257,8 +244,8 @@ const response = await fetch('https://app.documenso.com/api/v2/template/create',
|
||||
body: form,
|
||||
});
|
||||
|
||||
const template = await response.json();
|
||||
console.log('Created team template:', template.id);
|
||||
const { id } = await response.json();
|
||||
console.log('Created team template envelope:', id);
|
||||
````
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -268,14 +255,14 @@ console.log('Created team template:', template.id);
|
||||
<Tabs items={['curl', 'TypeScript']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X GET "https://app.documenso.com/api/v2/template" \
|
||||
-H "Authorization: api_team_xxxxxxxxxxxxxxxx"
|
||||
curl -X GET "https://app.documenso.com/api/v2/envelope?type=TEMPLATE" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx"
|
||||
````
|
||||
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch('https://app.documenso.com/api/v2/template', {
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope?type=TEMPLATE', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: TEAM_API_TOKEN,
|
||||
@@ -330,19 +317,19 @@ const SALES_TEAM_TOKEN = process.env.SALES_TEAM_API_TOKEN;
|
||||
const LEGAL_TEAM_TOKEN = process.env.LEGAL_TEAM_API_TOKEN;
|
||||
|
||||
// Get pending documents from sales team
|
||||
const salesResponse = await fetch('https://app.documenso.com/api/v2/envelope?status=PENDING', {
|
||||
const salesResponse = await fetch('https://app.documenso.com/api/v2/envelope?type=DOCUMENT&status=PENDING', {
|
||||
headers: { Authorization: SALES_TEAM_TOKEN },
|
||||
});
|
||||
const salesDocs = await salesResponse.json();
|
||||
|
||||
// Get completed documents from legal team
|
||||
const legalResponse = await fetch('https://app.documenso.com/api/v2/envelope?status=COMPLETED', {
|
||||
const legalResponse = await fetch('https://app.documenso.com/api/v2/envelope?type=DOCUMENT&status=COMPLETED', {
|
||||
headers: { Authorization: LEGAL_TEAM_TOKEN },
|
||||
});
|
||||
const legalDocs = await legalResponse.json();
|
||||
|
||||
console.log(`Sales team: ${salesDocs.pagination.totalItems} pending`);
|
||||
console.log(`Legal team: ${legalDocs.pagination.totalItems} completed`);
|
||||
console.log(`Sales team: ${salesDocs.count} pending`);
|
||||
console.log(`Legal team: ${legalDocs.count} completed`);
|
||||
```
|
||||
|
||||
## Error Responses
|
||||
|
||||
@@ -6,12 +6,201 @@ description: Create documents from reusable templates via API.
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Callout type="warn">
|
||||
This guide may not reflect the latest endpoints or parameters. For an always up-to-date reference,
|
||||
see the [OpenAPI Reference](https://openapi.documenso.com).
|
||||
</Callout>
|
||||
|
||||
## Template Object
|
||||
## Use a Template Envelope
|
||||
|
||||
New integrations should create a document from a template envelope with the Envelope API.
|
||||
|
||||
```
|
||||
POST /envelope/use
|
||||
Content-Type: multipart/form-data
|
||||
```
|
||||
|
||||
The request uses `multipart/form-data`:
|
||||
|
||||
| Part | Type | Required | Description |
|
||||
| --------- | ------- | -------- | ------------------------------------------------------------------ |
|
||||
| `payload` | JSON | Yes | Template envelope ID, recipient details, and document settings |
|
||||
| `files` | File(s) | No | Replacement PDFs referenced by entries in `customDocumentData` |
|
||||
|
||||
### Payload Schema
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------------- | ------- | -------- | ------------------------------------------------------------------------ |
|
||||
| `envelopeId` | string | Yes | ID of the template envelope |
|
||||
| `externalId` | string | No | Your identifier for the created document envelope |
|
||||
| `recipients` | array | No | Recipient details mapped to recipients in the template |
|
||||
| `distributeDocument` | boolean | No | If `true`, create the document as pending and distribute it |
|
||||
| `customDocumentData` | array | No | Maps uploaded replacement PDFs to template envelope items |
|
||||
| `folderId` | string | No | Folder in which to create the document |
|
||||
| `prefillFields` | array | No | Field values to prefill before distribution |
|
||||
| `override` | object | No | Template values to override for the created document |
|
||||
| `attachments` | array | No | Link attachments to add to the document |
|
||||
| `formValues` | object | No | PDF form values to apply |
|
||||
|
||||
Each recipient entry accepts the following fields:
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| -------------- | ------- | -------- | -------------------------------------------- |
|
||||
| `id` | number | Yes | Recipient ID from the template envelope |
|
||||
| `email` | string | Yes | Recipient email address |
|
||||
| `name` | string | No | Recipient display name |
|
||||
| `signingOrder` | number | No | Recipient position in sequential signing |
|
||||
|
||||
Each `customDocumentData` entry maps an uploaded file to a template item:
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | ---------------- | -------- | --------------------------------------------------------------- |
|
||||
| `identifier` | string \| number | Yes | Uploaded filename or zero-based file index |
|
||||
| `envelopeItemId` | string | Yes | Template envelope item whose PDF the uploaded file replaces |
|
||||
|
||||
### Code Examples
|
||||
|
||||
<Tabs items={['curl', 'TypeScript']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/use" \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx" \
|
||||
-F 'payload={
|
||||
"envelopeId": "envelope_template123",
|
||||
"externalId": "contract-2025-001",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 1,
|
||||
"email": "john.doe@example.com",
|
||||
"name": "John Doe"
|
||||
}
|
||||
],
|
||||
"prefillFields": [
|
||||
{
|
||||
"id": 101,
|
||||
"type": "text",
|
||||
"value": "Senior Software Engineer"
|
||||
}
|
||||
],
|
||||
"distributeDocument": false
|
||||
}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const form = new FormData();
|
||||
|
||||
form.append(
|
||||
'payload',
|
||||
JSON.stringify({
|
||||
envelopeId: 'envelope_template123',
|
||||
externalId: 'contract-2025-001',
|
||||
recipients: [
|
||||
{
|
||||
id: 1,
|
||||
email: 'john.doe@example.com',
|
||||
name: 'John Doe',
|
||||
},
|
||||
],
|
||||
prefillFields: [
|
||||
{
|
||||
id: 101,
|
||||
type: 'text',
|
||||
value: 'Senior Software Engineer',
|
||||
},
|
||||
],
|
||||
distributeDocument: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope/use', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'api_xxxxxxxxxxxxxxxx',
|
||||
},
|
||||
body: form,
|
||||
});
|
||||
|
||||
const document = await response.json();
|
||||
console.log('Created document envelope:', document.id);
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "envelope_document123",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "John Doe",
|
||||
"email": "john.doe@example.com",
|
||||
"token": "recipient_token",
|
||||
"role": "SIGNER",
|
||||
"signingOrder": 1,
|
||||
"signingUrl": "https://app.documenso.com/sign/recipient_token"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Distribute the Created Envelope
|
||||
|
||||
If you leave `distributeDocument` unset or set it to `false`, distribute the created document with
|
||||
`POST /envelope/distribute`. Its response confirms delivery and includes each recipient's signing URL.
|
||||
|
||||
```typescript
|
||||
const distributionResponse = await fetch(
|
||||
'https://app.documenso.com/api/v2/envelope/distribute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'api_xxxxxxxxxxxxxxxx',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: document.id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const distribution = await distributionResponse.json();
|
||||
console.log('Signing URL:', distribution.recipients[0].signingUrl);
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"id": "envelope_document123",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "John Doe",
|
||||
"email": "john.doe@example.com",
|
||||
"token": "recipient_token",
|
||||
"role": "SIGNER",
|
||||
"signingOrder": 1,
|
||||
"signingUrl": "https://app.documenso.com/sign/recipient_token"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deprecated Template Endpoint Reference
|
||||
|
||||
<Callout type="warn">
|
||||
Every `/template/*` endpoint below is deprecated. Use the Envelope API for new integrations and
|
||||
follow [Migrating to Envelopes](/docs/developers/api/migrate-to-envelopes) to replace existing calls.
|
||||
The legacy reference remains here to support migrations.
|
||||
</Callout>
|
||||
|
||||
## Legacy Template Object
|
||||
|
||||
A template object contains the following properties:
|
||||
|
||||
@@ -89,7 +278,7 @@ A template object contains the following properties:
|
||||
}
|
||||
```
|
||||
|
||||
## List Templates
|
||||
## List Templates (Deprecated)
|
||||
|
||||
Retrieve a paginated list of templates.
|
||||
|
||||
@@ -137,8 +326,8 @@ const response = await fetch(`${BASE_URL}/template`, {
|
||||
},
|
||||
});
|
||||
|
||||
const { data, pagination } = await response.json();
|
||||
console.log(`Found ${pagination.totalItems} templates`);
|
||||
const { data, count } = await response.json();
|
||||
console.log(`Found ${count} templates`);
|
||||
|
||||
// Filter by type
|
||||
const privateResponse = await fetch(
|
||||
@@ -179,18 +368,16 @@ const privateTemplates = await privateResponse.json();
|
||||
]
|
||||
}
|
||||
],
|
||||
"pagination": {
|
||||
"page": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 3,
|
||||
"totalItems": 25
|
||||
}
|
||||
"count": 25,
|
||||
"currentPage": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 3
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Get Template
|
||||
## Get Template (Deprecated)
|
||||
|
||||
Retrieve a single template by ID.
|
||||
|
||||
@@ -236,9 +423,9 @@ Returns the full template object including recipients, fields, and metadata.
|
||||
|
||||
---
|
||||
|
||||
## Create Document from Template
|
||||
## Create Document from Template (Deprecated)
|
||||
|
||||
Create a new document using a template. This is the primary way to use templates programmatically.
|
||||
Create a new document using the deprecated template endpoint.
|
||||
|
||||
<Callout type="info">
|
||||
This endpoint does not support [PDF placeholder parsing](/docs/users/documents/advanced/pdf-placeholders). Use `POST /envelope/create` for placeholder-based field positioning.
|
||||
@@ -413,32 +600,57 @@ const prefilledDocument = await prefillResponse.json();
|
||||
|
||||
### Response
|
||||
|
||||
Returns the created document object with recipients and signing URLs.
|
||||
The endpoint returns the full legacy document object. The selected fields below show both the numeric
|
||||
legacy `id` and canonical `envelopeId`. Recipient entries do not include a `signingUrl`.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "envelope_xyz789",
|
||||
"type": "DOCUMENT",
|
||||
"id": 789,
|
||||
"envelopeId": "envelope_xyz789",
|
||||
"status": "PENDING",
|
||||
"title": "Employment Contract",
|
||||
"source": "TEMPLATE",
|
||||
"title": "Employment Contract",
|
||||
"externalId": "contract-2025-001",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 1,
|
||||
"envelopeId": "envelope_xyz789",
|
||||
"documentId": 789,
|
||||
"templateId": null,
|
||||
"email": "john.doe@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
"signingStatus": "NOT_SIGNED",
|
||||
"signingUrl": "https://app.documenso.com/sign/abc123"
|
||||
"signingOrder": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
````
|
||||
```
|
||||
|
||||
To send a document created with `distributeDocument: false` and receive signing links, call
|
||||
`POST /envelope/distribute` with its `envelopeId`:
|
||||
|
||||
```typescript
|
||||
const document = await response.json();
|
||||
|
||||
const distributionResponse = await fetch(`${BASE_URL}/envelope/distribute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: document.envelopeId,
|
||||
}),
|
||||
});
|
||||
|
||||
const distribution = await distributionResponse.json();
|
||||
console.log('Signing URL:', distribution.recipients[0].signingUrl);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Override Template Settings
|
||||
## Override Template Settings (Deprecated)
|
||||
|
||||
When creating a document from a template, you can override various settings:
|
||||
|
||||
@@ -486,7 +698,7 @@ const response = await fetch(`${BASE_URL}/template/use`, {
|
||||
|
||||
---
|
||||
|
||||
## Prefill Fields
|
||||
## Prefill Fields (Deprecated)
|
||||
|
||||
Prefill field values when creating a document from a template. This is useful for populating known data before sending.
|
||||
|
||||
@@ -575,7 +787,7 @@ const response = await fetch(`${BASE_URL}/template/use`, {
|
||||
|
||||
---
|
||||
|
||||
## Update Template
|
||||
## Update Template (Deprecated)
|
||||
|
||||
Update a template's properties.
|
||||
|
||||
@@ -641,7 +853,7 @@ const template = await response.json();
|
||||
|
||||
---
|
||||
|
||||
## Duplicate Template
|
||||
## Duplicate Template (Deprecated)
|
||||
|
||||
Create a copy of an existing template.
|
||||
|
||||
@@ -693,7 +905,7 @@ console.log('New template ID:', duplicatedTemplate.id);
|
||||
|
||||
---
|
||||
|
||||
## Delete Template
|
||||
## Delete Template (Deprecated)
|
||||
|
||||
Delete a template.
|
||||
|
||||
@@ -752,7 +964,7 @@ const { success } = await response.json();
|
||||
|
||||
---
|
||||
|
||||
## Direct Link Templates
|
||||
## Direct Link Templates (Deprecated)
|
||||
|
||||
Direct link templates allow recipients to create and sign documents without requiring you to explicitly create each document. When a recipient visits the direct link, a new document is automatically created from the template.
|
||||
|
||||
@@ -896,7 +1108,7 @@ const { success } = await response.json();
|
||||
|
||||
---
|
||||
|
||||
## Custom Document Data
|
||||
## Custom Document Data (Deprecated)
|
||||
|
||||
When creating a document from a template, you can replace the template's PDF with a custom PDF by using the `customDocumentData` parameter. This is useful when you need to generate the PDF dynamically while reusing the template's recipient and field configuration.
|
||||
|
||||
@@ -911,7 +1123,7 @@ See the [OpenAPI Reference](https://openapi.documenso.com) for the full request
|
||||
|
||||
---
|
||||
|
||||
## Template Types
|
||||
## Template Types (Legacy)
|
||||
|
||||
| Type | Description |
|
||||
| --------- | ------------------------------------------------------------------ |
|
||||
@@ -920,7 +1132,7 @@ See the [OpenAPI Reference](https://openapi.documenso.com) for the full request
|
||||
|
||||
---
|
||||
|
||||
## Complete Example: Contract Workflow
|
||||
## Complete Legacy Example: Contract Workflow (Deprecated)
|
||||
|
||||
This example demonstrates a complete workflow for using templates to send contracts.
|
||||
|
||||
@@ -994,16 +1206,29 @@ async function sendEmploymentContract(employeeData: {
|
||||
subject: `Employment Contract for ${employeeData.name}`,
|
||||
message: `Hi ${employeeData.name},\n\nPlease review and sign your employment contract.`,
|
||||
},
|
||||
distributeDocument: true,
|
||||
distributeDocument: false,
|
||||
externalId: `emp-contract-${Date.now()}`,
|
||||
}),
|
||||
});
|
||||
|
||||
const document = await documentResponse.json();
|
||||
|
||||
// 5. Distribute the envelope and get recipient signing links
|
||||
const distributionResponse = await fetch(`${BASE_URL}/envelope/distribute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
envelopeId: document.envelopeId,
|
||||
}),
|
||||
});
|
||||
const distribution = await distributionResponse.json();
|
||||
|
||||
return {
|
||||
documentId: document.id,
|
||||
signingUrl: document.recipients[0].signingUrl,
|
||||
envelopeId: document.envelopeId,
|
||||
signingUrl: distribution.recipients[0].signingUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1016,7 +1241,7 @@ const result = await sendEmploymentContract({
|
||||
startDate: '2025-03-01',
|
||||
});
|
||||
|
||||
console.log('Document created:', result.documentId);
|
||||
console.log('Document created:', result.envelopeId);
|
||||
console.log('Signing URL:', result.signingUrl);
|
||||
````
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ description: Versioning information for the Documenso public API.
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Overview
|
||||
|
||||
Documenso uses API versioning to manage changes to the public API. This allows us to introduce new features, fix bugs, and make other changes without breaking existing integrations.
|
||||
@@ -19,7 +21,16 @@ Also, we may deprecate certain features or endpoints in the API. When we depreca
|
||||
|
||||
---
|
||||
|
||||
## Documents, Templates, and Envelopes
|
||||
|
||||
Documenso has unified documents and templates into a single resource called an **envelope**. New integrations should create documents and templates through the `/envelope/*` endpoints. The `POST /document/create` and `POST /template/create` endpoints (including their `/beta` variants) are deprecated in favor of `POST /envelope/create`.
|
||||
|
||||
See [Migrating to the Envelope API](/docs/developers/api/migrate-to-envelopes) for the rationale and step-by-step migration examples.
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Migrating to the Envelope API](/docs/developers/api/migrate-to-envelopes) - Move from the document and template create endpoints
|
||||
- [Authentication](/docs/developers/getting-started/authentication) - API authentication guide
|
||||
- [Rate Limits](/docs/developers/api/rate-limits) - API rate limit details
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Workflow 1: Send a Document for Signature
|
||||
|
||||
The most common workflow: upload a PDF, add recipients with signature fields, and send for signing.
|
||||
@@ -49,6 +51,7 @@ async function createAndSendDocument(
|
||||
pdfBuffer: Buffer,
|
||||
filename: string,
|
||||
title: string,
|
||||
externalId: string,
|
||||
recipients: Recipient[],
|
||||
): Promise<CreateAndSendResult> {
|
||||
const recipientPayload = recipients.map((recipient, index) => ({
|
||||
@@ -87,6 +90,7 @@ async function createAndSendDocument(
|
||||
JSON.stringify({
|
||||
type: 'DOCUMENT',
|
||||
title,
|
||||
externalId,
|
||||
recipients: recipientPayload,
|
||||
meta: {
|
||||
subject: `Please sign: ${title}`,
|
||||
@@ -143,6 +147,7 @@ const result = await createAndSendDocument(
|
||||
pdfBuffer,
|
||||
'contract.pdf',
|
||||
'Service Agreement',
|
||||
'nda-contract-ndac214',
|
||||
[
|
||||
{ email: 'client@example.com', name: 'John Smith', role: 'SIGNER' },
|
||||
{ email: 'manager@company.com', name: 'Jane Doe', role: 'SIGNER' },
|
||||
@@ -170,6 +175,7 @@ ENVELOPE_RESPONSE=$(curl -s -X POST "${BASE_URL}/envelope/create" \
|
||||
-F 'payload={
|
||||
"type": "DOCUMENT",
|
||||
"title": "Service Agreement",
|
||||
"externalId": "nda-contract-ndac214",
|
||||
"recipients": [
|
||||
{
|
||||
"email": "client@example.com",
|
||||
@@ -239,6 +245,8 @@ echo $DISTRIBUTE_RESPONSE | jq '.recipients[] | {email, signingUrl}'
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
`externalId` is your application's own reference for this document, such as an invoice number or a database key. Documenso stores it on the envelope and repeats it in every webhook as `payload.externalId`, so your handler can match the event to your record without keeping a lookup table of Documenso IDs. To react when everyone has signed, see [Workflow 4](#workflow-4-wait-for-completion-with-webhooks). To fetch the finished PDF, see [Workflow 5](#workflow-5-download-signed-documents).
|
||||
|
||||
---
|
||||
|
||||
## Workflow 2: Create Document from Template with Custom Data
|
||||
@@ -254,8 +262,11 @@ Use templates for repeatable document workflows. This example creates an employm
|
||||
Map template fields by label and build a <code>prefillFields</code> array
|
||||
</Step>
|
||||
<Step>
|
||||
Call <code>POST /template/use</code> with recipients, prefill data, and{' '}
|
||||
<code>distributeDocument: true</code>
|
||||
Call <code>POST /template/use</code> with recipients and prefill data
|
||||
</Step>
|
||||
<Step>
|
||||
Distribute the returned envelope via <code>POST /envelope/distribute</code> and read its signing
|
||||
links
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
@@ -289,7 +300,7 @@ type TemplateRecipient = {
|
||||
async function sendEmploymentContract(
|
||||
templateId: number,
|
||||
employee: EmployeeData,
|
||||
): Promise<{ documentId: string; signingUrl: string }> {
|
||||
): Promise<{ documentId: number; signingUrl: string }> {
|
||||
const templateResponse = await fetch(`${BASE_URL}/template/${templateId}`, {
|
||||
headers: { Authorization: API_TOKEN },
|
||||
});
|
||||
@@ -366,7 +377,6 @@ async function sendEmploymentContract(
|
||||
subject: `Your Employment Contract at ${employee.department}`,
|
||||
message: `Hi ${employee.name},\n\nPlease review and sign your employment contract for the ${employee.position} position.\n\nStart date: ${employee.startDate}`,
|
||||
},
|
||||
distributeDocument: true,
|
||||
externalId: `emp-${Date.now()}-${employee.email.split('@')[0]}`,
|
||||
}),
|
||||
});
|
||||
@@ -378,9 +388,25 @@ async function sendEmploymentContract(
|
||||
|
||||
const document = await createResponse.json();
|
||||
|
||||
const distributeResponse = await fetch(`${BASE_URL}/envelope/distribute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ envelopeId: document.envelopeId }),
|
||||
});
|
||||
|
||||
if (!distributeResponse.ok) {
|
||||
const error = await distributeResponse.json();
|
||||
throw new Error(`Failed to send document: ${error.message}`);
|
||||
}
|
||||
|
||||
const distributeResult = await distributeResponse.json();
|
||||
|
||||
return {
|
||||
documentId: document.id,
|
||||
signingUrl: document.recipients[0].signingUrl,
|
||||
signingUrl: distributeResult.recipients[0].signingUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -445,12 +471,17 @@ RESPONSE=$(curl -s -X POST "${BASE_URL}/template/use" \
|
||||
\"subject\": \"Your Employment Contract\",
|
||||
\"message\": \"Please review and sign your employment contract.\"
|
||||
},
|
||||
\"distributeDocument\": true,
|
||||
\"externalId\": \"emp-$(date +%s)-alice\"
|
||||
}")
|
||||
|
||||
echo "Document created:"
|
||||
echo $RESPONSE | jq '{id, signingUrl: .recipients[0].signingUrl}'
|
||||
ENVELOPE_ID=$(echo $RESPONSE | jq -r '.envelopeId')
|
||||
DISTRIBUTE_RESPONSE=$(curl -s -X POST "${BASE_URL}/envelope/distribute" \
|
||||
-H "Authorization: ${API_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"envelopeId\": \"${ENVELOPE_ID}\"}")
|
||||
|
||||
echo "Document created: $(echo $RESPONSE | jq -r '.id')"
|
||||
echo "Signing URL: $(echo $DISTRIBUTE_RESPONSE | jq -r '.recipients[0].signingUrl')"
|
||||
````
|
||||
|
||||
</Tab>
|
||||
@@ -468,11 +499,13 @@ Send the same document to multiple recipients in parallel. Useful for policy ack
|
||||
Fetch the template and get the signer recipient slot ID
|
||||
</Step>
|
||||
<Step>
|
||||
For each recipient, call <code>POST /template/use</code> with{' '}
|
||||
<code>distributeDocument: true</code>
|
||||
For each recipient, call <code>POST /template/use</code>
|
||||
</Step>
|
||||
<Step>
|
||||
Process in batches with a short delay to respect rate limits (e.g. 100 requests/minute)
|
||||
Distribute each returned envelope via <code>POST /envelope/distribute</code>
|
||||
</Step>
|
||||
<Step>
|
||||
Process in batches with a short delay to respect rate limits (e.g. 1000 requests/minute)
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
@@ -532,7 +565,6 @@ async function bulkSendFromTemplate(
|
||||
recipients: [
|
||||
{ id: signerSlot.id, email: recipient.email, name: recipient.name },
|
||||
],
|
||||
distributeDocument: true,
|
||||
externalId: `bulk-${Date.now()}-${recipient.email}`,
|
||||
}),
|
||||
});
|
||||
@@ -543,10 +575,26 @@ async function bulkSendFromTemplate(
|
||||
}
|
||||
|
||||
const document = await response.json();
|
||||
|
||||
const distributeResponse = await fetch(`${BASE_URL}/envelope/distribute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ envelopeId: document.envelopeId }),
|
||||
});
|
||||
|
||||
if (!distributeResponse.ok) {
|
||||
const error = await distributeResponse.json();
|
||||
throw new Error(error.message || 'Failed to distribute document');
|
||||
}
|
||||
|
||||
const distributeResult = await distributeResponse.json();
|
||||
return {
|
||||
email: recipient.email,
|
||||
envelopeId: document.id,
|
||||
signingUrl: document.recipients[0].signingUrl,
|
||||
envelopeId: document.envelopeId,
|
||||
signingUrl: distributeResult.recipients[0].signingUrl,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -619,14 +667,24 @@ for RECIPIENT in "${RECIPIENTS[@]}"; do
|
||||
\"email\": \"${EMAIL}\",
|
||||
\"name\": \"${NAME}\"
|
||||
}],
|
||||
\"distributeDocument\": true,
|
||||
\"externalId\": \"bulk-$(date +%s)-${EMAIL}\"
|
||||
}")
|
||||
|
||||
if echo $RESPONSE | jq -e '.id' > /dev/null 2>&1; then
|
||||
echo " Success: $(echo $RESPONSE | jq -r '.id')"
|
||||
if echo $RESPONSE | jq -e '.envelopeId' > /dev/null 2>&1; then
|
||||
ENVELOPE_ID=$(echo $RESPONSE | jq -r '.envelopeId')
|
||||
DISTRIBUTE_RESPONSE=$(curl -s -X POST "${BASE_URL}/envelope/distribute" \
|
||||
-H "Authorization: ${API_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"envelopeId\": \"${ENVELOPE_ID}\"}")
|
||||
|
||||
if echo $DISTRIBUTE_RESPONSE | jq -e '.success' > /dev/null 2>&1; then
|
||||
echo " Success: ${ENVELOPE_ID}"
|
||||
echo " Signing URL: $(echo $DISTRIBUTE_RESPONSE | jq -r '.recipients[0].signingUrl')"
|
||||
else
|
||||
echo " Failed to distribute: $(echo $DISTRIBUTE_RESPONSE | jq -r '.message')"
|
||||
fi
|
||||
else
|
||||
echo " Failed: $(echo $RESPONSE | jq -r '.message')"
|
||||
echo " Failed to create: $(echo $RESPONSE | jq -r '.message')"
|
||||
fi
|
||||
|
||||
# Rate limiting delay
|
||||
@@ -638,8 +696,8 @@ done
|
||||
</Tabs>
|
||||
|
||||
<Callout type="info">
|
||||
The API allows 100 requests per minute. For large batches, implement rate limiting with delays
|
||||
between requests to avoid hitting limits.
|
||||
The API allows 1000 requests per minute (your organisation may have its own lower limit). For large
|
||||
batches, implement rate limiting with delays between requests to avoid hitting limits.
|
||||
</Callout>
|
||||
|
||||
---
|
||||
@@ -829,13 +887,15 @@ After a document is completed, download the signed PDF with all signatures embed
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
The `version` query parameter accepts `original`, `pending`, or `signed`.
|
||||
|
||||
<Tabs items={['TypeScript', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const API_TOKEN = process.env.DOCUMENSO_API_TOKEN;
|
||||
const BASE_URL = 'https://app.documenso.com/api/v2';
|
||||
|
||||
type DownloadVersion = 'signed' | 'original';
|
||||
type DownloadVersion = 'original' | 'pending' | 'signed';
|
||||
|
||||
async function downloadDocument(
|
||||
envelopeId: string,
|
||||
@@ -889,7 +949,7 @@ async function downloadAllCompletedDocuments(outputDir: string): Promise<void> {
|
||||
{ headers: { Authorization: API_TOKEN } },
|
||||
);
|
||||
|
||||
const { data, pagination } = await response.json();
|
||||
const { data, count, currentPage, perPage, totalPages } = await response.json();
|
||||
|
||||
for (const envelope of data) {
|
||||
try {
|
||||
@@ -903,8 +963,8 @@ async function downloadAllCompletedDocuments(outputDir: string): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
|
||||
hasMore = page < pagination.totalPages;
|
||||
page++;
|
||||
hasMore = currentPage < totalPages;
|
||||
page = currentPage + 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,9 +1058,12 @@ async function fetchWithRetry(
|
||||
// Retry on rate limit
|
||||
if (response.status === 429) {
|
||||
const retryAfter = response.headers.get('Retry-After');
|
||||
const delay = retryAfter ? parseInt(retryAfter) * 1000 : baseDelayMs * Math.pow(2, attempt);
|
||||
// Honor Retry-After exactly; the cap only applies to the exponential fallback.
|
||||
const delay = retryAfter
|
||||
? parseInt(retryAfter) * 1000
|
||||
: Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
|
||||
console.log(`Rate limited, waiting ${delay}ms...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, maxDelayMs)));
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ title: Examples
|
||||
description: Common integration patterns and end-to-end workflows.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Cards>
|
||||
<Card
|
||||
title="Common Workflows"
|
||||
|
||||
@@ -7,6 +7,8 @@ import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Documenso account (cloud or self-hosted)
|
||||
@@ -22,20 +24,18 @@ import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
{/* prettier-ignore */}
|
||||
<Steps>
|
||||
<Step>
|
||||
### Open settings
|
||||
### Select a team
|
||||
|
||||
- Log in to your Documenso account
|
||||
- Click your avatar in the top right corner
|
||||
- Select **Settings** from the dropdown menu
|
||||
|
||||

|
||||
Log in to Documenso and open the team that the integration should access. API tokens are scoped to a
|
||||
team.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Navigate to the API Tokens tab
|
||||
### Open API Tokens
|
||||
|
||||
Go to **Settings** and open the **API Tokens** tab.
|
||||
Go to **Team Settings** → **API Tokens**, or open
|
||||
`/t/{teamUrl}/settings/tokens` after replacing `{teamUrl}` with your team's URL.
|
||||
|
||||

|
||||
|
||||
@@ -46,7 +46,7 @@ Go to **Settings** and open the **API Tokens** tab.
|
||||
|
||||
- Click **Create Token**
|
||||
- Enter a descriptive name (e.g., `production-backend`, `zapier-integration`)
|
||||
- Select an expiration period: never expires, 7 days, 1 month, 3 months, 6 months, or 1 year
|
||||
- Select an expiration period: 7 days, 1 month, 3 months, 6 months, 12 months, or Never
|
||||
- Click **Create Token**
|
||||
|
||||
</Step>
|
||||
@@ -73,21 +73,21 @@ Include the token in the `Authorization` header of your HTTP requests.
|
||||
### cURL
|
||||
|
||||
```bash
|
||||
curl https://app.documenso.com/api/v2/document \
|
||||
curl https://app.documenso.com/api/v2/envelope \
|
||||
-H "Authorization: api_xxxxxxxxxxxxxxxx"
|
||||
```
|
||||
|
||||
### JavaScript / TypeScript
|
||||
|
||||
```typescript
|
||||
const response = await fetch('https://app.documenso.com/api/v2/document', {
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: 'api_xxxxxxxxxxxxxxxx',
|
||||
},
|
||||
});
|
||||
|
||||
const documents = await response.json();
|
||||
const envelopes = await response.json();
|
||||
```
|
||||
|
||||
### Using the TypeScript SDK
|
||||
@@ -127,7 +127,7 @@ SDKs are available for [TypeScript](https://github.com/documenso/sdk-typescript)
|
||||
|
||||
## Token Security
|
||||
|
||||
API tokens grant full access to your account. Follow these practices to keep them secure:
|
||||
API tokens grant full API access to the team they were created for. Follow these practices to keep them secure:
|
||||
|
||||
- **Never commit tokens to version control.** Use environment variables instead.
|
||||
- **Use descriptive names.** Names like `zapier-prod` or `backend-staging` help you identify token usage.
|
||||
@@ -153,12 +153,11 @@ const client = new Documenso({
|
||||
|
||||
## Token Scope
|
||||
|
||||
API tokens have full access to your account, including:
|
||||
API tokens have full API access to the team they were created for, including:
|
||||
|
||||
- Creating, reading, updating, and deleting documents
|
||||
- Managing recipients and fields
|
||||
- Accessing templates
|
||||
- Managing team resources (if the token owner has team access)
|
||||
|
||||
There is currently no way to create tokens with limited scopes or permissions.
|
||||
|
||||
@@ -169,7 +168,7 @@ To revoke a token:
|
||||
{/* prettier-ignore */}
|
||||
<Steps>
|
||||
<Step>
|
||||
Go to **Settings** > **API Tokens**
|
||||
Go to **Team Settings** → **API Tokens**
|
||||
</Step>
|
||||
<Step>
|
||||
Find the token you want to revoke
|
||||
@@ -192,7 +191,7 @@ Revoked tokens stop working immediately. Any integrations using that token will
|
||||
</Accordion>
|
||||
<Accordion title="401 Unauthorized — Expired token">Create a new token in settings.</Accordion>
|
||||
<Accordion title="403 Forbidden — Token doesn't have access to the resource">
|
||||
Ensure you're accessing resources owned by the token's account.
|
||||
Ensure you're accessing resources owned by the token's team.
|
||||
</Accordion>
|
||||
</Accordions>
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import { Callout } from 'fumadocs-ui/components/callout';
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before starting, you need:
|
||||
@@ -76,12 +78,10 @@ A successful response returns a list of your documents (envelopes):
|
||||
"createdAt": "2025-01-15T10:30:00.000Z"
|
||||
}
|
||||
],
|
||||
"pagination": {
|
||||
"page": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 1,
|
||||
"totalItems": 1
|
||||
}
|
||||
"count": 1,
|
||||
"currentPage": 1,
|
||||
"perPage": 10,
|
||||
"totalPages": 1
|
||||
}
|
||||
````
|
||||
|
||||
@@ -226,9 +226,12 @@ After creating a document, it's in `DRAFT` status. To send it to recipients, use
|
||||
<Tabs items={['curl', 'JavaScript']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/envelope_abc123/distribute" \
|
||||
curl -X POST "https://app.documenso.com/api/v2/envelope/distribute" \
|
||||
-H "Authorization: YOUR_API_TOKEN" \
|
||||
-H "Content-Type: application/json"
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"envelopeId": "envelope_abc123"
|
||||
}'
|
||||
````
|
||||
|
||||
</Tab>
|
||||
@@ -236,16 +239,14 @@ curl -X POST "https://app.documenso.com/api/v2/envelope/envelope_abc123/distribu
|
||||
```javascript
|
||||
const envelopeId = 'envelope_abc123';
|
||||
|
||||
const response = await fetch(
|
||||
`https://app.documenso.com/api/v2/envelope/${envelopeId}/distribute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'YOUR_API_TOKEN',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
const response = await fetch('https://app.documenso.com/api/v2/envelope/distribute', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'YOUR_API_TOKEN',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
body: JSON.stringify({ envelopeId }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Document sent:', data);
|
||||
@@ -335,16 +336,14 @@ async function createAndSendDocument(pdfPath, recipientEmail, recipientName) {
|
||||
console.log('Created envelope:', envelope.id);
|
||||
|
||||
// Step 2: Send the document for signing
|
||||
const distributeResponse = await fetch(
|
||||
`${BASE_URL}/envelope/${envelope.id}/distribute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}
|
||||
);
|
||||
const distributeResponse = await fetch(`${BASE_URL}/envelope/distribute`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': API_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ envelopeId: envelope.id }),
|
||||
});
|
||||
|
||||
if (!distributeResponse.ok) {
|
||||
const error = await distributeResponse.json();
|
||||
@@ -420,9 +419,12 @@ echo "Created envelope: ${ENVELOPE_ID}"
|
||||
# Step 2: Send the document for signing
|
||||
|
||||
echo "Sending document..."
|
||||
curl -s -X POST "${BASE_URL}/envelope/${ENVELOPE_ID}/distribute" \
|
||||
curl -s -X POST "${BASE_URL}/envelope/distribute" \
|
||||
-H "Authorization: ${API_TOKEN}" \
|
||||
-H "Content-Type: application/json"
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"envelopeId\": \"${ENVELOPE_ID}\"
|
||||
}"
|
||||
|
||||
echo "Document sent for signing!"
|
||||
|
||||
@@ -439,7 +441,7 @@ The API returns standard HTTP status codes and JSON error responses:
|
||||
| `400` | Bad request - check your request payload |
|
||||
| `401` | Unauthorized - invalid or missing API token |
|
||||
| `404` | Not found - resource doesn't exist |
|
||||
| `429` | Rate limited - wait 60 seconds and retry |
|
||||
| `429` | Rate limit or plan quota. If `Retry-After` is present, retry the request. |
|
||||
| `500` | Server error - retry or contact support |
|
||||
|
||||
### Error Response Format
|
||||
@@ -483,7 +485,9 @@ The API returns standard HTTP status codes and JSON error responses:
|
||||
|
||||
### Handling Rate Limits
|
||||
|
||||
The API allows 100 requests per minute per IP address. When rate limited, wait at least 60 seconds before retrying:
|
||||
The API has a limit of 1000 requests per minute for each IP address, and your organisation can have a lower limit. Each response includes `X-RateLimit-Remaining` and `X-RateLimit-Reset` (an epoch timestamp in seconds). A windowed rate-limit `429` response includes `Retry-After`. Wait for that number of seconds before you send the request again. A quota `429` response does not include `Retry-After` because a wait cannot correct the quota error. If `Retry-After` is not present, do not send the request again automatically.
|
||||
|
||||
Refer to [Error Handling Patterns](/docs/developers/examples/common-workflows#error-handling-patterns) for more retry information.
|
||||
|
||||
```javascript
|
||||
async function fetchWithRetry(url, options, maxRetries = 3) {
|
||||
@@ -491,8 +495,15 @@ async function fetchWithRetry(url, options, maxRetries = 3) {
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (response.status === 429) {
|
||||
console.log('Rate limited, waiting 60 seconds...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 60000));
|
||||
const retryAfter = response.headers.get('Retry-After');
|
||||
|
||||
if (!retryAfter) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const retryAfterSeconds = Number.parseInt(retryAfter, 10);
|
||||
console.log(`Rate limit. Wait ${retryAfterSeconds} seconds...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, retryAfterSeconds * 1000));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ title: Getting Started
|
||||
description: Get your API key and make your first API call.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Cards>
|
||||
<Card
|
||||
title="Authentication"
|
||||
|
||||
@@ -3,6 +3,8 @@ title: Developer Guide
|
||||
description: Integrate Documenso into your applications using the REST API, webhooks, and embedding options.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Cards>
|
||||
|
||||
@@ -33,13 +33,14 @@ All webhook events share a common structure:
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------------- | --------- | ------------------------------------------------------ |
|
||||
| `id` | number | Document or template ID |
|
||||
| `id` | number | Legacy numeric v1 document or template ID |
|
||||
| `envelopeId` | string | Canonical v2 identifier (`envelope_` + 16 characters) |
|
||||
| `externalId` | string? | External identifier for integration |
|
||||
| `userId` | number | Owner's user ID |
|
||||
| `authOptions` | object? | Document-level authentication options |
|
||||
| `formValues` | object? | PDF form values associated with the document |
|
||||
| `title` | string | Document or template title |
|
||||
| `status` | string | Current status: `DRAFT`, `PENDING`, `COMPLETED` |
|
||||
| `status` | string | Current status: `DRAFT`, `PENDING`, `COMPLETED`, `REJECTED`, `CANCELLED` |
|
||||
| `visibility` | string | Document visibility setting |
|
||||
| `createdAt` | datetime | Document creation timestamp |
|
||||
| `updatedAt` | datetime | Last modification timestamp |
|
||||
@@ -47,8 +48,8 @@ All webhook events share a common structure:
|
||||
| `deletedAt` | datetime? | Deletion timestamp |
|
||||
| `teamId` | number? | Team ID if document belongs to a team |
|
||||
| `templateId` | number? | Template ID if created from a template |
|
||||
| `source` | string | Source: `DOCUMENT` or `TEMPLATE` |
|
||||
| `documentMeta` | object | Document metadata (subject, message, signing options) |
|
||||
| `source` | string | Source: `DOCUMENT`, `TEMPLATE`, or `TEMPLATE_DIRECT_LINK` |
|
||||
| `documentMeta` | object? | Nullable document metadata (subject, message, signing options) |
|
||||
| `recipients` | array | List of recipient objects |
|
||||
| `Recipient` | array | List of recipient objects (legacy, same as recipients) |
|
||||
|
||||
@@ -60,7 +61,6 @@ All webhook events share a common structure:
|
||||
| `subject` | string? | Email subject line |
|
||||
| `message` | string? | Email message body |
|
||||
| `timezone` | string | Timezone for date display |
|
||||
| `password` | string? | Document access password (if set) |
|
||||
| `dateFormat` | string | Date format string |
|
||||
| `redirectUrl` | string? | URL to redirect after signing |
|
||||
| `signingOrder` | string | `PARALLEL` or `SEQUENTIAL` |
|
||||
@@ -77,8 +77,9 @@ All webhook events share a common structure:
|
||||
| Field | Type | Description |
|
||||
| ---------------------- | --------- | ------------------------------------------ |
|
||||
| `id` | number | Recipient ID |
|
||||
| `documentId` | number? | Parent document ID |
|
||||
| `templateId` | number? | Template ID if created from a template |
|
||||
| `envelopeId` | string | Canonical parent envelope ID |
|
||||
| `documentId` | number? | Legacy parent document ID; null for templates |
|
||||
| `templateId` | number? | Legacy parent template ID; null for documents |
|
||||
| `email` | string | Recipient email address |
|
||||
| `name` | string | Recipient name |
|
||||
| `token` | string | Unique signing token |
|
||||
@@ -94,6 +95,8 @@ All webhook events share a common structure:
|
||||
| `sendStatus` | string | `NOT_SENT` or `SENT` |
|
||||
| `rejectionReason` | string? | Reason if recipient rejected |
|
||||
|
||||
Use `recipient.envelopeId` as the reliable parent link. The legacy `documentId` and `templateId` fields depend on the parent envelope type, so one of them is always null.
|
||||
|
||||
---
|
||||
|
||||
## Document Lifecycle Events
|
||||
@@ -111,6 +114,7 @@ Triggered when a new document is created.
|
||||
"event": "DOCUMENT_CREATED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"externalId": null,
|
||||
"userId": 1,
|
||||
"authOptions": null,
|
||||
@@ -129,9 +133,8 @@ Triggered when a new document is created.
|
||||
"id": "doc_meta_123",
|
||||
"subject": "Please sign this document",
|
||||
"message": "Hello, please review and sign this document.",
|
||||
"timezone": "UTC",
|
||||
"password": null,
|
||||
"dateFormat": "MM/DD/YYYY",
|
||||
"timezone": "Etc/UTC",
|
||||
"dateFormat": "yyyy-MM-dd hh:mm a",
|
||||
"redirectUrl": null,
|
||||
"signingOrder": "PARALLEL",
|
||||
"allowDictateNextSigner": false,
|
||||
@@ -145,6 +148,7 @@ Triggered when a new document is created.
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -166,6 +170,7 @@ Triggered when a new document is created.
|
||||
"Recipient": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -203,6 +208,7 @@ The document status changes to `PENDING` and recipients have `sendStatus: "SENT"
|
||||
"event": "DOCUMENT_SENT",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"externalId": null,
|
||||
"userId": 1,
|
||||
"authOptions": null,
|
||||
@@ -221,9 +227,8 @@ The document status changes to `PENDING` and recipients have `sendStatus: "SENT"
|
||||
"id": "doc_meta_123",
|
||||
"subject": "Please sign this document",
|
||||
"message": "Hello, please review and sign this document.",
|
||||
"timezone": "UTC",
|
||||
"password": null,
|
||||
"dateFormat": "MM/DD/YYYY",
|
||||
"timezone": "Etc/UTC",
|
||||
"dateFormat": "yyyy-MM-dd hh:mm a",
|
||||
"redirectUrl": null,
|
||||
"signingOrder": "PARALLEL",
|
||||
"allowDictateNextSigner": false,
|
||||
@@ -237,6 +242,7 @@ The document status changes to `PENDING` and recipients have `sendStatus: "SENT"
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -258,6 +264,7 @@ The document status changes to `PENDING` and recipients have `sendStatus: "SENT"
|
||||
"Recipient": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -295,12 +302,14 @@ The recipient's `readStatus` changes to `OPENED`.
|
||||
"event": "DOCUMENT_OPENED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "PENDING",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -328,6 +337,7 @@ The recipient's `signingStatus` changes to `SIGNED` and `signedAt` is populated.
|
||||
"event": "DOCUMENT_SIGNED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "COMPLETED",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
@@ -335,6 +345,7 @@ The recipient's `signingStatus` changes to `SIGNED` and `signedAt` is populated.
|
||||
"recipients": [
|
||||
{
|
||||
"id": 51,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -361,12 +372,14 @@ Triggered when an individual recipient completes their required action (signing,
|
||||
"event": "DOCUMENT_RECIPIENT_COMPLETED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "PENDING",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -395,6 +408,7 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
"event": "DOCUMENT_COMPLETED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"externalId": null,
|
||||
"userId": 1,
|
||||
"authOptions": null,
|
||||
@@ -413,9 +427,8 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
"id": "doc_meta_123",
|
||||
"subject": "Please sign this document",
|
||||
"message": "Hello, please review and sign this document.",
|
||||
"timezone": "UTC",
|
||||
"password": null,
|
||||
"dateFormat": "MM/DD/YYYY",
|
||||
"timezone": "Etc/UTC",
|
||||
"dateFormat": "yyyy-MM-dd hh:mm a",
|
||||
"redirectUrl": null,
|
||||
"signingOrder": "PARALLEL",
|
||||
"allowDictateNextSigner": false,
|
||||
@@ -429,6 +442,7 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
"recipients": [
|
||||
{
|
||||
"id": 50,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "reviewer@example.com",
|
||||
@@ -451,6 +465,7 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -475,6 +490,7 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
"Recipient": [
|
||||
{
|
||||
"id": 50,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "reviewer@example.com",
|
||||
@@ -497,6 +513,7 @@ The document status changes to `COMPLETED` and `completedAt` is set.
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -537,12 +554,14 @@ The recipient's `signingStatus` changes to `REJECTED` and `rejectionReason` cont
|
||||
"event": "DOCUMENT_REJECTED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "PENDING",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -561,7 +580,7 @@ The recipient's `signingStatus` changes to `REJECTED` and `rejectionReason` cont
|
||||
|
||||
### `document.cancelled`
|
||||
|
||||
Triggered when the document owner or a team member deletes a document. Draft and pending documents are hard-deleted, while completed documents are soft-deleted.
|
||||
Triggered when a pending document is explicitly cancelled with `POST /envelope/cancel`, or when a document owner or team member deletes a document. Deleting a draft or pending document hard-deletes it, while deleting a completed document soft-deletes it.
|
||||
|
||||
This event is **not** triggered when a recipient hides a document from their inbox.
|
||||
|
||||
@@ -572,6 +591,7 @@ This event is **not** triggered when a recipient hides a document from their inb
|
||||
"event": "DOCUMENT_CANCELLED",
|
||||
"payload": {
|
||||
"id": 7,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"externalId": null,
|
||||
"userId": 3,
|
||||
"authOptions": null,
|
||||
@@ -591,7 +611,6 @@ This event is **not** triggered when a recipient hides a document from their inb
|
||||
"subject": "",
|
||||
"message": "",
|
||||
"timezone": "Etc/UTC",
|
||||
"password": null,
|
||||
"dateFormat": "yyyy-MM-dd hh:mm a",
|
||||
"redirectUrl": "",
|
||||
"signingOrder": "PARALLEL",
|
||||
@@ -606,6 +625,7 @@ This event is **not** triggered when a recipient hides a document from their inb
|
||||
"recipients": [
|
||||
{
|
||||
"id": 7,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 7,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -627,6 +647,7 @@ This event is **not** triggered when a recipient hides a document from their inb
|
||||
"Recipient": [
|
||||
{
|
||||
"id": 7,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 7,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
@@ -651,6 +672,45 @@ This event is **not** triggered when a recipient hides a document from their inb
|
||||
}
|
||||
```
|
||||
|
||||
### `recipient.expired`
|
||||
|
||||
Triggered when a recipient's signing deadline passes on a pending document before they sign or reject it.
|
||||
|
||||
**Event name:** `RECIPIENT_EXPIRED`
|
||||
|
||||
The recipient's `expiresAt` contains the signing deadline, and `expirationNotifiedAt` is set when the expiration is processed.
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "RECIPIENT_EXPIRED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "PENDING",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"documentId": 10,
|
||||
"templateId": null,
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
"expiresAt": "2024-04-22T11:51:00.000Z",
|
||||
"expirationNotifiedAt": "2024-04-22T11:52:00.000Z",
|
||||
"readStatus": "OPENED",
|
||||
"signingStatus": "NOT_SIGNED",
|
||||
"sendStatus": "SENT"
|
||||
}
|
||||
]
|
||||
},
|
||||
"createdAt": "2024-04-22T11:52:00.000Z",
|
||||
"webhookEndpoint": "https://your-endpoint.com/webhook"
|
||||
}
|
||||
```
|
||||
|
||||
### `document.reminder.sent`
|
||||
|
||||
Triggered when a reminder email is sent to a recipient who has not yet completed their action.
|
||||
@@ -662,12 +722,14 @@ Triggered when a reminder email is sent to a recipient who has not yet completed
|
||||
"event": "DOCUMENT_REMINDER_SENT",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"status": "PENDING",
|
||||
"title": "contract.pdf",
|
||||
"source": "DOCUMENT",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 52,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"name": "John Doe",
|
||||
"role": "SIGNER",
|
||||
@@ -686,7 +748,7 @@ Triggered when a reminder email is sent to a recipient who has not yet completed
|
||||
|
||||
## Template Events
|
||||
|
||||
Template events track changes to reusable document templates. Template payloads use the same structure as document payloads, with `source` set to `TEMPLATE` and `templateId` populated.
|
||||
Template events track changes to reusable document templates. Template payloads use the same structure as document payloads. For `TEMPLATE_CREATED`, `TEMPLATE_UPDATED`, and `TEMPLATE_DELETED` the template's own legacy numeric ID is in `id` and `templateId` is `null`. Only `TEMPLATE_USED` — whose payload describes the new document envelope created from the template — carries the originating template's legacy ID in `templateId`, with `source` set to `TEMPLATE`.
|
||||
|
||||
### `template.created`
|
||||
|
||||
@@ -699,9 +761,10 @@ Triggered when a new template is created.
|
||||
"event": "TEMPLATE_CREATED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"title": "My Template",
|
||||
"status": "DRAFT",
|
||||
"templateId": 10,
|
||||
"templateId": null,
|
||||
"source": "TEMPLATE",
|
||||
"recipients": []
|
||||
},
|
||||
@@ -721,9 +784,10 @@ Triggered when a template's settings, recipients, or fields are modified.
|
||||
"event": "TEMPLATE_UPDATED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"title": "My Updated Template",
|
||||
"status": "DRAFT",
|
||||
"templateId": 10,
|
||||
"templateId": null,
|
||||
"source": "TEMPLATE",
|
||||
"recipients": []
|
||||
},
|
||||
@@ -743,9 +807,10 @@ Triggered when a template is deleted.
|
||||
"event": "TEMPLATE_DELETED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"title": "Deleted Template",
|
||||
"status": "DRAFT",
|
||||
"templateId": 10,
|
||||
"templateId": null,
|
||||
"source": "TEMPLATE",
|
||||
"recipients": []
|
||||
},
|
||||
@@ -765,6 +830,7 @@ Triggered when a document is created from a template. This event fires alongside
|
||||
"event": "TEMPLATE_USED",
|
||||
"payload": {
|
||||
"id": 10,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"title": "Document from Template",
|
||||
"status": "DRAFT",
|
||||
"templateId": 10,
|
||||
@@ -791,7 +857,8 @@ Triggered when a document is created from a template. This event fires alongside
|
||||
| `DOCUMENT_RECIPIENT_COMPLETED` | Recipient completes their action | Recipient `signingStatus: "SIGNED"`, `signedAt` set |
|
||||
| `DOCUMENT_COMPLETED` | All recipients complete actions | `status: "COMPLETED"`, `completedAt` set |
|
||||
| `DOCUMENT_REJECTED` | Recipient rejects document | Recipient `signingStatus: "REJECTED"`, `rejectionReason` set |
|
||||
| `DOCUMENT_CANCELLED` | Owner or team member deletes document | Document cancelled or deleted |
|
||||
| `DOCUMENT_CANCELLED` | Pending document explicitly cancelled, or document deleted | `status: "CANCELLED"` after explicit cancellation; deletion may remove or soft-delete the document |
|
||||
| `RECIPIENT_EXPIRED` | Recipient signing deadline passes | Recipient `expiresAt` passed, `expirationNotifiedAt` set |
|
||||
| `DOCUMENT_REMINDER_SENT` | Reminder email sent to recipient | No status changes |
|
||||
|
||||
### Template Events
|
||||
@@ -821,7 +888,7 @@ When processing webhook events:
|
||||
**Process idempotently** — Webhooks may be retried, so handle duplicate events
|
||||
</Step>
|
||||
<Step>
|
||||
**Respond quickly** — Return a 200 status code within 30 seconds
|
||||
**Respond quickly** — Return a `2xx` status code within 10 seconds
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ description: Receive real-time notifications for document and template events.
|
||||
2. When an event occurs, Documenso sends an HTTP POST to your URL
|
||||
3. Your application processes the event and responds with 200 OK
|
||||
|
||||
Documenso supports webhook events for the full document lifecycle (created, sent, opened, signed, completed, rejected, cancelled) as well as template events (created, updated, deleted, used).
|
||||
Documenso supports webhook events for the full document lifecycle (created, sent, opened, signed, completed, rejected, cancelled), recipient-level events (recipient completed, reminder sent, recipient expired), and template events (created, updated, deleted, used).
|
||||
|
||||
---
|
||||
|
||||
@@ -42,12 +42,14 @@ Documenso supports webhook events for the full document lifecycle (created, sent
|
||||
"event": "DOCUMENT_COMPLETED",
|
||||
"payload": {
|
||||
"id": 123,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"title": "Contract",
|
||||
"status": "COMPLETED",
|
||||
"completedAt": "2024-01-15T10:30:00.000Z",
|
||||
"recipients": [
|
||||
{
|
||||
"id": 1,
|
||||
"envelopeId": "envelope_abcdefhiklmnorst",
|
||||
"email": "signer@example.com",
|
||||
"signingStatus": "SIGNED"
|
||||
}
|
||||
@@ -58,6 +60,8 @@ Documenso supports webhook events for the full document lifecycle (created, sent
|
||||
}
|
||||
```
|
||||
|
||||
`payload.id` is the legacy numeric v1 ID. Use `payload.envelopeId` as the canonical v2 identifier. Each recipient repeats `envelopeId` as the reliable parent link because the legacy `documentId` and `templateId` fields depend on the parent envelope type, leaving one of them null.
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
@@ -148,7 +148,7 @@ func main() {
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warn">
|
||||
Always respond with a `200 OK` status within 30 seconds. Documenso will retry failed deliveries.
|
||||
Always respond with a `2xx` status within 10 seconds. Documenso will retry failed deliveries according to the configured background-job provider.
|
||||
</Callout>
|
||||
|
||||
## Configuring Webhooks in Documenso via the Dashboard
|
||||
@@ -184,7 +184,7 @@ Fill in the following fields:
|
||||
|
||||
| Field | Description |
|
||||
| ----- | ----------- |
|
||||
| **Webhook URL** | The HTTPS endpoint that will receive webhook events |
|
||||
| **Webhook URL** | The HTTP or HTTPS endpoint that will receive webhook events |
|
||||
| **Events** | Select which events should trigger this webhook |
|
||||
| **Secret** (optional) | A secret key used to sign the payload for verification |
|
||||
</Step>
|
||||
@@ -202,12 +202,21 @@ Your webhook endpoint must meet these requirements:
|
||||
|
||||
| Requirement | Details |
|
||||
| ----------- | ------- |
|
||||
| **Protocol** | HTTPS required (HTTP not allowed in production) |
|
||||
| **Response** | Must return `2xx` status code within 30 seconds |
|
||||
| **Protocol** | HTTP and HTTPS are accepted; use HTTPS in production |
|
||||
| **Response** | Must return a `2xx` status code within 10 seconds |
|
||||
| **Method** | Must accept HTTP POST requests |
|
||||
| **Content-Type** | Must accept `application/json` payloads |
|
||||
| **Availability** | Must be publicly accessible from the internet |
|
||||
|
||||
<Callout type="warn">
|
||||
Documenso performs a best-effort check that rejects webhook URLs which use or resolve to private
|
||||
or loopback addresses. This is not a complete SSRF mitigation — it does not cover DNS rebinding
|
||||
and fails open on DNS lookup errors or timeouts — so self-hosted deployments should still enforce
|
||||
network-level egress rules. Self-hosters that need to deliver to a hostname resolving to a
|
||||
private address can add that hostname to the comma-separated
|
||||
`NEXT_PRIVATE_WEBHOOK_SSRF_BYPASS_HOSTS` environment variable.
|
||||
</Callout>
|
||||
|
||||
<Callout type="info">
|
||||
For local development, use a tunneling service like [ngrok](https://ngrok.com) or [localtunnel](https://localtunnel.me) to expose your local server.
|
||||
</Callout>
|
||||
@@ -225,7 +234,8 @@ When creating a webhook, you can subscribe to one or more events:
|
||||
| `DOCUMENT_RECIPIENT_COMPLETED` | A recipient completes their required action |
|
||||
| `DOCUMENT_COMPLETED` | All recipients have completed their actions |
|
||||
| `DOCUMENT_REJECTED` | A recipient rejects the document |
|
||||
| `DOCUMENT_CANCELLED` | The document owner deletes the document |
|
||||
| `DOCUMENT_CANCELLED` | A pending document is explicitly cancelled or a document owner deletes it |
|
||||
| `RECIPIENT_EXPIRED` | A recipient's signing deadline passes before they sign or reject |
|
||||
| `DOCUMENT_REMINDER_SENT` | A reminder email is sent to a recipient |
|
||||
| `TEMPLATE_CREATED` | A new template is created |
|
||||
| `TEMPLATE_UPDATED` | A template is modified |
|
||||
@@ -294,6 +304,7 @@ Each webhook call shows the following details:
|
||||
- Timestamp
|
||||
- Response code
|
||||
- Request and response bodies
|
||||
- Response headers
|
||||
|
||||
Click any call to see full details including headers and response data.
|
||||
</Step>
|
||||
@@ -318,17 +329,17 @@ Documenso will attempt to deliver the same payload again
|
||||
|
||||
## Retry Policy
|
||||
|
||||
When a webhook delivery fails (non-2xx response or timeout), Documenso automatically retries with exponential backoff:
|
||||
A delivery fails when the endpoint returns a non-`2xx` response, the 10-second timeout expires, or the request fails. Redirects are not followed, so `3xx` responses also fail. Network and SSRF-blocked requests are recorded with response code `0`.
|
||||
|
||||
| Attempt | Delay |
|
||||
| ------- | ----- |
|
||||
| 1 | Immediate |
|
||||
| 2 | 1 minute |
|
||||
| 3 | 5 minutes |
|
||||
| 4 | 30 minutes |
|
||||
| 5 | 2 hours |
|
||||
For self-hosted deployments, retries are handled by the background-job provider selected with `NEXT_PRIVATE_JOBS_PROVIDER`:
|
||||
|
||||
After 5 failed attempts, the webhook is marked as failed and no further automatic retries occur. You can manually resend failed webhooks from the dashboard.
|
||||
| Provider | Total attempts | Retry timing |
|
||||
| -------- | -------------- | ------------ |
|
||||
| Local (default) | 4 | Back-to-back, with no backoff |
|
||||
| BullMQ | 3 | Exponential backoff starting at 1 second |
|
||||
| Inngest | 5 | Inngest platform backoff |
|
||||
|
||||
Only the individual delivery (`WebhookCall`) record is marked as failed. Documenso does not automatically disable the webhook or apply a circuit breaker, so future matching events continue to be delivered. After automatic attempts are exhausted, you can manually resend a failed delivery from the dashboard.
|
||||
|
||||
<Callout type="warn">
|
||||
If your endpoint consistently fails, consider reviewing your server logs and ensuring your endpoint meets all [URL requirements](#webhook-url-requirements).
|
||||
|
||||
@@ -255,6 +255,7 @@ const validEvents = [
|
||||
'DOCUMENT_REJECTED',
|
||||
'DOCUMENT_CANCELLED',
|
||||
'DOCUMENT_REMINDER_SENT',
|
||||
'RECIPIENT_EXPIRED',
|
||||
'TEMPLATE_CREATED',
|
||||
'TEMPLATE_UPDATED',
|
||||
'TEMPLATE_DELETED',
|
||||
|
||||
@@ -41,12 +41,17 @@ When a limit is reached, requests return a `429 Too Many Requests` response with
|
||||
|
||||
| Action | Limit | Window |
|
||||
| --- | --- | --- |
|
||||
| API requests (v1 and v2) | 100 requests | 1 minute |
|
||||
| API requests (v1 and v2) | 1000 requests | 1 minute |
|
||||
| File uploads | 20 requests | 1 minute |
|
||||
| AI features | 3 requests | 1 minute |
|
||||
|
||||
Authentication endpoints (login, signup, password reset, etc.) are also rate-limited to protect against abuse.
|
||||
|
||||
<Callout type="info">
|
||||
The API request limit above is the global per-IP ceiling. Individual organisations also have their
|
||||
own rate limits, which may be configured below this value.
|
||||
</Callout>
|
||||
|
||||
<Callout type="info">
|
||||
Rate limits may vary by plan. Enterprise plans can include higher or custom limits. Contact
|
||||
[sales](https://documen.so/sales) for details.
|
||||
|
||||
@@ -13,7 +13,7 @@ There are three distinct kinds of limit:
|
||||
| ---------------------- | ------------------------------------------------- | ----------------------- |
|
||||
| Resource quota | Documents, emails, and API requests **per month** | Yes — per claim and org |
|
||||
| Resource rate limit | The same resources over a short window (e.g. `1h`) | Yes — per claim and org |
|
||||
| Global HTTP rate limit | API requests per IP (100/min, hardcoded) | No — see [Limitations](#limitations) |
|
||||
| Global HTTP rate limit | API requests per IP (1000/min, hardcoded) | No — see [Limitations](#limitations) |
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -91,7 +91,7 @@ Monthly quota usage is keyed to the **UTC calendar month**. There is no schedule
|
||||
|
||||
## Limitations
|
||||
|
||||
The **global HTTP rate limit is not configurable.** Documenso enforces a hardcoded **100 requests per minute per IP address** on its API endpoint groups (`/api/v1`, `/api/v2`, and the tRPC API are limited separately), returning `429 Too Many Requests`. It is a per-IP safeguard applied at the HTTP layer — not per-organisation, not stored on any claim, and not adjustable from the admin panel. See [Rate Limits](/docs/developers/api/rate-limits).
|
||||
The **global HTTP rate limit is not configurable.** Documenso enforces a hardcoded **1000 requests per minute per IP address** on its API endpoint groups (`/api/v1`, `/api/v2`, and the tRPC API are limited separately), returning `429 Too Many Requests`. It is a per-IP safeguard applied at the HTTP layer — not per-organisation, not stored on any claim, and not adjustable from the admin panel. See [Rate Limits](/docs/developers/api/rate-limits).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ services:
|
||||
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?err}
|
||||
- POSTGRES_DB=${POSTGRES_DB:?err}
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U ${POSTGRES_USER}']
|
||||
test: ['CMD-SHELL', 'pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}']
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
@@ -102,7 +102,7 @@ See [Email Configuration](/docs/self-hosting/configuration/email) for other tran
|
||||
| Variable | Description | Default |
|
||||
| ------------------------------------------- | -------------------------------------------------------------- | ------------------------- |
|
||||
| `PORT` | Port the application listens on | `3000` |
|
||||
| `NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH` | Path to signing certificate inside container | `/opt/documenso/cert.p12` |
|
||||
| `NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH` | Path to signing certificate inside container — set to the volume-mount path (e.g. `/opt/documenso/cert.p12`). Only Docker Compose defaults this; plain `docker run` must set it explicitly | - |
|
||||
| `NEXT_PRIVATE_SIGNING_PASSPHRASE` | Passphrase for the signing certificate | - |
|
||||
| `NEXT_PRIVATE_SIGNING_LOCAL_FILE_CONTENTS` | Base64-encoded `.p12` certificate (alternative to file path) | - |
|
||||
| `NEXT_PUBLIC_UPLOAD_TRANSPORT` | Document storage: `database` or `s3` | `database` |
|
||||
@@ -136,6 +136,7 @@ docker run -d \
|
||||
-e NEXT_PUBLIC_WEBAPP_URL="https://sign.example.com" \
|
||||
-e NEXT_PRIVATE_INTERNAL_WEBAPP_URL="http://localhost:3000" \
|
||||
-e NEXT_PRIVATE_DATABASE_URL="postgresql://user:password@db-host:5432/documenso" \
|
||||
-e NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH="/opt/documenso/cert.p12" \
|
||||
-e NEXT_PRIVATE_SIGNING_PASSPHRASE="your-certificate-password" \
|
||||
-e NEXT_PRIVATE_SMTP_TRANSPORT="smtp-auth" \
|
||||
-e NEXT_PRIVATE_SMTP_HOST="smtp.example.com" \
|
||||
@@ -154,6 +155,12 @@ A signing certificate is required for document signing. You have two options for
|
||||
- **Volume mount** — mount a `.p12` file from the host into the container at `/opt/documenso/cert.p12` (shown above). This is the simplest approach for small to moderate deployments.
|
||||
- **Base64-encoded contents** — set `NEXT_PRIVATE_SIGNING_LOCAL_FILE_CONTENTS` with the base64-encoded certificate string. Use this when file mounting is not available (e.g., Railway, Vercel).
|
||||
|
||||
<Callout type="warn">
|
||||
Plain `docker run` deployments must set `NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH` explicitly. This
|
||||
prevents production deployments from accidentally using the insecure example certificate.
|
||||
Docker Compose sets the file path for you.
|
||||
</Callout>
|
||||
|
||||
For production deployments that require Adobe Approved Trust List recognition, consider using a [Google Cloud HSM](/docs/self-hosting/configuration/signing-certificate/google-cloud-hsm) or another external HSM.
|
||||
|
||||
<Callout type="warn">
|
||||
@@ -178,6 +185,7 @@ NEXT_PUBLIC_WEBAPP_URL=https://sign.example.com
|
||||
NEXT_PRIVATE_INTERNAL_WEBAPP_URL=http://localhost:3000
|
||||
NEXT_PRIVATE_DATABASE_URL=postgresql://user:password@db-host:5432/documenso
|
||||
NEXT_PRIVATE_DIRECT_DATABASE_URL=postgresql://user:password@db-host:5432/documenso
|
||||
NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH=/opt/documenso/cert.p12
|
||||
NEXT_PRIVATE_SIGNING_PASSPHRASE=your-certificate-password
|
||||
NEXT_PRIVATE_SMTP_TRANSPORT=smtp-auth
|
||||
NEXT_PRIVATE_SMTP_HOST=smtp.example.com
|
||||
@@ -203,6 +211,12 @@ docker run -d \
|
||||
|
||||
Documenso provides health check endpoints for monitoring:
|
||||
|
||||
<Callout type="info">
|
||||
If a certificate is mounted but signing fails, ensure `NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH`
|
||||
explicitly points to its path inside the container. Production does not use the development
|
||||
example certificate as a fallback.
|
||||
</Callout>
|
||||
|
||||
| Endpoint | Purpose |
|
||||
| ------------------------- | -------------------------------------------------------------- |
|
||||
| `/api/health` | Checks database connectivity and certificate status |
|
||||
|
||||
@@ -14,8 +14,8 @@ import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 22 or later
|
||||
- npm 11 or later
|
||||
- Node.js 24 or later
|
||||
- npm 11.17 or later
|
||||
- PostgreSQL 14 or later
|
||||
- A Linux server (for systemd service setup)
|
||||
|
||||
|
||||
@@ -141,8 +141,8 @@ If building from source (not using Docker images):
|
||||
|
||||
| Requirement | Version |
|
||||
| ----------- | ------- |
|
||||
| Node.js | 22+ |
|
||||
| npm | 11+ |
|
||||
| Node.js | 24+ |
|
||||
| npm | 11.17+ |
|
||||
|
||||
---
|
||||
|
||||
@@ -169,7 +169,7 @@ Documenso runs on:
|
||||
| MySQL/MariaDB | PostgreSQL-specific features required |
|
||||
| SQLite | Not suitable for production workloads |
|
||||
| MongoDB | Relational database required |
|
||||
| Node.js < 22 | Modern JavaScript features required |
|
||||
| Node.js < 24 | Modern JavaScript features required |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ To access the preferences, navigate to either the organisation or teams settings
|
||||
| **Default Recipients** | Recipients that are automatically added to new documents. Can be overridden per document. |
|
||||
| **Default Envelope Expiration** | How long recipients have to sign before the signing link expires. See [recipient expiration](/docs/users/documents/advanced/recipient-expiration). |
|
||||
| **Default Signing Reminders** | When and how often to email recipients who have not yet signed. See [signing reminders](/docs/users/documents/advanced/signing-reminders). |
|
||||
| **Delegate Document Ownership** | Allow team API tokens to delegate document ownership to another team member. |
|
||||
| **Delegate Document Ownership** | By default, documents created with a team API token are owned by the user who created the token. Enable this setting to let supported API requests assign ownership to another team member. |
|
||||
| **AI Features** | Enable AI-powered features such as automatic recipient detection. Only shown if AI features are configured on the instance. |
|
||||
|
||||
Document visibility, language, and signature settings can be overridden per document.
|
||||
|
||||
@@ -3,20 +3,19 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "NEXT_IGNORE_INCORRECT_LOCKFILE=true next build",
|
||||
"build": "next build",
|
||||
"dev": "next dev",
|
||||
"start": "next start",
|
||||
"types:check": "fumadocs-mdx && next typegen && tsc --noEmit",
|
||||
"postinstall": "fumadocs-mdx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"fumadocs-core": "16.5.0",
|
||||
"fumadocs-mdx": "14.2.6",
|
||||
"fumadocs-ui": "16.5.0",
|
||||
"fumadocs-core": "16.14.3",
|
||||
"fumadocs-mdx": "15.2.3",
|
||||
"fumadocs-ui": "16.14.3",
|
||||
"lucide-react": "^0.563.0",
|
||||
"mermaid": "^11.12.2",
|
||||
"next": "16.2.6",
|
||||
"next": "^16.3.3",
|
||||
"next-plausible": "^3.12.5",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.4",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Callout } from 'fumadocs-ui/components/callout';
|
||||
|
||||
const MIGRATION_GUIDE_HREF = '/docs/developers/api/migrate-to-envelopes';
|
||||
|
||||
/**
|
||||
* Deprecation banner steering API consumers away from the legacy document and
|
||||
* template create endpoints and towards the unified Envelope API.
|
||||
*
|
||||
* Registered globally in `mdx-components.tsx`, so it can be used in any MDX page
|
||||
* as `<EnvelopeWarning />` without an explicit import.
|
||||
*/
|
||||
export function EnvelopeWarning() {
|
||||
return (
|
||||
<Callout type="error">
|
||||
<strong>Documents and templates are being deprecated and replaced by envelopes.</strong>{' '}
|
||||
<a href={MIGRATION_GUIDE_HREF}>Read the migration guide here.</a>
|
||||
</Callout>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as TabsComponents from 'fumadocs-ui/components/tabs';
|
||||
import defaultMdxComponents from 'fumadocs-ui/mdx';
|
||||
import type { MDXComponents } from 'mdx/types';
|
||||
import { EnvelopeWarning } from '@/components/mdx/envelope-warning';
|
||||
import { Mermaid } from '@/components/mdx/mermaid';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -9,6 +10,7 @@ export function getMDXComponents(components?: MDXComponents): any {
|
||||
...defaultMdxComponents,
|
||||
...TabsComponents,
|
||||
Mermaid,
|
||||
EnvelopeWarning,
|
||||
...components,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,142 +1,23 @@
|
||||
/**
|
||||
* Multi purpose CORS lib.
|
||||
* Note: Based on the `cors` package in npm but using only web APIs.
|
||||
* Taken from: https://github.com/vercel/examples/blob/main/edge-functions/cors/lib/cors.ts
|
||||
* Apply the public statistics API's wildcard CORS policy, without credentials.
|
||||
*/
|
||||
|
||||
type StaticOrigin = boolean | string | RegExp | (boolean | string | RegExp)[];
|
||||
|
||||
type OriginFn = (origin: string | undefined, req: Request) => StaticOrigin | Promise<StaticOrigin>;
|
||||
|
||||
interface CorsOptions {
|
||||
origin?: StaticOrigin | OriginFn;
|
||||
methods?: string | string[];
|
||||
allowedHeaders?: string | string[];
|
||||
exposedHeaders?: string | string[];
|
||||
credentials?: boolean;
|
||||
maxAge?: number;
|
||||
preflightContinue?: boolean;
|
||||
optionsSuccessStatus?: number;
|
||||
}
|
||||
|
||||
const defaultOptions: CorsOptions = {
|
||||
origin: '*',
|
||||
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
|
||||
preflightContinue: false,
|
||||
optionsSuccessStatus: 204,
|
||||
};
|
||||
|
||||
function isOriginAllowed(origin: string, allowed: StaticOrigin): boolean {
|
||||
return Array.isArray(allowed)
|
||||
? allowed.some((o) => isOriginAllowed(origin, o))
|
||||
: typeof allowed === 'string'
|
||||
? origin === allowed
|
||||
: allowed instanceof RegExp
|
||||
? allowed.test(origin)
|
||||
: !!allowed;
|
||||
}
|
||||
|
||||
function getOriginHeaders(reqOrigin: string | undefined, origin: StaticOrigin) {
|
||||
const headers = new Headers();
|
||||
|
||||
if (origin === '*') {
|
||||
headers.set('Access-Control-Allow-Origin', '*');
|
||||
} else if (typeof origin === 'string') {
|
||||
headers.set('Access-Control-Allow-Origin', origin);
|
||||
headers.append('Vary', 'Origin');
|
||||
} else {
|
||||
const allowed = isOriginAllowed(reqOrigin ?? '', origin);
|
||||
|
||||
if (allowed && reqOrigin) {
|
||||
headers.set('Access-Control-Allow-Origin', reqOrigin);
|
||||
}
|
||||
headers.append('Vary', 'Origin');
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function originHeadersFromReq(req: Request, origin: StaticOrigin | OriginFn) {
|
||||
const reqOrigin = req.headers.get('Origin') || undefined;
|
||||
const value = typeof origin === 'function' ? await origin(reqOrigin, req) : origin;
|
||||
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
return getOriginHeaders(reqOrigin, value);
|
||||
}
|
||||
|
||||
function getAllowedHeaders(req: Request, allowed?: string | string[]) {
|
||||
const headers = new Headers();
|
||||
|
||||
if (!allowed) {
|
||||
allowed = req.headers.get('Access-Control-Request-Headers')!;
|
||||
headers.append('Vary', 'Access-Control-Request-Headers');
|
||||
} else if (Array.isArray(allowed)) {
|
||||
allowed = allowed.join(',');
|
||||
}
|
||||
if (allowed) {
|
||||
headers.set('Access-Control-Allow-Headers', allowed);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
export default async function cors(req: Request, res: Response, options?: CorsOptions) {
|
||||
const opts = { ...defaultOptions, ...options };
|
||||
export default async function cors(req: Request, res: Response): Promise<Response> {
|
||||
const { headers } = res;
|
||||
const originHeaders = await originHeadersFromReq(req, opts.origin ?? false);
|
||||
const mergeHeaders = (v: string, k: string) => {
|
||||
if (k === 'Vary') {
|
||||
headers.append(k, v);
|
||||
} else {
|
||||
headers.set(k, v);
|
||||
}
|
||||
};
|
||||
headers.set('Access-Control-Allow-Origin', '*');
|
||||
|
||||
// If there's no origin we won't touch the response
|
||||
if (!originHeaders) {
|
||||
return res;
|
||||
}
|
||||
|
||||
originHeaders.forEach(mergeHeaders);
|
||||
|
||||
if (opts.credentials) {
|
||||
headers.set('Access-Control-Allow-Credentials', 'true');
|
||||
}
|
||||
|
||||
const exposed = Array.isArray(opts.exposedHeaders) ? opts.exposedHeaders.join(',') : opts.exposedHeaders;
|
||||
|
||||
if (exposed) {
|
||||
headers.set('Access-Control-Expose-Headers', exposed);
|
||||
}
|
||||
|
||||
// Handle the preflight request
|
||||
if (req.method === 'OPTIONS') {
|
||||
if (opts.methods) {
|
||||
const methods = Array.isArray(opts.methods) ? opts.methods.join(',') : opts.methods;
|
||||
headers.set('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
|
||||
headers.set('Vary', 'Access-Control-Request-Headers');
|
||||
|
||||
headers.set('Access-Control-Allow-Methods', methods);
|
||||
}
|
||||
const allowedHeaders = req.headers.get('Access-Control-Request-Headers');
|
||||
|
||||
getAllowedHeaders(req, opts.allowedHeaders).forEach(mergeHeaders);
|
||||
|
||||
if (typeof opts.maxAge === 'number') {
|
||||
headers.set('Access-Control-Max-Age', String(opts.maxAge));
|
||||
}
|
||||
|
||||
if (opts.preflightContinue) {
|
||||
return res;
|
||||
if (allowedHeaders) {
|
||||
headers.set('Access-Control-Allow-Headers', allowedHeaders);
|
||||
}
|
||||
|
||||
headers.set('Content-Length', '0');
|
||||
return new Response(null, { status: opts.optionsSuccessStatus, headers });
|
||||
return new Response(null, { status: 204, headers });
|
||||
}
|
||||
|
||||
// If we got here, it's a normal request
|
||||
return res;
|
||||
}
|
||||
|
||||
export function initCors(options?: CorsOptions) {
|
||||
return async (req: Request, res: Response) => cors(req, res, options);
|
||||
}
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
"dependencies": {
|
||||
"@documenso/prisma": "*",
|
||||
"luxon": "^3.7.2",
|
||||
"next": "16.2.6"
|
||||
"next": "^16.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/react": "18.3.27",
|
||||
"@types/react": "^19.2.17",
|
||||
"typescript": "5.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
FROM oven/bun:1 AS dependencies-env
|
||||
COPY . /app
|
||||
|
||||
FROM dependencies-env AS development-dependencies-env
|
||||
COPY ./package.json bun.lockb /app/
|
||||
WORKDIR /app
|
||||
RUN bun i --frozen-lockfile
|
||||
|
||||
FROM dependencies-env AS production-dependencies-env
|
||||
COPY ./package.json bun.lockb /app/
|
||||
WORKDIR /app
|
||||
RUN bun i --production
|
||||
|
||||
FROM dependencies-env AS build-env
|
||||
COPY ./package.json bun.lockb /app/
|
||||
COPY --from=development-dependencies-env /app/node_modules /app/node_modules
|
||||
WORKDIR /app
|
||||
RUN bun run build
|
||||
|
||||
FROM dependencies-env
|
||||
COPY ./package.json bun.lockb /app/
|
||||
COPY --from=production-dependencies-env /app/node_modules /app/node_modules
|
||||
COPY --from=build-env /app/build /app/build
|
||||
WORKDIR /app
|
||||
CMD ["bun", "run", "start"]
|
||||
@@ -1,26 +0,0 @@
|
||||
FROM node:20-alpine AS dependencies-env
|
||||
RUN npm i -g pnpm
|
||||
COPY . /app
|
||||
|
||||
FROM dependencies-env AS development-dependencies-env
|
||||
COPY ./package.json pnpm-lock.yaml /app/
|
||||
WORKDIR /app
|
||||
RUN pnpm i --frozen-lockfile
|
||||
|
||||
FROM dependencies-env AS production-dependencies-env
|
||||
COPY ./package.json pnpm-lock.yaml /app/
|
||||
WORKDIR /app
|
||||
RUN pnpm i --prod --frozen-lockfile
|
||||
|
||||
FROM dependencies-env AS build-env
|
||||
COPY ./package.json pnpm-lock.yaml /app/
|
||||
COPY --from=development-dependencies-env /app/node_modules /app/node_modules
|
||||
WORKDIR /app
|
||||
RUN pnpm build
|
||||
|
||||
FROM dependencies-env
|
||||
COPY ./package.json pnpm-lock.yaml /app/
|
||||
COPY --from=production-dependencies-env /app/node_modules /app/node_modules
|
||||
COPY --from=build-env /app/build /app/build
|
||||
WORKDIR /app
|
||||
CMD ["pnpm", "start"]
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@documenso/ui/primitives/dialog';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useState } from 'react';
|
||||
|
||||
export type BrandingPreferencesResetDialogProps = {
|
||||
hasAdvancedBranding: boolean;
|
||||
isSubmitting: boolean;
|
||||
onReset: () => Promise<void>;
|
||||
trigger?: React.ReactNode;
|
||||
};
|
||||
|
||||
export const BrandingPreferencesResetDialog = ({
|
||||
hasAdvancedBranding,
|
||||
isSubmitting,
|
||||
onReset,
|
||||
trigger,
|
||||
}: BrandingPreferencesResetDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isResetting, setIsResetting] = useState(false);
|
||||
|
||||
const isLoading = isSubmitting || isResetting;
|
||||
|
||||
const handleResetToDefaults = async () => {
|
||||
setIsResetting(true);
|
||||
|
||||
try {
|
||||
await onReset();
|
||||
setOpen(false);
|
||||
} catch {
|
||||
// The submit handler surfaces its own error toast. Keep the dialog open
|
||||
// so the user can retry.
|
||||
} finally {
|
||||
setIsResetting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(value) => !isLoading && setOpen(value)}>
|
||||
<DialogTrigger asChild>
|
||||
{trigger ?? (
|
||||
<Button variant="destructive" type="button" size="sm" disabled={isLoading}>
|
||||
<Trans>Reset to defaults</Trans>
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
<Trans>Reset branding preferences</Trans>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogDescription>
|
||||
<Trans>
|
||||
This will reset all branding preferences to their default values and save the changes immediately.
|
||||
</Trans>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert variant="warning">
|
||||
<AlertDescription>
|
||||
<p>
|
||||
<Trans>Once confirmed, the following will be reset:</Trans>
|
||||
</p>
|
||||
|
||||
<ul className="mt-0.5 list-inside list-disc">
|
||||
<li>
|
||||
<Trans>Custom branding enabled setting</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Branding logo</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Brand website and brand details</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Brand colours, including background, foreground, primary, and border colours</Trans>
|
||||
</li>
|
||||
|
||||
{hasAdvancedBranding && (
|
||||
<>
|
||||
<li>
|
||||
<Trans>Border radius</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Custom CSS</Trans>
|
||||
</li>
|
||||
</>
|
||||
)}
|
||||
</ul>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="secondary" disabled={isLoading}>
|
||||
<Trans>Cancel</Trans>
|
||||
</Button>
|
||||
</DialogClose>
|
||||
|
||||
<Button type="button" variant="destructive" loading={isLoading} onClick={() => void handleResetToDefaults()}>
|
||||
<Trans>Reset to defaults</Trans>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@documenso/ui/primitives/dialog';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useState } from 'react';
|
||||
|
||||
export type DocumentPreferencesResetDialogProps = {
|
||||
isSubmitting: boolean;
|
||||
onReset: () => Promise<void>;
|
||||
showAiFeatures?: boolean;
|
||||
showDocumentVisibility?: boolean;
|
||||
};
|
||||
|
||||
export const DocumentPreferencesResetDialog = ({
|
||||
isSubmitting,
|
||||
onReset,
|
||||
showAiFeatures = false,
|
||||
showDocumentVisibility = false,
|
||||
}: DocumentPreferencesResetDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isResetting, setIsResetting] = useState(false);
|
||||
|
||||
const isLoading = isSubmitting || isResetting;
|
||||
|
||||
const handleResetToDefaults = async () => {
|
||||
setIsResetting(true);
|
||||
|
||||
try {
|
||||
await onReset();
|
||||
setOpen(false);
|
||||
} catch {
|
||||
// The submit handler surfaces its own error toast. Keep the dialog open
|
||||
// so the user can retry.
|
||||
} finally {
|
||||
setIsResetting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(value) => !isLoading && setOpen(value)}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="destructive" type="button" size="sm" disabled={isLoading}>
|
||||
<Trans>Reset to defaults</Trans>
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
<Trans>Reset document preferences</Trans>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogDescription>
|
||||
<Trans>
|
||||
This will reset all document preferences to their default values and save the changes immediately.
|
||||
</Trans>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert variant="warning">
|
||||
<AlertDescription>
|
||||
<p>
|
||||
<Trans>Once confirmed, the following will be reset:</Trans>
|
||||
</p>
|
||||
|
||||
<ul className="mt-0.5 list-inside list-disc">
|
||||
{showDocumentVisibility && (
|
||||
<li>
|
||||
<Trans>Default document visibility</Trans>
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<Trans>Default document language</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default date format</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default time zone</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default signature settings</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default recipients</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Delegate document ownership</Trans>
|
||||
</li>
|
||||
{showAiFeatures && (
|
||||
<li>
|
||||
<Trans>AI features</Trans>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="secondary" disabled={isLoading}>
|
||||
<Trans>Cancel</Trans>
|
||||
</Button>
|
||||
</DialogClose>
|
||||
|
||||
<Button type="button" variant="destructive" loading={isLoading} onClick={() => void handleResetToDefaults()}>
|
||||
<Trans>Reset to defaults</Trans>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { useCurrentEnvelopeEditor } from '@documenso/lib/client-only/providers/envelope-editor-provider';
|
||||
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
|
||||
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
|
||||
@@ -71,6 +72,7 @@ export const EnvelopeDistributeDialog = ({
|
||||
const { toast } = useToast();
|
||||
const { t, i18n } = useLingui();
|
||||
const navigate = useNavigate();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
@@ -200,6 +202,12 @@ export const EnvelopeDistributeDialog = ({
|
||||
} catch (err) {
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'editor',
|
||||
location: 'distribute_document',
|
||||
envelopeId: envelope.id,
|
||||
});
|
||||
|
||||
const errorMessage = getDistributeErrorMessage(error.code);
|
||||
|
||||
toast({
|
||||
|
||||
@@ -122,7 +122,7 @@ export const EnvelopeItemEditDialog = ({
|
||||
|
||||
toast({
|
||||
title: t`Failed to read file`,
|
||||
description: t`The file is not a valid PDF.`,
|
||||
description: t`The file is not a valid PDF or is password protected.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { getRecipientType } from '@documenso/lib/client-only/recipient-type';
|
||||
import { AppError } from '@documenso/lib/errors/app-error';
|
||||
import type { TEnvelope } from '@documenso/lib/types/envelope';
|
||||
@@ -51,6 +52,7 @@ export const EnvelopeRedistributeDialog = ({ envelope, envelopeType, trigger }:
|
||||
|
||||
const { toast } = useToast();
|
||||
const { t, i18n } = useLingui();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
@@ -95,6 +97,13 @@ export const EnvelopeRedistributeDialog = ({ envelope, envelopeType, trigger }:
|
||||
setIsOpen(false);
|
||||
} catch (err) {
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'editor',
|
||||
location: 'redistribute_document',
|
||||
envelopeId: envelope.id,
|
||||
});
|
||||
|
||||
const errorMessage = getDistributeErrorMessage(error.code);
|
||||
|
||||
toast({
|
||||
|
||||
@@ -44,7 +44,10 @@ export const EnvelopesBulkDeleteDialog = ({
|
||||
if (isDocument) {
|
||||
await trpcUtils.document.findDocumentsInternal.invalidate();
|
||||
} else {
|
||||
await trpcUtils.template.findTemplates.invalidate();
|
||||
await Promise.all([
|
||||
trpcUtils.template.findTemplates.invalidate(),
|
||||
trpcUtils.template.findTemplatesInternal.invalidate(),
|
||||
]);
|
||||
}
|
||||
|
||||
if (result.failedIds.length > 0) {
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import {
|
||||
createZipWriter,
|
||||
sanitizeZipPathSegment,
|
||||
type ZipFileEntry,
|
||||
} from '@documenso/lib/client-only/create-zip-writer';
|
||||
import { downloadFile } from '@documenso/lib/client-only/download-file';
|
||||
import { fetchPDF } from '@documenso/lib/client-only/download-pdf';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@documenso/ui/primitives/dialog';
|
||||
import { RadioGroupSegmented, RadioGroupSegmentedItem } from '@documenso/ui/primitives/radio-group';
|
||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
import { plural } from '@lingui/core/macro';
|
||||
import { Plural, Trans, useLingui } from '@lingui/react/macro';
|
||||
import { DocumentStatus } from '@prisma/client';
|
||||
import type * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { match } from 'ts-pattern';
|
||||
|
||||
/**
|
||||
* The maximum number of documents that can be downloaded in a single bulk
|
||||
* download. Each document requires fetching its full PDFs into the browser,
|
||||
* so this bounds both request volume and blob storage usage. Matches the
|
||||
* spirit of the server-side 100 cap on bulk move/delete/cancel.
|
||||
*/
|
||||
export const MAX_BULK_DOWNLOAD_ENVELOPES = 50;
|
||||
|
||||
type BulkDownloadVersion = 'signed' | 'original' | 'pending';
|
||||
|
||||
export type EnvelopeBulkDownloadItem = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: DocumentStatus;
|
||||
|
||||
/**
|
||||
* Whether the envelope is a legacy (v1) envelope. Legacy envelopes use a
|
||||
* different field-rendering pipeline that the partial PDF helper does not
|
||||
* implement, so the Partial option is hidden for them.
|
||||
*/
|
||||
isLegacy: boolean;
|
||||
};
|
||||
|
||||
const getDefaultVersion = (envelope: EnvelopeBulkDownloadItem): BulkDownloadVersion =>
|
||||
envelope.status === DocumentStatus.COMPLETED ? 'signed' : 'original';
|
||||
|
||||
export type EnvelopesBulkDownloadDialogProps = {
|
||||
envelopes: EnvelopeBulkDownloadItem[];
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSuccess?: (successfulEnvelopeIds: string[]) => void;
|
||||
} & Omit<DialogPrimitive.DialogProps, 'children'>;
|
||||
|
||||
export const EnvelopesBulkDownloadDialog = ({
|
||||
envelopes,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
...props
|
||||
}: EnvelopesBulkDownloadDialogProps) => {
|
||||
const { t } = useLingui();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [versionMap, setVersionMap] = useState<Record<string, BulkDownloadVersion>>({});
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
|
||||
const abortRef = useRef(false);
|
||||
|
||||
const trpcUtils = trpc.useUtils();
|
||||
|
||||
const isOverDownloadLimit = envelopes.length > MAX_BULK_DOWNLOAD_ENVELOPES;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
return;
|
||||
}
|
||||
|
||||
setVersionMap(Object.fromEntries(envelopes.map((envelope) => [envelope.id, getDefaultVersion(envelope)])));
|
||||
setProgress(0);
|
||||
}, [open]);
|
||||
|
||||
const getDownloadVersion = (envelope: EnvelopeBulkDownloadItem): BulkDownloadVersion =>
|
||||
versionMap[envelope.id] ?? getDefaultVersion(envelope);
|
||||
|
||||
/**
|
||||
* The version options selectable for an envelope, mirroring the gating used
|
||||
* by the single envelope download dialog:
|
||||
* - COMPLETED: signed or original.
|
||||
* - PENDING (non-legacy): partial or original. Legacy envelopes use a
|
||||
* field-rendering pipeline the partial PDF helper does not implement.
|
||||
* - Anything else: original only, so no choice is shown.
|
||||
*/
|
||||
const getVersionOptions = (
|
||||
envelope: EnvelopeBulkDownloadItem,
|
||||
): { value: BulkDownloadVersion; label: string }[] | null => {
|
||||
if (envelope.status === DocumentStatus.COMPLETED) {
|
||||
return [
|
||||
{ value: 'signed', label: t({ message: 'Signed', context: 'Signed document (adjective)' }) },
|
||||
{ value: 'original', label: t({ message: 'Original', context: 'Original document (adjective)' }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (envelope.status === DocumentStatus.PENDING && !envelope.isLegacy) {
|
||||
return [
|
||||
{ value: 'pending', label: t({ message: 'Partial', context: 'Partially signed document (adjective)' }) },
|
||||
{ value: 'original', label: t({ message: 'Original', context: 'Original document (adjective)' }) },
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getStatusLabel = (status: DocumentStatus) =>
|
||||
match(status)
|
||||
.with(DocumentStatus.COMPLETED, () => t`Completed`)
|
||||
.with(DocumentStatus.PENDING, () => t`Pending`)
|
||||
.with(DocumentStatus.DRAFT, () => t`Draft`)
|
||||
.with(DocumentStatus.REJECTED, () => t`Rejected`)
|
||||
.with(DocumentStatus.CANCELLED, () => t`Cancelled`)
|
||||
.exhaustive();
|
||||
|
||||
const onDownload = async () => {
|
||||
if (envelopes.length === 0 || isOverDownloadLimit || isDownloading) {
|
||||
return;
|
||||
}
|
||||
|
||||
abortRef.current = false;
|
||||
setIsDownloading(true);
|
||||
setProgress(0);
|
||||
|
||||
const zipWriter = createZipWriter();
|
||||
|
||||
const successfulEnvelopeIds: string[] = [];
|
||||
let failedDownloads = 0;
|
||||
|
||||
try {
|
||||
for (const envelope of envelopes) {
|
||||
if (abortRef.current) {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const downloadVersion = getDownloadVersion(envelope);
|
||||
|
||||
const { data: envelopeItems } = await trpcUtils.envelope.item.getManyByToken.fetch({
|
||||
envelopeId: envelope.id,
|
||||
access: {
|
||||
type: 'user',
|
||||
},
|
||||
});
|
||||
|
||||
// Each envelope's items are grouped in their own folder. The id
|
||||
// prefix guarantees uniqueness, the truncated title keeps it
|
||||
// readable without risking overly long extraction paths.
|
||||
const folderName = sanitizeZipPathSegment(`${envelope.id}_${envelope.title}`.slice(0, 96));
|
||||
|
||||
// Buffer this envelope's files before writing so a failed envelope
|
||||
// is either fully in the zip or not at all. Files from previous
|
||||
// envelopes have already been written to the zip stream and freed.
|
||||
const envelopeFiles: ZipFileEntry[] = [];
|
||||
|
||||
for (const envelopeItem of envelopeItems) {
|
||||
const { filename, blob } = await fetchPDF({
|
||||
envelopeItem,
|
||||
token: undefined,
|
||||
fileName: envelopeItem.title,
|
||||
version: downloadVersion,
|
||||
});
|
||||
|
||||
envelopeFiles.push({
|
||||
filename: `${folderName}/${sanitizeZipPathSegment(filename)}`,
|
||||
data: blob,
|
||||
});
|
||||
}
|
||||
|
||||
for (const file of envelopeFiles) {
|
||||
await zipWriter.addFile(file);
|
||||
}
|
||||
|
||||
successfulEnvelopeIds.push(envelope.id);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
failedDownloads++;
|
||||
}
|
||||
|
||||
setProgress((p) => p + 1);
|
||||
}
|
||||
|
||||
// The user intentionally stopped the download, discard anything fetched
|
||||
// so far without toasting an error.
|
||||
if (abortRef.current) {
|
||||
zipWriter.abort();
|
||||
return;
|
||||
}
|
||||
|
||||
if (successfulEnvelopeIds.length === 0) {
|
||||
zipWriter.abort();
|
||||
|
||||
toast({
|
||||
title: t`Error`,
|
||||
description: t`An error occurred while downloading the documents.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
downloadFile({
|
||||
filename: `documenso-documents-${new Date().toISOString().slice(0, 10)}.zip`,
|
||||
data: zipWriter.finalize(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
zipWriter.abort();
|
||||
|
||||
toast({
|
||||
title: t`Error`,
|
||||
description: t`An error occurred while downloading the documents.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (failedDownloads > 0) {
|
||||
toast({
|
||||
title: t`Documents partially downloaded`,
|
||||
description: t`${plural(successfulEnvelopeIds.length, {
|
||||
one: '# document downloaded.',
|
||||
other: '# documents downloaded.',
|
||||
})} ${plural(failedDownloads, {
|
||||
one: '# document could not be downloaded.',
|
||||
other: '# documents could not be downloaded.',
|
||||
})}`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
onSuccess?.(successfulEnvelopeIds);
|
||||
return;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t`Documents downloaded`,
|
||||
description: plural(successfulEnvelopeIds.length, {
|
||||
one: '# document has been downloaded.',
|
||||
other: '# documents have been downloaded.',
|
||||
}),
|
||||
});
|
||||
|
||||
onSuccess?.(successfulEnvelopeIds);
|
||||
onOpenChange(false);
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
{...props}
|
||||
open={open}
|
||||
onOpenChange={(value) => {
|
||||
if (!isDownloading) {
|
||||
onOpenChange(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
<Trans>Download Documents</Trans>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogDescription>
|
||||
<Plural
|
||||
value={envelopes.length}
|
||||
one="Select the version to download for the selected document."
|
||||
other="Select the version to download for each of the # selected documents."
|
||||
/>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isOverDownloadLimit && (
|
||||
<Alert variant="warning">
|
||||
<AlertDescription>
|
||||
<Plural
|
||||
value={MAX_BULK_DOWNLOAD_ENVELOPES}
|
||||
one="You can download up to # document at a time. Deselect some documents to continue."
|
||||
other="You can download up to # documents at a time. Deselect some documents to continue."
|
||||
/>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<fieldset disabled={isDownloading} className="min-w-0 space-y-4">
|
||||
<div className="-mx-3 max-h-96 overflow-y-auto px-3">
|
||||
<div className="divide-y divide-border rounded-lg border border-border">
|
||||
{envelopes.map((envelope) => {
|
||||
const versionOptions = getVersionOptions(envelope);
|
||||
|
||||
return (
|
||||
<div key={envelope.id} className="flex items-center gap-3 px-3 py-2.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium text-foreground text-sm" title={envelope.title}>
|
||||
{envelope.title}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs">{getStatusLabel(envelope.status)}</p>
|
||||
</div>
|
||||
|
||||
{versionOptions && (
|
||||
<RadioGroupSegmented
|
||||
className="shrink-0"
|
||||
value={getDownloadVersion(envelope)}
|
||||
onValueChange={(value) =>
|
||||
setVersionMap((prev) => ({
|
||||
...prev,
|
||||
[envelope.id]: value as BulkDownloadVersion,
|
||||
}))
|
||||
}
|
||||
aria-label={t`Download version for ${envelope.title}`}
|
||||
>
|
||||
{versionOptions.map((option) => (
|
||||
<RadioGroupSegmentedItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</RadioGroupSegmentedItem>
|
||||
))}
|
||||
</RadioGroupSegmented>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isDownloading && (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
Downloading {progress} / {envelopes.length}...
|
||||
</Trans>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
if (isDownloading) {
|
||||
abortRef.current = true;
|
||||
} else {
|
||||
onOpenChange(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isDownloading ? <Trans>Stop</Trans> : <Trans>Cancel</Trans>}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void onDownload()}
|
||||
loading={isDownloading}
|
||||
disabled={envelopes.length === 0 || isOverDownloadLimit}
|
||||
>
|
||||
<Trans>Download</Trans>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</fieldset>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -96,7 +96,10 @@ export const EnvelopesBulkMoveDialog = ({
|
||||
if (isDocument) {
|
||||
await trpcUtils.document.findDocumentsInternal.invalidate();
|
||||
} else {
|
||||
await trpcUtils.template.findTemplates.invalidate();
|
||||
await Promise.all([
|
||||
trpcUtils.template.findTemplates.invalidate(),
|
||||
trpcUtils.template.findTemplatesInternal.invalidate(),
|
||||
]);
|
||||
}
|
||||
|
||||
await onSuccess?.(data.folderId);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { InternalClaimPlans } from '@documenso/ee/server-only/stripe/get-internal-claim-plans';
|
||||
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
|
||||
import { DOCUMENSO_CLOUD_ENTERPRISE_CTA_URL, IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
|
||||
import { AppError } from '@documenso/lib/errors/app-error';
|
||||
import { INTERNAL_CLAIM_ID } from '@documenso/lib/types/subscription';
|
||||
import { parseMessageDescriptorMacro } from '@documenso/lib/utils/i18n';
|
||||
@@ -380,7 +380,7 @@ const BillingPlanForm = ({ value, onChange, plans, canCreateFreeOrganisation }:
|
||||
))}
|
||||
|
||||
<Link
|
||||
to="https://documen.so/enterprise-cta"
|
||||
to={DOCUMENSO_CLOUD_ENTERPRISE_CTA_URL}
|
||||
target="_blank"
|
||||
className="flex items-center space-x-2 rounded-md border bg-muted/30 p-4"
|
||||
>
|
||||
|
||||
@@ -17,28 +17,25 @@ import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
import type { Team, TeamEmail, TeamEmailVerification } from '@prisma/client';
|
||||
import { useState } from 'react';
|
||||
import { useRevalidator } from 'react-router';
|
||||
|
||||
export type TeamEmailDeleteDialogProps = {
|
||||
trigger?: React.ReactNode;
|
||||
teamName: string;
|
||||
team: Prisma.TeamGetPayload<{
|
||||
include: {
|
||||
teamEmail: true;
|
||||
emailVerification: {
|
||||
select: {
|
||||
expiresAt: true;
|
||||
name: true;
|
||||
email: true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}>;
|
||||
team: Pick<Team, 'id' | 'avatarImageId' | 'name'>;
|
||||
teamEmail: Pick<TeamEmail, 'email' | 'name'> | null;
|
||||
emailVerification: Pick<TeamEmailVerification, 'email' | 'name' | 'expiresAt'> | null;
|
||||
};
|
||||
|
||||
export const TeamEmailDeleteDialog = ({ trigger, teamName, team }: TeamEmailDeleteDialogProps) => {
|
||||
export const TeamEmailDeleteDialog = ({
|
||||
trigger,
|
||||
teamName,
|
||||
team,
|
||||
teamEmail,
|
||||
emailVerification,
|
||||
}: TeamEmailDeleteDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const { _ } = useLingui();
|
||||
@@ -83,11 +80,11 @@ export const TeamEmailDeleteDialog = ({ trigger, teamName, team }: TeamEmailDele
|
||||
});
|
||||
|
||||
const onRemove = async () => {
|
||||
if (team.teamEmail) {
|
||||
if (teamEmail) {
|
||||
await deleteTeamEmail({ teamId: team.id });
|
||||
}
|
||||
|
||||
if (team.emailVerification) {
|
||||
if (emailVerification) {
|
||||
await deleteTeamEmailVerification({ teamId: team.id });
|
||||
}
|
||||
|
||||
@@ -121,13 +118,13 @@ export const TeamEmailDeleteDialog = ({ trigger, teamName, team }: TeamEmailDele
|
||||
<AvatarWithText
|
||||
avatarClass="h-12 w-12"
|
||||
avatarSrc={formatAvatarUrl(team.avatarImageId)}
|
||||
avatarFallback={extractInitials((team.teamEmail?.name || team.emailVerification?.name) ?? '')}
|
||||
avatarFallback={extractInitials((teamEmail?.name || emailVerification?.name) ?? '')}
|
||||
primaryText={
|
||||
<span className="font-semibold text-foreground/80 text-sm">
|
||||
{team.teamEmail?.name || team.emailVerification?.name}
|
||||
{teamEmail?.name || emailVerification?.name}
|
||||
</span>
|
||||
}
|
||||
secondaryText={<span className="text-sm">{team.teamEmail?.email || team.emailVerification?.email}</span>}
|
||||
secondaryText={<span className="text-sm">{teamEmail?.email || emailVerification?.email}</span>}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@ import { useRevalidator } from 'react-router';
|
||||
import type { z } from 'zod';
|
||||
|
||||
export type TeamEmailUpdateDialogProps = {
|
||||
teamEmail: TeamEmail;
|
||||
teamId: number;
|
||||
teamEmail: Pick<TeamEmail, 'email' | 'name'>;
|
||||
trigger?: React.ReactNode;
|
||||
} & Omit<DialogPrimitive.DialogProps, 'children'>;
|
||||
|
||||
@@ -33,7 +34,7 @@ const ZUpdateTeamEmailFormSchema = ZUpdateTeamEmailMutationSchema.pick({
|
||||
|
||||
type TUpdateTeamEmailFormSchema = z.infer<typeof ZUpdateTeamEmailFormSchema>;
|
||||
|
||||
export const TeamEmailUpdateDialog = ({ teamEmail, trigger, ...props }: TeamEmailUpdateDialogProps) => {
|
||||
export const TeamEmailUpdateDialog = ({ teamId, teamEmail, trigger, ...props }: TeamEmailUpdateDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const { t } = useLingui();
|
||||
@@ -53,7 +54,7 @@ export const TeamEmailUpdateDialog = ({ teamEmail, trigger, ...props }: TeamEmai
|
||||
const onFormSubmit = async ({ name }: TUpdateTeamEmailFormSchema) => {
|
||||
try {
|
||||
await updateTeamEmail({
|
||||
teamId: teamEmail.teamId,
|
||||
teamId,
|
||||
data: {
|
||||
name,
|
||||
},
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import type { TBulkSendCsvError } from '@documenso/lib/server-only/template/validate-bulk-send-csv';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Checkbox } from '@documenso/ui/primitives/checkbox';
|
||||
import {
|
||||
@@ -15,9 +18,11 @@ import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { Plural, Trans } from '@lingui/react/macro';
|
||||
import { File as FileIcon, Upload, X } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { match } from 'ts-pattern';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { useCurrentTeam } from '~/providers/team';
|
||||
@@ -29,6 +34,8 @@ const ZBulkSendFormSchema = z.object({
|
||||
|
||||
type TBulkSendFormSchema = z.infer<typeof ZBulkSendFormSchema>;
|
||||
|
||||
type TBulkSendValidationError = TBulkSendCsvError | { type: 'UPLOAD_ERROR'; code: string };
|
||||
|
||||
export type TemplateBulkSendDialogProps = {
|
||||
templateId: number;
|
||||
recipients: Array<{ email: string; name?: string | null }>;
|
||||
@@ -42,6 +49,9 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
|
||||
const team = useCurrentTeam();
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [validationError, setValidationError] = useState<TBulkSendValidationError | null>(null);
|
||||
|
||||
const form = useForm<TBulkSendFormSchema>({
|
||||
resolver: zodResolver(ZBulkSendFormSchema),
|
||||
defaultValues: {
|
||||
@@ -51,6 +61,20 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
|
||||
const { mutateAsync: uploadBulkSend } = trpc.template.uploadBulkSend.useMutation();
|
||||
|
||||
const onOpenChange = (value: boolean) => {
|
||||
if (form.formState.isSubmitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
setOpen(value);
|
||||
|
||||
if (!value) {
|
||||
setValidationError(null);
|
||||
|
||||
form.reset();
|
||||
}
|
||||
};
|
||||
|
||||
const onDownloadTemplate = () => {
|
||||
const headers = recipients.flatMap((_, index) => [`recipient_${index + 1}_email`, `recipient_${index + 1}_name`]);
|
||||
|
||||
@@ -71,36 +95,44 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
};
|
||||
|
||||
const onSubmit = async (values: TBulkSendFormSchema) => {
|
||||
setValidationError(null);
|
||||
|
||||
try {
|
||||
const csv = await values.file.text();
|
||||
|
||||
await uploadBulkSend({
|
||||
const result = await uploadBulkSend({
|
||||
templateId,
|
||||
teamId: team?.id,
|
||||
csv: csv,
|
||||
sendImmediately: values.sendImmediately,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
setValidationError(result.error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: _(msg`Success`),
|
||||
description: _(msg`Your bulk send has been initiated. You will receive an email notification upon completion.`),
|
||||
});
|
||||
|
||||
setOpen(false);
|
||||
form.reset();
|
||||
|
||||
onSuccess?.();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
toast({
|
||||
title: _(msg`Error`),
|
||||
description: _(msg`Failed to upload CSV. Please check the file format and try again.`),
|
||||
variant: 'destructive',
|
||||
});
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
setValidationError({ type: 'UPLOAD_ERROR', code: error.code });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
{trigger ?? (
|
||||
<Button variant="outline" className="shrink-0" size="sm">
|
||||
@@ -174,7 +206,10 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
|
||||
if (file) {
|
||||
setValidationError(null);
|
||||
|
||||
onChange(file);
|
||||
}
|
||||
}}
|
||||
@@ -195,7 +230,11 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
type="button"
|
||||
variant="link"
|
||||
className="p-0 text-destructive text-xs hover:text-destructive"
|
||||
onClick={() => onChange(null)}
|
||||
onClick={() => {
|
||||
setValidationError(null);
|
||||
|
||||
form.resetField('file');
|
||||
}}
|
||||
disabled={form.formState.isSubmitting}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
@@ -218,6 +257,72 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
)}
|
||||
/>
|
||||
|
||||
{validationError !== null && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="max-h-32 overflow-y-auto">
|
||||
{match(validationError)
|
||||
.with({ type: 'PARSE_ERROR' }, () => (
|
||||
<Trans>The CSV could not be parsed. Please check the file format and try again.</Trans>
|
||||
))
|
||||
.with({ type: 'EMPTY' }, () => (
|
||||
<Trans>
|
||||
The CSV does not contain any rows. Please add at least one row of recipient details.
|
||||
</Trans>
|
||||
))
|
||||
.with({ type: 'ROW_LIMIT_EXCEEDED' }, ({ rowCount, maxRows }) => (
|
||||
<Trans>
|
||||
<Plural value={rowCount} one="The CSV contains # row." other="The CSV contains # rows." />{' '}
|
||||
<Plural
|
||||
value={maxRows}
|
||||
one="A maximum of # row is allowed per upload."
|
||||
other="A maximum of # rows is allowed per upload."
|
||||
/>
|
||||
</Trans>
|
||||
))
|
||||
.with({ type: 'MISSING_COLUMNS' }, ({ missingColumns }) => (
|
||||
<>
|
||||
<Trans>
|
||||
The CSV is missing the following required columns. Please download the template CSV for the
|
||||
correct format.
|
||||
</Trans>
|
||||
|
||||
<ul className="mt-1 list-inside list-disc">
|
||||
{missingColumns.map((column) => (
|
||||
<li key={column} className="font-mono">
|
||||
{column}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
))
|
||||
.with({ type: 'INVALID_RECIPIENTS' }, ({ rowErrors }) => (
|
||||
<>
|
||||
<Trans>The CSV contains invalid recipient emails. Please fix the following rows:</Trans>
|
||||
|
||||
<ul className="mt-1 list-inside list-disc">
|
||||
{rowErrors.map((rowError, index) => (
|
||||
<li key={index}>
|
||||
<Trans>
|
||||
Row {rowError.row}: <span className="font-mono">{rowError.column}</span> must be a valid
|
||||
email or empty
|
||||
</Trans>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
))
|
||||
.with({ type: 'UPLOAD_ERROR' }, ({ code }) =>
|
||||
code === AppErrorCode.LIMIT_EXCEEDED ? (
|
||||
<Trans>The CSV exceeds the maximum file size.</Trans>
|
||||
) : (
|
||||
<Trans>Failed to upload CSV. Please check the file format and try again.</Trans>
|
||||
),
|
||||
)
|
||||
.exhaustive()}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="sendImmediately"
|
||||
@@ -240,7 +345,12 @@ export const TemplateBulkSendDialog = ({ templateId, recipients, trigger, onSucc
|
||||
/>
|
||||
|
||||
<DialogFooter className="mt-4">
|
||||
<Button variant="secondary" onClick={() => form.reset()} type="button">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={form.formState.isSubmitting}
|
||||
type="button"
|
||||
>
|
||||
<Trans>Cancel</Trans>
|
||||
</Button>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AppError } from '@documenso/lib/errors/app-error';
|
||||
import { type TRecipientLite, ZRecipientEmailSchema } from '@documenso/lib/types/recipient';
|
||||
import { putPdfFile } from '@documenso/lib/universal/upload/put-file';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { DOCUMENT_TITLE_MAX_LENGTH } from '@documenso/trpc/server/document-router/schema';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Checkbox } from '@documenso/ui/primitives/checkbox';
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
} from '@documenso/ui/primitives/dialog';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@documenso/ui/primitives/form/form';
|
||||
import { Input } from '@documenso/ui/primitives/input';
|
||||
import { RadioGroup, RadioGroupItem } from '@documenso/ui/primitives/radio-group';
|
||||
import { SpinnerBox } from '@documenso/ui/primitives/spinner';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
|
||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
@@ -38,27 +40,64 @@ import { useNavigate } from 'react-router';
|
||||
import * as z from 'zod';
|
||||
import { getTemplateUseErrorMessage } from '~/utils/toast-error-messages';
|
||||
|
||||
const ZAddRecipientsForNewDocumentSchema = z.object({
|
||||
distributeDocument: z.boolean(),
|
||||
useCustomDocument: z.boolean().default(false),
|
||||
customDocumentData: z
|
||||
.array(
|
||||
const DOCUMENT_NAME_SOURCE = {
|
||||
TEMPLATE: 'template',
|
||||
UPLOAD: 'upload',
|
||||
CUSTOM: 'custom',
|
||||
} as const;
|
||||
|
||||
const getUploadedDocumentTitle = (file: File) => {
|
||||
return file.name.replace(/\.[^/.]+$/, '').trim();
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the file name can be used as a document title.
|
||||
*/
|
||||
const isUploadedFileNameUsable = (file?: File): file is File => {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const title = getUploadedDocumentTitle(file);
|
||||
|
||||
return title.length > 0 && title.length <= DOCUMENT_TITLE_MAX_LENGTH;
|
||||
};
|
||||
|
||||
const ZAddRecipientsForNewDocumentSchema = z
|
||||
.object({
|
||||
distributeDocument: z.boolean(),
|
||||
useCustomDocument: z.boolean().default(false),
|
||||
documentNameSource: z.enum([
|
||||
DOCUMENT_NAME_SOURCE.TEMPLATE,
|
||||
DOCUMENT_NAME_SOURCE.UPLOAD,
|
||||
DOCUMENT_NAME_SOURCE.CUSTOM,
|
||||
]),
|
||||
customDocumentName: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(DOCUMENT_TITLE_MAX_LENGTH, { message: msg`Document name is too long`.id }),
|
||||
customDocumentData: z
|
||||
.array(
|
||||
z.object({
|
||||
title: z.string(),
|
||||
data: z.instanceof(File).optional(),
|
||||
envelopeItemId: z.string(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
recipients: z.array(
|
||||
z.object({
|
||||
title: z.string(),
|
||||
data: z.instanceof(File).optional(),
|
||||
envelopeItemId: z.string(),
|
||||
id: z.number(),
|
||||
email: ZRecipientEmailSchema,
|
||||
name: z.string(),
|
||||
signingOrder: z.number().optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
recipients: z.array(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
email: ZRecipientEmailSchema,
|
||||
name: z.string(),
|
||||
signingOrder: z.number().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
),
|
||||
})
|
||||
.refine((data) => data.documentNameSource !== DOCUMENT_NAME_SOURCE.CUSTOM || data.customDocumentName.length > 0, {
|
||||
message: msg`Document name is required`.id,
|
||||
path: ['customDocumentName'],
|
||||
});
|
||||
|
||||
type TAddRecipientsForNewDocumentSchema = z.infer<typeof ZAddRecipientsForNewDocumentSchema>;
|
||||
|
||||
@@ -87,6 +126,7 @@ export function TemplateUseDialog({
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [lastUploadedFile, setLastUploadedFile] = useState<File>();
|
||||
|
||||
const { data: response, isLoading: isLoadingEnvelopeItems } = trpc.envelope.item.getMany.useQuery(
|
||||
{
|
||||
@@ -106,6 +146,8 @@ export function TemplateUseDialog({
|
||||
return {
|
||||
distributeDocument: false,
|
||||
useCustomDocument: false,
|
||||
documentNameSource: DOCUMENT_NAME_SOURCE.TEMPLATE,
|
||||
customDocumentName: '',
|
||||
customDocumentData: envelopeItems.map((item) => ({
|
||||
title: item.title,
|
||||
data: undefined,
|
||||
@@ -140,11 +182,39 @@ export function TemplateUseDialog({
|
||||
|
||||
const { mutateAsync: createDocumentFromTemplate } = trpc.template.createDocumentFromTemplate.useMutation();
|
||||
|
||||
/**
|
||||
* Track the most recently uploaded file so its name can be used as the document name.
|
||||
* Files with an unusable name are ignored, and the document name source is reset if
|
||||
* no usable file remains.
|
||||
*/
|
||||
const updateLastUploadedFile = (file?: File) => {
|
||||
const usableFile = isUploadedFileNameUsable(file) ? file : undefined;
|
||||
|
||||
setLastUploadedFile(usableFile);
|
||||
|
||||
if (!usableFile && form.getValues('documentNameSource') === DOCUMENT_NAME_SOURCE.UPLOAD) {
|
||||
form.setValue('documentNameSource', DOCUMENT_NAME_SOURCE.TEMPLATE);
|
||||
}
|
||||
};
|
||||
|
||||
const getDocumentTitle = (data: TAddRecipientsForNewDocumentSchema) => {
|
||||
if (data.documentNameSource === DOCUMENT_NAME_SOURCE.CUSTOM) {
|
||||
return data.customDocumentName;
|
||||
}
|
||||
|
||||
if (data.documentNameSource === DOCUMENT_NAME_SOURCE.UPLOAD && lastUploadedFile) {
|
||||
return getUploadedDocumentTitle(lastUploadedFile);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const onSubmit = async (data: TAddRecipientsForNewDocumentSchema) => {
|
||||
try {
|
||||
const customFilesToUpload = (data.customDocumentData || []).filter(
|
||||
(item): item is { data: File; envelopeItemId: string; title: string } =>
|
||||
item.data !== undefined && item.envelopeItemId !== undefined && item.title !== undefined,
|
||||
const documentTitle = getDocumentTitle(data);
|
||||
|
||||
const customFilesToUpload = (data.customDocumentData ?? []).filter(
|
||||
(item): item is typeof item & { data: File } => item.data !== undefined,
|
||||
);
|
||||
|
||||
const customDocumentData = await Promise.all(
|
||||
@@ -163,6 +233,7 @@ export function TemplateUseDialog({
|
||||
recipients: data.recipients,
|
||||
distributeDocument: data.distributeDocument,
|
||||
customDocumentData,
|
||||
...(documentTitle ? { override: { title: documentTitle } } : {}),
|
||||
});
|
||||
|
||||
toast({
|
||||
@@ -195,9 +266,14 @@ export function TemplateUseDialog({
|
||||
name: 'recipients',
|
||||
});
|
||||
|
||||
const useCustomDocument = form.watch('useCustomDocument');
|
||||
const documentNameSource = form.watch('documentNameSource');
|
||||
const canUseUploadedDocumentName = Boolean(lastUploadedFile);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(generateDefaultFormValues());
|
||||
setLastUploadedFile(undefined);
|
||||
}
|
||||
}, [open, form]);
|
||||
|
||||
@@ -238,9 +314,9 @@ export function TemplateUseDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<fieldset className="flex h-full flex-col" disabled={form.formState.isSubmitting}>
|
||||
<div className="custom-scrollbar -m-1 max-h-[60vh] space-y-4 overflow-y-auto p-1">
|
||||
<form className="min-w-0" onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<fieldset className="flex h-full min-w-0 flex-col" disabled={form.formState.isSubmitting}>
|
||||
<div className="custom-scrollbar -m-1 max-h-[60vh] w-full min-w-0 max-w-full space-y-4 overflow-y-auto overflow-x-hidden p-1">
|
||||
{formRecipients.map((recipient, index) => (
|
||||
<div className="flex w-full flex-row space-x-4" key={recipient.id}>
|
||||
{templateSigningOrder === DocumentSigningOrder.SEQUENTIAL && (
|
||||
@@ -401,7 +477,17 @@ export function TemplateUseDialog({
|
||||
onCheckedChange={(checked) => {
|
||||
field.onChange(checked);
|
||||
if (!checked) {
|
||||
form.setValue('customDocumentData', undefined);
|
||||
const customDocumentData = form.getValues('customDocumentData');
|
||||
|
||||
form.setValue(
|
||||
'customDocumentData',
|
||||
customDocumentData?.map((item) => ({
|
||||
...item,
|
||||
data: undefined,
|
||||
})),
|
||||
);
|
||||
form.clearErrors('customDocumentData');
|
||||
updateLastUploadedFile(undefined);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -428,7 +514,7 @@ export function TemplateUseDialog({
|
||||
)}
|
||||
/>
|
||||
|
||||
{form.watch('useCustomDocument') && (
|
||||
{useCustomDocument && (
|
||||
<div className="my-4 space-y-2">
|
||||
{isLoadingEnvelopeItems ? (
|
||||
<SpinnerBox className="py-16" />
|
||||
@@ -443,7 +529,7 @@ export function TemplateUseDialog({
|
||||
<FormControl>
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center gap-4 rounded-lg border border-border bg-card p-4 transition-colors hover:bg-accent/10"
|
||||
className="flex w-full min-w-0 items-center gap-4 overflow-hidden rounded-lg border border-border bg-card p-4 transition-colors hover:bg-accent/10"
|
||||
>
|
||||
<div className="flex-shrink-0">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
|
||||
@@ -451,13 +537,15 @@ export function TemplateUseDialog({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<h4 className="truncate font-medium text-foreground text-sm">{item.title}</h4>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<h4 className="truncate font-medium text-foreground text-sm">
|
||||
{field.value ? getUploadedDocumentTitle(field.value) : item.title}
|
||||
</h4>
|
||||
<p className="mt-0.5 text-muted-foreground text-xs">
|
||||
{field.value ? (
|
||||
<div>
|
||||
<span>
|
||||
<Trans>Custom {(field.value.size / (1024 * 1024)).toFixed(2)} MB file</Trans>
|
||||
</div>
|
||||
</span>
|
||||
) : (
|
||||
<Trans>Default file</Trans>
|
||||
)}
|
||||
@@ -475,6 +563,18 @@ export function TemplateUseDialog({
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
field.onChange(undefined);
|
||||
|
||||
if (field.value === lastUploadedFile) {
|
||||
// Fall back to any other uploaded file so the option stays available.
|
||||
const remainingUploadedFile = form
|
||||
.getValues('customDocumentData')
|
||||
?.find(
|
||||
(item) =>
|
||||
item.data !== field.value && isUploadedFileNameUsable(item.data),
|
||||
)?.data;
|
||||
|
||||
updateLastUploadedFile(remainingUploadedFile);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
@@ -517,7 +617,7 @@ export function TemplateUseDialog({
|
||||
}
|
||||
|
||||
if (file.type !== 'application/pdf') {
|
||||
form.setError('customDocumentData', {
|
||||
form.setError(`customDocumentData.${i}.data`, {
|
||||
type: 'manual',
|
||||
message: _(msg`Please select a PDF file`),
|
||||
});
|
||||
@@ -526,7 +626,7 @@ export function TemplateUseDialog({
|
||||
}
|
||||
|
||||
if (file.size > APP_DOCUMENT_UPLOAD_SIZE_LIMIT * 1024 * 1024) {
|
||||
form.setError('customDocumentData', {
|
||||
form.setError(`customDocumentData.${i}.data`, {
|
||||
type: 'manual',
|
||||
message: _(
|
||||
msg`File size exceeds the limit of ${APP_DOCUMENT_UPLOAD_SIZE_LIMIT} MB`,
|
||||
@@ -537,6 +637,8 @@ export function TemplateUseDialog({
|
||||
}
|
||||
|
||||
field.onChange(file);
|
||||
form.clearErrors(`customDocumentData.${i}.data`);
|
||||
updateLastUploadedFile(file);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -550,6 +652,112 @@ export function TemplateUseDialog({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="documentNameSource"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans>Document name</Trans>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
aria-label={_(msg`Document name`)}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
className="space-y-2"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="document-name-source-template" value={DOCUMENT_NAME_SOURCE.TEMPLATE} />
|
||||
<label className="text-sm" htmlFor="document-name-source-template">
|
||||
<Trans>Use template name</Trans>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-2">
|
||||
<RadioGroupItem
|
||||
id="document-name-source-upload"
|
||||
value={DOCUMENT_NAME_SOURCE.UPLOAD}
|
||||
disabled={!canUseUploadedDocumentName}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<label
|
||||
className={cn('text-sm', {
|
||||
'cursor-not-allowed text-muted-foreground': !canUseUploadedDocumentName,
|
||||
})}
|
||||
htmlFor="document-name-source-upload"
|
||||
>
|
||||
<Trans>Use uploaded file name</Trans>
|
||||
</label>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
type="button"
|
||||
aria-label={_(msg`About uploaded file naming`)}
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="z-[99999] max-w-xs">
|
||||
<Trans>
|
||||
The document name will use the most recently uploaded file name without its
|
||||
extension.
|
||||
</Trans>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{lastUploadedFile && (
|
||||
<p
|
||||
className="max-w-sm truncate text-muted-foreground text-xs"
|
||||
title={lastUploadedFile.name}
|
||||
>
|
||||
{lastUploadedFile.name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!canUseUploadedDocumentName && (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
<Trans>Upload a custom document to use its file name.</Trans>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="document-name-source-custom" value={DOCUMENT_NAME_SOURCE.CUSTOM} />
|
||||
<label className="text-sm" htmlFor="document-name-source-custom">
|
||||
<Trans>Enter custom document name</Trans>
|
||||
</label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{documentNameSource === DOCUMENT_NAME_SOURCE.CUSTOM && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="customDocumentName"
|
||||
render={({ field }) => (
|
||||
<FormItem className="ml-6">
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
aria-label={_(msg`Custom document name`)}
|
||||
placeholder={_(msg`Enter a document name`)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-4">
|
||||
|
||||
@@ -18,6 +18,8 @@ import { useCallback, useRef } from 'react';
|
||||
import type { Control } from 'react-hook-form';
|
||||
import { useFieldArray, useFormContext, useFormState } from 'react-hook-form';
|
||||
|
||||
import { useCspNonce } from '~/utils/nonce';
|
||||
|
||||
import { useConfigureDocument } from './configure-document-context';
|
||||
import type { TConfigureEmbedFormSchema } from './configure-document-view.types';
|
||||
|
||||
@@ -32,6 +34,7 @@ export interface ConfigureDocumentRecipientsProps {
|
||||
export const ConfigureDocumentRecipients = ({ control, isSubmitting }: ConfigureDocumentRecipientsProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { isTemplate } = useConfigureDocument();
|
||||
const cspNonce = useCspNonce();
|
||||
|
||||
const $sensorApi = useRef<SensorAPI | null>(null);
|
||||
|
||||
@@ -212,6 +215,7 @@ export const ConfigureDocumentRecipients = ({ control, isSubmitting }: Configure
|
||||
/>
|
||||
|
||||
<DragDropContext
|
||||
nonce={cspNonce}
|
||||
onDragEnd={onDragEnd}
|
||||
sensors={[
|
||||
(api: SensorAPI) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { useThrottleFn } from '@documenso/lib/client-only/hooks/use-throttle-fn';
|
||||
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
|
||||
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
|
||||
@@ -77,6 +78,7 @@ export const EmbedDirectTemplateClientPage = ({
|
||||
}: EmbedDirectTemplateClientPageProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
@@ -264,6 +266,13 @@ export const EmbedDirectTemplateClientPage = ({
|
||||
const error = AppError.parseError(err);
|
||||
const errorMessage = getDirectTemplateErrorMessage(error.code);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'direct_template',
|
||||
recipientId: recipient.id,
|
||||
envelopeId,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: _(errorMessage.title),
|
||||
description: _(errorMessage.description),
|
||||
@@ -308,6 +317,14 @@ export const EmbedDirectTemplateClientPage = ({
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'embed_init',
|
||||
recipientId: recipient.id,
|
||||
envelopeId,
|
||||
});
|
||||
|
||||
setHasFinishedInit(true);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { useThrottleFn } from '@documenso/lib/client-only/hooks/use-throttle-fn';
|
||||
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
|
||||
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
|
||||
import { AppError } from '@documenso/lib/errors/app-error';
|
||||
import { ZSignDocumentEmbedDataSchema } from '@documenso/lib/types/embed-document-sign-schema';
|
||||
import { isFieldUnsignedAndRequired } from '@documenso/lib/utils/advanced-fields-helpers';
|
||||
import { getDocumentDataUrlForPdfViewer } from '@documenso/lib/utils/envelope-download';
|
||||
@@ -32,6 +34,7 @@ import { useEffect, useId, useLayoutEffect, useMemo, useState } from 'react';
|
||||
import { BrandingLogo } from '~/components/general/branding-logo';
|
||||
import PDFViewerLazy from '~/components/general/pdf-viewer/pdf-viewer-lazy';
|
||||
import { injectCss } from '~/utils/css-vars';
|
||||
import { getSigningCompletionErrorMessage } from '~/utils/toast-error-messages';
|
||||
|
||||
import { DocumentSigningAttachmentsPopover } from '../general/document-signing/document-signing-attachments-popover';
|
||||
import { useRequiredDocumentSigningContext } from '../general/document-signing/document-signing-provider';
|
||||
@@ -73,6 +76,7 @@ export const EmbedSignDocumentV1ClientPage = ({
|
||||
}: EmbedSignDocumentV1ClientPageProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const { fullName, email, signature, setFullName, setEmail, setSignature } = useRequiredDocumentSigningContext();
|
||||
|
||||
@@ -152,6 +156,14 @@ export const EmbedSignDocumentV1ClientPage = ({
|
||||
|
||||
setHasCompletedDocument(true);
|
||||
} catch (err) {
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'complete_document',
|
||||
recipientId: recipient.id,
|
||||
documentId,
|
||||
envelopeId,
|
||||
});
|
||||
|
||||
if (window.parent) {
|
||||
window.parent.postMessage(
|
||||
{
|
||||
@@ -162,9 +174,12 @@ export const EmbedSignDocumentV1ClientPage = ({
|
||||
);
|
||||
}
|
||||
|
||||
const error = AppError.parseError(err);
|
||||
const toastMessage = getSigningCompletionErrorMessage(error.code);
|
||||
|
||||
toast({
|
||||
title: _(msg`Something went wrong`),
|
||||
description: _(msg`We were unable to submit this document at this time. Please try again later.`),
|
||||
title: _(toastMessage.title),
|
||||
description: _(toastMessage.description),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
@@ -231,6 +246,15 @@ export const EmbedSignDocumentV1ClientPage = ({
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'embed_init',
|
||||
recipientId: recipient.id,
|
||||
documentId,
|
||||
envelopeId,
|
||||
});
|
||||
|
||||
setHasFinishedInit(true);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { APP_I18N_OPTIONS } from '@documenso/lib/constants/i18n';
|
||||
import { ZSignDocumentEmbedDataSchema } from '@documenso/lib/types/embed-document-sign-schema';
|
||||
import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';
|
||||
@@ -25,6 +26,7 @@ export const EmbedSignDocumentV2ClientPage = ({
|
||||
allowWhitelabelling = false,
|
||||
}: EmbedSignDocumentV2ClientPageProps) => {
|
||||
const { _ } = useLingui();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const { envelope, recipient, envelopeData, setFullName, setEmail, fullName, email } =
|
||||
useRequiredEnvelopeSigningContext();
|
||||
@@ -170,6 +172,14 @@ export const EmbedSignDocumentV2ClientPage = ({
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'embed_init',
|
||||
recipientId: recipient.id,
|
||||
envelopeId: envelope.id,
|
||||
});
|
||||
|
||||
setHasFinishedInit(true);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
|
||||
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { getDocumentDataUrlForPdfViewer } from '@documenso/lib/utils/envelope-download';
|
||||
@@ -26,6 +27,7 @@ import { useState } from 'react';
|
||||
import { match, P } from 'ts-pattern';
|
||||
|
||||
import PDFViewerLazy from '~/components/general/pdf-viewer/pdf-viewer-lazy';
|
||||
import { getSigningCompletionErrorMessage } from '~/utils/toast-error-messages';
|
||||
|
||||
import { useRequiredDocumentSigningContext } from '../../general/document-signing/document-signing-provider';
|
||||
import { DocumentSigningRejectDialog } from '../../general/document-signing/document-signing-reject-dialog';
|
||||
@@ -56,6 +58,7 @@ export const MultiSignDocumentSigningView = ({
|
||||
}: MultiSignDocumentSigningViewProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const analytics = useAnalytics();
|
||||
|
||||
const { fullName, email, signature, setFullName, setSignature } = useRequiredDocumentSigningContext();
|
||||
|
||||
@@ -100,6 +103,13 @@ export const MultiSignDocumentSigningView = ({
|
||||
|
||||
console.error(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'sign_field',
|
||||
recipientId,
|
||||
documentId: document?.id,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: _(msg`Error`),
|
||||
description: _(msg`An error occurred while signing the document.`),
|
||||
@@ -119,6 +129,13 @@ export const MultiSignDocumentSigningView = ({
|
||||
}
|
||||
|
||||
console.error(err);
|
||||
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'remove_field',
|
||||
recipientId,
|
||||
documentId: document?.id,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -139,11 +156,21 @@ export const MultiSignDocumentSigningView = ({
|
||||
recipientId,
|
||||
});
|
||||
} catch (err) {
|
||||
analytics.captureException(err, {
|
||||
source: 'embed',
|
||||
location: 'complete_document',
|
||||
recipientId,
|
||||
documentId: document?.id,
|
||||
});
|
||||
|
||||
onDocumentError?.();
|
||||
|
||||
const error = AppError.parseError(err);
|
||||
const toastMessage = getSigningCompletionErrorMessage(error.code);
|
||||
|
||||
toast({
|
||||
title: _(msg`Error`),
|
||||
description: _(msg`Failed to complete the document. Please try again.`),
|
||||
title: _(toastMessage.title),
|
||||
description: _(toastMessage.description),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@documenso/ui/primitives/dialog';
|
||||
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from '@documenso/ui/primitives/form/form';
|
||||
import { Input } from '@documenso/ui/primitives/input';
|
||||
import { PinInput, PinInputGroup, PinInputSlot } from '@documenso/ui/primitives/pin-input';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type React from 'react';
|
||||
import { useState } from 'react';
|
||||
import { type FieldValues, type Path, useFormContext } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Schema for forms that accept a two factor code. Compose with `.extend()` or `.merge()`.
|
||||
*/
|
||||
export const ZTwoFactorCodeFieldSchema = z.object({
|
||||
totpCode: z.string().trim().optional(),
|
||||
backupCode: z.string().trim().optional(),
|
||||
});
|
||||
|
||||
export type TTwoFactorCodeFieldSchema = z.infer<typeof ZTwoFactorCodeFieldSchema>;
|
||||
|
||||
export const hasTwoFactorCode = (data: TTwoFactorCodeFieldSchema) => !!data.totpCode || !!data.backupCode;
|
||||
|
||||
type TwoFactorMethod = 'totp' | 'backup';
|
||||
|
||||
export type TwoFactorCodeDialogProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
isSubmitting?: boolean;
|
||||
submitLabel: React.ReactNode;
|
||||
|
||||
/**
|
||||
* Called when the user submits the code. Typically the parent form's submit handler.
|
||||
*/
|
||||
onSubmit: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Collects a TOTP or backup code on top of an existing form, mirroring the
|
||||
* sign in and disable 2FA dialogs.
|
||||
*
|
||||
* Must be rendered inside a `<Form>` whose values include `totpCode` and `backupCode`.
|
||||
*/
|
||||
export const TwoFactorCodeDialog = <T extends FieldValues & TTwoFactorCodeFieldSchema>({
|
||||
open,
|
||||
onOpenChange,
|
||||
isSubmitting,
|
||||
submitLabel,
|
||||
onSubmit,
|
||||
}: TwoFactorCodeDialogProps) => {
|
||||
const form = useFormContext<T>();
|
||||
|
||||
const [method, setMethod] = useState<TwoFactorMethod>('totp');
|
||||
|
||||
const totpCodeName = 'totpCode' as Path<T>;
|
||||
const backupCodeName = 'backupCode' as Path<T>;
|
||||
|
||||
const onToggleMethod = () => {
|
||||
form.resetField(totpCodeName);
|
||||
form.resetField(backupCodeName);
|
||||
|
||||
setMethod((current) => (current === 'totp' ? 'backup' : 'totp'));
|
||||
};
|
||||
|
||||
const handleOpenChange = (value: boolean) => {
|
||||
if (isSubmitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
form.resetField(totpCodeName);
|
||||
form.resetField(backupCodeName);
|
||||
setMethod('totp');
|
||||
}
|
||||
|
||||
onOpenChange(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
<Trans>Two-Factor Authentication</Trans>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogDescription>
|
||||
{method === 'totp' ? (
|
||||
<Trans>Enter the code from your authenticator app to continue.</Trans>
|
||||
) : (
|
||||
<Trans>Enter one of your backup codes to continue.</Trans>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<fieldset disabled={isSubmitting}>
|
||||
{method === 'totp' && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={totpCodeName}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<PinInput {...field} value={field.value ?? ''} maxLength={6} autoFocus>
|
||||
{Array(6)
|
||||
.fill(null)
|
||||
.map((_, i) => (
|
||||
<PinInputGroup key={i}>
|
||||
<PinInputSlot index={i} />
|
||||
</PinInputGroup>
|
||||
))}
|
||||
</PinInput>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{method === 'backup' && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={backupCodeName}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans>Backup Code</Trans>
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="text" autoComplete="off" autoFocus {...field} value={field.value ?? ''} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<DialogFooter className="mt-4">
|
||||
<Button type="button" variant="secondary" onClick={onToggleMethod}>
|
||||
{method === 'totp' ? <Trans>Use Backup Code</Trans> : <Trans>Use Authenticator</Trans>}
|
||||
</Button>
|
||||
|
||||
<Button type="button" loading={isSubmitting} onClick={onSubmit}>
|
||||
{submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</fieldset>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@documenso/lib/constants/branding';
|
||||
import { DEFAULT_BRAND_COLORS, DEFAULT_BRAND_RADIUS } from '@documenso/lib/constants/theme';
|
||||
import { ZCssVarsSchema } from '@documenso/lib/types/css-vars';
|
||||
import { normalizeBrandingColors } from '@documenso/lib/utils/normalize-branding-colors';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@documenso/ui/primitives/accordion';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
@@ -23,10 +24,12 @@ import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { BrandingPreferencesResetDialog } from '~/components/dialogs/branding-preferences-reset-dialog';
|
||||
import { useOptionalCurrentTeam } from '~/providers/team';
|
||||
import { useCspNonce } from '~/utils/nonce';
|
||||
|
||||
import { FormStickySaveBar } from './form-sticky-save-bar';
|
||||
import { InheritableField } from './inheritable-field';
|
||||
|
||||
const ZBrandingPreferencesFormSchema = z.object({
|
||||
brandingEnabled: z.boolean().nullable(),
|
||||
@@ -74,6 +77,7 @@ export function BrandingPreferencesForm({
|
||||
|
||||
const [previewUrl, setPreviewUrl] = useState<string>('');
|
||||
const [hasLoadedPreview, setHasLoadedPreview] = useState(false);
|
||||
const [colorPickerKey, setColorPickerKey] = useState(0);
|
||||
|
||||
const parsedColors = ZCssVarsSchema.safeParse(settings.brandingColors);
|
||||
const initialColors = parsedColors.success ? parsedColors.data : {};
|
||||
@@ -96,6 +100,42 @@ export function BrandingPreferencesForm({
|
||||
|
||||
const isBrandingEnabled = form.watch('brandingEnabled');
|
||||
|
||||
const hasResetBrandingColors =
|
||||
settings.brandingColors === null ||
|
||||
settings.brandingColors === undefined ||
|
||||
(parsedColors.success && normalizeBrandingColors(parsedColors.data) === null);
|
||||
|
||||
// Only show the reset action when the saved settings actually differ from the
|
||||
// defaults, so it never renders as a pointless disabled button.
|
||||
const isResetToDefaultsVisible =
|
||||
settings.brandingEnabled !== (canInherit ? null : false) ||
|
||||
!!settings.brandingLogo ||
|
||||
!!settings.brandingUrl ||
|
||||
!!settings.brandingCompanyDetails ||
|
||||
!!settings.brandingCss ||
|
||||
!hasResetBrandingColors;
|
||||
|
||||
const handleResetToDefaults = async () => {
|
||||
const data: TBrandingPreferencesFormSchema = {
|
||||
brandingEnabled: canInherit ? null : false,
|
||||
brandingLogo: null,
|
||||
brandingUrl: '',
|
||||
brandingCompanyDetails: '',
|
||||
brandingColors: {},
|
||||
brandingCss: '',
|
||||
};
|
||||
|
||||
await onFormSubmit(data);
|
||||
|
||||
if (previewUrl.startsWith('blob:')) {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
|
||||
setPreviewUrl('');
|
||||
setColorPickerKey((key) => key + 1);
|
||||
form.reset(data);
|
||||
};
|
||||
|
||||
const getSavedLogoPreviewUrl = () => {
|
||||
if (!settings.brandingLogo) {
|
||||
return '';
|
||||
@@ -171,11 +211,13 @@ export function BrandingPreferencesForm({
|
||||
control={form.control}
|
||||
name="brandingEnabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Enable Custom Branding</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Enable Custom Branding</Trans>}
|
||||
testId="branding-enabled"
|
||||
>
|
||||
<FormControl>
|
||||
<Select
|
||||
{...field}
|
||||
@@ -213,7 +255,7 @@ export function BrandingPreferencesForm({
|
||||
<Trans>Enable custom branding for all documents in this organisation</Trans>
|
||||
)}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -224,11 +266,13 @@ export function BrandingPreferencesForm({
|
||||
control={form.control}
|
||||
name="brandingLogo"
|
||||
render={({ field: { value: _value, onChange, ...field } }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Branding Logo</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={!previewUrl}
|
||||
label={<Trans>Branding Logo</Trans>}
|
||||
testId="branding-logo"
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="relative h-48 w-full overflow-hidden rounded-lg border border-border bg-background">
|
||||
{previewUrl ? (
|
||||
@@ -306,7 +350,7 @@ export function BrandingPreferencesForm({
|
||||
)}
|
||||
</FormDescription>
|
||||
</div>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -314,11 +358,13 @@ export function BrandingPreferencesForm({
|
||||
control={form.control}
|
||||
name="brandingUrl"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Brand Website</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={!field.value}
|
||||
label={<Trans>Brand Website</Trans>}
|
||||
testId="branding-url"
|
||||
>
|
||||
<FormControl>
|
||||
<Input type="url" placeholder="https://example.com" disabled={!isBrandingEnabled} {...field} />
|
||||
</FormControl>
|
||||
@@ -333,7 +379,7 @@ export function BrandingPreferencesForm({
|
||||
</span>
|
||||
)}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -341,11 +387,13 @@ export function BrandingPreferencesForm({
|
||||
control={form.control}
|
||||
name="brandingCompanyDetails"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Brand Details</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={!field.value}
|
||||
label={<Trans>Brand Details</Trans>}
|
||||
testId="branding-company-details"
|
||||
>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder={t`Enter your brand details`}
|
||||
@@ -365,7 +413,7 @@ export function BrandingPreferencesForm({
|
||||
</span>
|
||||
)}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
@@ -397,6 +445,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`background-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.background}
|
||||
@@ -420,6 +469,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`foreground-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.foreground}
|
||||
@@ -443,6 +493,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`primary-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.primary}
|
||||
@@ -466,6 +517,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`primary-foreground-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.primaryForeground}
|
||||
@@ -489,6 +541,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`border-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.border}
|
||||
@@ -512,6 +565,7 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`ring-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.ring}
|
||||
@@ -593,6 +647,15 @@ export function BrandingPreferencesForm({
|
||||
isDirty={hasUnsavedChanges}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={handleReset}
|
||||
resetToDefaults={
|
||||
isResetToDefaultsVisible ? (
|
||||
<BrandingPreferencesResetDialog
|
||||
hasAdvancedBranding={hasAdvancedBranding}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={handleResetToDefaults}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Form, FormControl, FormDescription, FormField } from '@documenso/ui/primitives/form/form';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { TeamGlobalSettings } from '@prisma/client';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { FormStickySaveBar } from './form-sticky-save-bar';
|
||||
import { InheritableField } from './inheritable-field';
|
||||
|
||||
const ZCertificatePreferencesFormSchema = z.object({
|
||||
includeSigningCertificate: z.boolean().nullable(),
|
||||
includeAuditLog: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
export type TCertificatePreferencesFormSchema = z.infer<typeof ZCertificatePreferencesFormSchema>;
|
||||
|
||||
type SettingsSubset = Pick<TeamGlobalSettings, 'includeSigningCertificate' | 'includeAuditLog'>;
|
||||
|
||||
export type CertificatePreferencesFormProps = {
|
||||
settings: SettingsSubset;
|
||||
canInherit: boolean;
|
||||
onFormSubmit: (data: TCertificatePreferencesFormSchema) => Promise<void>;
|
||||
};
|
||||
|
||||
export const CertificatePreferencesForm = ({ settings, canInherit, onFormSubmit }: CertificatePreferencesFormProps) => {
|
||||
const form = useForm<TCertificatePreferencesFormSchema>({
|
||||
defaultValues: {
|
||||
includeSigningCertificate: settings.includeSigningCertificate,
|
||||
includeAuditLog: settings.includeAuditLog,
|
||||
},
|
||||
resolver: zodResolver(ZCertificatePreferencesFormSchema),
|
||||
});
|
||||
|
||||
const handleFormSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
await onFormSubmit(data);
|
||||
} catch {
|
||||
// The page handler surfaces its own error toast. Keep the form dirty so
|
||||
// the save bar stays visible and the user can retry.
|
||||
return;
|
||||
}
|
||||
|
||||
form.reset(data);
|
||||
});
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleFormSubmit}>
|
||||
<fieldset className="flex h-full flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="includeSigningCertificate"
|
||||
render={({ field }) => (
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Include the Signing Certificate in the Document</Trans>}
|
||||
testId="include-signing-certificate"
|
||||
>
|
||||
<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"
|
||||
data-testid="include-signing-certificate-trigger"
|
||||
>
|
||||
<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 signing certificate will be included in the document when it is downloaded. The
|
||||
signing certificate can still be downloaded from the logs page separately.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="includeAuditLog"
|
||||
render={({ field }) => (
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Include the Audit Logs in the Document</Trans>}
|
||||
testId="include-audit-log"
|
||||
>
|
||||
<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"
|
||||
data-testid="include-audit-log-trigger"
|
||||
>
|
||||
<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>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormStickySaveBar
|
||||
isDirty={form.formState.isDirty}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={() => form.reset()}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -1,51 +1,35 @@
|
||||
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { IS_AI_FEATURES_CONFIGURED } from '@documenso/lib/constants/app';
|
||||
import { DATE_FORMATS } from '@documenso/lib/constants/date-formats';
|
||||
import { DOCUMENT_SIGNATURE_TYPES, DocumentSignatureType } from '@documenso/lib/constants/document';
|
||||
import {
|
||||
type TEnvelopeExpirationPeriod,
|
||||
ZEnvelopeExpirationPeriod,
|
||||
} from '@documenso/lib/constants/envelope-expiration';
|
||||
import { type TEnvelopeReminderSettings, ZEnvelopeReminderSettings } from '@documenso/lib/constants/envelope-reminder';
|
||||
import { isValidLanguageCode, SUPPORTED_LANGUAGE_CODES, SUPPORTED_LANGUAGES } from '@documenso/lib/constants/i18n';
|
||||
import { TIME_ZONES } from '@documenso/lib/constants/time-zones';
|
||||
import type { TDefaultRecipients } from '@documenso/lib/types/default-recipients';
|
||||
import { ZDefaultRecipientsSchema } from '@documenso/lib/types/default-recipients';
|
||||
import { type TDocumentMetaDateFormat, ZDocumentMetaTimezoneSchema } from '@documenso/lib/types/document-meta';
|
||||
import { isPersonalLayout } from '@documenso/lib/utils/organisations';
|
||||
import { type TDocumentMetaDateFormat, ZDocumentMetaDateFormatSchema } from '@documenso/lib/types/document-meta';
|
||||
import { generateDefaultOrganisationSettings, isPersonalLayout } from '@documenso/lib/utils/organisations';
|
||||
import { recipientAbbreviation } from '@documenso/lib/utils/recipient-formatter';
|
||||
import { extractTeamSignatureSettings } from '@documenso/lib/utils/teams';
|
||||
import { extractTeamSignatureSettings, generateDefaultTeamSettings } from '@documenso/lib/utils/teams';
|
||||
import { DocumentSignatureSettingsTooltip } from '@documenso/ui/components/document/document-signature-settings-tooltip';
|
||||
import { ExpirationPeriodPicker } from '@documenso/ui/components/document/expiration-period-picker';
|
||||
import { ReminderSettingsPicker } from '@documenso/ui/components/document/reminder-settings-picker';
|
||||
import { RecipientRoleSelect } from '@documenso/ui/components/recipient/recipient-role-select';
|
||||
import { Alert } from '@documenso/ui/primitives/alert';
|
||||
import { AvatarWithText } from '@documenso/ui/primitives/avatar';
|
||||
import { Combobox } from '@documenso/ui/primitives/combobox';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@documenso/ui/primitives/form/form';
|
||||
import { Form, FormControl, FormDescription, FormField, FormMessage } from '@documenso/ui/primitives/form/form';
|
||||
import { MultiSelectCombobox } from '@documenso/ui/primitives/multi-select-combobox';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { msg, t } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { TeamGlobalSettings } from '@prisma/client';
|
||||
import { DocumentVisibility, OrganisationType, type RecipientRole } from '@prisma/client';
|
||||
import { DocumentVisibility, type RecipientRole, type TeamGlobalSettings } from '@prisma/client';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { DocumentPreferencesResetDialog } from '~/components/dialogs/document-preferences-reset-dialog';
|
||||
import { useOptionalCurrentTeam } from '~/providers/team';
|
||||
|
||||
import { DefaultRecipientsMultiSelectCombobox } from '../general/default-recipients-multiselect-combobox';
|
||||
import { FormStickySaveBar } from './form-sticky-save-bar';
|
||||
import { InheritableField } from './inheritable-field';
|
||||
|
||||
/**
|
||||
* Can't infer this from the schema since we need to keep the schema inside the component to allow
|
||||
@@ -56,15 +40,10 @@ export type TDocumentPreferencesFormSchema = {
|
||||
documentLanguage: (typeof SUPPORTED_LANGUAGE_CODES)[number] | null;
|
||||
documentTimezone: string | null;
|
||||
documentDateFormat: TDocumentMetaDateFormat | null;
|
||||
includeSenderDetails: boolean | null;
|
||||
includeSigningCertificate: boolean | null;
|
||||
includeAuditLog: boolean | null;
|
||||
signatureTypes: DocumentSignatureType[];
|
||||
defaultRecipients: TDefaultRecipients | null;
|
||||
delegateDocumentOwnership: boolean | null;
|
||||
aiFeaturesEnabled: boolean | null;
|
||||
envelopeExpirationPeriod: TEnvelopeExpirationPeriod | null;
|
||||
reminderSettings: TEnvelopeReminderSettings | null;
|
||||
};
|
||||
|
||||
type SettingsSubset = Pick<
|
||||
@@ -73,80 +52,85 @@ type SettingsSubset = Pick<
|
||||
| 'documentLanguage'
|
||||
| 'documentTimezone'
|
||||
| 'documentDateFormat'
|
||||
| 'includeSenderDetails'
|
||||
| 'includeSigningCertificate'
|
||||
| 'includeAuditLog'
|
||||
| 'typedSignatureEnabled'
|
||||
| 'uploadSignatureEnabled'
|
||||
| 'drawSignatureEnabled'
|
||||
| 'defaultRecipients'
|
||||
| 'delegateDocumentOwnership'
|
||||
| 'aiFeaturesEnabled'
|
||||
| 'envelopeExpirationPeriod'
|
||||
| 'reminderSettings'
|
||||
>;
|
||||
|
||||
export type DocumentPreferencesFormProps = {
|
||||
settings: SettingsSubset;
|
||||
canInherit: boolean;
|
||||
isAiFeaturesConfigured?: boolean;
|
||||
onFormSubmit: (data: TDocumentPreferencesFormSchema) => Promise<void>;
|
||||
};
|
||||
|
||||
export const DocumentPreferencesForm = ({
|
||||
settings,
|
||||
onFormSubmit,
|
||||
canInherit,
|
||||
isAiFeaturesConfigured = false,
|
||||
}: DocumentPreferencesFormProps) => {
|
||||
const getDocumentPreferencesFormValues = (settings: SettingsSubset): TDocumentPreferencesFormSchema => {
|
||||
const parsedDocumentDateFormat = ZDocumentMetaDateFormatSchema.safeParse(settings.documentDateFormat);
|
||||
|
||||
return {
|
||||
documentVisibility: settings.documentVisibility,
|
||||
documentLanguage: isValidLanguageCode(settings.documentLanguage) ? settings.documentLanguage : null,
|
||||
documentTimezone: settings.documentTimezone,
|
||||
documentDateFormat: parsedDocumentDateFormat.success ? parsedDocumentDateFormat.data : null,
|
||||
signatureTypes: extractTeamSignatureSettings({ ...settings }),
|
||||
defaultRecipients: settings.defaultRecipients ? ZDefaultRecipientsSchema.parse(settings.defaultRecipients) : null,
|
||||
delegateDocumentOwnership: settings.delegateDocumentOwnership,
|
||||
aiFeaturesEnabled: settings.aiFeaturesEnabled,
|
||||
};
|
||||
};
|
||||
|
||||
export const DocumentPreferencesForm = ({ settings, onFormSubmit, canInherit }: DocumentPreferencesFormProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { user, organisations } = useSession();
|
||||
const { organisations } = useSession();
|
||||
const currentOrganisation = useCurrentOrganisation();
|
||||
const optionalTeam = useOptionalCurrentTeam();
|
||||
|
||||
const isPersonalLayoutMode = isPersonalLayout(organisations);
|
||||
const isPersonalOrganisation = currentOrganisation.type === OrganisationType.PERSONAL;
|
||||
const isAiFeaturesConfigured = IS_AI_FEATURES_CONFIGURED();
|
||||
|
||||
const placeholderEmail = user.email ?? 'user@example.com';
|
||||
const isPersonalLayoutMode = isPersonalLayout(organisations);
|
||||
|
||||
const ZDocumentPreferencesFormSchema = z.object({
|
||||
documentVisibility: z.nativeEnum(DocumentVisibility).nullable(),
|
||||
documentLanguage: z.enum(SUPPORTED_LANGUAGE_CODES).nullable(),
|
||||
documentTimezone: z.string().nullable(),
|
||||
documentDateFormat: ZDocumentMetaTimezoneSchema.nullable(),
|
||||
includeSenderDetails: z.boolean().nullable(),
|
||||
includeSigningCertificate: z.boolean().nullable(),
|
||||
includeAuditLog: z.boolean().nullable(),
|
||||
documentDateFormat: ZDocumentMetaDateFormatSchema.nullable(),
|
||||
signatureTypes: z.array(z.nativeEnum(DocumentSignatureType)).min(canInherit ? 0 : 1, {
|
||||
message: msg`At least one signature type must be enabled`.id,
|
||||
}),
|
||||
defaultRecipients: ZDefaultRecipientsSchema.nullable(),
|
||||
delegateDocumentOwnership: z.boolean().nullable(),
|
||||
aiFeaturesEnabled: z.boolean().nullable(),
|
||||
envelopeExpirationPeriod: ZEnvelopeExpirationPeriod.nullable(),
|
||||
reminderSettings: ZEnvelopeReminderSettings.nullable(),
|
||||
});
|
||||
|
||||
const defaultValues = getDocumentPreferencesFormValues(settings);
|
||||
const defaultSettings = canInherit ? generateDefaultTeamSettings() : generateDefaultOrganisationSettings();
|
||||
const baseResetValues = getDocumentPreferencesFormValues(defaultSettings);
|
||||
const resetValues = {
|
||||
...baseResetValues,
|
||||
aiFeaturesEnabled: isAiFeaturesConfigured ? baseResetValues.aiFeaturesEnabled : defaultValues.aiFeaturesEnabled,
|
||||
};
|
||||
|
||||
const form = useForm<TDocumentPreferencesFormSchema>({
|
||||
defaultValues: {
|
||||
documentVisibility: settings.documentVisibility,
|
||||
documentLanguage: isValidLanguageCode(settings.documentLanguage) ? settings.documentLanguage : null,
|
||||
documentTimezone: settings.documentTimezone,
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
documentDateFormat: settings.documentDateFormat as TDocumentMetaDateFormat | null,
|
||||
includeSenderDetails: settings.includeSenderDetails,
|
||||
includeSigningCertificate: settings.includeSigningCertificate,
|
||||
includeAuditLog: settings.includeAuditLog,
|
||||
signatureTypes: extractTeamSignatureSettings({ ...settings }),
|
||||
defaultRecipients: settings.defaultRecipients ? ZDefaultRecipientsSchema.parse(settings.defaultRecipients) : null,
|
||||
delegateDocumentOwnership: settings.delegateDocumentOwnership,
|
||||
aiFeaturesEnabled: settings.aiFeaturesEnabled,
|
||||
envelopeExpirationPeriod: settings.envelopeExpirationPeriod ?? null,
|
||||
reminderSettings: settings.reminderSettings ?? null,
|
||||
},
|
||||
defaultValues,
|
||||
resolver: zodResolver(ZDocumentPreferencesFormSchema),
|
||||
});
|
||||
|
||||
// Parse both sides through the schema so we compare canonical representations
|
||||
const parsedCurrentValues = ZDocumentPreferencesFormSchema.safeParse(defaultValues);
|
||||
const parsedResetValues = ZDocumentPreferencesFormSchema.safeParse(resetValues);
|
||||
|
||||
const isResetToDefaultsVisible =
|
||||
!parsedCurrentValues.success ||
|
||||
!parsedResetValues.success ||
|
||||
JSON.stringify(parsedCurrentValues.data) !== JSON.stringify(parsedResetValues.data);
|
||||
|
||||
const handleResetToDefaults = async () => {
|
||||
await onFormSubmit(resetValues);
|
||||
form.reset(resetValues);
|
||||
};
|
||||
|
||||
const handleFormSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
await onFormSubmit(data);
|
||||
@@ -162,17 +146,19 @@ export const DocumentPreferencesForm = ({
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleFormSubmit}>
|
||||
<fieldset className="flex h-full max-w-2xl flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
<fieldset className="flex h-full flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
{!isPersonalLayoutMode && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="documentVisibility"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Document Visibility</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Document Visibility</Trans>}
|
||||
testId="document-visibility"
|
||||
>
|
||||
<FormControl>
|
||||
<Select
|
||||
{...field}
|
||||
@@ -209,7 +195,7 @@ export const DocumentPreferencesForm = ({
|
||||
<FormDescription>
|
||||
<Trans>Controls the default visibility of an uploaded document.</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
@@ -218,11 +204,13 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="documentLanguage"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Document Language</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Document Language</Trans>}
|
||||
testId="document-language"
|
||||
>
|
||||
<FormControl>
|
||||
<Select
|
||||
{...field}
|
||||
@@ -256,7 +244,7 @@ export const DocumentPreferencesForm = ({
|
||||
communications with the recipients.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -264,11 +252,12 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="documentDateFormat"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans>Default Date Format</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Date Format</Trans>}
|
||||
testId="document-date-format"
|
||||
>
|
||||
<FormControl>
|
||||
<Select
|
||||
value={field.value === null ? '-1' : field.value}
|
||||
@@ -295,7 +284,7 @@ export const DocumentPreferencesForm = ({
|
||||
</FormControl>
|
||||
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -303,11 +292,12 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="documentTimezone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans>Default Time Zone</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Time Zone</Trans>}
|
||||
testId="document-timezone"
|
||||
>
|
||||
<FormControl>
|
||||
<Combobox
|
||||
triggerPlaceholder={canInherit ? t`Inherit from organisation` : t`Local timezone`}
|
||||
@@ -320,7 +310,7 @@ export const DocumentPreferencesForm = ({
|
||||
</FormControl>
|
||||
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -328,12 +318,18 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="signatureTypes"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel className="flex flex-row items-center">
|
||||
<Trans>Default Signature Settings</Trans>
|
||||
<DocumentSignatureSettingsTooltip />
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={canInherit && (field.value === null || field.value.length === 0)}
|
||||
label={
|
||||
<span className="flex flex-row items-center">
|
||||
<Trans>Default Signature Settings</Trans>
|
||||
<DocumentSignatureSettingsTooltip />
|
||||
</span>
|
||||
}
|
||||
testId="signature-types"
|
||||
>
|
||||
<FormControl>
|
||||
<MultiSelectCombobox
|
||||
options={Object.values(DOCUMENT_SIGNATURE_TYPES).map((option) => ({
|
||||
@@ -356,179 +352,7 @@ export const DocumentPreferencesForm = ({
|
||||
<Trans>Controls which signatures are allowed to be used when signing a document.</Trans>
|
||||
</FormDescription>
|
||||
)}
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!isPersonalLayoutMode && !isPersonalOrganisation && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="includeSenderDetails"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Send on Behalf of Team</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"
|
||||
data-testid="include-sender-details-trigger"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div className="pt-2">
|
||||
<div className="font-medium text-muted-foreground text-xs">
|
||||
<Trans>Preview</Trans>
|
||||
</div>
|
||||
|
||||
<Alert variant="neutral" className="mt-1 px-2.5 py-1.5 text-sm">
|
||||
{field.value ? (
|
||||
<Trans>
|
||||
"{placeholderEmail}" on behalf of "Team Name" has invited you to sign "example document".
|
||||
</Trans>
|
||||
) : (
|
||||
<Trans>"Team Name" has invited you to sign "example document".</Trans>
|
||||
)}
|
||||
</Alert>
|
||||
</div>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls the formatting of the message that will be sent when inviting a recipient to sign a
|
||||
document. If a custom message has been provided while configuring the document, it will be used
|
||||
instead.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="includeSigningCertificate"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Include the Signing Certificate 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"
|
||||
data-testid="include-signing-certificate-trigger"
|
||||
>
|
||||
<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 signing certificate will be included in the document when it is downloaded. The
|
||||
signing certificate can still be downloaded from the logs page separately.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<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>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -539,11 +363,13 @@ export const DocumentPreferencesForm = ({
|
||||
const recipients = field.value ?? [];
|
||||
|
||||
return (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Recipients</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Recipients</Trans>}
|
||||
testId="default-recipients"
|
||||
>
|
||||
{canInherit && (
|
||||
<Select
|
||||
value={field.value === null ? '-1' : '0'}
|
||||
@@ -611,7 +437,7 @@ export const DocumentPreferencesForm = ({
|
||||
<FormDescription>
|
||||
<Trans>Recipients that will be automatically added to new documents.</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
@@ -620,11 +446,13 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="delegateDocumentOwnership"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Delegate Document Ownership</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Delegate Document Ownership</Trans>}
|
||||
testId="delegate-document-ownership"
|
||||
>
|
||||
<Select
|
||||
{...field}
|
||||
value={field.value === null ? '-1' : field.value.toString()}
|
||||
@@ -654,65 +482,7 @@ export const DocumentPreferencesForm = ({
|
||||
<FormDescription>
|
||||
<Trans>Enable team API tokens to delegate document ownership to another team member.</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="envelopeExpirationPeriod"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Envelope Expiration</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<FormControl>
|
||||
<ExpirationPeriodPicker
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
inheritLabel={canInherit ? t`Inherit from organisation` : undefined}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls how long recipients have to complete signing before the document expires. After expiration,
|
||||
recipients can no longer sign the document.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="reminderSettings"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Signing Reminders</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<FormControl>
|
||||
<ReminderSettingsPicker
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
inheritLabel={canInherit ? t`Inherit from organisation` : undefined}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls when and how often reminder emails are sent to recipients who have not yet completed
|
||||
signing.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -721,11 +491,13 @@ export const DocumentPreferencesForm = ({
|
||||
control={form.control}
|
||||
name="aiFeaturesEnabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>AI Features</Trans>
|
||||
</FormLabel>
|
||||
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>AI Features</Trans>}
|
||||
testId="ai-features-enabled"
|
||||
>
|
||||
<FormControl>
|
||||
<Select
|
||||
{...field}
|
||||
@@ -763,7 +535,7 @@ export const DocumentPreferencesForm = ({
|
||||
prefer European regions where available.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
@@ -772,6 +544,16 @@ export const DocumentPreferencesForm = ({
|
||||
isDirty={form.formState.isDirty}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={() => form.reset()}
|
||||
resetToDefaults={
|
||||
isResetToDefaultsVisible ? (
|
||||
<DocumentPreferencesResetDialog
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={handleResetToDefaults}
|
||||
showAiFeatures={isAiFeaturesConfigured}
|
||||
showDocumentVisibility={!isPersonalLayoutMode}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useCurrentOrganisation } from '@documenso/lib/client-only/providers/organisation';
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { FROM_ADDRESS } from '@documenso/lib/constants/email';
|
||||
import { DEFAULT_DOCUMENT_EMAIL_SETTINGS, ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
|
||||
import { zEmail } from '@documenso/lib/utils/zod';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { DocumentEmailCheckboxes } from '@documenso/ui/components/document/document-email-checkboxes';
|
||||
import { Alert } from '@documenso/ui/primitives/alert';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -17,22 +19,27 @@ import { Input } from '@documenso/ui/primitives/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { TeamGlobalSettings } from '@prisma/client';
|
||||
import { OrganisationType, type TeamGlobalSettings } from '@prisma/client';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { FormStickySaveBar } from './form-sticky-save-bar';
|
||||
import { InheritableField } from './inheritable-field';
|
||||
|
||||
const ZEmailPreferencesFormSchema = z.object({
|
||||
emailId: z.string().nullable(),
|
||||
emailReplyTo: zEmail().nullable(),
|
||||
// emailReplyToName: z.string(),
|
||||
emailDocumentSettings: ZDocumentEmailSettingsSchema.nullable(),
|
||||
includeSenderDetails: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
export type TEmailPreferencesFormSchema = z.infer<typeof ZEmailPreferencesFormSchema>;
|
||||
|
||||
type SettingsSubset = Pick<TeamGlobalSettings, 'emailId' | 'emailReplyTo' | 'emailDocumentSettings'>;
|
||||
type SettingsSubset = Pick<
|
||||
TeamGlobalSettings,
|
||||
'emailId' | 'emailReplyTo' | 'emailDocumentSettings' | 'includeSenderDetails'
|
||||
>;
|
||||
|
||||
export type EmailPreferencesFormProps = {
|
||||
settings: SettingsSubset;
|
||||
@@ -41,14 +48,20 @@ export type EmailPreferencesFormProps = {
|
||||
};
|
||||
|
||||
export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: EmailPreferencesFormProps) => {
|
||||
const { user } = useSession();
|
||||
const organisation = useCurrentOrganisation();
|
||||
|
||||
const isPersonalOrganisation = organisation.type === OrganisationType.PERSONAL;
|
||||
|
||||
const placeholderEmail = user.email ?? 'user@example.com';
|
||||
|
||||
const form = useForm<TEmailPreferencesFormSchema>({
|
||||
defaultValues: {
|
||||
emailId: settings.emailId,
|
||||
emailReplyTo: settings.emailReplyTo,
|
||||
// emailReplyToName: settings.emailReplyToName,
|
||||
emailDocumentSettings: settings.emailDocumentSettings,
|
||||
includeSenderDetails: settings.includeSenderDetails,
|
||||
},
|
||||
resolver: zodResolver(ZEmailPreferencesFormSchema),
|
||||
});
|
||||
@@ -75,7 +88,7 @@ export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: Ema
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleFormSubmit}>
|
||||
<fieldset className="flex h-full max-w-2xl flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
<fieldset className="flex h-full flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
{organisation.organisationClaim.flags.emailDomains && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
@@ -122,10 +135,12 @@ export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: Ema
|
||||
control={form.control}
|
||||
name="emailReplyTo"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans>Reply to email</Trans>
|
||||
</FormLabel>
|
||||
<InheritableField
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Reply to email</Trans>}
|
||||
testId="email-reply-to"
|
||||
>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
@@ -146,7 +161,7 @@ export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: Ema
|
||||
</span>
|
||||
)}
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -170,10 +185,13 @@ export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: Ema
|
||||
control={form.control}
|
||||
name="emailDocumentSettings"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormLabel>
|
||||
<Trans>Default Email Settings</Trans>
|
||||
</FormLabel>
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Email Settings</Trans>}
|
||||
testId="email-document-settings"
|
||||
>
|
||||
{canInherit && (
|
||||
<Select
|
||||
value={field.value === null ? 'INHERIT' : 'CONTROLLED'}
|
||||
@@ -212,10 +230,83 @@ export const EmailPreferencesForm = ({ settings, onFormSubmit, canInherit }: Ema
|
||||
settings will not affect existing documents or templates.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!isPersonalOrganisation && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="includeSenderDetails"
|
||||
render={({ field }) => (
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Send on Behalf of Team</Trans>}
|
||||
testId="include-sender-details"
|
||||
>
|
||||
<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"
|
||||
data-testid="include-sender-details-trigger"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div className="pt-2">
|
||||
<div className="font-medium text-muted-foreground text-xs">
|
||||
<Trans>Preview</Trans>
|
||||
</div>
|
||||
|
||||
<Alert variant="neutral" className="mt-1 px-2.5 py-1.5 text-sm">
|
||||
{field.value ? (
|
||||
<Trans>
|
||||
"{placeholderEmail}" on behalf of "Team Name" has invited you to sign "example document".
|
||||
</Trans>
|
||||
) : (
|
||||
<Trans>"Team Name" has invited you to sign "example document".</Trans>
|
||||
)}
|
||||
</Alert>
|
||||
</div>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls the formatting of the message that will be sent when inviting a recipient to sign a
|
||||
document. If a custom message has been provided while configuring the document, it will be used
|
||||
instead.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormStickySaveBar
|
||||
isDirty={form.formState.isDirty}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
|
||||
@@ -3,12 +3,33 @@ import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Trans, useLingui } from '@lingui/react/macro';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { AlertTriangleIcon } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { type ReactNode, useEffect, useRef, useState } from 'react';
|
||||
|
||||
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
|
||||
let current = node.parentElement;
|
||||
|
||||
while (current) {
|
||||
const { overflowY } = getComputedStyle(current);
|
||||
|
||||
if (overflowY === 'auto' || overflowY === 'scroll') {
|
||||
return current;
|
||||
}
|
||||
|
||||
current = current.parentElement;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export type FormStickySaveBarProps = {
|
||||
isDirty: boolean;
|
||||
isSubmitting: boolean;
|
||||
onReset: () => void;
|
||||
/**
|
||||
* Slot for a "reset to defaults" action, rendered before the Undo button. Hidden while
|
||||
* the bar is floating so it never appears in the unsaved-changes island.
|
||||
*/
|
||||
resetToDefaults?: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -24,7 +45,7 @@ export type FormStickySaveBarProps = {
|
||||
* shared-layout morph). A 1px sentinel below it detects the stuck state so we can toggle
|
||||
* the pill chrome.
|
||||
*/
|
||||
export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset }: FormStickySaveBarProps) => {
|
||||
export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset, resetToDefaults }: FormStickySaveBarProps) => {
|
||||
const { t } = useLingui();
|
||||
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
@@ -38,14 +59,18 @@ export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset }: FormSticky
|
||||
}
|
||||
|
||||
// The sentinel sits at the bar's resting position (the end of the form). While the
|
||||
// bar is stuck to the bottom of the viewport the sentinel is scrolled past (out of
|
||||
// view); once you reach the form's end it comes into view and the bar settles.
|
||||
// bar is stuck to the bottom of the scroll container the sentinel is scrolled past
|
||||
// (out of view); once you reach the form's end it comes into view and the bar settles.
|
||||
//
|
||||
// Observe relative to the actual scroll container (not always the viewport) so a
|
||||
// banner shifting the page can't desync the detection from the sticky bar — both
|
||||
// then share the same reference box.
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
setIsStuck(!entry.isIntersecting);
|
||||
},
|
||||
{
|
||||
root: null,
|
||||
root: getScrollParent(sentinel),
|
||||
rootMargin: '0px 0px -24px 0px',
|
||||
threshold: 0,
|
||||
},
|
||||
@@ -100,6 +125,8 @@ export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset }: FormSticky
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="ml-auto flex flex-shrink-0 items-center gap-x-2">
|
||||
{!isFloating && resetToDefaults}
|
||||
|
||||
{isDirty && (
|
||||
<Button type="button" variant="secondary" size="sm" onClick={onReset} disabled={isSubmitting}>
|
||||
<Trans>Undo</Trans>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { FormItem, FormLabel } from '@documenso/ui/primitives/form/form';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export type InheritableFieldProps = {
|
||||
isInherited: boolean;
|
||||
canInherit: boolean;
|
||||
label: ReactNode;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
testId?: string;
|
||||
};
|
||||
|
||||
export const InheritableField = ({
|
||||
isInherited,
|
||||
canInherit,
|
||||
label,
|
||||
children,
|
||||
className,
|
||||
testId,
|
||||
}: InheritableFieldProps) => {
|
||||
if (!canInherit) {
|
||||
return (
|
||||
<FormItem className={className}>
|
||||
<FormLabel>{label}</FormLabel>
|
||||
{children}
|
||||
</FormItem>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<FormItem className={className} data-testid={testId ? `inheritable-${testId}` : undefined}>
|
||||
<FormLabel className="flex items-center gap-2">
|
||||
{label}
|
||||
<span
|
||||
className={cn(
|
||||
'rounded px-1.5 py-0.5 font-bold text-[9px] uppercase tracking-wide',
|
||||
isInherited
|
||||
? 'bg-muted text-muted-foreground'
|
||||
: 'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300',
|
||||
)}
|
||||
data-testid={testId ? `${testId}-status` : undefined}
|
||||
>
|
||||
{isInherited ? <Trans>Inherited</Trans> : <Trans>Override</Trans>}
|
||||
</span>
|
||||
</FormLabel>
|
||||
{children}
|
||||
</FormItem>
|
||||
);
|
||||
};
|
||||
@@ -56,7 +56,7 @@ export const OrganisationUpdateForm = () => {
|
||||
await refreshSession();
|
||||
|
||||
if (url !== organisation.url) {
|
||||
await navigate(`/o/${url}/settings`);
|
||||
await navigate(`/o/${url}/settings/general`);
|
||||
}
|
||||
|
||||
toast({
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { usePasswordSetupRequest } from '@documenso/lib/client-only/hooks/use-password-setup-request';
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { CheckIcon } from 'lucide-react';
|
||||
import { match } from 'ts-pattern';
|
||||
|
||||
/**
|
||||
* Compact "send me a setup link" button that reports via toast, for settings
|
||||
* cards where the surrounding layout provides the explanation.
|
||||
*/
|
||||
export const PasswordSetupRequestButton = () => {
|
||||
const { _ } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const { user } = useSession();
|
||||
|
||||
const { requestSetupLink, isPending, isSuccess } = usePasswordSetupRequest({
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: _(msg`Check your email`),
|
||||
description: _(msg`We've sent a link to ${user.email}. Follow it to set your password.`),
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
onError: (errorCode) => {
|
||||
toast({
|
||||
title: _(msg`An error occurred`),
|
||||
description: match(errorCode)
|
||||
.with('SIGNIN_DISABLED', () => _(msg`Password sign in is disabled for this instance.`))
|
||||
.otherwise(() => _(msg`We were unable to send the email. Please try again later.`)),
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (isSuccess) {
|
||||
return (
|
||||
<Button variant="outline" className="flex-shrink-0 bg-background" disabled>
|
||||
<CheckIcon className="mr-2 h-4 w-4" />
|
||||
<Trans>Link sent</Trans>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="outline" className="flex-shrink-0 bg-background" loading={isPending} onClick={requestSetupLink}>
|
||||
<Trans>Send setup link</Trans>
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { usePasswordSetupRequest } from '@documenso/lib/client-only/hooks/use-password-setup-request';
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { match } from 'ts-pattern';
|
||||
|
||||
export type PasswordSetupRequestProps = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Inline "send me a setup link" control with its own sent/error states, for
|
||||
* contexts like dialogs where a toast would be missed.
|
||||
*/
|
||||
export const PasswordSetupRequest = ({ className }: PasswordSetupRequestProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { user } = useSession();
|
||||
|
||||
const { requestSetupLink, isPending, isSuccess, errorCode } = usePasswordSetupRequest();
|
||||
|
||||
if (isSuccess) {
|
||||
return (
|
||||
<Alert className={className} variant="neutral">
|
||||
<AlertTitle>
|
||||
<Trans>Check your email</Trans>
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
<Trans>
|
||||
We've sent a link to {user.email}. Follow it to set your password, then sign in again to continue.
|
||||
</Trans>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{errorCode && (
|
||||
<Alert className="mb-4" variant="destructive">
|
||||
<AlertTitle>
|
||||
<Trans>An error occurred</Trans>
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{match(errorCode)
|
||||
.with('SIGNIN_DISABLED', () =>
|
||||
_(msg`Password sign in is disabled for this instance. Please contact support.`),
|
||||
)
|
||||
.otherwise(() => _(msg`We were unable to send the email. Please try again or contact support.`))}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button type="button" loading={isPending} onClick={requestSetupLink}>
|
||||
<Trans>Send setup link</Trans>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { authClient } from '@documenso/auth/client';
|
||||
import type { SessionUser } from '@documenso/auth/server/lib/session/session';
|
||||
import { AppError } from '@documenso/lib/errors/app-error';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { ZCurrentPasswordSchema, ZPasswordSchema } from '@documenso/trpc/server/auth-router/schema';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
@@ -11,20 +11,21 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { match } from 'ts-pattern';
|
||||
import { z } from 'zod';
|
||||
import type { z } from 'zod';
|
||||
|
||||
export const ZPasswordFormSchema = z
|
||||
.object({
|
||||
currentPassword: ZCurrentPasswordSchema,
|
||||
password: ZPasswordSchema,
|
||||
repeatedPassword: ZPasswordSchema,
|
||||
})
|
||||
.refine((data) => data.password === data.repeatedPassword, {
|
||||
message: 'Passwords do not match',
|
||||
path: ['repeatedPassword'],
|
||||
});
|
||||
import { hasTwoFactorCode, TwoFactorCodeDialog, ZTwoFactorCodeFieldSchema } from './2fa/two-factor-code-dialog';
|
||||
|
||||
export const ZPasswordFormSchema = ZTwoFactorCodeFieldSchema.extend({
|
||||
currentPassword: ZCurrentPasswordSchema,
|
||||
password: ZPasswordSchema,
|
||||
repeatedPassword: ZPasswordSchema,
|
||||
}).refine((data) => data.password === data.repeatedPassword, {
|
||||
message: 'Passwords do not match',
|
||||
path: ['repeatedPassword'],
|
||||
});
|
||||
|
||||
export type TPasswordFormSchema = z.infer<typeof ZPasswordFormSchema>;
|
||||
|
||||
@@ -33,29 +34,51 @@ export type PasswordFormProps = {
|
||||
user: SessionUser;
|
||||
};
|
||||
|
||||
export const PasswordForm = ({ className }: PasswordFormProps) => {
|
||||
export const PasswordForm = ({ className, user }: PasswordFormProps) => {
|
||||
const { _ } = useLingui();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [isTwoFactorDialogOpen, setIsTwoFactorDialogOpen] = useState(false);
|
||||
|
||||
const form = useForm<TPasswordFormSchema>({
|
||||
values: {
|
||||
currentPassword: '',
|
||||
password: '',
|
||||
repeatedPassword: '',
|
||||
totpCode: '',
|
||||
backupCode: '',
|
||||
},
|
||||
resolver: zodResolver(ZPasswordFormSchema),
|
||||
});
|
||||
|
||||
const isSubmitting = form.formState.isSubmitting;
|
||||
|
||||
const onFormSubmit = async ({ currentPassword, password }: TPasswordFormSchema) => {
|
||||
const onFormSubmit = async (values: TPasswordFormSchema) => {
|
||||
const { currentPassword, password, totpCode, backupCode } = values;
|
||||
|
||||
// Collect the 2FA code in a dialog once the password fields are valid.
|
||||
if (user.twoFactorEnabled && !hasTwoFactorCode(values)) {
|
||||
if (isTwoFactorDialogOpen) {
|
||||
const message = _(msg`A code is required`);
|
||||
|
||||
form.setError('totpCode', { message });
|
||||
form.setError('backupCode', { message });
|
||||
}
|
||||
|
||||
setIsTwoFactorDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await authClient.emailPassword.updatePassword({
|
||||
currentPassword,
|
||||
password,
|
||||
totpCode: totpCode || undefined,
|
||||
backupCode: backupCode || undefined,
|
||||
});
|
||||
|
||||
form.reset();
|
||||
setIsTwoFactorDialogOpen(false);
|
||||
|
||||
toast({
|
||||
title: _(msg`Password updated`),
|
||||
@@ -66,9 +89,14 @@ export const PasswordForm = ({ className }: PasswordFormProps) => {
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
const errorMessage = match(error.code)
|
||||
.with('NO_PASSWORD', () => msg`User has no password.`)
|
||||
.with('INCORRECT_PASSWORD', () => msg`Current password is incorrect.`)
|
||||
.with('SAME_PASSWORD', () => msg`Your new password cannot be the same as your old password.`)
|
||||
.with(AppErrorCode.NO_PASSWORD, () => msg`User has no password.`)
|
||||
.with(AppErrorCode.INCORRECT_PASSWORD, () => msg`Current password is incorrect.`)
|
||||
.with(AppErrorCode.SAME_PASSWORD, () => msg`Your new password cannot be the same as your old password.`)
|
||||
.with(
|
||||
AppErrorCode.INCORRECT_TWO_FACTOR_CODE,
|
||||
AppErrorCode.TWO_FACTOR_MISSING_CREDENTIALS,
|
||||
() => msg`The two factor code you provided is invalid. Please try again.`,
|
||||
)
|
||||
.otherwise(
|
||||
() => msg`We encountered an unknown error while attempting to update your password. Please try again later.`,
|
||||
);
|
||||
@@ -83,7 +111,12 @@ export const PasswordForm = ({ className }: PasswordFormProps) => {
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form className={cn('flex w-full flex-col gap-y-4', className)} onSubmit={form.handleSubmit(onFormSubmit)}>
|
||||
{/* method="post" so a pre-hydration native submit can't leak passwords into the URL. */}
|
||||
<form
|
||||
method="post"
|
||||
className={cn('flex w-full flex-col gap-y-4', className)}
|
||||
onSubmit={form.handleSubmit(onFormSubmit)}
|
||||
>
|
||||
<fieldset className="flex w-full flex-col gap-y-4" disabled={isSubmitting}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
@@ -140,6 +173,14 @@ export const PasswordForm = ({ className }: PasswordFormProps) => {
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<TwoFactorCodeDialog<TPasswordFormSchema>
|
||||
open={isTwoFactorDialogOpen}
|
||||
onOpenChange={setIsTwoFactorDialogOpen}
|
||||
isSubmitting={isSubmitting}
|
||||
submitLabel={<Trans>Update password</Trans>}
|
||||
onSubmit={form.handleSubmit(onFormSubmit)}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
type TEnvelopeExpirationPeriod,
|
||||
ZEnvelopeExpirationPeriod,
|
||||
} from '@documenso/lib/constants/envelope-expiration';
|
||||
import { type TEnvelopeReminderSettings, ZEnvelopeReminderSettings } from '@documenso/lib/constants/envelope-reminder';
|
||||
import { ExpirationPeriodPicker } from '@documenso/ui/components/document/expiration-period-picker';
|
||||
import { ReminderSettingsPicker } from '@documenso/ui/components/document/reminder-settings-picker';
|
||||
import { Form, FormControl, FormDescription, FormField, FormMessage } from '@documenso/ui/primitives/form/form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Trans, useLingui } from '@lingui/react/macro';
|
||||
import type { TeamGlobalSettings } from '@prisma/client';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { FormStickySaveBar } from './form-sticky-save-bar';
|
||||
import { InheritableField } from './inheritable-field';
|
||||
|
||||
const ZReminderPreferencesFormSchema = z.object({
|
||||
envelopeExpirationPeriod: ZEnvelopeExpirationPeriod.nullable(),
|
||||
reminderSettings: ZEnvelopeReminderSettings.nullable(),
|
||||
});
|
||||
|
||||
export type TReminderPreferencesFormSchema = {
|
||||
envelopeExpirationPeriod: TEnvelopeExpirationPeriod | null;
|
||||
reminderSettings: TEnvelopeReminderSettings | null;
|
||||
};
|
||||
|
||||
type SettingsSubset = Pick<TeamGlobalSettings, 'envelopeExpirationPeriod' | 'reminderSettings'>;
|
||||
|
||||
export type ReminderPreferencesFormProps = {
|
||||
settings: SettingsSubset;
|
||||
canInherit: boolean;
|
||||
onFormSubmit: (data: TReminderPreferencesFormSchema) => Promise<void>;
|
||||
};
|
||||
|
||||
export const ReminderPreferencesForm = ({ settings, canInherit, onFormSubmit }: ReminderPreferencesFormProps) => {
|
||||
const { t } = useLingui();
|
||||
|
||||
const form = useForm<TReminderPreferencesFormSchema>({
|
||||
defaultValues: {
|
||||
envelopeExpirationPeriod: settings.envelopeExpirationPeriod ?? null,
|
||||
reminderSettings: settings.reminderSettings ?? null,
|
||||
},
|
||||
resolver: zodResolver(ZReminderPreferencesFormSchema),
|
||||
});
|
||||
|
||||
const handleFormSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
await onFormSubmit(data);
|
||||
} catch {
|
||||
// The page handler surfaces its own error toast. Keep the form dirty so
|
||||
// the save bar stays visible and the user can retry.
|
||||
return;
|
||||
}
|
||||
|
||||
form.reset(data);
|
||||
});
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleFormSubmit}>
|
||||
<fieldset className="flex h-full flex-col gap-y-6" disabled={form.formState.isSubmitting}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="envelopeExpirationPeriod"
|
||||
render={({ field }) => (
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Envelope Expiration</Trans>}
|
||||
testId="envelope-expiration-period"
|
||||
>
|
||||
<FormControl>
|
||||
<ExpirationPeriodPicker
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
inheritLabel={canInherit ? t`Inherit from organisation` : undefined}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls how long recipients have to complete signing before the document expires. After expiration,
|
||||
recipients can no longer sign the document.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
|
||||
<FormMessage />
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="reminderSettings"
|
||||
render={({ field }) => (
|
||||
<InheritableField
|
||||
className="flex-1"
|
||||
canInherit={canInherit}
|
||||
isInherited={field.value === null}
|
||||
label={<Trans>Default Signing Reminders</Trans>}
|
||||
testId="reminder-settings"
|
||||
>
|
||||
<FormControl>
|
||||
<ReminderSettingsPicker
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
inheritLabel={canInherit ? t`Inherit from organisation` : undefined}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormDescription>
|
||||
<Trans>
|
||||
Controls when and how often reminder emails are sent to recipients who have not yet completed
|
||||
signing.
|
||||
</Trans>
|
||||
</FormDescription>
|
||||
|
||||
<FormMessage />
|
||||
</InheritableField>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormStickySaveBar
|
||||
isDirty={form.formState.isDirty}
|
||||
isSubmitting={form.formState.isSubmitting}
|
||||
onReset={() => form.reset()}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { authClient } from '@documenso/auth/client';
|
||||
import { AuthenticationErrorCode } from '@documenso/auth/server/lib/errors/error-codes';
|
||||
import { formatPath } from '@documenso/lib/constants/app';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { env } from '@documenso/lib/utils/env';
|
||||
import { zEmail } from '@documenso/lib/utils/zod';
|
||||
@@ -44,7 +45,7 @@ const handleFallbackErrorMessages = (code: string) => {
|
||||
return message;
|
||||
};
|
||||
|
||||
const LOGIN_REDIRECT_PATH = '/';
|
||||
const LOGIN_REDIRECT_PATH = formatPath('/');
|
||||
|
||||
export const ZSignInFormSchema = z.object({
|
||||
email: zEmail().min(1),
|
||||
|
||||
@@ -65,7 +65,7 @@ export const TeamUpdateForm = ({ teamId, teamName, teamUrl }: UpdateTeamDialogPr
|
||||
});
|
||||
|
||||
if (url !== teamUrl) {
|
||||
await navigate(`/t/${url}/settings`);
|
||||
await navigate(`/t/${url}/settings/general`);
|
||||
}
|
||||
} catch (err) {
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCopyToClipboard } from '@documenso/lib/client-only/hooks/use-copy-to-clipboard';
|
||||
import type { TCachedLicense } from '@documenso/lib/types/license';
|
||||
import { SUBSCRIPTION_CLAIM_FEATURE_FLAGS } from '@documenso/lib/types/subscription';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
@@ -9,6 +10,7 @@ import { Trans, useLingui } from '@lingui/react/macro';
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
CheckCircle2Icon,
|
||||
CopyIcon,
|
||||
EyeIcon,
|
||||
EyeOffIcon,
|
||||
KeyRoundIcon,
|
||||
@@ -29,6 +31,8 @@ type AdminLicenseCardProps = {
|
||||
|
||||
export const AdminLicenseCard = ({ licenseData }: AdminLicenseCardProps) => {
|
||||
const { t, i18n } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const [, copy] = useCopyToClipboard();
|
||||
const [isLicenseKeyVisible, setIsLicenseKeyVisible] = useState(false);
|
||||
|
||||
const { license } = licenseData || {};
|
||||
@@ -147,6 +151,24 @@ export const AdminLicenseCard = ({ licenseData }: AdminLicenseCardProps) => {
|
||||
>
|
||||
{isLicenseKeyVisible ? <EyeOffIcon className="h-3.5 w-3.5" /> : <EyeIcon className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground"
|
||||
aria-label={t`Copy license key`}
|
||||
onClick={async () =>
|
||||
copy(license.licenseKey).then(() => {
|
||||
toast({
|
||||
title: t`Copied to clipboard`,
|
||||
description: t`The license key has been copied to your clipboard`,
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
<CopyIcon className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
import { formatAvatarUrl } from '@documenso/lib/utils/avatars';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@documenso/ui/primitives/avatar';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
|
||||
import { Input } from '@documenso/ui/primitives/input';
|
||||
import { Skeleton } from '@documenso/ui/primitives/skeleton';
|
||||
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 type { LucideIcon } from 'lucide-react';
|
||||
import { SearchIcon, UsersIcon } from 'lucide-react';
|
||||
import type { MouseEvent, ReactNode } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
|
||||
import type { AnalyticsQueryResult } from '~/utils/analytics';
|
||||
import { formatRelativeDate } from '~/utils/analytics';
|
||||
|
||||
import { AnalyticsQueryError } from './analytics-query-error';
|
||||
|
||||
/** A single scope-agnostic row: a team member on the team page, a team on the organisation page. */
|
||||
export type AnalyticsActivityRow = {
|
||||
key: string | number;
|
||||
avatar: {
|
||||
imageId: string | null;
|
||||
fallback: string;
|
||||
};
|
||||
title: string;
|
||||
subtitle?: string | null;
|
||||
sent: number;
|
||||
completed: number;
|
||||
pending: number;
|
||||
/** 0-100, null when nothing was sent. */
|
||||
completionRate: number | null;
|
||||
lastActiveAt: Date | null;
|
||||
/** When set the whole row navigates here and the title becomes a link. */
|
||||
href?: string;
|
||||
};
|
||||
|
||||
export type AnalyticsActivityTableCardProps = {
|
||||
query: AnalyticsQueryResult<unknown>;
|
||||
/** Rows derived from `query.data`; empty while loading. */
|
||||
rows: AnalyticsActivityRow[];
|
||||
/** Identifies the current window (preset or custom span), so "Show all" resets whenever it changes. */
|
||||
rangeKey: string;
|
||||
title: ReactNode;
|
||||
description: ReactNode;
|
||||
/** Header of the first column, e.g. "Member". */
|
||||
columnLabel: ReactNode;
|
||||
/** Rendered next to the title once rows are loaded, e.g. "3 members · 2 active this period". */
|
||||
renderSummary: (count: number, activeCount: number) => ReactNode;
|
||||
/** Rendered next to "Show all", e.g. "Showing 8 of 9 members". */
|
||||
renderShowing: (visibleCount: number, totalCount: number) => ReactNode;
|
||||
emptyLabel: ReactNode;
|
||||
emptyIcon?: LucideIcon;
|
||||
/** Placeholder for the search input, e.g. "Search members". */
|
||||
searchPlaceholder: string;
|
||||
/** Rendered when the search matches nothing, e.g. "No members match your search". */
|
||||
noSearchResultsLabel: ReactNode;
|
||||
/** Builds the `analytics-{prefix}-*` test ids, e.g. `member` or `team`. */
|
||||
testIdPrefix: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export const AnalyticsActivityTableCard = ({
|
||||
query,
|
||||
rows,
|
||||
rangeKey,
|
||||
title,
|
||||
description,
|
||||
columnLabel,
|
||||
renderSummary,
|
||||
renderShowing,
|
||||
emptyLabel,
|
||||
emptyIcon: EmptyIcon = UsersIcon,
|
||||
searchPlaceholder,
|
||||
noSearchResultsLabel,
|
||||
testIdPrefix,
|
||||
className,
|
||||
}: AnalyticsActivityTableCardProps) => {
|
||||
const { i18n } = useLingui();
|
||||
|
||||
// Tracks which window "Show all" was pressed for, so it resets whenever the window changes.
|
||||
const [expandedRangeKey, setExpandedRangeKey] = useState<string | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
const isExpanded = expandedRangeKey === rangeKey;
|
||||
|
||||
const { data, isLoading, isError, refetch } = query;
|
||||
|
||||
const activeCount = rows.filter((row) => row.sent > 0).length;
|
||||
|
||||
const normalisedSearchTerm = searchTerm.trim().toLowerCase();
|
||||
const isSearching = normalisedSearchTerm.length > 0;
|
||||
|
||||
// Search always shows every match; the preview limit only applies to the unfiltered list.
|
||||
const filteredRows = isSearching ? rows.filter((row) => matchesSearch(row, normalisedSearchTerm)) : rows;
|
||||
const visibleRows = isExpanded || isSearching ? filteredRows : filteredRows.slice(0, ROW_PREVIEW_LIMIT);
|
||||
const hasHiddenRows = filteredRows.length > visibleRows.length;
|
||||
|
||||
const testId = (suffix: string) => `analytics-${testIdPrefix}-${suffix}`;
|
||||
|
||||
return (
|
||||
<Card className={className} data-testid={testId('activity')}>
|
||||
<CardHeader className="gap-4 space-y-0 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="flex flex-col space-y-1.5">
|
||||
<CardTitle>{title}</CardTitle>
|
||||
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</div>
|
||||
|
||||
{data !== undefined && rows.length > 0 && (
|
||||
<p className="shrink-0 text-muted-foreground text-sm tabular-nums" data-testid={testId('summary')}>
|
||||
{renderSummary(rows.length, activeCount)}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
{isError ? (
|
||||
<AnalyticsQueryError onRetry={refetch} />
|
||||
) : isLoading || data === undefined ? (
|
||||
<ul className="flex flex-col gap-y-3">
|
||||
{Array.from({ length: 4 }, (_, index) => (
|
||||
<li key={index} className="flex items-center gap-x-3">
|
||||
<Skeleton className="h-9 w-9 shrink-0 rounded-full" />
|
||||
|
||||
<div className="flex flex-1 flex-col gap-y-1.5">
|
||||
<Skeleton className="h-4 w-1/3" />
|
||||
<Skeleton className="h-3 w-1/4" />
|
||||
</div>
|
||||
|
||||
<Skeleton className="h-4 w-10" />
|
||||
<Skeleton className="hidden h-4 w-10 md:block" />
|
||||
<Skeleton className="hidden h-4 w-10 md:block" />
|
||||
<Skeleton className="h-4 w-28" />
|
||||
<Skeleton className="hidden h-4 w-20 md:block" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-y-3 py-10 text-center">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
|
||||
<EmptyIcon className="h-6 w-6 text-muted-foreground" aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
<p className="max-w-sm text-muted-foreground text-sm">{emptyLabel}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-y-3">
|
||||
<div className="relative sm:max-w-xs">
|
||||
<SearchIcon
|
||||
className="pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="search"
|
||||
className="pl-9"
|
||||
placeholder={searchPlaceholder}
|
||||
aria-label={searchPlaceholder}
|
||||
value={searchTerm}
|
||||
onChange={(event) => setSearchTerm(event.target.value)}
|
||||
data-testid={testId('search')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredRows.length === 0 ? (
|
||||
<p className="py-8 text-center text-muted-foreground text-sm" data-testid={testId('no-results')}>
|
||||
{noSearchResultsLabel}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{/* Pull the table out to the card edge so the first/last cell gutters (px-6) line up with the header. */}
|
||||
<div className="-mx-6">
|
||||
<Table className="[&_td]:px-2 md:[&_td]:px-4 [&_th]:px-2 md:[&_th]:px-4">
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className={FIRST_CELL_CLASS}>{columnLabel}</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<Trans>Sent</Trans>
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell">
|
||||
<Trans>Completed</Trans>
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell">
|
||||
<Trans>Pending</Trans>
|
||||
</TableHead>
|
||||
<TableHead className={cn('text-right', LAST_CELL_ON_MOBILE_CLASS)}>
|
||||
<Trans>Completion rate</Trans>
|
||||
</TableHead>
|
||||
<TableHead className={cn('hidden text-right md:table-cell', LAST_CELL_CLASS)}>
|
||||
<Trans>Last active</Trans>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
||||
<TableBody>
|
||||
{visibleRows.map((row) => (
|
||||
<ActivityRow key={row.key} row={row} locale={i18n.locale} testIdPrefix={testIdPrefix} />
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{hasHiddenRows && (
|
||||
<div className="flex items-center justify-between gap-x-4 border-border border-t pt-3">
|
||||
<p className="text-muted-foreground text-sm" data-testid={testId('showing')}>
|
||||
{renderShowing(visibleRows.length, filteredRows.length)}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="-mr-2"
|
||||
onClick={() => setExpandedRangeKey(rangeKey)}
|
||||
data-testid={testId('show-all')}
|
||||
>
|
||||
<Trans>Show all</Trans>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
type ActivityRowProps = {
|
||||
row: AnalyticsActivityRow;
|
||||
locale: string;
|
||||
testIdPrefix: string;
|
||||
};
|
||||
|
||||
const ActivityRow = ({ row, locale, testIdPrefix }: ActivityRowProps) => {
|
||||
const { _ } = useLingui();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const isActive = row.sent > 0;
|
||||
|
||||
const testId = (suffix: string) => `analytics-${testIdPrefix}-${suffix}`;
|
||||
|
||||
// Only "Completed" and the rate are emphasised; supporting counts stay muted. Inactive rows are muted throughout.
|
||||
const primaryNumberClass = cn('text-right tabular-nums', isActive ? 'text-foreground' : 'text-muted-foreground');
|
||||
const secondaryNumberClass = 'text-right text-muted-foreground tabular-nums';
|
||||
|
||||
// role="img" so the aria-label is valid (a bare span has no role that supports it).
|
||||
const notAvailable = (
|
||||
<span role="img" aria-label={_(msg`Not available`)}>
|
||||
—
|
||||
</span>
|
||||
);
|
||||
|
||||
/**
|
||||
* The title link is the accessible target; clicking anywhere else on the row
|
||||
* navigates too. Modifier clicks and clicks on the link itself are left to the
|
||||
* browser so open-in-new-tab keeps working, and drag-selecting text does not
|
||||
* navigate.
|
||||
*/
|
||||
const handleRowClick = (event: MouseEvent<HTMLTableRowElement>) => {
|
||||
if (!row.href || event.defaultPrevented || event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target instanceof Element && event.target.closest('a')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.getSelection()?.toString()) {
|
||||
return;
|
||||
}
|
||||
|
||||
void navigate(row.href);
|
||||
};
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
className={cn(row.href && 'cursor-pointer')}
|
||||
onClick={handleRowClick}
|
||||
data-testid={testId('row')}
|
||||
data-active={isActive ? 'true' : 'false'}
|
||||
>
|
||||
{/* w-full + max-w-0 lets this cell absorb the remaining width while still truncating its content. */}
|
||||
<TableCell truncate={false} className={cn('w-full max-w-0', FIRST_CELL_CLASS)}>
|
||||
<div className="flex min-w-0 items-center gap-x-3">
|
||||
<Avatar className="h-9 w-9 shrink-0">
|
||||
{row.avatar.imageId && <AvatarImage src={formatAvatarUrl(row.avatar.imageId)} />}
|
||||
<AvatarFallback className="text-muted-foreground text-xs">{row.avatar.fallback}</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div className="flex min-w-0 flex-col">
|
||||
{row.href ? (
|
||||
<Link
|
||||
to={row.href}
|
||||
className={cn(
|
||||
'truncate font-medium text-sm hover:underline',
|
||||
isActive ? 'text-foreground' : 'text-foreground/80',
|
||||
)}
|
||||
>
|
||||
{row.title}
|
||||
</Link>
|
||||
) : (
|
||||
<span className={cn('truncate font-medium text-sm', isActive ? 'text-foreground' : 'text-foreground/80')}>
|
||||
{row.title}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{row.subtitle && <span className="truncate text-muted-foreground text-xs">{row.subtitle}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className={secondaryNumberClass} data-testid={testId('sent')}>
|
||||
{row.sent.toLocaleString(locale)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className={cn('hidden md:table-cell', primaryNumberClass)} data-testid={testId('completed')}>
|
||||
{row.completed.toLocaleString(locale)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className={cn('hidden md:table-cell', secondaryNumberClass)} data-testid={testId('pending')}>
|
||||
{row.pending.toLocaleString(locale)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className={cn(primaryNumberClass, LAST_CELL_ON_MOBILE_CLASS)} data-testid={testId('completion-rate')}>
|
||||
{row.completionRate === null ? (
|
||||
notAvailable
|
||||
) : (
|
||||
<div className="flex items-center justify-end gap-x-2">
|
||||
<div className="hidden h-1.5 w-16 overflow-hidden rounded-full bg-muted sm:block" aria-hidden="true">
|
||||
<div className="h-full rounded-full bg-primary" style={{ width: `${row.completionRate}%` }} />
|
||||
</div>
|
||||
|
||||
<span className="w-9 text-right">{Math.round(row.completionRate)}%</span>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
<TableCell
|
||||
className={cn('hidden md:table-cell', secondaryNumberClass, LAST_CELL_CLASS)}
|
||||
data-testid={testId('last-active')}
|
||||
>
|
||||
{row.lastActiveAt === null ? notAvailable : formatRelativeDate(row.lastActiveAt, locale)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
|
||||
const ROW_PREVIEW_LIMIT = 8;
|
||||
|
||||
const matchesSearch = (row: AnalyticsActivityRow, term: string) => {
|
||||
return row.title.toLowerCase().includes(term) || (row.subtitle ?? '').toLowerCase().includes(term);
|
||||
};
|
||||
|
||||
/**
|
||||
* The table is pulled out to the card edge (-mx-6), so the outer cells get the
|
||||
* card's px-6 gutter to line up with the header. "Last active" is hidden below
|
||||
* md, so "Completion rate" takes the right gutter there.
|
||||
*/
|
||||
const FIRST_CELL_CLASS = '!pl-6';
|
||||
const LAST_CELL_CLASS = '!pr-6';
|
||||
const LAST_CELL_ON_MOBILE_CLASS = '!pr-6 md:!pr-4';
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { TGetTeamAnalyticsDocumentsOverTimeResponse } from '@documenso/trpc/server/team-router/get-team-analytics.types';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
|
||||
import { Skeleton } from '@documenso/ui/primitives/skeleton';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Plural, Trans } from '@lingui/react/macro';
|
||||
import { BarChart3Icon } from 'lucide-react';
|
||||
import { DateTime } from 'luxon';
|
||||
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
|
||||
import type { AnalyticsQueryResult, AnalyticsRangeValue } from '~/utils/analytics';
|
||||
import { getAnalyticsDateRangeDays } from '~/utils/analytics';
|
||||
|
||||
import { AnalyticsQueryError } from './analytics-query-error';
|
||||
|
||||
export type AnalyticsDocumentsOverTimeCardProps = {
|
||||
range: AnalyticsRangeValue;
|
||||
query: AnalyticsQueryResult<TGetTeamAnalyticsDocumentsOverTimeResponse>;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
type Bucket = TGetTeamAnalyticsDocumentsOverTimeResponse['range']['bucket'];
|
||||
|
||||
export const AnalyticsDocumentsOverTimeCard = ({ range, query, className }: AnalyticsDocumentsOverTimeCardProps) => {
|
||||
const { i18n } = useLingui();
|
||||
|
||||
const { data, isLoading, isError, refetch } = query;
|
||||
|
||||
// The backend decides the bucket, and it must match the points being rendered so
|
||||
// the tick and tooltip formatting line up. Before data arrives it is guessed from
|
||||
// the requested range.
|
||||
const bucket: Bucket = data ? data.range.bucket : guessBucket(range);
|
||||
|
||||
const tickInterval = data ? getTickInterval(data.points.length, bucket) : 0;
|
||||
|
||||
return (
|
||||
<Card className={cn('flex flex-col', className)} data-testid="analytics-documents-over-time">
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-x-4 space-y-0">
|
||||
<div className="space-y-1.5">
|
||||
<CardTitle>
|
||||
<Trans>Documents created</Trans>
|
||||
</CardTitle>
|
||||
|
||||
<CardDescription>{bucket === 'month' ? <Trans>Monthly</Trans> : <Trans>Daily</Trans>}</CardDescription>
|
||||
</div>
|
||||
|
||||
{data && (
|
||||
<p className="shrink-0 whitespace-nowrap" data-testid="analytics-documents-over-time-total">
|
||||
<span className="font-semibold text-2xl text-foreground tabular-nums tracking-tight">
|
||||
{data.total.toLocaleString(i18n.locale)}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground text-sm">
|
||||
<Trans>total</Trans>
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
{/* flex-1 + justify-center keeps the fixed-height chart vertically level with the status breakdown card. */}
|
||||
<CardContent className="flex flex-1 flex-col justify-center">
|
||||
{isError ? (
|
||||
<AnalyticsQueryError onRetry={refetch} />
|
||||
) : isLoading || !data ? (
|
||||
<Skeleton className="w-full" style={{ height: CHART_HEIGHT }} />
|
||||
) : data.total === 0 ? (
|
||||
<div
|
||||
className="flex flex-col items-center justify-center gap-y-3 text-center"
|
||||
style={{ height: CHART_HEIGHT }}
|
||||
>
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
|
||||
<BarChart3Icon className="h-6 w-6 text-muted-foreground" aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<Trans>No documents created in this period</Trans>
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={CHART_HEIGHT}>
|
||||
<BarChart data={data.points} margin={{ top: 8, right: 0, bottom: 0, left: 0 }} barCategoryGap="20%">
|
||||
<CartesianGrid vertical={false} strokeDasharray="3 3" stroke="hsl(var(--border))" />
|
||||
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
interval={tickInterval}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }}
|
||||
tickFormatter={(value: string) => formatTickLabel(value, bucket, i18n.locale)}
|
||||
/>
|
||||
|
||||
<YAxis
|
||||
allowDecimals={false}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
width={36}
|
||||
tickCount={4}
|
||||
tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }}
|
||||
/>
|
||||
|
||||
<Tooltip
|
||||
content={<DocumentsOverTimeTooltip bucket={bucket} locale={i18n.locale} />}
|
||||
cursor={{ fill: 'hsl(var(--muted-foreground) / 0.08)' }}
|
||||
/>
|
||||
|
||||
<Bar
|
||||
dataKey="count"
|
||||
fill="hsl(var(--primary))"
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={28}
|
||||
background={{ fill: 'hsl(var(--muted) / 0.5)', radius: 4 }}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
type DocumentsOverTimeTooltipProps = {
|
||||
active?: boolean;
|
||||
payload?: Array<{ payload: { date: string; count: number } }>;
|
||||
bucket: Bucket;
|
||||
locale: string;
|
||||
};
|
||||
|
||||
const DocumentsOverTimeTooltip = ({ active, payload, bucket, locale }: DocumentsOverTimeTooltipProps) => {
|
||||
const point = payload?.[0]?.payload;
|
||||
|
||||
if (!active || !point) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const count = Number(point.count ?? 0);
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-border bg-popover px-3 py-2 text-popover-foreground text-sm shadow-md">
|
||||
<p className="text-muted-foreground text-xs">{formatTooltipLabel(point.date, bucket, locale)}</p>
|
||||
|
||||
<p className="mt-0.5 font-medium tabular-nums">
|
||||
<Plural value={count} one="# document" other="# documents" />
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CHART_HEIGHT = 240;
|
||||
|
||||
const TARGET_DAILY_TICK_COUNT = 6;
|
||||
|
||||
/** Mirrors the backend resolver: custom windows longer than this are bucketed by month. */
|
||||
const CUSTOM_RANGE_MONTH_BUCKET_THRESHOLD_DAYS = 92;
|
||||
|
||||
const guessBucket = (range: AnalyticsRangeValue): Bucket => {
|
||||
if (range.range === '12m') {
|
||||
return 'month';
|
||||
}
|
||||
|
||||
if (range.range === 'custom') {
|
||||
return getAnalyticsDateRangeDays(range.from, range.to) > CUSTOM_RANGE_MONTH_BUCKET_THRESHOLD_DAYS ? 'month' : 'day';
|
||||
}
|
||||
|
||||
return 'day';
|
||||
};
|
||||
|
||||
/**
|
||||
* Month buckets label every month (12 fit at the lg width) and let recharts drop
|
||||
* overlapping ones on narrow screens; daily buckets show roughly six evenly spaced labels.
|
||||
*/
|
||||
const getTickInterval = (pointCount: number, bucket: Bucket): number | 'preserveStartEnd' => {
|
||||
if (bucket === 'month') {
|
||||
return 'preserveStartEnd';
|
||||
}
|
||||
|
||||
if (pointCount <= TARGET_DAILY_TICK_COUNT) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.max(0, Math.round(pointCount / TARGET_DAILY_TICK_COUNT) - 1);
|
||||
};
|
||||
|
||||
const formatTickLabel = (date: string, bucket: Bucket, locale: string) => {
|
||||
const parsed = DateTime.fromISO(date).setLocale(locale);
|
||||
|
||||
if (bucket === 'month') {
|
||||
return parsed.toLocaleString({ month: 'short' });
|
||||
}
|
||||
|
||||
return parsed.toLocaleString({ month: 'short', day: 'numeric' });
|
||||
};
|
||||
|
||||
const formatTooltipLabel = (date: string, bucket: Bucket, locale: string) => {
|
||||
const parsed = DateTime.fromISO(date).setLocale(locale);
|
||||
|
||||
if (bucket === 'month') {
|
||||
return parsed.toLocaleString({ month: 'long', year: 'numeric' });
|
||||
}
|
||||
|
||||
return parsed.toLocaleString(DateTime.DATE_FULL);
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import { SpinnerBox } from '@documenso/ui/primitives/spinner';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
|
||||
/**
|
||||
* Shown while the analytics route's `clientLoader` resolves the browser timezone
|
||||
* during hydration.
|
||||
*/
|
||||
export const AnalyticsHydrateFallback = () => {
|
||||
return (
|
||||
<div role="status" aria-live="polite" data-testid="analytics-loading">
|
||||
<SpinnerBox />
|
||||
<span className="sr-only">
|
||||
<Trans>Loading analytics</Trans>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { TTeamAnalyticsRange } from '@documenso/trpc/server/team-router/get-team-analytics.types';
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { InfoIcon } from 'lucide-react';
|
||||
|
||||
import { ANALYTICS_NO_ACTIVITY_LABELS } from '~/utils/analytics';
|
||||
|
||||
export type AnalyticsNoActivityAlertProps = {
|
||||
range: TTeamAnalyticsRange;
|
||||
/** Invoked when the user asks to widen the range to the last 12 months. */
|
||||
onShowLastYear: () => void;
|
||||
};
|
||||
|
||||
export const AnalyticsNoActivityAlert = ({ range, onShowLastYear }: AnalyticsNoActivityAlertProps) => {
|
||||
const { _ } = useLingui();
|
||||
|
||||
const canWidenRange = range !== '12m';
|
||||
|
||||
return (
|
||||
<Alert variant="neutral" padding="tight" className="mt-6" data-testid="analytics-no-activity">
|
||||
<AlertDescription className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<span className="flex items-center gap-x-2">
|
||||
<InfoIcon className="h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
<span>
|
||||
{_(ANALYTICS_NO_ACTIVITY_LABELS[range])}
|
||||
{canWidenRange && (
|
||||
<>
|
||||
{' '}
|
||||
<Trans>Try a longer range.</Trans>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
{canWidenRange && (
|
||||
<Button variant="ghost" size="sm" className="-mr-2" onClick={onShowLastYear}>
|
||||
<Trans>Show last 12 months</Trans>
|
||||
</Button>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { TGetTeamAnalyticsOverviewResponse } from '@documenso/trpc/server/team-router/get-team-analytics.types';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { ArrowDownRightIcon, ArrowUpRightIcon, CircleCheckIcon, SendIcon } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { AnalyticsQueryResult } from '~/utils/analytics';
|
||||
|
||||
import { AnalyticsStatCard } from './analytics-stat-card';
|
||||
|
||||
/** The part of the overview response shared by the team and organisation procedures. */
|
||||
export type AnalyticsOverviewData = Pick<TGetTeamAnalyticsOverviewResponse, 'sent' | 'completionRate'>;
|
||||
|
||||
/**
|
||||
* The third card counts the scope's "entities" (team members, organisation teams)
|
||||
* and how many of them were active in the period.
|
||||
*/
|
||||
export type AnalyticsOverviewEntityCard<TData> = {
|
||||
icon: LucideIcon;
|
||||
title: ReactNode;
|
||||
/** Applied to the value element, e.g. `analytics-members`. */
|
||||
testId: string;
|
||||
select: (data: TData) => { active: number; total: number };
|
||||
};
|
||||
|
||||
export type AnalyticsOverviewCardsProps<TData extends AnalyticsOverviewData> = {
|
||||
query: AnalyticsQueryResult<TData>;
|
||||
entity: AnalyticsOverviewEntityCard<TData>;
|
||||
};
|
||||
|
||||
export const AnalyticsOverviewCards = <TData extends AnalyticsOverviewData>({
|
||||
query,
|
||||
entity,
|
||||
}: AnalyticsOverviewCardsProps<TData>) => {
|
||||
const { i18n } = useLingui();
|
||||
|
||||
const { data, isLoading, isError, refetch } = query;
|
||||
|
||||
const entityCounts = data ? entity.select(data) : null;
|
||||
|
||||
const formatNumber = (value: number) => value.toLocaleString(i18n.locale);
|
||||
|
||||
const sharedProps = {
|
||||
isLoading: isLoading || !data,
|
||||
isError,
|
||||
onRetry: refetch,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<AnalyticsStatCard
|
||||
{...sharedProps}
|
||||
icon={SendIcon}
|
||||
title={<Trans>Documents sent</Trans>}
|
||||
value={data ? formatNumber(data.sent.current) : null}
|
||||
badge={data ? <SentDeltaBadge current={data.sent.current} previous={data.sent.previous} /> : null}
|
||||
description={<Trans>vs. previous period</Trans>}
|
||||
testId="analytics-sent"
|
||||
/>
|
||||
|
||||
<AnalyticsStatCard
|
||||
{...sharedProps}
|
||||
icon={CircleCheckIcon}
|
||||
title={<Trans>Completion rate</Trans>}
|
||||
value={data ? formatRate(data.completionRate.rate) : null}
|
||||
badge={
|
||||
data ? (
|
||||
<CompletionRateDeltaBadge rate={data.completionRate.rate} previousRate={data.completionRate.previousRate} />
|
||||
) : null
|
||||
}
|
||||
description={<Trans>of sent documents completed</Trans>}
|
||||
testId="analytics-completion-rate"
|
||||
/>
|
||||
|
||||
<AnalyticsStatCard
|
||||
{...sharedProps}
|
||||
icon={entity.icon}
|
||||
title={entity.title}
|
||||
value={entityCounts ? `${formatNumber(entityCounts.active)}/${formatNumber(entityCounts.total)}` : null}
|
||||
description={
|
||||
entityCounts ? (
|
||||
<Trans>
|
||||
{formatNumber(entityCounts.active)} active · {formatNumber(entityCounts.total - entityCounts.active)}{' '}
|
||||
inactive
|
||||
</Trans>
|
||||
) : null
|
||||
}
|
||||
testId={entity.testId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type SentDeltaBadgeProps = {
|
||||
current: number;
|
||||
previous: number;
|
||||
};
|
||||
|
||||
const SentDeltaBadge = ({ current, previous }: SentDeltaBadgeProps) => {
|
||||
if (previous === 0 && current === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (previous === 0) {
|
||||
return (
|
||||
<DeltaBadge tone="new" testId="analytics-sent-delta">
|
||||
<Trans>New</Trans>
|
||||
</DeltaBadge>
|
||||
);
|
||||
}
|
||||
|
||||
const delta = Math.round(((current - previous) / previous) * 100);
|
||||
|
||||
// Percentages off a tiny base (e.g. 1 → 165) are noise; cap the display.
|
||||
const label =
|
||||
delta > MAX_DISPLAYED_DELTA_PERCENT ? `>${MAX_DISPLAYED_DELTA_PERCENT}%` : `${formatSignedNumber(delta)}%`;
|
||||
|
||||
return (
|
||||
<DeltaBadge tone={getDeltaTone(delta)} testId="analytics-sent-delta">
|
||||
{label}
|
||||
</DeltaBadge>
|
||||
);
|
||||
};
|
||||
|
||||
type CompletionRateDeltaBadgeProps = {
|
||||
rate: number | null;
|
||||
previousRate: number | null;
|
||||
};
|
||||
|
||||
const CompletionRateDeltaBadge = ({ rate, previousRate }: CompletionRateDeltaBadgeProps) => {
|
||||
if (rate === null || previousRate === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Compare the rounded values so the delta always agrees with the displayed rate.
|
||||
const delta = Math.round(rate) - Math.round(previousRate);
|
||||
|
||||
return (
|
||||
<DeltaBadge tone={getDeltaTone(delta)} testId="analytics-completion-rate-delta">
|
||||
{formatSignedNumber(delta)}%
|
||||
</DeltaBadge>
|
||||
);
|
||||
};
|
||||
|
||||
type DeltaTone = 'positive' | 'negative' | 'zero' | 'new';
|
||||
|
||||
type DeltaBadgeProps = {
|
||||
tone: DeltaTone;
|
||||
testId: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
const DeltaBadge = ({ tone, testId, children }: DeltaBadgeProps) => {
|
||||
const DeltaIcon = DELTA_TONE_ICONS[tone];
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center gap-x-0.5 rounded-full px-1.5 py-0.5 font-medium text-xs tabular-nums leading-none',
|
||||
DELTA_TONE_CLASSES[tone],
|
||||
)}
|
||||
data-testid={testId}
|
||||
>
|
||||
{DeltaIcon && <DeltaIcon className="-ml-0.5 h-3 w-3" aria-hidden="true" />}
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const DELTA_TONE_CLASSES: Record<DeltaTone, string> = {
|
||||
positive: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
|
||||
negative: 'bg-red-500/10 text-red-600 dark:text-red-400',
|
||||
zero: 'bg-muted text-muted-foreground',
|
||||
new: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
|
||||
};
|
||||
|
||||
const MAX_DISPLAYED_DELTA_PERCENT = 999;
|
||||
|
||||
const DELTA_TONE_ICONS: Record<DeltaTone, typeof ArrowUpRightIcon | null> = {
|
||||
positive: ArrowUpRightIcon,
|
||||
negative: ArrowDownRightIcon,
|
||||
zero: null,
|
||||
new: null,
|
||||
};
|
||||
|
||||
const formatRate = (rate: number | null) => {
|
||||
if (rate === null) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
return `${Math.round(rate)}%`;
|
||||
};
|
||||
|
||||
const formatSignedNumber = (value: number) => {
|
||||
if (value > 0) {
|
||||
return `+${value}`;
|
||||
}
|
||||
|
||||
return String(value);
|
||||
};
|
||||
|
||||
const getDeltaTone = (delta: number): DeltaTone => {
|
||||
if (delta > 0) {
|
||||
return 'positive';
|
||||
}
|
||||
|
||||
if (delta < 0) {
|
||||
return 'negative';
|
||||
}
|
||||
|
||||
return 'zero';
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { formatAvatarUrl } from '@documenso/lib/utils/avatars';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@documenso/ui/primitives/avatar';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { AnalyticsRangeValue } from '~/utils/analytics';
|
||||
import { ANALYTICS_RANGE_LABELS, formatAnalyticsDateRange } from '~/utils/analytics';
|
||||
|
||||
import { AnalyticsRangePicker } from './analytics-range-picker';
|
||||
|
||||
export type AnalyticsPageHeaderProps = {
|
||||
avatarImageId: string | null;
|
||||
/** The team or organisation name. */
|
||||
name: string;
|
||||
range: AnalyticsRangeValue;
|
||||
onRangeChange: (range: AnalyticsRangeValue) => void;
|
||||
/** Rendered before the range picker, e.g. a link to a related analytics page. */
|
||||
actions?: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export const AnalyticsPageHeader = ({
|
||||
avatarImageId,
|
||||
name,
|
||||
range,
|
||||
onRangeChange,
|
||||
actions,
|
||||
className,
|
||||
}: AnalyticsPageHeaderProps) => {
|
||||
const { _, i18n } = useLingui();
|
||||
|
||||
const rangeLabel =
|
||||
range.range === 'custom'
|
||||
? formatAnalyticsDateRange(range.from, range.to, i18n.locale)
|
||||
: _(ANALYTICS_RANGE_LABELS[range.range]);
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between', className)}>
|
||||
<div className="flex flex-row items-center">
|
||||
<Avatar className="mr-3 h-12 w-12 border-2 border-white border-solid dark:border-border">
|
||||
{avatarImageId && <AvatarImage src={formatAvatarUrl(avatarImageId)} />}
|
||||
<AvatarFallback className="text-muted-foreground text-xs">{name.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div>
|
||||
<h2 className="font-semibold text-4xl">
|
||||
<Trans>Analytics</Trans>
|
||||
</h2>
|
||||
|
||||
<p className="mt-1 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
Usage overview for {name} · {rangeLabel}
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{actions}
|
||||
|
||||
<AnalyticsRangePicker value={range} onValueChange={onRangeChange} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useState } from 'react';
|
||||
|
||||
export type AnalyticsQueryErrorProps = {
|
||||
onRetry: () => Promise<unknown>;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export const AnalyticsQueryError = ({ onRetry, className }: AnalyticsQueryErrorProps) => {
|
||||
const [isRetrying, setIsRetrying] = useState(false);
|
||||
|
||||
const handleRetry = async () => {
|
||||
setIsRetrying(true);
|
||||
|
||||
try {
|
||||
await onRetry();
|
||||
} finally {
|
||||
setIsRetrying(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Alert variant="neutral" padding="tight" className={className} data-testid="analytics-error">
|
||||
<AlertDescription className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span>
|
||||
<Trans>This data could not be loaded.</Trans>
|
||||
</span>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={() => void handleRetry()} loading={isRetrying}>
|
||||
<Trans>Retry</Trans>
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,264 @@
|
||||
import { useWindowSize } from '@documenso/lib/client-only/hooks/use-window-size';
|
||||
import { ANALYTICS_CUSTOM_RANGE_MAX_LOOKBACK } from '@documenso/trpc/server/team-router/get-team-analytics.types';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import type { CalendarProps } from '@documenso/ui/primitives/calendar';
|
||||
import { Calendar } from '@documenso/ui/primitives/calendar';
|
||||
import { Popover, PopoverAnchor, PopoverContent } from '@documenso/ui/primitives/popover';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@documenso/ui/primitives/select';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Plural, Trans } from '@lingui/react/macro';
|
||||
import { DateTime } from 'luxon';
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
import type { AnalyticsRangeValue, TAnalyticsPresetRange } from '~/utils/analytics';
|
||||
import {
|
||||
ANALYTICS_PRESET_RANGES,
|
||||
ANALYTICS_RANGE_LABELS,
|
||||
formatAnalyticsDate,
|
||||
formatAnalyticsDateRange,
|
||||
getAnalyticsDateRangeDays,
|
||||
} from '~/utils/analytics';
|
||||
|
||||
export type AnalyticsRangePickerProps = {
|
||||
value: AnalyticsRangeValue;
|
||||
onValueChange: (value: AnalyticsRangeValue) => void;
|
||||
};
|
||||
|
||||
/** The calendar selection while the popover is open; `to` is unset until the second day is picked. */
|
||||
type DraftRange = {
|
||||
from: Date | undefined;
|
||||
to: Date | undefined;
|
||||
};
|
||||
|
||||
/** A single react-day-picker matcher, e.g. `{ after: Date }`. */
|
||||
type DayMatcher = Exclude<CalendarProps['disabled'], undefined | unknown[]>;
|
||||
|
||||
/**
|
||||
* A preset select with a "Custom range…" item that opens a two month range
|
||||
* calendar anchored to the select. The custom window is only committed when
|
||||
* "Apply" is pressed.
|
||||
*/
|
||||
export const AnalyticsRangePicker = ({ value, onValueChange }: AnalyticsRangePickerProps) => {
|
||||
const { _, i18n } = useLingui();
|
||||
const { width } = useWindowSize();
|
||||
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [isPickerOpen, setIsPickerOpen] = useState(false);
|
||||
const [draft, setDraft] = useState<DraftRange | undefined>();
|
||||
|
||||
const numberOfMonths = width >= SM_BREAKPOINT ? 2 : 1;
|
||||
|
||||
const today = DateTime.local().startOf('day');
|
||||
|
||||
const openPicker = () => {
|
||||
setDraft(
|
||||
value.range === 'custom'
|
||||
? { from: DateTime.fromISO(value.from).toJSDate(), to: DateTime.fromISO(value.to).toJSDate() }
|
||||
: undefined,
|
||||
);
|
||||
|
||||
setIsPickerOpen(true);
|
||||
};
|
||||
|
||||
const closePicker = () => {
|
||||
setIsPickerOpen(false);
|
||||
setDraft(undefined);
|
||||
};
|
||||
|
||||
const handleSelectValueChange = (nextValue: string) => {
|
||||
if (nextValue === CUSTOM_RANGE_VALUE) {
|
||||
openPicker();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const preset = ANALYTICS_PRESET_RANGES.find((range) => range === nextValue);
|
||||
|
||||
if (!preset) {
|
||||
return;
|
||||
}
|
||||
|
||||
onValueChange({ range: preset });
|
||||
};
|
||||
|
||||
/**
|
||||
* Picking a day starts a new window unless one end is already pending, in which
|
||||
* case it completes it. This replaces react-day-picker's default, which extends
|
||||
* a completed window instead of starting over.
|
||||
*/
|
||||
const handleDaySelect = (_nextRange: unknown, day: Date) => {
|
||||
if (draft?.from && !draft.to) {
|
||||
setDraft(day < draft.from ? { from: day, to: draft.from } : { from: draft.from, to: day });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setDraft({ from: day, to: undefined });
|
||||
};
|
||||
|
||||
const handleApply = () => {
|
||||
if (!draft?.from || !draft.to) {
|
||||
return;
|
||||
}
|
||||
|
||||
onValueChange({ range: 'custom', from: formatAnalyticsDate(draft.from), to: formatAnalyticsDate(draft.to) });
|
||||
|
||||
closePicker();
|
||||
};
|
||||
|
||||
// Only the last year (plus a day) up to today is selectable.
|
||||
const earliestDay = today.minus(ANALYTICS_CUSTOM_RANGE_MAX_LOOKBACK);
|
||||
const disabledDays: DayMatcher[] = [{ before: earliestDay.toJSDate() }, { after: today.toJSDate() }];
|
||||
|
||||
// Open on the month of the pending window (or today), keeping the current month
|
||||
// as the right-most one so no fully disabled future month is shown.
|
||||
const anchorMonth = draft?.from ? DateTime.fromJSDate(draft.from).startOf('month') : today.startOf('month');
|
||||
const lastVisibleMonth = today.startOf('month').minus({ months: numberOfMonths - 1 });
|
||||
const defaultMonth = DateTime.min(anchorMonth, lastVisibleMonth).toJSDate();
|
||||
|
||||
const draftFrom = draft?.from ? formatAnalyticsDate(draft.from) : null;
|
||||
const draftTo = draft?.to ? formatAnalyticsDate(draft.to) : null;
|
||||
const draftDays = draftFrom && draftTo ? getAnalyticsDateRangeDays(draftFrom, draftTo) : 0;
|
||||
|
||||
const customLabel =
|
||||
value.range === 'custom' ? formatAnalyticsDateRange(value.from, value.to, i18n.locale) : undefined;
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={isPickerOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
closePicker();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/*
|
||||
* The select never holds "custom" as its value so choosing "Custom range…" always
|
||||
* fires a change, letting an active custom window be adjusted. The trigger shows
|
||||
* the formatted window through the placeholder instead.
|
||||
*/}
|
||||
<Select value={value.range === 'custom' ? '' : value.range} onValueChange={handleSelectValueChange}>
|
||||
<PopoverAnchor asChild>
|
||||
<SelectTrigger
|
||||
ref={triggerRef}
|
||||
className="w-full sm:w-auto sm:min-w-44"
|
||||
aria-label={_(msg`Date range`)}
|
||||
data-testid="analytics-range"
|
||||
>
|
||||
<SelectValue placeholder={customLabel} />
|
||||
</SelectTrigger>
|
||||
</PopoverAnchor>
|
||||
|
||||
<SelectContent position="popper">
|
||||
{ANALYTICS_PRESET_OPTIONS.map(({ value: optionValue, label }) => (
|
||||
<SelectItem key={optionValue} value={optionValue}>
|
||||
{_(label)}
|
||||
</SelectItem>
|
||||
))}
|
||||
|
||||
<SelectSeparator />
|
||||
|
||||
<SelectItem value={CUSTOM_RANGE_VALUE} data-testid="analytics-range-custom">
|
||||
<Trans>Custom range…</Trans>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<PopoverContent
|
||||
ref={contentRef}
|
||||
align="end"
|
||||
className="w-auto p-0"
|
||||
// The select refocuses its trigger (asynchronously) as it closes, which
|
||||
// would otherwise dismiss the popover that has just opened and strand
|
||||
// keyboard focus outside it. Pointer interaction with the trigger still
|
||||
// dismisses the popover so the select can be reopened.
|
||||
onFocusOutside={(event) => {
|
||||
if (!(event.target instanceof Node) || !triggerRef.current?.contains(event.target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const content = contentRef.current;
|
||||
const firstTabbable = content?.querySelector<HTMLElement>(TABBABLE_SELECTOR);
|
||||
|
||||
(firstTabbable ?? content)?.focus();
|
||||
}}
|
||||
// There is no popover trigger element, so hand focus back to the select.
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
triggerRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<div data-testid="analytics-range-calendar">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={draft}
|
||||
onSelect={handleDaySelect}
|
||||
numberOfMonths={numberOfMonths}
|
||||
// Adjacent months would otherwise show the same days twice.
|
||||
showOutsideDays={false}
|
||||
defaultMonth={defaultMonth}
|
||||
fromDate={earliestDay.toJSDate()}
|
||||
toDate={today.toJSDate()}
|
||||
disabled={disabledDays}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-border border-t px-3 py-2">
|
||||
<p className="text-muted-foreground text-sm" aria-live="polite">
|
||||
{draftFrom && draftTo ? (
|
||||
<>
|
||||
{formatAnalyticsDateRange(draftFrom, draftTo, i18n.locale)} ·{' '}
|
||||
<Plural value={draftDays} one="# day" other="# days" />
|
||||
</>
|
||||
) : draftFrom ? (
|
||||
<Trans>Pick an end date</Trans>
|
||||
) : (
|
||||
<Trans>Pick a start date</Trans>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="secondary" size="sm" onClick={closePicker}>
|
||||
<Trans>Cancel</Trans>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleApply}
|
||||
disabled={!draftFrom || !draftTo}
|
||||
data-testid="analytics-range-apply"
|
||||
>
|
||||
<Trans>Apply</Trans>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
const CUSTOM_RANGE_VALUE = 'custom';
|
||||
|
||||
/** Tailwind `sm` breakpoint; two months are shown from here up. */
|
||||
const SM_BREAKPOINT = 640;
|
||||
|
||||
/** First element the popover should focus: the calendar's month navigation, then the days. */
|
||||
const TABBABLE_SELECTOR = 'button:not([disabled]):not([tabindex="-1"]), [tabindex="0"]';
|
||||
|
||||
const ANALYTICS_PRESET_OPTIONS = ANALYTICS_PRESET_RANGES.map((value: TAnalyticsPresetRange) => ({
|
||||
value,
|
||||
label: ANALYTICS_RANGE_LABELS[value],
|
||||
}));
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Card, CardContent } from '@documenso/ui/primitives/card';
|
||||
import { Skeleton } from '@documenso/ui/primitives/skeleton';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { AnalyticsQueryError } from './analytics-query-error';
|
||||
|
||||
export type AnalyticsStatCardProps = {
|
||||
icon: LucideIcon;
|
||||
title: ReactNode;
|
||||
value: ReactNode;
|
||||
description: ReactNode;
|
||||
badge?: ReactNode;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
onRetry: () => Promise<unknown>;
|
||||
testId: string;
|
||||
};
|
||||
|
||||
export const AnalyticsStatCard = ({
|
||||
icon: Icon,
|
||||
title,
|
||||
value,
|
||||
description,
|
||||
badge,
|
||||
isLoading,
|
||||
isError,
|
||||
onRetry,
|
||||
testId,
|
||||
}: AnalyticsStatCardProps) => {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col p-5">
|
||||
<div className="flex items-center justify-between gap-x-3">
|
||||
<h3 className="font-medium text-muted-foreground text-sm">{title}</h3>
|
||||
|
||||
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
{isError ? (
|
||||
<AnalyticsQueryError onRetry={onRetry} className="mt-3" />
|
||||
) : isLoading ? (
|
||||
<div className="mt-3 flex flex-col gap-y-2">
|
||||
<Skeleton className="h-9 w-24" />
|
||||
<Skeleton className="h-3.5 w-32" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap items-baseline gap-x-2 gap-y-1">
|
||||
<p className="font-semibold text-3xl text-foreground tabular-nums tracking-tight" data-testid={testId}>
|
||||
{value}
|
||||
</p>
|
||||
|
||||
{badge}
|
||||
</div>
|
||||
|
||||
<p className="mt-1 text-muted-foreground text-xs">{description}</p>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,198 @@
|
||||
import type { TGetTeamAnalyticsStatusBreakdownResponse } from '@documenso/trpc/server/team-router/get-team-analytics.types';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
|
||||
import { Skeleton } from '@documenso/ui/primitives/skeleton';
|
||||
import type { MessageDescriptor } from '@lingui/core';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
|
||||
import type { AnalyticsQueryResult } from '~/utils/analytics';
|
||||
|
||||
import { AnalyticsQueryError } from './analytics-query-error';
|
||||
|
||||
export type AnalyticsStatusBreakdownCardProps = {
|
||||
query: AnalyticsQueryResult<TGetTeamAnalyticsStatusBreakdownResponse>;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export const AnalyticsStatusBreakdownCard = ({ query, className }: AnalyticsStatusBreakdownCardProps) => {
|
||||
const { _, i18n } = useLingui();
|
||||
|
||||
const { data, isLoading, isError, refetch } = query;
|
||||
|
||||
const rows = data ? allocatePercentages(STATUS_ROWS.map((row) => ({ ...row, count: data[row.key] }))) : [];
|
||||
|
||||
return (
|
||||
<Card className={cn('flex flex-col', className)} data-testid="analytics-status-breakdown">
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-x-4 space-y-0">
|
||||
<div className="space-y-1.5">
|
||||
<CardTitle>
|
||||
<Trans>Status breakdown</Trans>
|
||||
</CardTitle>
|
||||
|
||||
<CardDescription>
|
||||
<Trans>Documents created in this period</Trans>
|
||||
</CardDescription>
|
||||
</div>
|
||||
|
||||
{data && (
|
||||
<p className="shrink-0 whitespace-nowrap">
|
||||
<span className="font-semibold text-2xl text-foreground tabular-nums tracking-tight">
|
||||
{data.total.toLocaleString(i18n.locale)}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground text-sm">
|
||||
<Trans>total</Trans>
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex flex-1 flex-col">
|
||||
{isError ? (
|
||||
<AnalyticsQueryError onRetry={refetch} />
|
||||
) : isLoading || !data ? (
|
||||
<div className="flex flex-col gap-y-4">
|
||||
<Skeleton className="h-2.5 w-full rounded-full" />
|
||||
|
||||
<div className="flex flex-col gap-y-2">
|
||||
{STATUS_ROWS.slice(0, 3).map((row) => (
|
||||
<Skeleton key={row.key} className="h-5 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : data.total === 0 ? (
|
||||
<div className="flex flex-1 flex-col gap-y-4">
|
||||
<StatusBar segments={[]} label={_(msg`No documents in this period`)} />
|
||||
|
||||
<p className="flex flex-1 items-center justify-center text-center text-muted-foreground text-sm">
|
||||
<Trans>No documents in this period</Trans>
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-y-2">
|
||||
<StatusBar segments={rows} label={_(msg`Document status distribution`)} />
|
||||
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{rows.map((row) => (
|
||||
<li key={row.key} className="flex items-center justify-between gap-x-3 py-2.5 text-sm">
|
||||
<div className="flex min-w-0 items-center gap-x-2">
|
||||
<span
|
||||
className="h-2.5 w-2.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: row.color }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="truncate text-foreground">{_(row.label)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-baseline gap-x-2 tabular-nums">
|
||||
<span className="font-medium text-foreground" data-testid={`analytics-status-${row.key}`}>
|
||||
{row.count.toLocaleString(i18n.locale)}
|
||||
</span>
|
||||
<span className="w-10 text-right text-muted-foreground">{row.percent}%</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
type StatusBarProps = {
|
||||
segments: Array<{ key: string; percent: number; color: string }>;
|
||||
label: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Stacked horizontal bar. Segment widths come from the largest-remainder
|
||||
* percentages so they always add up to the full width; an empty list renders
|
||||
* the muted track on its own.
|
||||
*/
|
||||
const StatusBar = ({ segments, label }: StatusBarProps) => {
|
||||
return (
|
||||
<div className="flex h-2.5 w-full gap-px overflow-hidden rounded-full bg-muted" role="img" aria-label={label}>
|
||||
{segments.map((segment) => (
|
||||
<div
|
||||
key={segment.key}
|
||||
className="h-full"
|
||||
style={{ width: `${segment.percent}%`, backgroundColor: segment.color }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type StatusKey = 'completed' | 'pending' | 'draft' | 'rejected' | 'cancelled';
|
||||
|
||||
type StatusRow = {
|
||||
key: StatusKey;
|
||||
label: MessageDescriptor;
|
||||
color: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Single source of truth for status colours so the bar and the legend cannot drift.
|
||||
*/
|
||||
const STATUS_ROWS: StatusRow[] = [
|
||||
{ key: 'completed', label: msg`Completed`, color: 'hsl(var(--primary))' },
|
||||
{ key: 'pending', label: msg`Pending`, color: '#f59e0b' },
|
||||
{ key: 'rejected', label: msg`Rejected`, color: '#ef4444' },
|
||||
{ key: 'cancelled', label: msg`Cancelled`, color: '#f97316' },
|
||||
{ key: 'draft', label: msg`Draft`, color: 'hsl(var(--muted-foreground) / 0.35)' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Assign integer percentages to the non-zero rows using largest-remainder
|
||||
* allocation so the values always sum to exactly 100, with every non-zero row
|
||||
* shown as at least 1%.
|
||||
*/
|
||||
const allocatePercentages = <T extends { count: number }>(rows: T[]): Array<T & { percent: number }> => {
|
||||
const visibleRows = rows.filter((row) => row.count > 0);
|
||||
const total = visibleRows.reduce((sum, row) => sum + row.count, 0);
|
||||
|
||||
if (total === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const allocations = visibleRows.map((row, index) => {
|
||||
const exact = (row.count / total) * 100;
|
||||
const floored = Math.floor(exact);
|
||||
|
||||
return { index, percent: floored, remainder: exact - floored };
|
||||
});
|
||||
|
||||
let remaining = 100 - allocations.reduce((sum, allocation) => sum + allocation.percent, 0);
|
||||
|
||||
const byRemainder = [...allocations].sort((a, b) => b.remainder - a.remainder || a.index - b.index);
|
||||
|
||||
for (const allocation of byRemainder) {
|
||||
if (remaining <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
allocation.percent += 1;
|
||||
remaining -= 1;
|
||||
}
|
||||
|
||||
// Every non-zero row must display at least 1%; take the difference from the largest rows.
|
||||
const byPercentDesc = [...allocations].sort((a, b) => b.percent - a.percent || a.index - b.index);
|
||||
|
||||
for (const allocation of allocations) {
|
||||
if (allocation.percent > 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
allocation.percent = 1;
|
||||
|
||||
const donor = byPercentDesc.find((candidate) => candidate !== allocation && candidate.percent > 1);
|
||||
|
||||
if (donor) {
|
||||
donor.percent -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
return visibleRows.map((row, index) => ({ ...row, percent: allocations[index].percent }));
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user