diff --git a/.agents/plans/wild-indigo-wave-rejected-expired-recipient-filters.md b/.agents/plans/wild-indigo-wave-rejected-expired-recipient-filters.md new file mode 100644 index 000000000..b8e9fb39c --- /dev/null +++ b/.agents/plans/wild-indigo-wave-rejected-expired-recipient-filters.md @@ -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` 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. \ No newline at end of file diff --git a/.npmrc b/.npmrc index 75baad7f0..cbc6b6537 100644 --- a/.npmrc +++ b/.npmrc @@ -1,3 +1,3 @@ legacy-peer-deps = true prefer-dedupe = true -# min-release-age = 7 +min-release-age = 7 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index be9dbb555..d3cee2f37 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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/`) diff --git a/apps/docs/content/docs/developers/api/documents.mdx b/apps/docs/content/docs/developers/api/documents.mdx index a21a2740b..dbe2e6a85 100644 --- a/apps/docs/content/docs/developers/api/documents.mdx +++ b/apps/docs/content/docs/developers/api/documents.mdx @@ -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'; + + 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). diff --git a/apps/docs/content/docs/developers/api/index.mdx b/apps/docs/content/docs/developers/api/index.mdx index 7f446c7ad..e8d7139eb 100644 --- a/apps/docs/content/docs/developers/api/index.mdx +++ b/apps/docs/content/docs/developers/api/index.mdx @@ -5,6 +5,8 @@ description: Complete reference for the Documenso REST API. import { Callout } from 'fumadocs-ui/components/callout'; + + 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). diff --git a/apps/docs/content/docs/developers/api/meta.json b/apps/docs/content/docs/developers/api/meta.json index 7a19089dd..7906bbe97 100644 --- a/apps/docs/content/docs/developers/api/meta.json +++ b/apps/docs/content/docs/developers/api/meta.json @@ -8,6 +8,7 @@ "teams", "rate-limits", "versioning", + "migrate-to-envelopes", "developer-mode", "common-errors" ] diff --git a/apps/docs/content/docs/developers/api/migrate-to-envelopes.mdx b/apps/docs/content/docs/developers/api/migrate-to-envelopes.mdx new file mode 100644 index 000000000..2bd5c8568 --- /dev/null +++ b/apps/docs/content/docs/developers/api/migrate-to-envelopes.mdx @@ -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 1st of March 2027: + +- API V1 +- A subset of SDK/API V2 endpoints +- Legacy documents and templates +- EmbedCreateDocumentV1 +- EmbedCreateTemplateV1 +- EmbedUpdateDocumentV1 +- EmbedUpdateTemplateV1 + +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 envelopes. + +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 */} + + + ### Switch to the envelope endpoints + + Replace each deprecated endpoint with its `/api/v2/envelope/*` equivalent from the [mapping tables](#endpoint-mapping-reference) below. + + + ### 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. + + + ### Update how you store IDs + + Envelope IDs are **strings** (for example `envelope_abc123`), not numbers. Update any code that stores, parses, or compares IDs. + + + ### Test, then remove the old calls + + Verify the new flow against your account, then delete the deprecated calls. + + + +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` | +| `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` | +| `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 + + + + 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. + + + 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. + + + No. Authentication is unchanged. The same API token works for the envelope endpoints under + `https://app.documenso.com/api/v2`. + + + Both are envelopes, distinguished by a `type` field of `DOCUMENT` or `TEMPLATE`. They share the same + endpoints, recipients, fields, and attachments. + + + 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. + + + Reach out to [support@documenso.com](mailto:support@documenso.com) with your use case and we will + help you plan the migration. + + + +## 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 diff --git a/apps/docs/content/docs/developers/api/rate-limits.mdx b/apps/docs/content/docs/developers/api/rate-limits.mdx index d2e31b1d4..95b0a68fe 100644 --- a/apps/docs/content/docs/developers/api/rate-limits.mdx +++ b/apps/docs/content/docs/developers/api/rate-limits.mdx @@ -11,9 +11,14 @@ Documenso enforces rate limits on all API endpoints to ensure service stability. ## HTTP Rate Limits -**Limit:** 100 requests per minute per IP address +**Limit:** 1000 requests per minute per IP address **Response:** 429 Too Many Requests + + 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. + + ### Rate Limit Response ```json diff --git a/apps/docs/content/docs/developers/api/templates.mdx b/apps/docs/content/docs/developers/api/templates.mdx index 8f5c5b667..b3f52e146 100644 --- a/apps/docs/content/docs/developers/api/templates.mdx +++ b/apps/docs/content/docs/developers/api/templates.mdx @@ -6,6 +6,8 @@ description: Create documents from reusable templates via API. import { Callout } from 'fumadocs-ui/components/callout'; import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; + + 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). diff --git a/apps/docs/content/docs/developers/api/versioning.mdx b/apps/docs/content/docs/developers/api/versioning.mdx index c137a869a..9e9435034 100644 --- a/apps/docs/content/docs/developers/api/versioning.mdx +++ b/apps/docs/content/docs/developers/api/versioning.mdx @@ -5,6 +5,8 @@ description: Versioning information for the Documenso public API. import { Callout } from 'fumadocs-ui/components/callout'; + + ## 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 diff --git a/apps/docs/content/docs/developers/examples/common-workflows.mdx b/apps/docs/content/docs/developers/examples/common-workflows.mdx index fe7887d5b..704bf415f 100644 --- a/apps/docs/content/docs/developers/examples/common-workflows.mdx +++ b/apps/docs/content/docs/developers/examples/common-workflows.mdx @@ -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'; + + ## Workflow 1: Send a Document for Signature The most common workflow: upload a PDF, add recipients with signature fields, and send for signing. @@ -472,7 +474,7 @@ Send the same document to multiple recipients in parallel. Useful for policy ack distributeDocument: true - Process in batches with a short delay to respect rate limits (e.g. 100 requests/minute) + Process in batches with a short delay to respect rate limits (e.g. 1000 requests/minute) @@ -638,8 +640,8 @@ done - 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. --- diff --git a/apps/docs/content/docs/developers/examples/index.mdx b/apps/docs/content/docs/developers/examples/index.mdx index bdbcdb0b5..aab7191cc 100644 --- a/apps/docs/content/docs/developers/examples/index.mdx +++ b/apps/docs/content/docs/developers/examples/index.mdx @@ -3,6 +3,8 @@ title: Examples description: Common integration patterns and end-to-end workflows. --- + + + ## Prerequisites - A Documenso account (cloud or self-hosted) diff --git a/apps/docs/content/docs/developers/getting-started/first-api-call.mdx b/apps/docs/content/docs/developers/getting-started/first-api-call.mdx index 5ae0a6c67..e87b85438 100644 --- a/apps/docs/content/docs/developers/getting-started/first-api-call.mdx +++ b/apps/docs/content/docs/developers/getting-started/first-api-call.mdx @@ -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'; + + ## Prerequisites Before starting, you need: @@ -483,7 +485,7 @@ 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 allows 1000 requests per minute per IP address. Your organisation may have its own lower rate limits. When rate limited, wait at least 60 seconds before retrying: ```javascript async function fetchWithRetry(url, options, maxRetries = 3) { diff --git a/apps/docs/content/docs/developers/getting-started/index.mdx b/apps/docs/content/docs/developers/getting-started/index.mdx index d2070f2b5..f38145d7e 100644 --- a/apps/docs/content/docs/developers/getting-started/index.mdx +++ b/apps/docs/content/docs/developers/getting-started/index.mdx @@ -3,6 +3,8 @@ title: Getting Started description: Get your API key and make your first API call. --- + + + ## Getting Started diff --git a/apps/docs/content/docs/developers/webhooks/events.mdx b/apps/docs/content/docs/developers/webhooks/events.mdx index 9f63f78ac..5bfaa7a42 100644 --- a/apps/docs/content/docs/developers/webhooks/events.mdx +++ b/apps/docs/content/docs/developers/webhooks/events.mdx @@ -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 - **Respond quickly** — Return a 200 status code within 30 seconds + **Respond quickly** — Return a `2xx` status code within 10 seconds diff --git a/apps/docs/content/docs/developers/webhooks/index.mdx b/apps/docs/content/docs/developers/webhooks/index.mdx index 14bb89123..8c27eccbd 100644 --- a/apps/docs/content/docs/developers/webhooks/index.mdx +++ b/apps/docs/content/docs/developers/webhooks/index.mdx @@ -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 diff --git a/apps/docs/content/docs/developers/webhooks/setup.mdx b/apps/docs/content/docs/developers/webhooks/setup.mdx index 1725bec05..88fda57ea 100644 --- a/apps/docs/content/docs/developers/webhooks/setup.mdx +++ b/apps/docs/content/docs/developers/webhooks/setup.mdx @@ -148,7 +148,7 @@ func main() { - 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. ## 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 | @@ -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 | + + 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. + + For local development, use a tunneling service like [ngrok](https://ngrok.com) or [localtunnel](https://localtunnel.me) to expose your local server. @@ -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. @@ -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. If your endpoint consistently fails, consider reviewing your server logs and ensuring your endpoint meets all [URL requirements](#webhook-url-requirements). diff --git a/apps/docs/content/docs/developers/webhooks/verification.mdx b/apps/docs/content/docs/developers/webhooks/verification.mdx index a6cac916d..751d30d89 100644 --- a/apps/docs/content/docs/developers/webhooks/verification.mdx +++ b/apps/docs/content/docs/developers/webhooks/verification.mdx @@ -255,6 +255,7 @@ const validEvents = [ 'DOCUMENT_REJECTED', 'DOCUMENT_CANCELLED', 'DOCUMENT_REMINDER_SENT', + 'RECIPIENT_EXPIRED', 'TEMPLATE_CREATED', 'TEMPLATE_UPDATED', 'TEMPLATE_DELETED', diff --git a/apps/docs/content/docs/policies/fair-use.mdx b/apps/docs/content/docs/policies/fair-use.mdx index 0c4de348d..98d94dd5f 100644 --- a/apps/docs/content/docs/policies/fair-use.mdx +++ b/apps/docs/content/docs/policies/fair-use.mdx @@ -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. + + 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. + + Rate limits may vary by plan. Enterprise plans can include higher or custom limits. Contact [sales](https://documen.so/sales) for details. diff --git a/apps/docs/content/docs/self-hosting/configuration/organisation-limits.mdx b/apps/docs/content/docs/self-hosting/configuration/organisation-limits.mdx index 2459812ce..c225975e5 100644 --- a/apps/docs/content/docs/self-hosting/configuration/organisation-limits.mdx +++ b/apps/docs/content/docs/self-hosting/configuration/organisation-limits.mdx @@ -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 diff --git a/apps/docs/content/docs/self-hosting/deployment/docker-compose.mdx b/apps/docs/content/docs/self-hosting/deployment/docker-compose.mdx index 84e228115..a5ac58807 100644 --- a/apps/docs/content/docs/self-hosting/deployment/docker-compose.mdx +++ b/apps/docs/content/docs/self-hosting/deployment/docker-compose.mdx @@ -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 diff --git a/apps/docs/package.json b/apps/docs/package.json index da9966679..be8dfc789 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -3,14 +3,13 @@ "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", diff --git a/apps/docs/src/components/mdx/envelope-warning.tsx b/apps/docs/src/components/mdx/envelope-warning.tsx new file mode 100644 index 000000000..18676a78d --- /dev/null +++ b/apps/docs/src/components/mdx/envelope-warning.tsx @@ -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 `` without an explicit import. + */ +export function EnvelopeWarning() { + return ( + + Documents and templates are being deprecated and replaced by envelopes.{' '} + Read the migration guide here. + + ); +} diff --git a/apps/docs/src/mdx-components.tsx b/apps/docs/src/mdx-components.tsx index 298b70960..a0116880a 100644 --- a/apps/docs/src/mdx-components.tsx +++ b/apps/docs/src/mdx-components.tsx @@ -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, }; } diff --git a/apps/openpage-api/package.json b/apps/openpage-api/package.json index bcc93e039..4efc1dff8 100644 --- a/apps/openpage-api/package.json +++ b/apps/openpage-api/package.json @@ -16,7 +16,7 @@ }, "devDependencies": { "@types/node": "^20", - "@types/react": "18.3.27", + "@types/react": "^19.2.17", "typescript": "5.6.2" } } diff --git a/apps/remix/app/components/dialogs/branding-preferences-reset-dialog.tsx b/apps/remix/app/components/dialogs/branding-preferences-reset-dialog.tsx new file mode 100644 index 000000000..6205b1341 --- /dev/null +++ b/apps/remix/app/components/dialogs/branding-preferences-reset-dialog.tsx @@ -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; + 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 ( + !isLoading && setOpen(value)}> + + {trigger ?? ( + + )} + + + + + + Reset branding preferences + + + + + This will reset all branding preferences to their default values and save the changes immediately. + + + + + + +

+ Once confirmed, the following will be reset: +

+ +
    +
  • + Custom branding enabled setting +
  • +
  • + Branding logo +
  • +
  • + Brand website and brand details +
  • +
  • + Brand colours, including background, foreground, primary, and border colours +
  • + + {hasAdvancedBranding && ( + <> +
  • + Border radius +
  • +
  • + Custom CSS +
  • + + )} +
+
+
+ + + + + + + + +
+
+ ); +}; diff --git a/apps/remix/app/components/dialogs/document-preferences-reset-dialog.tsx b/apps/remix/app/components/dialogs/document-preferences-reset-dialog.tsx new file mode 100644 index 000000000..ed7184ef7 --- /dev/null +++ b/apps/remix/app/components/dialogs/document-preferences-reset-dialog.tsx @@ -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; + 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 ( + !isLoading && setOpen(value)}> + + + + + + + + Reset document preferences + + + + + This will reset all document preferences to their default values and save the changes immediately. + + + + + + +

+ Once confirmed, the following will be reset: +

+ +
    + {showDocumentVisibility && ( +
  • + Default document visibility +
  • + )} +
  • + Default document language +
  • +
  • + Default date format +
  • +
  • + Default time zone +
  • +
  • + Default signature settings +
  • +
  • + Default recipients +
  • +
  • + Delegate document ownership +
  • + {showAiFeatures && ( +
  • + AI features +
  • + )} +
+
+
+ + + + + + + + +
+
+ ); +}; diff --git a/apps/remix/app/components/dialogs/envelopes-bulk-download-dialog.tsx b/apps/remix/app/components/dialogs/envelopes-bulk-download-dialog.tsx new file mode 100644 index 000000000..940055854 --- /dev/null +++ b/apps/remix/app/components/dialogs/envelopes-bulk-download-dialog.tsx @@ -0,0 +1,377 @@ +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; + +export const EnvelopesBulkDownloadDialog = ({ + envelopes, + open, + onOpenChange, + onSuccess, + ...props +}: EnvelopesBulkDownloadDialogProps) => { + const { t } = useLingui(); + const { toast } = useToast(); + + const [versionMap, setVersionMap] = useState>({}); + 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 ( + { + if (!isDownloading) { + onOpenChange(value); + } + }} + > + + + + Download Documents + + + + + + + + {isOverDownloadLimit && ( + + + + You can download up to {MAX_BULK_DOWNLOAD_ENVELOPES} documents at a time. Deselect some documents to + continue. + + + + )} + +
+
+
+ {envelopes.map((envelope) => { + const versionOptions = getVersionOptions(envelope); + + return ( +
+
+

+ {envelope.title} +

+

{getStatusLabel(envelope.status)}

+
+ + {versionOptions && ( + + setVersionMap((prev) => ({ + ...prev, + [envelope.id]: value as BulkDownloadVersion, + })) + } + aria-label={t`Download version for ${envelope.title}`} + > + {versionOptions.map((option) => ( + + {option.label} + + ))} + + )} +
+ ); + })} +
+
+ + {isDownloading && ( +

+ + Downloading {progress} / {envelopes.length}... + +

+ )} + + + + + + +
+
+
+ ); +}; diff --git a/apps/remix/app/components/dialogs/organisation-create-dialog.tsx b/apps/remix/app/components/dialogs/organisation-create-dialog.tsx index c76bc00a2..9bbec2636 100644 --- a/apps/remix/app/components/dialogs/organisation-create-dialog.tsx +++ b/apps/remix/app/components/dialogs/organisation-create-dialog.tsx @@ -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 }: ))} diff --git a/apps/remix/app/components/dialogs/team-email-delete-dialog.tsx b/apps/remix/app/components/dialogs/team-email-delete-dialog.tsx index 7c08cf7d3..147cf3b40 100644 --- a/apps/remix/app/components/dialogs/team-email-delete-dialog.tsx +++ b/apps/remix/app/components/dialogs/team-email-delete-dialog.tsx @@ -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; + teamEmail: Pick | null; + emailVerification: Pick | 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 - {team.teamEmail?.name || team.emailVerification?.name} + {teamEmail?.name || emailVerification?.name} } - secondaryText={{team.teamEmail?.email || team.emailVerification?.email}} + secondaryText={{teamEmail?.email || emailVerification?.email}} /> diff --git a/apps/remix/app/components/dialogs/team-email-update-dialog.tsx b/apps/remix/app/components/dialogs/team-email-update-dialog.tsx index 3fbddc3c2..449d5ec36 100644 --- a/apps/remix/app/components/dialogs/team-email-update-dialog.tsx +++ b/apps/remix/app/components/dialogs/team-email-update-dialog.tsx @@ -23,7 +23,8 @@ import { useRevalidator } from 'react-router'; import type { z } from 'zod'; export type TeamEmailUpdateDialogProps = { - teamEmail: TeamEmail; + teamId: number; + teamEmail: Pick; trigger?: React.ReactNode; } & Omit; @@ -33,7 +34,7 @@ const ZUpdateTeamEmailFormSchema = ZUpdateTeamEmailMutationSchema.pick({ type TUpdateTeamEmailFormSchema = z.infer; -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, }, diff --git a/apps/remix/app/components/forms/branding-preferences-form.tsx b/apps/remix/app/components/forms/branding-preferences-form.tsx index ef3ff6b34..1cb5be35d 100644 --- a/apps/remix/app/components/forms/branding-preferences-form.tsx +++ b/apps/remix/app/components/forms/branding-preferences-form.tsx @@ -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(''); 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 }) => ( - - - Enable Custom Branding - - + Enable Custom Branding} + testId="branding-enabled" + > @@ -333,7 +379,7 @@ export function BrandingPreferencesForm({ )} - + )} /> @@ -341,11 +387,13 @@ export function BrandingPreferencesForm({ control={form.control} name="brandingCompanyDetails" render={({ field }) => ( - - - Brand Details - - + Brand Details} + testId="branding-company-details" + >