mirror of
https://github.com/documenso/documenso.git
synced 2026-07-25 17:35:05 +10:00
Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6b8eb9fc6a | |||
| 12d44e1c59 | |||
| 9dc66afc7b | |||
| 7a13be6bf2 | |||
| 1032028395 | |||
| 2396d0d5d0 | |||
| dac262edc9 | |||
| 25eb4ffedf | |||
| ee0ea82635 | |||
| 5f7f6698fd | |||
| 402809c809 | |||
| 733e273c05 | |||
| 7c7933c2d4 | |||
| bb120d65dd | |||
| 9c14aa6297 | |||
| 6387e809a8 | |||
| 5b2b1591a4 | |||
| e5cb4c6bfd | |||
| 8185f916d3 | |||
| c308dbf257 |
@@ -0,0 +1,222 @@
|
||||
---
|
||||
date: 2026-05-07
|
||||
title: Pdf Placeholder Selection Fields
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Extend PDF placeholders so radio and dropdown fields can be configured from the existing Documenso placeholder syntax:
|
||||
|
||||
```text
|
||||
{{FIELD_TYPE, RECIPIENT, key=value, key=value}}
|
||||
```
|
||||
|
||||
Do not introduce a new delimiter style. Existing applications may already generate placeholders in this format, so the new selection-field behavior should fit into it.
|
||||
|
||||
## Goals
|
||||
|
||||
- Keep the current placeholder grammar unchanged.
|
||||
- Support checkbox placeholders with option lists, checked values, validation, direction, required, read-only, and font size.
|
||||
- Support radio placeholders with option lists, default/preselected values, direction, required, read-only, and font size.
|
||||
- Support dropdown placeholders with option lists, default value, required, read-only, and font size.
|
||||
- Use `options` as the only public list key in PDF placeholders.
|
||||
- Convert `options` into internal `fieldMeta.values` during parsing.
|
||||
- Make generated fields usable immediately in the editor, signing UI, preview renderer, and final PDF export.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No semicolon placeholder syntax.
|
||||
- No `values` alias in PDF placeholder syntax.
|
||||
- No database migration.
|
||||
- No behavior change for existing placeholders such as `{{text, r1, required=true}}`.
|
||||
|
||||
## Placeholder Syntax
|
||||
|
||||
Use the existing comma-separated placeholder format:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, defaultValue=Check}}
|
||||
{{radio, r1, options=Basic|Pro|Enterprise, selected=Pro, direction=horizontal}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Use `|` inside `options` because `,` is already the top-level placeholder delimiter.
|
||||
|
||||
Parsing rules:
|
||||
|
||||
- Split top-level placeholder tokens on unescaped commas.
|
||||
- Split metadata tokens on the first unescaped equals sign.
|
||||
- Split `options` on unescaped pipes.
|
||||
- Trim option values and drop empty values.
|
||||
- Preserve option order.
|
||||
- Support escaped delimiters: `\,`, `\=`, and `\|`.
|
||||
- Treat field type values case-insensitively.
|
||||
|
||||
## Field Type Mapping
|
||||
|
||||
- `checkbox` maps to `FieldType.CHECKBOX`.
|
||||
- `radio` maps to `FieldType.RADIO`.
|
||||
- `dropdown` maps to `FieldType.DROPDOWN`.
|
||||
|
||||
## Metadata Mapping
|
||||
|
||||
### Checkbox
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.CHECKBOX,
|
||||
fieldMeta: {
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, value: 'Email', checked: true },
|
||||
{ id: 2, value: 'SMS', checked: false },
|
||||
{ id: 3, value: 'Phone', checked: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `checked`
|
||||
- `direction=vertical|horizontal`
|
||||
- `validationRule=atLeast|exactly|atMost`
|
||||
- `validationLength=1`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Map checkbox validation aliases internally: `atLeast` -> `Select at least`, `exactly` -> `Select exactly`, `atMost` -> `Select at most`.
|
||||
|
||||
Checkbox placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Radio
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Bank transfer}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.RADIO,
|
||||
fieldMeta: {
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, value: 'Card', checked: false },
|
||||
{ id: 2, value: 'Bank transfer', checked: true },
|
||||
{ id: 3, value: 'Check', checked: false },
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `direction=vertical|horizontal`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
Radio placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
### Dropdown
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
{{dropdown, r1, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
Normalize to:
|
||||
|
||||
```ts
|
||||
{
|
||||
type: FieldType.DROPDOWN,
|
||||
fieldMeta: {
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales' }, { value: 'Legal' }, { value: 'Finance' }],
|
||||
defaultValue: 'Legal',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Accepted keys:
|
||||
|
||||
- `options`
|
||||
- `selected`, `default`, or `defaultValue`
|
||||
- `required=true|false`
|
||||
- `readOnly=true|false`
|
||||
- `fontSize=12`
|
||||
|
||||
`defaultValue` should only be set if it matches one parsed option.
|
||||
|
||||
Dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
## Code Touchpoints
|
||||
|
||||
- `packages/lib/server-only/pdf/helpers.ts`
|
||||
- Extend `parseFieldMetaFromPlaceholder` so `options` normalizes into checkbox/radio/dropdown `fieldMeta.values`.
|
||||
- Add delimiter-aware helpers for commas, equals signs, and pipes.
|
||||
- `packages/lib/server-only/pdf/auto-place-fields.ts`
|
||||
- Replace plain comma splitting with delimiter-aware splitting.
|
||||
- Preserve the existing positional structure: field type, recipient, metadata.
|
||||
- `packages/lib/types/field-meta.ts`
|
||||
- Keep current internal schemas: checkbox/radio/dropdown still store options as `fieldMeta.values`.
|
||||
- `packages/ui/primitives/document-flow/field-content.tsx`
|
||||
- Display a radio fallback when a placeholder-created radio has no options.
|
||||
- Docs:
|
||||
- `apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx`
|
||||
- `apps/docs/content/docs/developers/api/fields.mdx`
|
||||
|
||||
## Test Plan
|
||||
|
||||
Unit tests:
|
||||
|
||||
- `options=Yes|No|Maybe` becomes stable radio values.
|
||||
- `selected=No` marks only the matching radio option checked.
|
||||
- Checkbox `options`, `checked`, `validationRule`, and `validationLength` normalize correctly.
|
||||
- Dropdown `options` and `defaultValue` normalize correctly.
|
||||
- Escaped delimiters parse correctly, for example `options=Sales\|Ops|Legal\, Compliance|A\=B`.
|
||||
|
||||
E2E/API tests:
|
||||
|
||||
- Add a PDF fixture with checkbox, radio, and dropdown placeholders using the current syntax.
|
||||
- Verify created fields have schema-compatible metadata and expected options/defaults.
|
||||
|
||||
Suggested verification:
|
||||
|
||||
```bash
|
||||
npm run test -w @documenso/lib -- server-only/pdf/helpers.test.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/auto-placing-fields/auto-place-fields-document.spec.ts
|
||||
npm run test:dev -w @documenso/app-tests -- e2e/envelope-editor-v2/envelope-fields.spec.ts
|
||||
npx tsc --noEmit -p packages/lib/tsconfig.json
|
||||
npx tsc --noEmit -p apps/remix/tsconfig.json
|
||||
```
|
||||
|
||||
Do not use `npm run build` for routine verification unless explicitly requested.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Keep the existing placeholder format.
|
||||
- Use only `options` publicly.
|
||||
- Keep `values` as an internal metadata field only.
|
||||
- Use `|` as the option delimiter inside `options`.
|
||||
+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/`)
|
||||
|
||||
|
||||
@@ -6,8 +6,6 @@ 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).
|
||||
|
||||
@@ -5,8 +5,6 @@ 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).
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
"teams",
|
||||
"rate-limits",
|
||||
"versioning",
|
||||
"migrate-to-envelopes",
|
||||
"developer-mode",
|
||||
"common-errors"
|
||||
]
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
---
|
||||
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` |
|
||||
| `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
|
||||
|
||||
<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,14 +11,9 @@ Documenso enforces rate limits on all API endpoints to ensure service stability.
|
||||
|
||||
## HTTP Rate Limits
|
||||
|
||||
**Limit:** 1000 requests per minute per IP address
|
||||
**Limit:** 100 requests per minute per IP address
|
||||
**Response:** 429 Too Many Requests
|
||||
|
||||
<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>
|
||||
|
||||
### Rate Limit Response
|
||||
|
||||
```json
|
||||
|
||||
@@ -6,8 +6,6 @@ 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).
|
||||
|
||||
@@ -5,8 +5,6 @@ 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.
|
||||
@@ -21,16 +19,7 @@ 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,8 +8,6 @@ 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.
|
||||
@@ -474,7 +472,7 @@ Send the same document to multiple recipients in parallel. Useful for policy ack
|
||||
<code>distributeDocument: true</code>
|
||||
</Step>
|
||||
<Step>
|
||||
Process in batches with a short delay to respect rate limits (e.g. 1000 requests/minute)
|
||||
Process in batches with a short delay to respect rate limits (e.g. 100 requests/minute)
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
@@ -640,8 +638,8 @@ done
|
||||
</Tabs>
|
||||
|
||||
<Callout type="info">
|
||||
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.
|
||||
The API allows 100 requests per minute. For large batches, implement rate limiting with delays
|
||||
between requests to avoid hitting limits.
|
||||
</Callout>
|
||||
|
||||
---
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Examples
|
||||
description: Common integration patterns and end-to-end workflows.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Cards>
|
||||
<Card
|
||||
title="Common Workflows"
|
||||
|
||||
@@ -7,8 +7,6 @@ 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)
|
||||
|
||||
@@ -7,8 +7,6 @@ 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:
|
||||
@@ -485,7 +483,7 @@ The API returns standard HTTP status codes and JSON error responses:
|
||||
|
||||
### Handling Rate Limits
|
||||
|
||||
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:
|
||||
The API allows 100 requests per minute per IP address. When rate limited, wait at least 60 seconds before retrying:
|
||||
|
||||
```javascript
|
||||
async function fetchWithRetry(url, options, maxRetries = 3) {
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Getting Started
|
||||
description: Get your API key and make your first API call.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
<Cards>
|
||||
<Card
|
||||
title="Authentication"
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Developer Guide
|
||||
description: Integrate Documenso into your applications using the REST API, webhooks, and embedding options.
|
||||
---
|
||||
|
||||
<EnvelopeWarning />
|
||||
|
||||
## Getting Started
|
||||
|
||||
<Cards>
|
||||
|
||||
@@ -41,17 +41,12 @@ When a limit is reached, requests return a `429 Too Many Requests` response with
|
||||
|
||||
| Action | Limit | Window |
|
||||
| --- | --- | --- |
|
||||
| API requests (v1 and v2) | 1000 requests | 1 minute |
|
||||
| API requests (v1 and v2) | 100 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 (1000/min, hardcoded) | No — see [Limitations](#limitations) |
|
||||
| Global HTTP rate limit | API requests per IP (100/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 **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).
|
||||
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).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -109,6 +109,37 @@ You can customize fields by adding options after the recipient identifier:
|
||||
| `maxValue` | Number | Maximum allowed value |
|
||||
| `numberFormat` | Format string | Number display format |
|
||||
|
||||
### Selection Field Options
|
||||
|
||||
Checkbox, radio, and dropdown placeholders can define their selectable choices via the `options` property.
|
||||
Separate choices with pipe (`|`) characters.
|
||||
Checkbox, radio, and dropdown placeholders do not support `label` or `placeholder` metadata.
|
||||
|
||||
| Option | Applies To | Values | Description |
|
||||
| ------------------ | ------------------------- | ------------------------ | ---------------------------------------- |
|
||||
| `options` | Checkbox, Radio, Dropdown | `Option 1|Option 2` | Selectable choices |
|
||||
| `checked` | Checkbox | `Option 1|Option 2` | Pre-checked choices |
|
||||
| `selected` | Radio, Dropdown | One option value | Pre-selected/default choice |
|
||||
| `default` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `defaultValue` | Radio, Dropdown | One option value | Alias for `selected` |
|
||||
| `direction` | Checkbox, Radio | `vertical`, `horizontal` | Option layout |
|
||||
| `validationRule` | Checkbox | `atLeast`, `exactly`, `atMost` | Checkbox selection validation rule |
|
||||
| `validationLength` | Checkbox | Number (e.g., `1`) | Checkbox validation option count |
|
||||
| `required` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the field must be completed |
|
||||
| `readOnly` | Checkbox, Radio, Dropdown | `true`, `false` | Whether the pre-selected value is locked |
|
||||
| `fontSize` | Checkbox, Radio, Dropdown | Number (e.g., `12`) | Field text size |
|
||||
|
||||
For checkbox validation, `validationLength` defines the option count:
|
||||
- `atLeast` means at least that many options must be selected
|
||||
- `exactly` means exactly that many options must be selected
|
||||
- `atMost` means at most that many options must be selected
|
||||
|
||||
If an option needs a literal delimiter, escape it with a backslash:
|
||||
|
||||
```
|
||||
{{dropdown, r1, options=Sales\|Ops|Legal\, Compliance|A\=B}}
|
||||
```
|
||||
|
||||
### Examples with Options
|
||||
|
||||
```
|
||||
@@ -116,6 +147,10 @@ You can customize fields by adding options after the recipient identifier:
|
||||
{{number, r1, minValue=0, maxValue=100, value=50}}
|
||||
{{name, r1, fontSize=14}}
|
||||
{{text, r2, readOnly=true, text=Contract #12345}}
|
||||
{{checkbox, r1, options=Email|SMS|Phone, checked=Email|Phone, validationRule=atLeast, validationLength=1}}
|
||||
{{radio, r1, options=Card|Bank transfer|Check, selected=Check}}
|
||||
{{dropdown, r1, options=United States|Canada|United Kingdom}}
|
||||
{{dropdown, r2, options=Sales|Legal|Finance, defaultValue=Legal}}
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "next build",
|
||||
"build": "NEXT_IGNORE_INCORRECT_LOCKFILE=true next build",
|
||||
"dev": "next dev",
|
||||
"start": "next start",
|
||||
"types:check": "fumadocs-mdx && next typegen && tsc --noEmit",
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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,7 +1,6 @@
|
||||
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
|
||||
@@ -10,7 +9,6 @@ export function getMDXComponents(components?: MDXComponents): any {
|
||||
...defaultMdxComponents,
|
||||
...TabsComponents,
|
||||
Mermaid,
|
||||
EnvelopeWarning,
|
||||
...components,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -1,141 +0,0 @@
|
||||
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;
|
||||
showIncludeSenderDetails?: boolean;
|
||||
};
|
||||
|
||||
export const DocumentPreferencesResetDialog = ({
|
||||
isSubmitting,
|
||||
onReset,
|
||||
showAiFeatures = false,
|
||||
showDocumentVisibility = false,
|
||||
showIncludeSenderDetails = 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>
|
||||
{showIncludeSenderDetails && (
|
||||
<li>
|
||||
<Trans>Send on behalf of team</Trans>
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<Trans>Include the signing certificate in the document</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Include the audit logs in the document</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default recipients</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Delegate document ownership</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default envelope expiration</Trans>
|
||||
</li>
|
||||
<li>
|
||||
<Trans>Default signing reminders</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>
|
||||
);
|
||||
};
|
||||
@@ -7,7 +7,6 @@ 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';
|
||||
@@ -24,7 +23,6 @@ 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';
|
||||
|
||||
@@ -76,7 +74,6 @@ 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 : {};
|
||||
@@ -99,42 +96,6 @@ 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 '';
|
||||
@@ -436,7 +397,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`background-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.background}
|
||||
@@ -460,7 +420,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`foreground-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.foreground}
|
||||
@@ -484,7 +443,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`primary-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.primary}
|
||||
@@ -508,7 +466,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`primary-foreground-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.primaryForeground}
|
||||
@@ -532,7 +489,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`border-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.border}
|
||||
@@ -556,7 +512,6 @@ export function BrandingPreferencesForm({
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<ColorPicker
|
||||
key={`ring-${colorPickerKey}`}
|
||||
nonce={nonce}
|
||||
value={field.value ?? ''}
|
||||
defaultValue={DEFAULT_BRAND_COLORS.ring}
|
||||
@@ -638,15 +593,6 @@ 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>
|
||||
|
||||
@@ -11,10 +11,10 @@ import { isValidLanguageCode, SUPPORTED_LANGUAGE_CODES, SUPPORTED_LANGUAGES } fr
|
||||
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, ZDocumentMetaDateFormatSchema } from '@documenso/lib/types/document-meta';
|
||||
import { generateDefaultOrganisationSettings, isPersonalLayout } from '@documenso/lib/utils/organisations';
|
||||
import { type TDocumentMetaDateFormat, ZDocumentMetaTimezoneSchema } from '@documenso/lib/types/document-meta';
|
||||
import { isPersonalLayout } from '@documenso/lib/utils/organisations';
|
||||
import { recipientAbbreviation } from '@documenso/lib/utils/recipient-formatter';
|
||||
import { extractTeamSignatureSettings, generateDefaultTeamSettings } from '@documenso/lib/utils/teams';
|
||||
import { extractTeamSignatureSettings } 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';
|
||||
@@ -37,11 +37,11 @@ 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 { DocumentVisibility, OrganisationType, type RecipientRole, type TeamGlobalSettings } from '@prisma/client';
|
||||
import type { TeamGlobalSettings } from '@prisma/client';
|
||||
import { DocumentVisibility, OrganisationType, type RecipientRole } 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';
|
||||
@@ -93,26 +93,6 @@ export type DocumentPreferencesFormProps = {
|
||||
onFormSubmit: (data: TDocumentPreferencesFormSchema) => Promise<void>;
|
||||
};
|
||||
|
||||
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,
|
||||
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,
|
||||
};
|
||||
};
|
||||
|
||||
export const DocumentPreferencesForm = ({
|
||||
settings,
|
||||
onFormSubmit,
|
||||
@@ -133,7 +113,7 @@ export const DocumentPreferencesForm = ({
|
||||
documentVisibility: z.nativeEnum(DocumentVisibility).nullable(),
|
||||
documentLanguage: z.enum(SUPPORTED_LANGUAGE_CODES).nullable(),
|
||||
documentTimezone: z.string().nullable(),
|
||||
documentDateFormat: ZDocumentMetaDateFormatSchema.nullable(),
|
||||
documentDateFormat: ZDocumentMetaTimezoneSchema.nullable(),
|
||||
includeSenderDetails: z.boolean().nullable(),
|
||||
includeSigningCertificate: z.boolean().nullable(),
|
||||
includeAuditLog: z.boolean().nullable(),
|
||||
@@ -147,33 +127,26 @@ export const DocumentPreferencesForm = ({
|
||||
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,
|
||||
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,
|
||||
},
|
||||
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);
|
||||
@@ -799,17 +772,6 @@ 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}
|
||||
showIncludeSenderDetails={!isPersonalLayoutMode && !isPersonalOrganisation}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
@@ -3,17 +3,12 @@ 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 { type ReactNode, useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -29,7 +24,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, resetToDefaults }: FormStickySaveBarProps) => {
|
||||
export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset }: FormStickySaveBarProps) => {
|
||||
const { t } = useLingui();
|
||||
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
@@ -105,8 +100,6 @@ export const FormStickySaveBar = ({ isDirty, isSubmitting, onReset, resetToDefau
|
||||
</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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,36 +0,0 @@
|
||||
import type { MessageDescriptor } from '@lingui/core';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
|
||||
export type PromptItem = {
|
||||
id: string;
|
||||
label: string | MessageDescriptor;
|
||||
sublabel?: string;
|
||||
path?: string;
|
||||
onAction?: () => void;
|
||||
icon?: LucideIcon;
|
||||
initials?: string;
|
||||
shortcut?: string;
|
||||
isChecked?: boolean;
|
||||
};
|
||||
|
||||
export type PromptCategory = {
|
||||
id: string;
|
||||
label: MessageDescriptor;
|
||||
items: PromptItem[];
|
||||
/**
|
||||
* The number of actual results, excluding utility rows such as the
|
||||
* "View all results" link.
|
||||
*/
|
||||
count: number;
|
||||
/**
|
||||
* The count shown on the category chip, or null to not show a chip at all.
|
||||
* Categories which only contain hardcoded page links have no chip.
|
||||
*/
|
||||
chipCount: number | null;
|
||||
isCapped: boolean;
|
||||
/**
|
||||
* Global admin categories are marked with a globe icon to distinguish them
|
||||
* from the equally named personal categories.
|
||||
*/
|
||||
isGlobal: boolean;
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { AlertTriangleIcon } from 'lucide-react';
|
||||
|
||||
export const DirectTemplateInvalidPageView = () => {
|
||||
return (
|
||||
<div className="mx-auto flex h-[70vh] w-full max-w-md flex-col items-center justify-center">
|
||||
<div>
|
||||
<AlertTriangleIcon className="h-10 w-10 text-destructive" />
|
||||
|
||||
<h1 className="mt-4 font-semibold text-3xl">
|
||||
<Trans>Invalid direct link template</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
This direct link template cannot be used because one or more signers do not have a signature field assigned.
|
||||
Please contact the sender to update the template.
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -54,7 +54,6 @@ import { useCurrentTeam } from '~/providers/team';
|
||||
|
||||
import { EnvelopeEditorFieldDragDrop } from './envelope-editor-fields-drag-drop';
|
||||
import { EnvelopeEditorFieldsPageRenderer } from './envelope-editor-fields-page-renderer';
|
||||
import { EnvelopeEditorInvalidDirectTemplateAlert } from './envelope-editor-invalid-direct-template-alert';
|
||||
import { EnvelopeRendererFileSelector } from './envelope-file-selector';
|
||||
import { EnvelopeRecipientSelector } from './envelope-recipient-selector';
|
||||
|
||||
@@ -239,8 +238,6 @@ export const EnvelopeEditorFieldsPage = () => {
|
||||
}
|
||||
/>
|
||||
|
||||
<EnvelopeEditorInvalidDirectTemplateAlert />
|
||||
|
||||
{/* Document View */}
|
||||
<div className="mt-4 flex h-full flex-col items-center justify-center">
|
||||
{envelope.recipients.length === 0 && (
|
||||
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
import { useCurrentEnvelopeEditor } from '@documenso/lib/client-only/providers/envelope-editor-provider';
|
||||
import { getRecipientsWithMissingFields } from '@documenso/lib/utils/recipients';
|
||||
import { cn } from '@documenso/ui/lib/utils';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export type EnvelopeEditorInvalidDirectTemplateAlertProps = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Warns that a direct link template cannot be used because one or more signers
|
||||
* are missing a signature field.
|
||||
*/
|
||||
export const EnvelopeEditorInvalidDirectTemplateAlert = ({
|
||||
className,
|
||||
}: EnvelopeEditorInvalidDirectTemplateAlertProps) => {
|
||||
const { envelope, isTemplate } = useCurrentEnvelopeEditor();
|
||||
|
||||
const signersMissingSignatureFields = useMemo(() => {
|
||||
if (!isTemplate || !envelope.directLink?.enabled) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return getRecipientsWithMissingFields(envelope.recipients, envelope.fields);
|
||||
}, [isTemplate, envelope.directLink, envelope.recipients, envelope.fields]);
|
||||
|
||||
if (signersMissingSignatureFields.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className={cn('mx-auto w-full max-w-[800px] flex-row items-start gap-3 rounded-sm', className)}
|
||||
>
|
||||
<AlertTitle>
|
||||
<Trans>Invalid direct link template</Trans>
|
||||
</AlertTitle>
|
||||
|
||||
<AlertDescription>
|
||||
<Trans>
|
||||
Recipients cannot use this direct link template because the following signers are missing a signature field
|
||||
</Trans>
|
||||
|
||||
<ul className="list-disc pl-5">
|
||||
{signersMissingSignatureFields.map((recipient, i) => (
|
||||
<li key={recipient.id}>{recipient.email || recipient.name || `Recipient ${i + 1}`}</li>
|
||||
))}
|
||||
</ul>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
@@ -22,7 +22,6 @@ import { match } from 'ts-pattern';
|
||||
import { EnvelopeGenericPageRenderer } from '~/components/general/envelope-editor/envelope-generic-page-renderer';
|
||||
import { EnvelopePdfViewer } from '~/components/general/pdf-viewer/envelope-pdf-viewer';
|
||||
|
||||
import { EnvelopeEditorInvalidDirectTemplateAlert } from './envelope-editor-invalid-direct-template-alert';
|
||||
import { EnvelopeRendererFileSelector } from './envelope-file-selector';
|
||||
|
||||
export const EnvelopeEditorPreviewPage = () => {
|
||||
@@ -229,8 +228,6 @@ export const EnvelopeEditorPreviewPage = () => {
|
||||
{/* Horizontal envelope item selector */}
|
||||
<EnvelopeRendererFileSelector className="px-0" fields={editorFields.localFields} />
|
||||
|
||||
<EnvelopeEditorInvalidDirectTemplateAlert className="mb-4" />
|
||||
|
||||
<Alert variant="warning" className="mx-auto max-w-[800px]">
|
||||
<AlertTitle>
|
||||
<Trans>Preview Mode</Trans>
|
||||
|
||||
+44
-71
@@ -7,12 +7,7 @@ import { useOptionalSession } from '@documenso/lib/client-only/providers/session
|
||||
import type { TDetectedRecipientSchema } from '@documenso/lib/server-only/ai/envelope/detect-recipients/schema';
|
||||
import { ZRecipientAuthOptionsSchema } from '@documenso/lib/types/document-auth';
|
||||
import { nanoid } from '@documenso/lib/universal/id';
|
||||
import {
|
||||
isAssistantLastSigner,
|
||||
isCcRecipient,
|
||||
normalizeRecipientSigningOrders,
|
||||
canRecipientBeModified as utilCanRecipientBeModified,
|
||||
} from '@documenso/lib/utils/recipients';
|
||||
import { canRecipientBeModified as utilCanRecipientBeModified } from '@documenso/lib/utils/recipients';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { RecipientActionAuthSelect } from '@documenso/ui/components/recipient/recipient-action-auth-select';
|
||||
import {
|
||||
@@ -161,12 +156,16 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
}, [watchedSigners]);
|
||||
|
||||
const normalizeSigningOrders = (signers: typeof watchedSigners) => {
|
||||
return normalizeRecipientSigningOrders(signers, (signer) => canRecipientBeModified(signer.id));
|
||||
return signers
|
||||
.sort((a, b) => (a.signingOrder ?? 0) - (b.signingOrder ?? 0))
|
||||
.map((signer, index) => ({ ...signer, signingOrder: index + 1 }));
|
||||
};
|
||||
|
||||
const activeRecipientCount = watchedSigners.filter((signer) => !isCcRecipient(signer)).length;
|
||||
|
||||
const { fields: signers, remove: removeSigner } = useFieldArray({
|
||||
const {
|
||||
append: appendSigner,
|
||||
fields: signers,
|
||||
remove: removeSigner,
|
||||
} = useFieldArray({
|
||||
control,
|
||||
name: 'signers',
|
||||
keyName: 'nativeId',
|
||||
@@ -209,31 +208,14 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
return utilCanRecipientBeModified(recipient, fields);
|
||||
};
|
||||
|
||||
const appendNormalizedSigner = (signer: (typeof watchedSigners)[number], shouldFocus = false) => {
|
||||
const updatedSigners = normalizeSigningOrders([...form.getValues('signers'), signer]);
|
||||
|
||||
form.setValue('signers', updatedSigners, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
});
|
||||
|
||||
if (shouldFocus) {
|
||||
const signerIndex = updatedSigners.findIndex((updatedSigner) => updatedSigner.formId === signer.formId);
|
||||
|
||||
if (signerIndex !== -1) {
|
||||
requestAnimationFrame(() => form.setFocus(`signers.${signerIndex}.email`));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onAddSigner = () => {
|
||||
appendNormalizedSigner({
|
||||
appendSigner({
|
||||
formId: nanoid(12),
|
||||
name: '',
|
||||
email: '',
|
||||
role: RecipientRole.SIGNER,
|
||||
actionAuth: [],
|
||||
signingOrder: activeRecipientCount + 1,
|
||||
signingOrder: signers.length > 0 ? (signers[signers.length - 1]?.signingOrder ?? 0) + 1 : 1,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -341,16 +323,18 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
|
||||
form.setFocus(`signers.${emptySignerIndex}.email`);
|
||||
} else {
|
||||
appendNormalizedSigner(
|
||||
appendSigner(
|
||||
{
|
||||
formId: nanoid(12),
|
||||
name: currentEditorName ?? '',
|
||||
email: currentEditorEmail ?? '',
|
||||
role: RecipientRole.SIGNER,
|
||||
actionAuth: [],
|
||||
signingOrder: activeRecipientCount + 1,
|
||||
signingOrder: signers.length > 0 ? (signers[signers.length - 1]?.signingOrder ?? 0) + 1 : 1,
|
||||
},
|
||||
{
|
||||
shouldFocus: true,
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
void form.trigger('signers');
|
||||
@@ -385,14 +369,18 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
|
||||
items.splice(insertIndex, 0, reorderedSigner);
|
||||
|
||||
const updatedSigners = normalizeSigningOrders(items);
|
||||
const updatedSigners = items.map((signer, index) => ({
|
||||
...signer,
|
||||
signingOrder: !canRecipientBeModified(signer.id) ? signer.signingOrder : index + 1,
|
||||
}));
|
||||
|
||||
form.setValue('signers', updatedSigners, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
});
|
||||
|
||||
if (isAssistantLastSigner(updatedSigners)) {
|
||||
const lastSigner = updatedSigners[updatedSigners.length - 1];
|
||||
if (lastSigner.role === RecipientRole.ASSISTANT) {
|
||||
toast({
|
||||
title: t`Warning: Assistant as last signer`,
|
||||
description: t`Having an assistant as the last signer means they will be unable to take any action as there are no subsequent signers to assist.`,
|
||||
@@ -423,19 +411,18 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedSigners = normalizeSigningOrders(
|
||||
currentSigners.map((signer, idx) => ({
|
||||
...signer,
|
||||
role: idx === index ? role : signer.role,
|
||||
})),
|
||||
);
|
||||
const updatedSigners = currentSigners.map((signer, idx) => ({
|
||||
...signer,
|
||||
role: idx === index ? role : signer.role,
|
||||
signingOrder: !canRecipientBeModified(signer.id) ? signer.signingOrder : idx + 1,
|
||||
}));
|
||||
|
||||
form.setValue('signers', updatedSigners, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
});
|
||||
|
||||
if (role === RecipientRole.ASSISTANT && isAssistantLastSigner(updatedSigners)) {
|
||||
if (role === RecipientRole.ASSISTANT && index === updatedSigners.length - 1) {
|
||||
toast({
|
||||
title: t`Warning: Assistant as last signer`,
|
||||
description: t`Having an assistant as the last signer means they will be unable to take any action as there are no subsequent signers to assist.`,
|
||||
@@ -460,30 +447,22 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
const currentSigners = form.getValues('signers');
|
||||
const signer = currentSigners[index];
|
||||
|
||||
if (isCcRecipient(signer)) {
|
||||
return;
|
||||
}
|
||||
// Remove signer from current position and insert at new position
|
||||
const remainingSigners = currentSigners.filter((_, idx) => idx !== index);
|
||||
const newPosition = Math.min(Math.max(0, newOrder - 1), currentSigners.length - 1);
|
||||
remainingSigners.splice(newPosition, 0, signer);
|
||||
|
||||
const nonCcSigners = currentSigners.filter((s) => !isCcRecipient(s));
|
||||
const ccSigners = currentSigners.filter((s) => isCcRecipient(s));
|
||||
const currentSigningOrderIndex = nonCcSigners.findIndex((s) => s.formId === signer.formId);
|
||||
|
||||
if (currentSigningOrderIndex === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [reorderedSigner] = nonCcSigners.splice(currentSigningOrderIndex, 1);
|
||||
const newPosition = Math.min(Math.max(0, newOrder - 1), nonCcSigners.length);
|
||||
nonCcSigners.splice(newPosition, 0, reorderedSigner);
|
||||
|
||||
const updatedSigners = normalizeSigningOrders([...nonCcSigners, ...ccSigners]);
|
||||
const updatedSigners = remainingSigners.map((s, idx) => ({
|
||||
...s,
|
||||
signingOrder: !canRecipientBeModified(s.id) ? s.signingOrder : idx + 1,
|
||||
}));
|
||||
|
||||
form.setValue('signers', updatedSigners, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
});
|
||||
|
||||
if (signer.role === RecipientRole.ASSISTANT && isAssistantLastSigner(updatedSigners)) {
|
||||
if (signer.role === RecipientRole.ASSISTANT && newPosition === remainingSigners.length - 1) {
|
||||
toast({
|
||||
title: t`Warning: Assistant as last signer`,
|
||||
description: t`Having an assistant as the last signer means they will be unable to take any action as there are no subsequent signers to assist.`,
|
||||
@@ -497,12 +476,10 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
setShowSigningOrderConfirmation(false);
|
||||
|
||||
const currentSigners = form.getValues('signers');
|
||||
const updatedSigners = normalizeSigningOrders(
|
||||
currentSigners.map((signer) => ({
|
||||
...signer,
|
||||
role: signer.role === RecipientRole.ASSISTANT ? RecipientRole.SIGNER : signer.role,
|
||||
})),
|
||||
);
|
||||
const updatedSigners = currentSigners.map((signer) => ({
|
||||
...signer,
|
||||
role: signer.role === RecipientRole.ASSISTANT ? RecipientRole.SIGNER : signer.role,
|
||||
}));
|
||||
|
||||
form.setValue('signers', updatedSigners, {
|
||||
shouldValidate: true,
|
||||
@@ -819,7 +796,6 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
isDragDisabled={
|
||||
!isSigningOrderSequential ||
|
||||
isSubmitting ||
|
||||
isCcRecipient(signer) ||
|
||||
!canRecipientBeModified(signer.id) ||
|
||||
!signer.signingOrder
|
||||
}
|
||||
@@ -843,11 +819,7 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
})}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-x-2">
|
||||
{isSigningOrderSequential && isCcRecipient(signer) && (
|
||||
<div className="mt-auto h-10 w-[4.25rem] flex-shrink-0" />
|
||||
)}
|
||||
|
||||
{isSigningOrderSequential && !isCcRecipient(signer) && (
|
||||
{isSigningOrderSequential && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`signers.${index}.signingOrder`}
|
||||
@@ -863,7 +835,7 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
max={activeRecipientCount}
|
||||
max={signers.length}
|
||||
data-testid="signing-order-input"
|
||||
className={cn(
|
||||
'w-10 text-center',
|
||||
@@ -1004,6 +976,7 @@ export const EnvelopeEditorRecipientForm = () => {
|
||||
onValueChange={(value) => {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
handleRoleChange(index, value as RecipientRole);
|
||||
field.onChange(value);
|
||||
}}
|
||||
disabled={
|
||||
snapshot.isDragging || isSubmitting || !canRecipientBeModified(signer.id)
|
||||
|
||||
@@ -26,7 +26,6 @@ import { ErrorCode as DropzoneErrorCode, type FileRejection, useDropzone } from
|
||||
|
||||
import { EnvelopeItemDeleteDialog } from '~/components/dialogs/envelope-item-delete-dialog';
|
||||
|
||||
import { EnvelopeEditorInvalidDirectTemplateAlert } from './envelope-editor-invalid-direct-template-alert';
|
||||
import { EnvelopeEditorRecipientForm } from './envelope-editor-recipient-form';
|
||||
import { EnvelopeItemTitleInput } from './envelope-editor-title-input';
|
||||
|
||||
@@ -450,9 +449,6 @@ export const EnvelopeEditorUploadPage = () => {
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl space-y-6 p-8">
|
||||
<input {...getReplaceInputProps()} />
|
||||
|
||||
<EnvelopeEditorInvalidDirectTemplateAlert className="max-w-none" />
|
||||
|
||||
<Card backdropBlur={false} className="border">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle>
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
import { useSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION, SKIP_QUERY_BATCH_META } from '@documenso/lib/constants/trpc';
|
||||
import { isAdmin } from '@documenso/lib/utils/is-admin';
|
||||
import { extractInitials } from '@documenso/lib/utils/recipient-formatter';
|
||||
import { trpc as trpcReact } from '@documenso/trpc/react';
|
||||
import type { TAdminSearchResultType } from '@documenso/trpc/server/admin-router/admin-search.types';
|
||||
import { ADMIN_SEARCH_MAX_QUERY_LENGTH } from '@documenso/trpc/server/admin-router/admin-search.types';
|
||||
|
||||
import type { MessageDescriptor } from '@lingui/core';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { keepPreviousData } from '@tanstack/react-query';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { ArrowRightIcon, Building2Icon, CreditCardIcon, FileTextIcon, UserIcon, UsersIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import type { PromptCategory, PromptItem } from './app-command-menu.types';
|
||||
|
||||
/**
|
||||
* The maximum number of results the admin search returns per resource type.
|
||||
*/
|
||||
const ADMIN_SEARCH_RESULTS_CAP = 5;
|
||||
|
||||
const ADMIN_GROUP_LABELS: Record<TAdminSearchResultType, MessageDescriptor> = {
|
||||
document: msg`Documents`,
|
||||
user: msg`Users`,
|
||||
organisation: msg`Organisations`,
|
||||
team: msg`Teams`,
|
||||
recipient: msg`Recipients`,
|
||||
subscription: msg`Subscriptions`,
|
||||
};
|
||||
|
||||
const ADMIN_GROUP_ICONS: Record<TAdminSearchResultType, LucideIcon> = {
|
||||
document: FileTextIcon,
|
||||
user: UserIcon,
|
||||
organisation: Building2Icon,
|
||||
team: UsersIcon,
|
||||
recipient: UserIcon,
|
||||
subscription: CreditCardIcon,
|
||||
};
|
||||
|
||||
/**
|
||||
* Admin list pages which support prefilling their search from the URL, used
|
||||
* for the "View all results" links on capped groups. Teams, recipients and
|
||||
* subscriptions have no admin list pages.
|
||||
*/
|
||||
const ADMIN_GROUP_LIST_PATHS: Partial<Record<TAdminSearchResultType, (_query: string) => string>> = {
|
||||
document: (query) => `/admin/documents?term=${encodeURIComponent(query)}`,
|
||||
user: (query) => `/admin/users?search=${encodeURIComponent(query)}`,
|
||||
organisation: (query) => `/admin/organisations?query=${encodeURIComponent(query)}`,
|
||||
};
|
||||
|
||||
export type UseAdminSearchCategoriesOptions = {
|
||||
/**
|
||||
* The trimmed, debounced search query.
|
||||
*/
|
||||
query: string;
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The isolated admin portion of the command prompt: searches every admin
|
||||
* resource and maps the results to prompt categories marked as global.
|
||||
*
|
||||
* Returns no categories and never queries for non admin users. The admin
|
||||
* search endpoint is additionally guarded server side by the admin procedure.
|
||||
*/
|
||||
export const useAdminSearchCategories = ({ query, open }: UseAdminSearchCategoriesOptions) => {
|
||||
const { user } = useSession();
|
||||
|
||||
const isUserAdmin = isAdmin(user);
|
||||
|
||||
// Admin searches hit every resource table, so require a longer query unless
|
||||
// it is a number, which could be a resource ID of any length. Queries over
|
||||
// the endpoint's length limit are skipped entirely instead of being sent
|
||||
// and rejected.
|
||||
const hasValidAdminSearch =
|
||||
isUserAdmin && query.length <= ADMIN_SEARCH_MAX_QUERY_LENGTH && (query.length > 3 || /^\d+$/.test(query));
|
||||
|
||||
const {
|
||||
data: adminSearchData,
|
||||
isFetching,
|
||||
isError,
|
||||
} = trpcReact.admin.search.useQuery(
|
||||
{
|
||||
query,
|
||||
},
|
||||
{
|
||||
enabled: open && hasValidAdminSearch,
|
||||
placeholderData: keepPreviousData,
|
||||
// Retyping is the retry in a search-as-you-type flow: fail fast so the
|
||||
// prompt can surface an honest error state instead of retrying.
|
||||
retry: false,
|
||||
...SKIP_QUERY_BATCH_META,
|
||||
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
|
||||
},
|
||||
);
|
||||
|
||||
const categories = useMemo((): PromptCategory[] => {
|
||||
if (!hasValidAdminSearch || !adminSearchData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return adminSearchData.groups.map((group) => {
|
||||
const isCapped = group.results.length >= ADMIN_SEARCH_RESULTS_CAP;
|
||||
const buildListPath = ADMIN_GROUP_LIST_PATHS[group.type];
|
||||
|
||||
const items: PromptItem[] = group.results.map((result) => ({
|
||||
id: `admin-${group.type}-${result.value}`,
|
||||
label: result.label,
|
||||
sublabel: result.sublabel,
|
||||
path: result.path,
|
||||
icon: ADMIN_GROUP_ICONS[group.type],
|
||||
initials: group.type === 'user' || group.type === 'recipient' ? extractInitials(result.label) : undefined,
|
||||
}));
|
||||
|
||||
// Capped groups link to the full admin list page with the search
|
||||
// prefilled so the cap is never a dead end.
|
||||
if (isCapped && buildListPath) {
|
||||
items.push({
|
||||
id: `admin-${group.type}-view-all`,
|
||||
label: msg`View all results`,
|
||||
path: buildListPath(query),
|
||||
icon: ArrowRightIcon,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
id: `admin-${group.type}`,
|
||||
label: ADMIN_GROUP_LABELS[group.type],
|
||||
items,
|
||||
count: group.results.length,
|
||||
chipCount: group.results.length,
|
||||
isCapped,
|
||||
isGlobal: true,
|
||||
};
|
||||
});
|
||||
}, [hasValidAdminSearch, adminSearchData, query]);
|
||||
|
||||
return {
|
||||
isUserAdmin,
|
||||
categories,
|
||||
isFetching,
|
||||
isError,
|
||||
};
|
||||
};
|
||||
@@ -88,7 +88,7 @@ export default function OrganisationSettingsDocumentPage() {
|
||||
typedSignatureEnabled: signatureTypes.includes(DocumentSignatureType.TYPE),
|
||||
uploadSignatureEnabled: signatureTypes.includes(DocumentSignatureType.UPLOAD),
|
||||
drawSignatureEnabled: signatureTypes.includes(DocumentSignatureType.DRAW),
|
||||
delegateDocumentOwnership,
|
||||
delegateDocumentOwnership: delegateDocumentOwnership,
|
||||
aiFeaturesEnabled,
|
||||
envelopeExpirationPeriod: envelopeExpirationPeriod ?? undefined,
|
||||
reminderSettings: reminderSettings ?? undefined,
|
||||
|
||||
@@ -82,7 +82,7 @@ export default function TeamsSettingsPage() {
|
||||
uploadSignatureEnabled: signatureTypes.includes(DocumentSignatureType.UPLOAD),
|
||||
drawSignatureEnabled: signatureTypes.includes(DocumentSignatureType.DRAW),
|
||||
}),
|
||||
delegateDocumentOwnership,
|
||||
delegateDocumentOwnership: delegateDocumentOwnership,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import { getEnvelopeForDirectTemplateSigning } from '@documenso/lib/server-only/
|
||||
import { getTemplateByDirectLinkToken } from '@documenso/lib/server-only/template/get-template-by-direct-link-token';
|
||||
import { DocumentAccessAuth } from '@documenso/lib/types/document-auth';
|
||||
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
|
||||
import { getRecipientsWithMissingFields } from '@documenso/lib/utils/recipients';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { Plural } from '@lingui/react/macro';
|
||||
import { UsersIcon } from 'lucide-react';
|
||||
@@ -15,7 +14,6 @@ import { redirect } from 'react-router';
|
||||
import { match } from 'ts-pattern';
|
||||
|
||||
import { Header as AuthenticatedHeader } from '~/components/general/app-header';
|
||||
import { DirectTemplateInvalidPageView } from '~/components/general/direct-template/direct-template-invalid-page';
|
||||
import { DirectTemplatePageView } from '~/components/general/direct-template/direct-template-page';
|
||||
import { DirectTemplateAuthPageView } from '~/components/general/direct-template/direct-template-signing-auth-page';
|
||||
import { DocumentSigningAuthPageView } from '~/components/general/document-signing/document-signing-auth-page';
|
||||
@@ -72,18 +70,8 @@ const handleV1Loader = async ({ params, request }: Route.LoaderArgs) => {
|
||||
};
|
||||
}
|
||||
|
||||
const recipientsWithMissingFields = getRecipientsWithMissingFields(template.recipients, template.fields);
|
||||
|
||||
if (recipientsWithMissingFields.length > 0) {
|
||||
return {
|
||||
isAccessAuthValid: true,
|
||||
isTemplateMissingSignatures: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
isAccessAuthValid: true,
|
||||
isTemplateMissingSignatures: false,
|
||||
template: {
|
||||
...template,
|
||||
folder: null,
|
||||
@@ -108,7 +96,6 @@ const handleV2Loader = async ({ params, request }: Route.LoaderArgs) => {
|
||||
.then((envelopeForSigning) => {
|
||||
return {
|
||||
isDocumentAccessValid: true,
|
||||
isTemplateMissingSignatures: false,
|
||||
envelopeForSigning,
|
||||
} as const;
|
||||
})
|
||||
@@ -121,13 +108,6 @@ const handleV2Loader = async ({ params, request }: Route.LoaderArgs) => {
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (error.code === AppErrorCode.MISSING_SIGNATURE_FIELD) {
|
||||
return {
|
||||
isDocumentAccessValid: true,
|
||||
isTemplateMissingSignatures: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
throw new Response('Not Found', { status: 404 });
|
||||
});
|
||||
};
|
||||
@@ -201,10 +181,6 @@ const DirectSigningPageV1 = ({ data }: { data: Awaited<ReturnType<typeof handleV
|
||||
return <DirectTemplateAuthPageView />;
|
||||
}
|
||||
|
||||
if (data.isTemplateMissingSignatures) {
|
||||
return <DirectTemplateInvalidPageView />;
|
||||
}
|
||||
|
||||
const { template, directTemplateRecipient } = data;
|
||||
|
||||
return (
|
||||
@@ -259,10 +235,6 @@ const DirectSigningPageV2 = ({ data }: { data: Awaited<ReturnType<typeof handleV
|
||||
return <DocumentSigningAuthPageView email={''} emailHasAccount={true} />;
|
||||
}
|
||||
|
||||
if (data.isTemplateMissingSignatures) {
|
||||
return <DirectTemplateInvalidPageView />;
|
||||
}
|
||||
|
||||
const { envelope, recipient } = data.envelopeForSigning;
|
||||
|
||||
const { derivedRecipientAccessAuth } = extractDocumentAuthMethods({
|
||||
|
||||
@@ -1,15 +1,98 @@
|
||||
import { redirect } from 'react-router';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { OrganisationMemberInviteStatus } from '@prisma/client';
|
||||
import { Link } from 'react-router';
|
||||
|
||||
import type { Route } from './+types/organisation.decline.$token';
|
||||
|
||||
export function loader({ params }: Route.LoaderArgs) {
|
||||
export async function loader({ params }: Route.LoaderArgs) {
|
||||
const { token } = params;
|
||||
|
||||
if (!token) {
|
||||
throw redirect('/');
|
||||
return {
|
||||
state: 'InvalidLink',
|
||||
} as const;
|
||||
}
|
||||
|
||||
// Declining now happens on the invite page via tRPC. Redirect there with the
|
||||
// `action=decline` flag so it renders the decline-only view (no accept).
|
||||
throw redirect(`/organisation/invite/${token}?action=decline`);
|
||||
const organisationMemberInvite = await prisma.organisationMemberInvite.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
include: {
|
||||
organisation: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!organisationMemberInvite) {
|
||||
return {
|
||||
state: 'InvalidLink',
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (organisationMemberInvite.status !== OrganisationMemberInviteStatus.DECLINED) {
|
||||
await prisma.organisationMemberInvite.update({
|
||||
where: {
|
||||
id: organisationMemberInvite.id,
|
||||
},
|
||||
data: {
|
||||
status: OrganisationMemberInviteStatus.DECLINED,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
state: 'Success',
|
||||
organisationName: organisationMemberInvite.organisation.name,
|
||||
} as const;
|
||||
}
|
||||
|
||||
export default function DeclineInvitationPage({ loaderData }: Route.ComponentProps) {
|
||||
const data = loaderData;
|
||||
|
||||
if (data.state === 'InvalidLink') {
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invalid token</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>This token is invalid or has expired. No action is needed.</Trans>
|
||||
</p>
|
||||
|
||||
<Button asChild>
|
||||
<Link to="/">
|
||||
<Trans>Return</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invitation declined</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have declined the invitation from <strong>{data.organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
<Button asChild>
|
||||
<Link to="/">
|
||||
<Trans>Return to Home</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
|
||||
import { useOptionalSession } from '@documenso/lib/client-only/providers/session';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { acceptOrganisationInvitation } from '@documenso/lib/server-only/organisation/accept-organisation-invitation';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { trpc } from '@documenso/trpc/react';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import { useToast } from '@documenso/ui/primitives/use-toast';
|
||||
import { Trans, useLingui } from '@lingui/react/macro';
|
||||
import { OrganisationMemberInviteStatus } from '@prisma/client';
|
||||
import { useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router';
|
||||
import { match } from 'ts-pattern';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import { Link } from 'react-router';
|
||||
|
||||
import type { Route } from './+types/organisation.invite.$token';
|
||||
|
||||
@@ -43,22 +37,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
} as const;
|
||||
}
|
||||
|
||||
const organisationName = organisationMemberInvite.organisation.name;
|
||||
|
||||
if (organisationMemberInvite.status === OrganisationMemberInviteStatus.ACCEPTED) {
|
||||
return {
|
||||
state: 'AlreadyAccepted',
|
||||
organisationName,
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (organisationMemberInvite.status === OrganisationMemberInviteStatus.DECLINED) {
|
||||
return {
|
||||
state: 'AlreadyDeclined',
|
||||
organisationName,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: {
|
||||
@@ -71,13 +49,26 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
},
|
||||
});
|
||||
|
||||
// Directly convert the team member invite to a team member if they already have an account.
|
||||
if (user) {
|
||||
await acceptOrganisationInvitation({ token: organisationMemberInvite.token });
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
state: 'LoginRequired',
|
||||
email: organisationMemberInvite.email,
|
||||
organisationName: organisationMemberInvite.organisation.name,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const isSessionUserTheInvitedUser = user.id === session.user?.id;
|
||||
|
||||
return {
|
||||
state: 'Pending',
|
||||
token: organisationMemberInvite.token,
|
||||
state: 'Success',
|
||||
email: organisationMemberInvite.email,
|
||||
organisationName,
|
||||
userExists: user !== null,
|
||||
isSessionUserTheInvitedUser: user !== null && user.id === session.user?.id,
|
||||
organisationName: organisationMemberInvite.organisation.name,
|
||||
isSessionUserTheInvitedUser,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -106,253 +97,57 @@ export default function AcceptInvitationPage({ loaderData }: Route.ComponentProp
|
||||
);
|
||||
}
|
||||
|
||||
if (data.state === 'AlreadyAccepted') {
|
||||
if (data.state === 'LoginRequired') {
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invitation already accepted</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You are already a member of <strong>{data.organisationName}</strong>.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
<Button asChild>
|
||||
<Link to="/">
|
||||
<Trans>Continue</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (data.state === 'AlreadyDeclined') {
|
||||
return <InvitationDeclined organisationName={data.organisationName} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PendingInvitation
|
||||
token={data.token}
|
||||
email={data.email}
|
||||
organisationName={data.organisationName}
|
||||
userExists={data.userExists}
|
||||
isSessionUserTheInvitedUser={data.isSessionUserTheInvitedUser}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type PendingInvitationProps = {
|
||||
token: string;
|
||||
email: string;
|
||||
organisationName: string;
|
||||
userExists: boolean;
|
||||
isSessionUserTheInvitedUser: boolean;
|
||||
};
|
||||
|
||||
type InvitationResult = 'idle' | 'accepted' | 'declined';
|
||||
|
||||
type AcceptFailureReason = 'CapExceeded' | 'SubscriptionInactive' | 'Unknown';
|
||||
|
||||
const PendingInvitation = ({
|
||||
token,
|
||||
email,
|
||||
organisationName,
|
||||
userExists,
|
||||
isSessionUserTheInvitedUser,
|
||||
}: PendingInvitationProps) => {
|
||||
const { t } = useLingui();
|
||||
const { toast } = useToast();
|
||||
const { refreshSession } = useOptionalSession();
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const actionIsDecline = searchParams.get('action') === 'decline';
|
||||
|
||||
const [result, setResult] = useState<InvitationResult>('idle');
|
||||
const [acceptFailureReason, setAcceptFailureReason] = useState<AcceptFailureReason | null>(null);
|
||||
|
||||
const acceptInvitation = trpc.organisation.member.invite.accept.useMutation({
|
||||
onSuccess: async () => {
|
||||
await refreshSession();
|
||||
|
||||
setResult('accepted');
|
||||
},
|
||||
onError: (err) => {
|
||||
const error = AppError.parseError(err);
|
||||
|
||||
const failureReason = match(error.code)
|
||||
.with(AppErrorCode.LIMIT_EXCEEDED, () => 'CapExceeded' as const)
|
||||
.with('SUBSCRIPTION_INACTIVE', () => 'SubscriptionInactive' as const)
|
||||
.otherwise(() => 'Unknown' as const);
|
||||
|
||||
setAcceptFailureReason(failureReason);
|
||||
},
|
||||
});
|
||||
|
||||
const declineInvitation = trpc.organisation.member.invite.decline.useMutation({
|
||||
onSuccess: async () => {
|
||||
await refreshSession();
|
||||
|
||||
setResult('declined');
|
||||
},
|
||||
onError: () => {
|
||||
toast({
|
||||
title: t`Something went wrong`,
|
||||
description: t`Unable to decline this invitation at this time.`,
|
||||
variant: 'destructive',
|
||||
duration: 10000,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (result === 'accepted') {
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invitation accepted!</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have accepted an invitation from <strong>{organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
{isSessionUserTheInvitedUser ? (
|
||||
<Button asChild>
|
||||
<Link to="/">
|
||||
<Trans>Continue</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild>
|
||||
<Link to={`/signin#email=${encodeURIComponent(email)}`}>
|
||||
<Trans>Continue to login</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (result === 'declined') {
|
||||
return <InvitationDeclined organisationName={organisationName} />;
|
||||
}
|
||||
|
||||
// Accepting requires an account (acceptance keys off the invited email).
|
||||
// Declining does not, so we only gate account creation on the accept flow.
|
||||
if (!actionIsDecline && !userExists) {
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Organisation invitation</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have been invited by <strong>{organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
<p className="mt-1 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>To accept this invitation you must create an account.</Trans>
|
||||
</p>
|
||||
|
||||
<Button asChild>
|
||||
<Link to={`/signup#email=${encodeURIComponent(email)}`}>
|
||||
<Trans>Create account</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isPending = acceptInvitation.isPending || declineInvitation.isPending;
|
||||
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<div>
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Organisation invitation</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<p className="mt-2 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have been invited to join <strong>{organisationName}</strong> on Documenso.
|
||||
You have been invited by <strong>{data.organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
{acceptFailureReason && (
|
||||
<p className="mt-2 mb-4 text-destructive text-sm">
|
||||
{match(acceptFailureReason)
|
||||
.with('CapExceeded', () => (
|
||||
<Trans>
|
||||
<strong>{organisationName}</strong> has reached its member limit. Please contact the organisation
|
||||
administrator to upgrade their plan before accepting this invitation.
|
||||
</Trans>
|
||||
))
|
||||
.with('SubscriptionInactive', () => (
|
||||
<Trans>
|
||||
<strong>{organisationName}</strong> does not have an active subscription. Please contact the
|
||||
organisation administrator to renew their plan before accepting this invitation.
|
||||
</Trans>
|
||||
))
|
||||
.with('Unknown', () => (
|
||||
<Trans>
|
||||
We were unable to add you to <strong>{organisationName}</strong> at this time. Please try again later,
|
||||
or contact the organisation administrator.
|
||||
</Trans>
|
||||
))
|
||||
.exhaustive()}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>To accept this invitation you must create an account.</Trans>
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-x-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={async () => declineInvitation.mutateAsync({ token })}
|
||||
loading={declineInvitation.isPending}
|
||||
disabled={isPending}
|
||||
>
|
||||
<Trans>Decline</Trans>
|
||||
</Button>
|
||||
|
||||
{!actionIsDecline && (
|
||||
<Button
|
||||
onClick={async () => acceptInvitation.mutateAsync({ token })}
|
||||
loading={acceptInvitation.isPending}
|
||||
disabled={isPending}
|
||||
>
|
||||
<Trans>Accept</Trans>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link to={`/signup#email=${encodeURIComponent(data.email)}`}>
|
||||
<Trans>Create account</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
);
|
||||
}
|
||||
|
||||
const InvitationDeclined = ({ organisationName }: { organisationName: string }) => {
|
||||
return (
|
||||
<div className="w-screen max-w-lg px-4">
|
||||
<div className="w-full">
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invitation declined</Trans>
|
||||
</h1>
|
||||
<div>
|
||||
<h1 className="font-semibold text-4xl">
|
||||
<Trans>Invitation accepted!</Trans>
|
||||
</h1>
|
||||
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have declined the invitation from <strong>{organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-2 mb-4 text-muted-foreground text-sm">
|
||||
<Trans>
|
||||
You have accepted an invitation from <strong>{data.organisationName}</strong> to join their organisation.
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
{data.isSessionUserTheInvitedUser ? (
|
||||
<Button asChild>
|
||||
<Link to="/">
|
||||
<Trans>Continue</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild>
|
||||
<Link to={`/signin#email=${encodeURIComponent(data.email)}`}>
|
||||
<Trans>Continue to login</Trans>
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -32,10 +32,6 @@ export const getDirectTemplateErrorMessage = (code: string): ToastMessageDescrip
|
||||
return match(code)
|
||||
.with('RECIPIENT_LIMIT_EXCEEDED', () => RECIPIENT_LIMIT_EXCEEDED_ERROR_MESSAGE)
|
||||
.with(AppErrorCode.TOO_MANY_REQUESTS, () => FAIR_USE_LIMIT_EXCEEDED_ERROR_MESSAGE)
|
||||
.with(AppErrorCode.MISSING_SIGNATURE_FIELD, () => ({
|
||||
title: msg`Missing signature fields`,
|
||||
description: msg`This direct link template cannot be used because one or more signers do not have a signature field assigned.`,
|
||||
}))
|
||||
.otherwise(() => ({
|
||||
title: msg`Something went wrong`,
|
||||
description: msg`We were unable to submit this document at this time. Please try again later.`,
|
||||
@@ -81,10 +77,6 @@ export const getTemplateUseErrorMessage = (code: string): ToastMessageDescriptor
|
||||
title: msg`Error`,
|
||||
description: msg`The document was created but could not be sent to recipients.`,
|
||||
}))
|
||||
.with(AppErrorCode.MISSING_SIGNATURE_FIELD, () => ({
|
||||
title: msg`Missing signature fields`,
|
||||
description: msg`The document could not be sent because some signers do not have a signature field. Please edit the template and add a signature field for each signer.`,
|
||||
}))
|
||||
.with(AppErrorCode.INVALID_BODY, AppErrorCode.INVALID_REQUEST, () => ({
|
||||
title: msg`Error`,
|
||||
description: msg`The document could not be created because of missing or invalid information. Please review the template's recipients and fields.`,
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
"vite-plugin-babel-macros": "^1.0.6",
|
||||
"vite-tsconfig-paths": "^5.1.4"
|
||||
},
|
||||
"version": "2.16.0"
|
||||
"version": "2.15.0"
|
||||
}
|
||||
|
||||
Generated
+27
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@documenso/root",
|
||||
"version": "2.16.0",
|
||||
"version": "2.15.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@documenso/root",
|
||||
"version": "2.16.0",
|
||||
"version": "2.15.0",
|
||||
"hasInstallScript": true,
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
@@ -366,7 +366,7 @@
|
||||
},
|
||||
"apps/remix": {
|
||||
"name": "@documenso/remix",
|
||||
"version": "2.16.0",
|
||||
"version": "2.15.0",
|
||||
"dependencies": {
|
||||
"@cantoo/pdf-lib": "^2.5.3",
|
||||
"@documenso/api": "*",
|
||||
@@ -2952,6 +2952,9 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2969,6 +2972,9 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2986,6 +2992,9 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3003,6 +3012,9 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -25014,6 +25026,9 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -25030,6 +25045,9 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -25046,6 +25064,9 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -25062,6 +25083,9 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
"apps/*",
|
||||
"packages/*"
|
||||
],
|
||||
"version": "2.16.0",
|
||||
"version": "2.15.0",
|
||||
"scripts": {
|
||||
"postinstall": "patch-package",
|
||||
"build": "turbo run build",
|
||||
|
||||
@@ -11,7 +11,7 @@ export const OpenAPIV1 = Object.assign(
|
||||
title: 'Documenso API',
|
||||
version: '1.0.0',
|
||||
description:
|
||||
'API V1 has been deprecated. For more details, see https://docs.documenso.com/docs/developers/api/migrate-to-envelopes. \n\nThe Documenso API for retrieving, creating, updating and deleting documents.',
|
||||
'API V1 is deprecated, but will continue to be supported. For more details, see https://docs.documenso.com/developers/public-api. \n\nThe Documenso API for retrieving, creating, updating and deleting documents.',
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
|
||||
@@ -1,439 +0,0 @@
|
||||
import { seedPendingDocument } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { openCommandMenu } from '../fixtures/command-menu';
|
||||
|
||||
test.describe.configure({ mode: 'parallel' });
|
||||
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10);
|
||||
|
||||
const ADMIN_PROMPT_PLACEHOLDER = 'Search documents, users, organisations…';
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: numeric query shows verified user result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(String(targetUser.id));
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
// The category chips include the admin groups with their result counts.
|
||||
await expect(page.getByRole('button', { name: /Global Users/ })).toBeVisible();
|
||||
|
||||
const userOption = page.getByRole('option').filter({ hasText: targetUser.email }).first();
|
||||
|
||||
// Admin results are real links so they support native link behaviour such
|
||||
// as opening in a new tab.
|
||||
await expect(userOption.getByRole('link')).toHaveAttribute('href', `/admin/users/${targetUser.id}`);
|
||||
|
||||
await userOption.click();
|
||||
|
||||
await page.waitForURL(`/admin/users/${targetUser.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: numeric query shows verified team result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { team: targetTeam } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(String(targetTeam.id));
|
||||
|
||||
await expect(page.getByText('Global Teams', { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: targetTeam.url }).first().click();
|
||||
|
||||
await page.waitForURL(`/admin/teams/${targetTeam.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: text query shows document result and navigates', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-ui-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.title);
|
||||
|
||||
await expect(page.getByText('Global Documents', { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: document.secondaryId }).first().click();
|
||||
|
||||
await page.waitForURL(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: envelope_ prefixed query resolves exact document', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-ui-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.id);
|
||||
|
||||
await expect(page.getByText('Global Documents', { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: document.title }).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: admin search requires more than 3 characters unless numeric', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
// A 3 character non-numeric query must not trigger the admin search. The
|
||||
// personal document search fires for any non-empty query, so its response
|
||||
// is the synchronization anchor proving the debounced queries have fired.
|
||||
const documentSearchResponse = page.waitForResponse((response) => response.url().includes('document.search'));
|
||||
|
||||
await input.fill('abc');
|
||||
|
||||
await documentSearchResponse;
|
||||
|
||||
await expect(page.getByText(/^Global /)).toHaveCount(0);
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
|
||||
// A numeric query fires regardless of length.
|
||||
const adminSearchRequest = page.waitForRequest((request) => request.url().includes('admin.search'));
|
||||
|
||||
await input.fill('7');
|
||||
|
||||
await adminSearchRequest;
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: search bar position stays fixed while searching', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
const initialY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(initialY).toBeGreaterThan(0);
|
||||
|
||||
// The height of the prompt may change as results come and go, but the
|
||||
// search bar must never move.
|
||||
await input.fill(String(targetUser.id));
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
const resultsY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(resultsY).toBe(initialY);
|
||||
|
||||
// The search bar must not move when there are no results at all.
|
||||
await input.fill('zzzz-no-such-thing-9x7q');
|
||||
|
||||
await expect(page.getByText('No results for')).toBeVisible();
|
||||
|
||||
const emptyY = (await input.boundingBox())?.y;
|
||||
|
||||
expect(emptyY).toBe(initialY);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: default view shows the document page links outside a team context', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Admin pages have no current team, the page links must still show.
|
||||
await page.goto('/admin/stats');
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'All documents' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Draft documents' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'All templates' })).toBeVisible();
|
||||
|
||||
// Chips only show for categories with actual results, not for the
|
||||
// hardcoded page links.
|
||||
await expect(page.getByRole('button', { name: /^Documents/ })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: /^Templates/ })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: /^Settings/ })).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: theme can be changed from the prompt', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Change theme' }).first().click();
|
||||
|
||||
// The sub page has a contextual placeholder and a back option.
|
||||
await expect(page.getByPlaceholder('Search themes…')).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Back' }).first()).toBeVisible();
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Dark Mode' })).toBeVisible();
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Dark Mode' }).first().click();
|
||||
|
||||
await expect(page.locator('html')).toHaveClass(/dark/);
|
||||
|
||||
// The back option returns to the root view.
|
||||
await page.getByRole('option').filter({ hasText: 'Back' }).first().click();
|
||||
|
||||
await expect(page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: capped admin groups offer a view all link', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const namePrefix = `viewall-${nanoid()}`;
|
||||
|
||||
// Seed enough users sharing a name prefix to hit the 5 result cap.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await seedUser({ name: `${namePrefix}-${i}` });
|
||||
}
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(namePrefix);
|
||||
|
||||
await expect(page.getByText('Global Users', { exact: true })).toBeVisible();
|
||||
|
||||
const viewAllOption = page.getByRole('option').filter({ hasText: 'View all results' }).first();
|
||||
|
||||
await expect(viewAllOption.getByRole('link')).toHaveAttribute(
|
||||
'href',
|
||||
`/admin/users?search=${encodeURIComponent(namePrefix)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: first result is highlighted after every search', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: firstUser } = await seedUser();
|
||||
const { user: secondUser } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
const input = page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first();
|
||||
|
||||
// First search selects the first result.
|
||||
await input.fill(String(firstUser.id));
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: firstUser.email }).first()).toBeVisible();
|
||||
await expect(page.locator('[cmdk-item]').first()).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
// A subsequent search with entirely new results must select the first
|
||||
// result again.
|
||||
await input.fill(String(secondUser.id));
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: secondUser.email }).first()).toBeVisible();
|
||||
await expect(page.locator('[cmdk-item]').first()).toHaveAttribute('aria-selected', 'true');
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: static items match fuzzy queries', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
// "setg" is a non-contiguous abbreviation of "Settings".
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('setg');
|
||||
|
||||
// Wait for the debounced filter to apply first, "Draft documents" can
|
||||
// never match "setg" under either matching strategy.
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Draft documents' })).toHaveCount(0);
|
||||
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Settings' }).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: page scrollbar is hidden while the prompt is open', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await expect
|
||||
.poll(async () => await page.evaluate(() => getComputedStyle(document.documentElement).overflow))
|
||||
.toBe('hidden');
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
await expect
|
||||
.poll(async () => await page.evaluate(() => getComputedStyle(document.documentElement).overflow))
|
||||
.toBe('visible');
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: non-admin gets the prompt without the admin search', async ({ page }) => {
|
||||
const { user, team } = await seedUser({ isAdmin: false });
|
||||
|
||||
const document = await seedPendingDocument(user, team.id, []);
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: user.email });
|
||||
|
||||
// Non-admins get the same prompt with a non-admin placeholder.
|
||||
await openCommandMenu(page, 'Type a command or search...');
|
||||
|
||||
await expect(page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER)).toHaveCount(0);
|
||||
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
|
||||
// Wait for the regular (non-admin) search to resolve so we know the
|
||||
// debounced queries have fired.
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
|
||||
await expect(page.getByText(/^Global /)).toHaveCount(0);
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: typing on a sub page fires no search requests', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const searchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (/api\/trpc\/(document|template|admin)\.search/.test(request.url())) {
|
||||
searchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByRole('option').filter({ hasText: 'Change theme' }).first().click();
|
||||
|
||||
const input = page.getByPlaceholder('Search themes…');
|
||||
|
||||
await expect(input).toBeVisible();
|
||||
|
||||
// Long enough to pass the admin search threshold if it were enabled.
|
||||
await input.fill('dark');
|
||||
|
||||
// The client-side filter applying proves the typing registered.
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Dark Mode' })).toBeVisible();
|
||||
await expect(page.getByRole('option').filter({ hasText: 'Light Mode' })).toHaveCount(0);
|
||||
|
||||
// Wait out the 200ms search debounce with a wide margin before asserting
|
||||
// that no requests fired: there is no response to anchor on when the
|
||||
// desired behaviour is "no requests at all".
|
||||
await page.waitForTimeout(750);
|
||||
|
||||
expect(searchRequests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: failed searches show an error state instead of no results', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await page.route(/api\/trpc\/(document|template|admin)\.search/, async (route) => {
|
||||
await route.fulfill({ status: 500, contentType: 'application/json', body: '{}' });
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('zzzz-no-such-thing-9x7q');
|
||||
|
||||
// A failed search must be honest about it, not claim there are no results.
|
||||
await expect(page.getByText('Something went wrong')).toBeVisible();
|
||||
await expect(page.getByText('No results for')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: partial search failure still shows results with a notice', async ({ page }) => {
|
||||
const { user: adminUser, team } = await seedUser({ isAdmin: true });
|
||||
|
||||
const document = await seedPendingDocument(adminUser, team.id, [], {
|
||||
createDocumentOptions: { title: `partial-fail-${nanoid()}` },
|
||||
});
|
||||
|
||||
// Only the admin search fails: the personal searches succeed.
|
||||
await page.route(/api\/trpc\/admin\.search/, async (route) => {
|
||||
await route.fulfill({ status: 500, contentType: 'application/json', body: '{}' });
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill(document.title);
|
||||
|
||||
// The successful personal document search must still render its results.
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
|
||||
// The failed admin search must be flagged rather than silently dropped.
|
||||
await expect(page.getByText('Some searches failed')).toBeVisible();
|
||||
});
|
||||
|
||||
test('[ADMIN][GLOBAL_SEARCH]: over-length query skips the admin search without erroring', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
const adminSearchRequests: string[] = [];
|
||||
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('admin.search')) {
|
||||
adminSearchRequests.push(request.url());
|
||||
}
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
await openCommandMenu(page, ADMIN_PROMPT_PLACEHOLDER);
|
||||
|
||||
// The admin search endpoint rejects queries longer than 100 characters, so
|
||||
// the client must not send them. The personal searches accept up to 1024
|
||||
// characters and still run, anchoring the debounced query flush.
|
||||
const documentSearchResponse = page.waitForResponse((response) => response.url().includes('document.search'));
|
||||
|
||||
await page.getByPlaceholder(ADMIN_PROMPT_PLACEHOLDER).first().fill('a'.repeat(150));
|
||||
|
||||
await documentSearchResponse;
|
||||
|
||||
// The personal searches ran and found nothing: the honest empty state, with
|
||||
// no error in sight.
|
||||
await expect(page.getByText('No results for')).toBeVisible();
|
||||
await expect(page.getByText('Something went wrong')).toHaveCount(0);
|
||||
|
||||
expect(adminSearchRequests).toHaveLength(0);
|
||||
});
|
||||
@@ -1,249 +0,0 @@
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
|
||||
import { seedPendingDocument } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
|
||||
import { apiSignin } from '../../../fixtures/authentication';
|
||||
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10);
|
||||
|
||||
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
|
||||
|
||||
test.describe.configure({ mode: 'parallel' });
|
||||
|
||||
type AdminSearchGroup = {
|
||||
type: string;
|
||||
results: Array<{ label: string; sublabel?: string; path: string; value: string }>;
|
||||
};
|
||||
|
||||
const callAdminSearch = async (page: Page, query: string) => {
|
||||
const inputParam = encodeURIComponent(JSON.stringify({ json: { query } }));
|
||||
const url = `${WEBAPP_BASE_URL}/api/trpc/admin.search?input=${inputParam}`;
|
||||
|
||||
const res = await page.context().request.get(url);
|
||||
|
||||
return {
|
||||
res,
|
||||
groups: res.ok()
|
||||
? // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
((await res.json()).result.data.json.groups as AdminSearchGroup[])
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
const findGroup = (groups: AdminSearchGroup[] | null, type: string) =>
|
||||
(groups ?? []).find((group) => group.type === type);
|
||||
|
||||
// ─── Access control ──────────────────────────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: unauthenticated request is rejected with 401', async ({ page }) => {
|
||||
const { res } = await callAdminSearch(page, 'anything');
|
||||
|
||||
expect(res.ok()).toBeFalsy();
|
||||
expect(res.status()).toBe(401);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: non-admin authenticated user is rejected with 401', async ({ page }) => {
|
||||
const { user: nonAdminUser } = await seedUser({ isAdmin: false });
|
||||
|
||||
await apiSignin({ page, email: nonAdminUser.email });
|
||||
|
||||
const { res } = await callAdminSearch(page, 'anything');
|
||||
|
||||
expect(res.ok()).toBeFalsy();
|
||||
expect(res.status()).toBe(401);
|
||||
});
|
||||
|
||||
// ─── Numeric queries: verified ID lookups ────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query returns verified user and team rows', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: targetUser, team: targetTeam } = await seedUser();
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by user ID.
|
||||
const userSearch = await callAdminSearch(page, String(targetUser.id));
|
||||
|
||||
expect(userSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const userGroup = findGroup(userSearch.groups, 'user');
|
||||
expect(userGroup).toBeDefined();
|
||||
expect(userGroup?.results).toHaveLength(1);
|
||||
expect(userGroup?.results[0].path).toBe(`/admin/users/${targetUser.id}`);
|
||||
expect(userGroup?.results[0].sublabel).toContain(targetUser.email);
|
||||
|
||||
// The cmdk `value` contract: value must contain the raw query.
|
||||
expect(userGroup?.results[0].value).toContain(String(targetUser.id));
|
||||
|
||||
// Search by team ID.
|
||||
const teamSearch = await callAdminSearch(page, String(targetTeam.id));
|
||||
|
||||
expect(teamSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const teamGroup = findGroup(teamSearch.groups, 'team');
|
||||
expect(teamGroup).toBeDefined();
|
||||
expect(teamGroup?.results).toHaveLength(1);
|
||||
expect(teamGroup?.results[0].path).toBe(`/admin/teams/${targetTeam.id}`);
|
||||
expect(teamGroup?.results[0].label).toBe(targetTeam.name);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query returns verified document and recipient rows', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
const { user: recipientUser } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [recipientUser]);
|
||||
const legacyDocumentId = document.secondaryId.replace('document_', '');
|
||||
const recipient = document.recipients[0];
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by legacy document ID (bare number).
|
||||
const documentSearch = await callAdminSearch(page, legacyDocumentId);
|
||||
|
||||
expect(documentSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(documentSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results).toHaveLength(1);
|
||||
expect(documentGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
expect(documentGroup?.results[0].label).toBe(document.title);
|
||||
|
||||
// Search by recipient ID: links to the parent document.
|
||||
const recipientSearch = await callAdminSearch(page, String(recipient.id));
|
||||
|
||||
expect(recipientSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const recipientGroup = findGroup(recipientSearch.groups, 'recipient');
|
||||
expect(recipientGroup).toBeDefined();
|
||||
expect(recipientGroup?.results).toHaveLength(1);
|
||||
expect(recipientGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
expect(recipientGroup?.results[0].label).toBe(recipient.email);
|
||||
expect(recipientGroup?.results[0].sublabel).toBe(`#${recipient.id} · ${recipient.name} · ${document.title}`);
|
||||
|
||||
// Search by the full document_<id> secondary ID: exercises the prefix branch.
|
||||
const secondaryIdSearch = await callAdminSearch(page, document.secondaryId);
|
||||
|
||||
expect(secondaryIdSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const secondaryIdGroup = findGroup(secondaryIdSearch.groups, 'document');
|
||||
expect(secondaryIdGroup).toBeDefined();
|
||||
expect(secondaryIdGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: numeric query with no matches returns no groups', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, '999999999');
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(groups).toEqual([]);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: oversized number does not error and falls back to text search', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
// 99999999999999 exceeds Int4, so it cannot be an ID lookup: it must be
|
||||
// treated as text (and must not 500).
|
||||
const oversizedNumber = '99999999999999';
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `${oversizedNumber}-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, oversizedNumber);
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results.map((result) => result.path)).toContain(`/admin/documents/${document.id}`);
|
||||
});
|
||||
|
||||
// ─── Prefixed ID queries: exact lookups ──────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: envelope_ and org_ prefixes resolve exact matches', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, organisation, team } = await seedUser();
|
||||
|
||||
const document = await seedPendingDocument(sender, team.id, []);
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// envelope_<id> resolves the document.
|
||||
const envelopeSearch = await callAdminSearch(page, document.id);
|
||||
|
||||
expect(envelopeSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(envelopeSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results[0].path).toBe(`/admin/documents/${document.id}`);
|
||||
|
||||
// Only the document group is returned for a recognized prefix.
|
||||
expect(envelopeSearch.groups).toHaveLength(1);
|
||||
|
||||
// org_<id> resolves the organisation.
|
||||
const orgSearch = await callAdminSearch(page, organisation.id);
|
||||
|
||||
expect(orgSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const orgGroup = findGroup(orgSearch.groups, 'organisation');
|
||||
expect(orgGroup).toBeDefined();
|
||||
expect(orgGroup?.results[0].path).toBe(`/admin/organisations/${organisation.id}`);
|
||||
expect(orgGroup?.results[0].label).toBe(organisation.name);
|
||||
|
||||
// Only the organisation group is returned for a recognized prefix.
|
||||
expect(orgSearch.groups).toHaveLength(1);
|
||||
});
|
||||
|
||||
// ─── Free text queries ───────────────────────────────────────────────────────
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: text query matches documents by title and users by email', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
const { user: sender, team } = await seedUser();
|
||||
|
||||
// A unique title: the default seeded title is shared across the whole suite,
|
||||
// and global search only returns the newest few matches.
|
||||
const document = await seedPendingDocument(sender, team.id, [], {
|
||||
createDocumentOptions: { title: `admin-search-${nanoid()}` },
|
||||
});
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
// Search by document title.
|
||||
const titleSearch = await callAdminSearch(page, document.title);
|
||||
|
||||
expect(titleSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const documentGroup = findGroup(titleSearch.groups, 'document');
|
||||
expect(documentGroup).toBeDefined();
|
||||
expect(documentGroup?.results.map((result) => result.path)).toContain(`/admin/documents/${document.id}`);
|
||||
|
||||
// Search by user email (emails are unique nanoid-based, so this is specific).
|
||||
const emailSearch = await callAdminSearch(page, sender.email);
|
||||
|
||||
expect(emailSearch.res.ok()).toBeTruthy();
|
||||
|
||||
const userGroup = findGroup(emailSearch.groups, 'user');
|
||||
expect(userGroup).toBeDefined();
|
||||
expect(userGroup?.results[0].path).toBe(`/admin/users/${sender.id}`);
|
||||
});
|
||||
|
||||
test('[ADMIN][TRPC][SEARCH]: gibberish query returns no groups', async ({ page }) => {
|
||||
const { user: adminUser } = await seedUser({ isAdmin: true });
|
||||
|
||||
await apiSignin({ page, email: adminUser.email });
|
||||
|
||||
const { res, groups } = await callAdminSearch(page, 'zzzz-no-such-thing-9x7q');
|
||||
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(groups).toEqual([]);
|
||||
});
|
||||
@@ -2,20 +2,10 @@ import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
|
||||
import { createApiToken } from '@documenso/lib/server-only/public-api/create-api-token';
|
||||
import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import {
|
||||
DocumentSigningOrder,
|
||||
DocumentStatus,
|
||||
FieldType,
|
||||
RecipientRole,
|
||||
SendStatus,
|
||||
SigningStatus,
|
||||
} from '@documenso/prisma/client';
|
||||
import { FieldType, RecipientRole } from '@documenso/prisma/client';
|
||||
import { seedBlankDocument, seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
import { signSignaturePad } from '../../fixtures/signature';
|
||||
|
||||
test.describe('Document API', () => {
|
||||
test('sendDocument: should respect sendCompletionEmails setting', async ({ request }) => {
|
||||
@@ -442,194 +432,4 @@ test.describe('Document API', () => {
|
||||
expect(response.ok()).toBeTruthy();
|
||||
expect(response.status()).toBe(200);
|
||||
});
|
||||
|
||||
test('sendDocument: should complete document immediately when all recipients are CC', async ({ request }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
// Create a blank document and get it with envelope items
|
||||
const blankDocument = await seedBlankDocument(user, team.id);
|
||||
const document = await prisma.envelope.findUniqueOrThrow({
|
||||
where: { id: blankDocument.id },
|
||||
include: { envelopeItems: true },
|
||||
});
|
||||
|
||||
// Add two CC recipients without any fields, mirroring the production
|
||||
// state where CC recipients are created pre-signed.
|
||||
for (const email of ['cc1@example.com', 'cc2@example.com']) {
|
||||
await prisma.recipient.create({
|
||||
data: {
|
||||
email,
|
||||
name: 'Test CC',
|
||||
role: RecipientRole.CC,
|
||||
signingStatus: SigningStatus.SIGNED,
|
||||
sendStatus: SendStatus.SENT,
|
||||
token: nanoid(),
|
||||
envelopeId: document.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { token } = await createApiToken({
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
tokenName: 'test',
|
||||
expiresIn: null,
|
||||
});
|
||||
|
||||
const response = await request.post(
|
||||
`${NEXT_PUBLIC_WEBAPP_URL()}/api/v1/documents/${mapSecondaryIdToDocumentId(document.secondaryId)}/send`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {},
|
||||
},
|
||||
);
|
||||
|
||||
expect(response.ok()).toBeTruthy();
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
// The document seals asynchronously and completes without anyone signing.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const updatedDocument = await prisma.envelope.findFirstOrThrow({
|
||||
where: { id: document.id },
|
||||
});
|
||||
|
||||
return updatedDocument.status;
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(DocumentStatus.COMPLETED);
|
||||
});
|
||||
|
||||
test('sendDocument: should not block initial sequential send when CC recipient is first in signing order', async ({
|
||||
request,
|
||||
page,
|
||||
}) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
// Create a blank document and get it with envelope items
|
||||
const blankDocument = await seedBlankDocument(user, team.id);
|
||||
const document = await prisma.envelope.findUniqueOrThrow({
|
||||
where: { id: blankDocument.id },
|
||||
include: { envelopeItems: true },
|
||||
});
|
||||
|
||||
await prisma.documentMeta.update({
|
||||
where: { id: document.documentMetaId },
|
||||
data: { signingOrder: DocumentSigningOrder.SEQUENTIAL },
|
||||
});
|
||||
|
||||
// CC recipient first in the signing order, mirroring the production
|
||||
// state where CC recipients are created pre-signed.
|
||||
await prisma.recipient.create({
|
||||
data: {
|
||||
email: 'cc@example.com',
|
||||
name: 'Test CC',
|
||||
role: RecipientRole.CC,
|
||||
signingOrder: 1,
|
||||
signingStatus: SigningStatus.SIGNED,
|
||||
sendStatus: SendStatus.SENT,
|
||||
token: nanoid(),
|
||||
envelopeId: document.id,
|
||||
},
|
||||
});
|
||||
|
||||
const [signerA, signerB] = await Promise.all(
|
||||
[
|
||||
{ email: 'signer-a@example.com', name: 'Signer A', signingOrder: 2 },
|
||||
{ email: 'signer-b@example.com', name: 'Signer B', signingOrder: 3 },
|
||||
].map(async ({ email, name, signingOrder }) =>
|
||||
prisma.recipient.create({
|
||||
data: {
|
||||
email,
|
||||
name,
|
||||
role: RecipientRole.SIGNER,
|
||||
signingOrder,
|
||||
token: nanoid(),
|
||||
envelopeId: document.id,
|
||||
fields: {
|
||||
create: {
|
||||
type: FieldType.SIGNATURE,
|
||||
page: 1,
|
||||
positionX: signingOrder * 10,
|
||||
positionY: 10,
|
||||
width: 5,
|
||||
height: 5,
|
||||
customText: '',
|
||||
inserted: false,
|
||||
envelopeId: document.id,
|
||||
envelopeItemId: document.envelopeItems[0].id,
|
||||
fieldMeta: { type: 'signature', fontSize: 14 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const { token } = await createApiToken({
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
tokenName: 'test',
|
||||
expiresIn: null,
|
||||
});
|
||||
|
||||
const response = await request.post(
|
||||
`${NEXT_PUBLIC_WEBAPP_URL()}/api/v1/documents/${mapSecondaryIdToDocumentId(document.secondaryId)}/send`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {},
|
||||
},
|
||||
);
|
||||
|
||||
expect(response.ok()).toBeTruthy();
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
// The CC recipient at order 1 must not block signer A at order 2.
|
||||
await page.goto(`/sign/${signerA.token}`);
|
||||
await expect(page).not.toHaveURL(`/sign/${signerA.token}/waiting`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
|
||||
// Signer B at order 3 must still wait for signer A.
|
||||
await page.goto(`/sign/${signerB.token}`);
|
||||
await expect(page).toHaveURL(`/sign/${signerB.token}/waiting`);
|
||||
|
||||
// Sign as signer A then signer B.
|
||||
for (const signer of [signerA, signerB]) {
|
||||
await page.goto(`/sign/${signer.token}`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
await signSignaturePad(page);
|
||||
|
||||
const signerField = await prisma.field.findFirstOrThrow({
|
||||
where: { recipientId: signer.id },
|
||||
});
|
||||
|
||||
await page.locator(`#field-${signerField.id}`).getByRole('button').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`/sign/${signer.token}/complete`);
|
||||
}
|
||||
|
||||
// The document completes without any action from the CC recipient.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const updatedDocument = await prisma.envelope.findFirstOrThrow({
|
||||
where: { id: document.id },
|
||||
});
|
||||
|
||||
return updatedDocument.status;
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(DocumentStatus.COMPLETED);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,7 +50,7 @@ import type { Organisation, Team, User } from '@prisma/client';
|
||||
*
|
||||
* --- GLOBAL LIMIT AWARENESS ---
|
||||
* apps/remix/server/router.ts applies a GLOBAL per-IP limiter to /api/v1/*:
|
||||
* apiV1RateLimit = 1000 requests / 1 minute (action `api.v1`, see rate-limits.ts).
|
||||
* apiV1RateLimit = 100 requests / 1 minute (action `api.v1`, see rate-limits.ts).
|
||||
* Every per-org limit/quota configured here is kept FAR below that ceiling (single
|
||||
* digits) and the suite runs serially so the shared-IP global bucket is never the
|
||||
* thing that trips. A global-limit 429 is shaped `{ error }` whereas an org-limit
|
||||
@@ -62,7 +62,7 @@ const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
|
||||
const baseUrl = `${WEBAPP_BASE_URL}/api/v1`;
|
||||
|
||||
// Run serially: all workers share one IP, and the global /api/v1 limiter is
|
||||
// per-IP. Serial execution keeps the shared global bucket well under 1000/min.
|
||||
// per-IP. Serial execution keeps the shared global bucket well under 100/min.
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
// This suite is only meaningful with real rate limiting enabled. CI sets the
|
||||
@@ -125,7 +125,7 @@ const setClaimLimits = async (team: Team, limits: ClaimLimits) => {
|
||||
* GLOBAL /api/v1 IP bucket so a fresh scenario starts from zero.
|
||||
*
|
||||
* - The org windowed limiter keys its rows `ip:org:<id>`.
|
||||
* - The GLOBAL limiter (apps/remix/server/router.ts -> apiV1RateLimit, 1000/min
|
||||
* - The GLOBAL limiter (apps/remix/server/router.ts -> apiV1RateLimit, 100/min
|
||||
* per IP, action `api.v1`) is shared by EVERY v1 request from this test client.
|
||||
* Across the suite (and especially across repeated local runs within the same
|
||||
* minute) that shared bucket would otherwise fill up and trip BEFORE the org
|
||||
|
||||
@@ -37,7 +37,7 @@ import type { Organisation, Team, User } from '@prisma/client';
|
||||
*
|
||||
* --- GLOBAL LIMIT AWARENESS ---
|
||||
* apps/remix/server/router.ts applies a GLOBAL per-IP limiter to /api/v2/*:
|
||||
* apiV2RateLimit = 1000 requests / 1 minute (see rate-limits.ts).
|
||||
* apiV2RateLimit = 100 requests / 1 minute (see rate-limits.ts).
|
||||
* Every per-org limit/quota configured here is kept FAR below that ceiling (single
|
||||
* digits) and the suite runs serially so the shared-IP global bucket is never the
|
||||
* thing that trips. A global-limit 429 is shaped `{ error }` whereas an org-limit
|
||||
@@ -49,7 +49,7 @@ const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
|
||||
const baseUrl = `${WEBAPP_BASE_URL}/api/v2-beta`;
|
||||
|
||||
// Run serially: all workers share one IP, and the global /api/v2 limiter is
|
||||
// per-IP. Serial execution keeps the shared global bucket well under 1000/min.
|
||||
// per-IP. Serial execution keeps the shared global bucket well under 100/min.
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
// This suite is only meaningful with real rate limiting enabled. CI sets the
|
||||
|
||||
@@ -3,9 +3,6 @@ import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { openCommandMenu } from '../fixtures/command-menu';
|
||||
|
||||
const COMMAND_MENU_PLACEHOLDER = 'Type a command or search...';
|
||||
|
||||
test('[COMMAND_MENU]: should see sent documents', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
@@ -17,9 +14,9 @@ test('[COMMAND_MENU]: should see sent documents', async ({ page }) => {
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(document.title);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -33,9 +30,9 @@ test('[COMMAND_MENU]: should see received documents', async ({ page }) => {
|
||||
email: recipient.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(document.title);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(document.title);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -49,8 +46,8 @@ test('[COMMAND_MENU]: should be able to search by recipient', async ({ page }) =
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
await openCommandMenu(page, COMMAND_MENU_PLACEHOLDER);
|
||||
await page.keyboard.press('Meta+K');
|
||||
|
||||
await page.getByPlaceholder(COMMAND_MENU_PLACEHOLDER).first().fill(recipient.email);
|
||||
await page.getByPlaceholder('Type a command or search...').first().fill(recipient.email);
|
||||
await expect(page.getByRole('option', { name: document.title })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -2,14 +2,7 @@ import { prisma } from '@documenso/prisma';
|
||||
import { seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import {
|
||||
DocumentSigningOrder,
|
||||
DocumentStatus,
|
||||
FieldType,
|
||||
RecipientRole,
|
||||
SendStatus,
|
||||
SigningStatus,
|
||||
} from '@prisma/client';
|
||||
import { DocumentSigningOrder, DocumentStatus, FieldType, RecipientRole, SigningStatus } from '@prisma/client';
|
||||
|
||||
import { signDirectSignaturePad, signSignaturePad } from '../fixtures/signature';
|
||||
|
||||
@@ -377,221 +370,3 @@ test('[NEXT_RECIPIENT_DICTATION]: should allow assistant to dictate next signer'
|
||||
expect(thirdRecipient.role).toBe(RecipientRole.SIGNER);
|
||||
}).toPass();
|
||||
});
|
||||
|
||||
test('[NEXT_RECIPIENT_DICTATION]: should skip CC recipient when dictating next signer', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
const { user: firstSigner } = await seedUser();
|
||||
const { user: ccUser } = await seedUser();
|
||||
const { user: secondSigner } = await seedUser();
|
||||
|
||||
const { recipients, document } = await seedPendingDocumentWithFullFields({
|
||||
owner: user,
|
||||
teamId: team.id,
|
||||
recipients: [firstSigner, ccUser, secondSigner],
|
||||
recipientsCreateOptions: [
|
||||
{ signingOrder: 1 },
|
||||
{
|
||||
// CC recipients are created pre-signed, mirroring production behaviour.
|
||||
signingOrder: 2,
|
||||
role: RecipientRole.CC,
|
||||
signingStatus: SigningStatus.SIGNED,
|
||||
sendStatus: SendStatus.SENT,
|
||||
},
|
||||
{ signingOrder: 3 },
|
||||
],
|
||||
updateDocumentOptions: {
|
||||
documentMeta: {
|
||||
upsert: {
|
||||
create: {
|
||||
allowDictateNextSigner: true,
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
update: {
|
||||
allowDictateNextSigner: true,
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const firstRecipient = recipients.find((r) => r.email === firstSigner.email);
|
||||
const ccRecipient = recipients.find((r) => r.email === ccUser.email);
|
||||
|
||||
if (!firstRecipient || !ccRecipient) {
|
||||
throw new Error('Recipients not found');
|
||||
}
|
||||
|
||||
// CC recipients cannot have fields.
|
||||
await prisma.field.deleteMany({
|
||||
where: {
|
||||
recipientId: ccRecipient.id,
|
||||
},
|
||||
});
|
||||
|
||||
const { token, fields } = firstRecipient;
|
||||
|
||||
const signUrl = `/sign/${token}`;
|
||||
|
||||
await page.goto(signUrl);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
|
||||
await signSignaturePad(page);
|
||||
|
||||
// Fill in all fields
|
||||
for (const field of fields) {
|
||||
await page.locator(`#field-${field.id}`).getByRole('button').click();
|
||||
|
||||
if (field.type === FieldType.TEXT) {
|
||||
await page.locator('#custom-text').fill('TEXT');
|
||||
await page.getByRole('button', { name: 'Save' }).click();
|
||||
}
|
||||
|
||||
await expect(page.locator(`#field-${field.id}`)).toHaveAttribute('data-inserted', 'true');
|
||||
}
|
||||
|
||||
// Complete signing and verify the offered next recipient
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(page.getByText('Next Recipient Name')).toBeVisible();
|
||||
|
||||
// The dictation dialog must offer the second signer, not the CC recipient.
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByLabel('Name')).toHaveValue(secondSigner.name ?? '');
|
||||
await expect(dialog.getByLabel('Email')).toHaveValue(secondSigner.email);
|
||||
|
||||
// Submit and verify completion
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`${signUrl}/complete`);
|
||||
|
||||
// Verify document and recipient states
|
||||
const updatedDocument = await prisma.envelope.findUniqueOrThrow({
|
||||
where: { id: document.id },
|
||||
include: {
|
||||
recipients: {
|
||||
orderBy: { signingOrder: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Document should still be pending as the second signer has not signed
|
||||
expect(updatedDocument.status).toBe(DocumentStatus.PENDING);
|
||||
|
||||
// The CC recipient must remain untouched
|
||||
const updatedCcRecipient = updatedDocument.recipients[1];
|
||||
expect(updatedCcRecipient.email).toBe(ccUser.email);
|
||||
expect(updatedCcRecipient.role).toBe(RecipientRole.CC);
|
||||
expect(updatedCcRecipient.signingStatus).toBe(SigningStatus.SIGNED);
|
||||
|
||||
// The second signer must remain the next pending recipient
|
||||
const updatedSecondRecipient = updatedDocument.recipients[2];
|
||||
expect(updatedSecondRecipient.email).toBe(secondSigner.email);
|
||||
expect(updatedSecondRecipient.signingOrder).toBe(3);
|
||||
expect(updatedSecondRecipient.signingStatus).toBe(SigningStatus.NOT_SIGNED);
|
||||
});
|
||||
|
||||
test('[NEXT_RECIPIENT_DICTATION]: should not offer dictation when CC recipient is last', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
const { user: firstSigner } = await seedUser();
|
||||
const { user: secondSigner } = await seedUser();
|
||||
const { user: ccUser } = await seedUser();
|
||||
|
||||
const { recipients, document } = await seedPendingDocumentWithFullFields({
|
||||
owner: user,
|
||||
teamId: team.id,
|
||||
recipients: [firstSigner, secondSigner, ccUser],
|
||||
recipientsCreateOptions: [
|
||||
{ signingOrder: 1 },
|
||||
{ signingOrder: 2 },
|
||||
{
|
||||
// CC recipients are created pre-signed, mirroring production behaviour.
|
||||
signingOrder: 3,
|
||||
role: RecipientRole.CC,
|
||||
signingStatus: SigningStatus.SIGNED,
|
||||
sendStatus: SendStatus.SENT,
|
||||
},
|
||||
],
|
||||
updateDocumentOptions: {
|
||||
documentMeta: {
|
||||
upsert: {
|
||||
create: {
|
||||
allowDictateNextSigner: true,
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
update: {
|
||||
allowDictateNextSigner: true,
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const firstRecipient = recipients.find((r) => r.email === firstSigner.email);
|
||||
const secondRecipient = recipients.find((r) => r.email === secondSigner.email);
|
||||
const ccRecipient = recipients.find((r) => r.email === ccUser.email);
|
||||
|
||||
if (!firstRecipient || !secondRecipient || !ccRecipient) {
|
||||
throw new Error('Recipients not found');
|
||||
}
|
||||
|
||||
// CC recipients cannot have fields.
|
||||
await prisma.field.deleteMany({
|
||||
where: {
|
||||
recipientId: ccRecipient.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Sign as both signers in order.
|
||||
for (const recipient of [firstRecipient, secondRecipient]) {
|
||||
const { token, fields } = recipient;
|
||||
|
||||
const signUrl = `/sign/${token}`;
|
||||
|
||||
await page.goto(signUrl);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
|
||||
await signSignaturePad(page);
|
||||
|
||||
// Fill in all fields
|
||||
for (const field of fields) {
|
||||
await page.locator(`#field-${field.id}`).getByRole('button').click();
|
||||
|
||||
if (field.type === FieldType.TEXT) {
|
||||
await page.locator('#custom-text').fill('TEXT');
|
||||
await page.getByRole('button', { name: 'Save' }).click();
|
||||
}
|
||||
|
||||
await expect(page.locator(`#field-${field.id}`)).toHaveAttribute('data-inserted', 'true');
|
||||
}
|
||||
|
||||
// Complete signing
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
if (recipient.id === secondRecipient.id) {
|
||||
// The last actionable signer must not be offered the CC recipient.
|
||||
await expect(page.getByText('Next Recipient Name')).not.toBeVisible();
|
||||
}
|
||||
|
||||
// Submit and verify completion
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`${signUrl}/complete`);
|
||||
}
|
||||
|
||||
// The document completes without any action from the CC recipient.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const finalDocument = await prisma.envelope.findUniqueOrThrow({
|
||||
where: { id: document.id },
|
||||
});
|
||||
|
||||
return finalDocument.status;
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(DocumentStatus.COMPLETED);
|
||||
});
|
||||
|
||||
@@ -4,14 +4,7 @@ import { prisma } from '@documenso/prisma';
|
||||
import { seedBlankDocument, seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import {
|
||||
DocumentSigningOrder,
|
||||
DocumentStatus,
|
||||
FieldType,
|
||||
RecipientRole,
|
||||
SendStatus,
|
||||
SigningStatus,
|
||||
} from '@prisma/client';
|
||||
import { DocumentSigningOrder, DocumentStatus, FieldType, RecipientRole, SigningStatus } from '@prisma/client';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
@@ -232,20 +225,15 @@ test('[DOCUMENT_FLOW]: should be able to create a document with multiple recipie
|
||||
await page.getByLabel('Receives copy').click();
|
||||
await page.getByRole('button', { name: 'Add Signer' }).click();
|
||||
|
||||
// CC recipients are kept last, so new rows are inserted above the CC row.
|
||||
await expect(page.getByLabel('Email')).toHaveCount(3);
|
||||
|
||||
await page.getByLabel('Email').nth(1).fill('user3@example.com');
|
||||
await page.getByLabel('Name').nth(1).fill('User 3');
|
||||
await page.getByRole('combobox').nth(1).click();
|
||||
await page.getByLabel('Email').nth(2).fill('user3@example.com');
|
||||
await page.getByLabel('Name').nth(2).fill('User 3');
|
||||
await page.getByRole('combobox').nth(2).click();
|
||||
await page.getByLabel('Needs to approve').click();
|
||||
await page.getByRole('button', { name: 'Add Signer' }).click();
|
||||
|
||||
await expect(page.getByLabel('Email')).toHaveCount(4);
|
||||
|
||||
await page.getByLabel('Email').nth(2).fill('user4@example.com');
|
||||
await page.getByLabel('Name').nth(2).fill('User 4');
|
||||
await page.getByRole('combobox').nth(2).click();
|
||||
await page.getByLabel('Email').nth(3).fill('user4@example.com');
|
||||
await page.getByLabel('Name').nth(3).fill('User 4');
|
||||
await page.getByRole('combobox').nth(3).click();
|
||||
await page.getByLabel('Needs to view').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Continue' }).click();
|
||||
@@ -673,182 +661,3 @@ test('[DOCUMENT_FLOW]: should prevent out-of-order signing in sequential mode',
|
||||
await expect(page).not.toHaveURL(`/sign/${activeRecipient?.token}/waiting`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('[DOCUMENT_FLOW]: should skip CC recipients in sequential signing order', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const { document, recipients } = await seedPendingDocumentWithFullFields({
|
||||
teamId: team.id,
|
||||
owner: user,
|
||||
recipients: ['signer1@example.com', 'cc@example.com', 'signer2@example.com'],
|
||||
fields: [FieldType.SIGNATURE],
|
||||
recipientsCreateOptions: [
|
||||
{ signingOrder: 1 },
|
||||
{
|
||||
// CC recipients are created pre-signed, mirroring production behaviour.
|
||||
signingOrder: 2,
|
||||
role: RecipientRole.CC,
|
||||
signingStatus: SigningStatus.SIGNED,
|
||||
sendStatus: SendStatus.SENT,
|
||||
},
|
||||
{ signingOrder: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
await prisma.documentMeta.update({
|
||||
where: {
|
||||
id: document.documentMetaId,
|
||||
},
|
||||
data: {
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
});
|
||||
|
||||
const firstSigner = recipients.find((r) => r.email === 'signer1@example.com');
|
||||
const ccRecipient = recipients.find((r) => r.email === 'cc@example.com');
|
||||
const lastSigner = recipients.find((r) => r.email === 'signer2@example.com');
|
||||
|
||||
// CC recipients cannot have fields.
|
||||
await prisma.field.deleteMany({
|
||||
where: {
|
||||
recipientId: ccRecipient?.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Sequential order is enforced: the last signer must wait while the first signer is pending.
|
||||
await page.goto(`/sign/${lastSigner?.token}`);
|
||||
await expect(page).toHaveURL(`/sign/${lastSigner?.token}/waiting`);
|
||||
|
||||
// Sign as the first signer.
|
||||
await page.goto(`/sign/${firstSigner?.token}`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
await signSignaturePad(page);
|
||||
|
||||
const firstSignerField = await prisma.field.findFirstOrThrow({
|
||||
where: { recipientId: firstSigner?.id },
|
||||
});
|
||||
|
||||
await page.locator(`#field-${firstSignerField.id}`).getByRole('button').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`/sign/${firstSigner?.token}/complete`);
|
||||
|
||||
// The CC recipient at order 2 must not block the last signer at order 3.
|
||||
await page.goto(`/sign/${lastSigner?.token}`);
|
||||
await expect(page).not.toHaveURL(`/sign/${lastSigner?.token}/waiting`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
|
||||
await signSignaturePad(page);
|
||||
|
||||
const lastSignerField = await prisma.field.findFirstOrThrow({
|
||||
where: { recipientId: lastSigner?.id },
|
||||
});
|
||||
|
||||
await page.locator(`#field-${lastSignerField.id}`).getByRole('button').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`/sign/${lastSigner?.token}/complete`);
|
||||
|
||||
// The document completes without any action from the CC recipient.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const finalDocument = await prisma.envelope.findFirstOrThrow({
|
||||
where: { id: document.id },
|
||||
});
|
||||
|
||||
return finalDocument.status;
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(DocumentStatus.COMPLETED);
|
||||
});
|
||||
|
||||
test('[DOCUMENT_FLOW]: should skip unsigned CC recipients in sequential signing order', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const { document, recipients } = await seedPendingDocumentWithFullFields({
|
||||
teamId: team.id,
|
||||
owner: user,
|
||||
recipients: ['signer1@example.com', 'cc@example.com', 'signer2@example.com'],
|
||||
fields: [FieldType.SIGNATURE],
|
||||
recipientsCreateOptions: [
|
||||
{ signingOrder: 1 },
|
||||
{
|
||||
// Legacy/inconsistent data: a CC recipient that was never marked as signed.
|
||||
signingOrder: 2,
|
||||
role: RecipientRole.CC,
|
||||
signingStatus: SigningStatus.NOT_SIGNED,
|
||||
},
|
||||
{ signingOrder: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
await prisma.documentMeta.update({
|
||||
where: {
|
||||
id: document.documentMetaId,
|
||||
},
|
||||
data: {
|
||||
signingOrder: DocumentSigningOrder.SEQUENTIAL,
|
||||
},
|
||||
});
|
||||
|
||||
const firstSigner = recipients.find((r) => r.email === 'signer1@example.com');
|
||||
const ccRecipient = recipients.find((r) => r.email === 'cc@example.com');
|
||||
const lastSigner = recipients.find((r) => r.email === 'signer2@example.com');
|
||||
|
||||
// CC recipients cannot have fields.
|
||||
await prisma.field.deleteMany({
|
||||
where: {
|
||||
recipientId: ccRecipient?.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Sign as the first signer.
|
||||
await page.goto(`/sign/${firstSigner?.token}`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
await signSignaturePad(page);
|
||||
|
||||
const firstSignerField = await prisma.field.findFirstOrThrow({
|
||||
where: { recipientId: firstSigner?.id },
|
||||
});
|
||||
|
||||
await page.locator(`#field-${firstSignerField.id}`).getByRole('button').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`/sign/${firstSigner?.token}/complete`);
|
||||
|
||||
// The unsigned CC recipient at order 2 must not block the last signer at order 3.
|
||||
await page.goto(`/sign/${lastSigner?.token}`);
|
||||
await expect(page).not.toHaveURL(`/sign/${lastSigner?.token}/waiting`);
|
||||
await expect(page.getByRole('heading', { name: 'Sign Document' })).toBeVisible();
|
||||
|
||||
await signSignaturePad(page);
|
||||
|
||||
const lastSignerField = await prisma.field.findFirstOrThrow({
|
||||
where: { recipientId: lastSigner?.id },
|
||||
});
|
||||
|
||||
await page.locator(`#field-${lastSignerField.id}`).getByRole('button').click();
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(`/sign/${lastSigner?.token}/complete`);
|
||||
|
||||
// The document completes without any action from the CC recipient.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const finalDocument = await prisma.envelope.findFirstOrThrow({
|
||||
where: { id: document.id },
|
||||
});
|
||||
|
||||
return finalDocument.status;
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(DocumentStatus.COMPLETED);
|
||||
});
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { seedDirectTemplate } from '@documenso/prisma/seed/templates';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, type Page, test } from '@playwright/test';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { clickEnvelopeEditorStep } from '../fixtures/envelope-editor';
|
||||
|
||||
const INVALID_DIRECT_TEMPLATE_ALERT_TITLE = 'Invalid direct link template';
|
||||
|
||||
/**
|
||||
* Place a field on the PDF canvas in the envelope editor.
|
||||
*/
|
||||
const placeFieldOnPdf = async (root: Page, fieldName: 'Signature' | 'Text', position: { x: number; y: number }) => {
|
||||
await root.getByRole('button', { name: fieldName, exact: true }).click();
|
||||
|
||||
const canvas = root.locator('.konva-container canvas').first();
|
||||
await expect(canvas).toBeVisible();
|
||||
await canvas.click({ position });
|
||||
};
|
||||
|
||||
/**
|
||||
* Seed a V2 direct template and open it in the native template editor.
|
||||
*
|
||||
* Only the native template editor is covered here: direct links only exist
|
||||
* for templates and are not part of the embedded editor surfaces.
|
||||
*/
|
||||
const openDirectTemplateEditor = async (page: Page, options: { createDirectRecipientSignatureField: boolean }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const template = await seedDirectTemplate({
|
||||
title: `E2E Direct Template Validation ${Date.now()}`,
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
internalVersion: 2,
|
||||
createDirectRecipientSignatureField: options.createDirectRecipientSignatureField,
|
||||
});
|
||||
|
||||
await apiSignin({
|
||||
page,
|
||||
email: user.email,
|
||||
redirectPath: `/t/${team.url}/templates/${template.id}/edit`,
|
||||
});
|
||||
|
||||
return { user, team, template };
|
||||
};
|
||||
|
||||
test.describe('template editor', () => {
|
||||
test('shows invalid direct template warning when a signer has no signature field', async ({ page }) => {
|
||||
await openDirectTemplateEditor(page, { createDirectRecipientSignatureField: false });
|
||||
|
||||
await expect(page.getByText(INVALID_DIRECT_TEMPLATE_ALERT_TITLE)).toBeVisible();
|
||||
await expect(page.getByText('are missing a signature field')).toBeVisible();
|
||||
});
|
||||
|
||||
test('does not show the warning when all signers have signature fields', async ({ page }) => {
|
||||
await openDirectTemplateEditor(page, { createDirectRecipientSignatureField: true });
|
||||
|
||||
// Wait for the editor to render before asserting the banner is absent.
|
||||
await expect(page.getByTestId('envelope-editor-step-upload')).toBeVisible();
|
||||
await expect(page.getByText(INVALID_DIRECT_TEMPLATE_ALERT_TITLE)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('warning disappears after placing a signature field', async ({ page }) => {
|
||||
await openDirectTemplateEditor(page, { createDirectRecipientSignatureField: false });
|
||||
|
||||
await expect(page.getByText(INVALID_DIRECT_TEMPLATE_ALERT_TITLE)).toBeVisible();
|
||||
|
||||
// Place a signature field for the direct recipient (auto-selected single recipient).
|
||||
await clickEnvelopeEditorStep(page, 'addFields');
|
||||
await expect(page.locator('.konva-container canvas').first()).toBeVisible();
|
||||
await placeFieldOnPdf(page, 'Signature', { x: 120, y: 140 });
|
||||
|
||||
// The banner clears once the field is autosaved and the envelope state updates.
|
||||
await expect(page.getByText(INVALID_DIRECT_TEMPLATE_ALERT_TITLE)).not.toBeVisible({ timeout: 15_000 });
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { nanoid } from '@documenso/lib/universal/id';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { seedBlankDocument } from '@documenso/prisma/seed/documents';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { DocumentSigningOrder, RecipientRole } from '@prisma/client';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import {
|
||||
assertRecipientRole,
|
||||
getRecipientEmailInputs,
|
||||
getRecipientRows,
|
||||
getSigningOrderInputs,
|
||||
openDocumentEnvelopeEditor,
|
||||
setRecipientEmail,
|
||||
setRecipientName,
|
||||
setRecipientRole,
|
||||
toggleSigningOrder,
|
||||
} from '../fixtures/envelope-editor';
|
||||
|
||||
const SIGNER_A = { email: 'cc-order-signer-a@example.com', name: 'Signer A' };
|
||||
const SIGNER_B = { email: 'cc-order-signer-b@example.com', name: 'Signer B' };
|
||||
const CC_RECIPIENT = { email: 'cc-order-cc@example.com', name: 'CC Recipient' };
|
||||
|
||||
const assertCcDisplayedLastWithNoOrderInput = async (root: Page) => {
|
||||
// CC recipient is displayed last despite being added/stored mid-list.
|
||||
await expect(getRecipientEmailInputs(root)).toHaveCount(3);
|
||||
await expect(getRecipientEmailInputs(root).nth(0)).toHaveValue(SIGNER_A.email);
|
||||
await expect(getRecipientEmailInputs(root).nth(1)).toHaveValue(SIGNER_B.email);
|
||||
await expect(getRecipientEmailInputs(root).nth(2)).toHaveValue(CC_RECIPIENT.email);
|
||||
|
||||
await assertRecipientRole(root, 0, 'Needs to sign');
|
||||
await assertRecipientRole(root, 1, 'Needs to sign');
|
||||
await assertRecipientRole(root, 2, 'Receives copy');
|
||||
|
||||
// Only the two signers have signing order inputs, showing 1 and 2.
|
||||
await expect(getSigningOrderInputs(root)).toHaveCount(2);
|
||||
await expect(getSigningOrderInputs(root).nth(0)).toHaveValue('1');
|
||||
await expect(getSigningOrderInputs(root).nth(1)).toHaveValue('2');
|
||||
|
||||
// The CC row itself renders no signing order input (placeholder div instead).
|
||||
const ccRow = getRecipientRows(root).nth(2);
|
||||
await expect(ccRow.locator('[data-testid="signing-order-input"]')).toHaveCount(0);
|
||||
};
|
||||
|
||||
test.describe('document editor', () => {
|
||||
test('CC recipient added mid-list is displayed last with no signing order input', async ({ page }) => {
|
||||
const surface = await openDocumentEnvelopeEditor(page);
|
||||
const { root } = surface;
|
||||
|
||||
await toggleSigningOrder(root, true);
|
||||
|
||||
// Add signer A into the initial empty row.
|
||||
await setRecipientEmail(root, 0, SIGNER_A.email);
|
||||
await setRecipientName(root, 0, SIGNER_A.name);
|
||||
|
||||
// Add the CC recipient second.
|
||||
await root.getByRole('button', { name: 'Add Signer' }).click();
|
||||
await setRecipientEmail(root, 1, CC_RECIPIENT.email);
|
||||
await setRecipientName(root, 1, CC_RECIPIENT.name);
|
||||
await setRecipientRole(root, 1, 'Receives copy');
|
||||
|
||||
// Once the row becomes CC, its signing order input disappears.
|
||||
await expect(getSigningOrderInputs(root)).toHaveCount(1);
|
||||
|
||||
// Add signer B third. The new row is inserted before the CC recipient,
|
||||
// which is kept last by the client-side sorting.
|
||||
await root.getByRole('button', { name: 'Add Signer' }).click();
|
||||
await expect(getRecipientEmailInputs(root).nth(2)).toHaveValue(CC_RECIPIENT.email);
|
||||
|
||||
await setRecipientEmail(root, 1, SIGNER_B.email);
|
||||
await setRecipientName(root, 1, SIGNER_B.name);
|
||||
|
||||
await assertCcDisplayedLastWithNoOrderInput(root);
|
||||
|
||||
// The editor autosaves with a debounce, poll the DB until all three
|
||||
// recipients have been persisted before reloading the page.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const recipients = await prisma.recipient.findMany({
|
||||
where: { envelopeId: surface.envelopeId },
|
||||
});
|
||||
|
||||
return recipients.length;
|
||||
},
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe(3);
|
||||
|
||||
// Reload the editor and assert the CC recipient is still displayed last.
|
||||
await root.reload();
|
||||
await expect(root.getByRole('heading', { name: 'Recipients' })).toBeVisible();
|
||||
|
||||
await assertCcDisplayedLastWithNoOrderInput(root);
|
||||
});
|
||||
|
||||
test('CC recipient seeded with mid-list signing order is displayed last', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const document = await seedBlankDocument(user, team.id, {
|
||||
internalVersion: 2,
|
||||
});
|
||||
|
||||
// Seed a CC recipient directly in the DB with a mid-list signing order
|
||||
// (2 of 3) BEFORE opening the editor, so the editor's autosave cannot
|
||||
// race with the seeded recipients, and assert the editor renders it last.
|
||||
await prisma.envelope.update({
|
||||
where: { id: document.id },
|
||||
data: {
|
||||
documentMeta: {
|
||||
update: { signingOrder: DocumentSigningOrder.SEQUENTIAL },
|
||||
},
|
||||
recipients: {
|
||||
createMany: {
|
||||
data: [
|
||||
{
|
||||
email: SIGNER_A.email,
|
||||
name: SIGNER_A.name,
|
||||
token: nanoid(),
|
||||
role: RecipientRole.SIGNER,
|
||||
signingOrder: 1,
|
||||
},
|
||||
{
|
||||
email: CC_RECIPIENT.email,
|
||||
name: CC_RECIPIENT.name,
|
||||
token: nanoid(),
|
||||
role: RecipientRole.CC,
|
||||
signingOrder: 2,
|
||||
},
|
||||
{
|
||||
email: SIGNER_B.email,
|
||||
name: SIGNER_B.name,
|
||||
token: nanoid(),
|
||||
role: RecipientRole.SIGNER,
|
||||
signingOrder: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await apiSignin({
|
||||
page,
|
||||
email: user.email,
|
||||
redirectPath: `/t/${team.url}/documents/${document.id}/edit?step=uploadAndRecipients`,
|
||||
});
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Recipients' })).toBeVisible();
|
||||
|
||||
await assertCcDisplayedLastWithNoOrderInput(page);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Opens the app command menu via the keyboard shortcut.
|
||||
*
|
||||
* Retries the shortcut until the menu appears since the keypress is a no-op
|
||||
* when it happens before the page has hydrated.
|
||||
*
|
||||
* @param placeholder The search input placeholder to wait for, which differs
|
||||
* between admin and non-admin users.
|
||||
*/
|
||||
export const openCommandMenu = async (page: Page, placeholder: string) => {
|
||||
await expect(async () => {
|
||||
await page.keyboard.press('Meta+K');
|
||||
await expect(page.getByPlaceholder(placeholder).first()).toBeVisible({ timeout: 1_000 });
|
||||
}).toPass({ timeout: 15_000 });
|
||||
};
|
||||
@@ -6,7 +6,6 @@ import { expect, test } from '@playwright/test';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { expectToastTextToBeVisible } from '../fixtures/generic';
|
||||
import { signSignaturePad } from '../fixtures/signature';
|
||||
|
||||
test('[PUBLIC_PROFILE]: create team profile', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
@@ -74,19 +73,8 @@ test('[PUBLIC_PROFILE]: create team profile', async ({ page }) => {
|
||||
await expect(page.locator('body')).toContainText('public-direct-template-title');
|
||||
await expect(page.locator('body')).toContainText('public-direct-template-description');
|
||||
|
||||
const directSignatureField = directTemplate.fields[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
}
|
||||
|
||||
await page.getByRole('link', { name: 'Sign' }).click();
|
||||
await page.getByRole('button', { name: 'Continue' }).click();
|
||||
|
||||
await signSignaturePad(page);
|
||||
await page.locator(`#field-${directSignatureField.id}`).getByRole('button').click();
|
||||
await expect(page.locator(`#field-${directSignatureField.id}`)).toHaveAttribute('data-inserted', 'true');
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ test.describe('Default Recipients', () => {
|
||||
await page.getByRole('button', { name: 'Add Signer' }).click();
|
||||
|
||||
// Add a regular signer using the v2 editor
|
||||
await page.getByTestId('signer-email-input').first().fill('regular-signer@documenso.com');
|
||||
await page.getByTestId('signer-email-input').last().fill('regular-signer@documenso.com');
|
||||
await page
|
||||
.getByPlaceholder(/Recipient/)
|
||||
.first()
|
||||
|
||||
@@ -197,18 +197,7 @@ test('[DIRECT_TEMPLATES]: V1 direct template link auth access', async ({ page })
|
||||
await expect(page.getByRole('heading', { name: 'General' })).toBeVisible();
|
||||
await expect(page.getByLabel('Email')).toBeDisabled();
|
||||
|
||||
const directSignatureField = directTemplateWithAuth.fields[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
}
|
||||
|
||||
await page.getByRole('button', { name: 'Continue' }).click();
|
||||
|
||||
await signSignaturePad(page);
|
||||
await page.locator(`#field-${directSignatureField.id}`).getByRole('button').click();
|
||||
await expect(page.locator(`#field-${directSignatureField.id}`)).toHaveAttribute('data-inserted', 'true');
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
@@ -246,37 +235,6 @@ test('[DIRECT_TEMPLATES]: V2 direct template link auth access', async ({ page })
|
||||
await page.goto(directTemplatePath);
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Personal direct template link' })).toBeVisible();
|
||||
|
||||
const directSignatureField = directTemplateWithAuth.fields[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
}
|
||||
|
||||
// Wait for the PDF and the Konva canvas overlay to be ready.
|
||||
await expect(page.locator('img[data-page-number]').first()).toBeVisible({ timeout: 30_000 });
|
||||
const canvas = page.locator('.konva-container canvas').first();
|
||||
await expect(canvas).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// Sign the direct template recipient's signature field via the canvas-based V2 UI.
|
||||
await signSignaturePad(page);
|
||||
|
||||
const canvasBox = await canvas.boundingBox();
|
||||
|
||||
if (!canvasBox) {
|
||||
throw new Error('Canvas bounding box not found');
|
||||
}
|
||||
|
||||
const x =
|
||||
(Number(directSignatureField.positionX) / 100) * canvasBox.width +
|
||||
((Number(directSignatureField.width) / 100) * canvasBox.width) / 2;
|
||||
const y =
|
||||
(Number(directSignatureField.positionY) / 100) * canvasBox.height +
|
||||
((Number(directSignatureField.height) / 100) * canvasBox.height) / 2;
|
||||
|
||||
await canvas.click({ position: { x, y } });
|
||||
await expect(page.getByText('0 Fields Remaining').first()).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await expect(page.getByLabel('Your Email')).not.toBeVisible();
|
||||
|
||||
@@ -308,16 +266,6 @@ test('[DIRECT_TEMPLATES]: use direct template link with 1 recipient', async ({ p
|
||||
|
||||
await expect(page.getByText('Next Recipient Name')).not.toBeVisible();
|
||||
|
||||
const directSignatureField = template.fields[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
}
|
||||
|
||||
await signSignaturePad(page);
|
||||
await page.locator(`#field-${directSignatureField.id}`).getByRole('button').click();
|
||||
await expect(page.locator(`#field-${directSignatureField.id}`)).toHaveAttribute('data-inserted', 'true');
|
||||
|
||||
await page.getByRole('button', { name: 'Complete' }).click();
|
||||
await page.getByRole('button', { name: 'Sign' }).click();
|
||||
await page.waitForURL(/\/sign/);
|
||||
@@ -351,13 +299,19 @@ test('[DIRECT_TEMPLATES]: V1 use direct template link with 2 recipients with nex
|
||||
},
|
||||
});
|
||||
|
||||
// The seeded direct template already includes a signature field for the direct recipient.
|
||||
const directSignatureField = template.fields[0];
|
||||
const directTemplateRecipient = template.recipients[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
if (!directTemplateRecipient) {
|
||||
throw new Error('Expected direct template recipient to exist');
|
||||
}
|
||||
|
||||
// All SIGNER recipients need a signature field for sendDocument to dispatch emails.
|
||||
const directSignatureField = await seedSignatureFieldForRecipient({
|
||||
envelopeId: template.id,
|
||||
recipientId: directTemplateRecipient.id,
|
||||
positionY: 10,
|
||||
});
|
||||
|
||||
const originalName = 'Signer 2';
|
||||
const originalSecondSignerEmail = seedTestEmail();
|
||||
|
||||
@@ -459,13 +413,19 @@ test('[DIRECT_TEMPLATES]: V2 use direct template link with 2 recipients with nex
|
||||
},
|
||||
});
|
||||
|
||||
// The seeded direct template already includes a signature field for the direct recipient.
|
||||
const directSignatureField = template.fields[0];
|
||||
const directTemplateRecipient = template.recipients[0];
|
||||
|
||||
if (!directSignatureField) {
|
||||
throw new Error('Expected seeded direct template signature field to exist');
|
||||
if (!directTemplateRecipient) {
|
||||
throw new Error('Expected direct template recipient to exist');
|
||||
}
|
||||
|
||||
// All SIGNER recipients need a signature field for sendDocument to dispatch emails.
|
||||
const directSignatureField = await seedSignatureFieldForRecipient({
|
||||
envelopeId: template.id,
|
||||
recipientId: directTemplateRecipient.id,
|
||||
positionY: 10,
|
||||
});
|
||||
|
||||
const originalName = 'Signer 2';
|
||||
const originalSecondSignerEmail = seedTestEmail();
|
||||
|
||||
@@ -561,48 +521,3 @@ test('[DIRECT_TEMPLATES]: V2 use direct template link with 2 recipients with nex
|
||||
expect(updatedSecondRecipient.email).toBe(newSecondSignerEmail);
|
||||
await expectSigningRequestJobForRecipient(updatedSecondRecipient.id);
|
||||
});
|
||||
|
||||
test('[DIRECT_TEMPLATES]: V1 direct template without signature fields shows invalid template page', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const template = await seedDirectTemplate({
|
||||
title: 'V1 invalid direct template',
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
createDirectRecipientSignatureField: false,
|
||||
});
|
||||
|
||||
await page.goto(formatDirectTemplatePath(template.directLink?.token || ''));
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Invalid direct link template' })).toBeVisible();
|
||||
await expect(page.getByText('This direct link template cannot be used because one or more signers')).toBeVisible();
|
||||
|
||||
// The signing flow must not render.
|
||||
await expect(page.getByRole('heading', { name: 'General' })).not.toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Continue' })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('[DIRECT_TEMPLATES]: V2 direct template without signature fields shows invalid template page', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const template = await seedDirectTemplate({
|
||||
title: 'V2 invalid direct template',
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
internalVersion: 2,
|
||||
createDirectRecipientSignatureField: false,
|
||||
});
|
||||
|
||||
await page.goto(formatDirectTemplatePath(template.directLink?.token || ''));
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Invalid direct link template' })).toBeVisible();
|
||||
await expect(page.getByText('This direct link template cannot be used because one or more signers')).toBeVisible();
|
||||
|
||||
// The signing flow (PDF canvas) must not render.
|
||||
await expect(page.locator('.konva-container canvas')).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Complete' })).not.toBeVisible();
|
||||
});
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
import { FIELD_SIGNATURE_META_DEFAULT_VALUES } from '@documenso/lib/types/field-meta';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { seedTemplate } from '@documenso/prisma/seed/templates';
|
||||
import { seedUser } from '@documenso/prisma/seed/users';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { DocumentStatus, FieldType } from '@prisma/client';
|
||||
|
||||
import { apiSignin } from '../fixtures/authentication';
|
||||
import { expectToastTextToBeVisible } from '../fixtures/generic';
|
||||
|
||||
const seedSignatureFieldForRecipient = async (options: { envelopeId: string; recipientId: number }) => {
|
||||
const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({
|
||||
where: { envelopeId: options.envelopeId },
|
||||
});
|
||||
|
||||
return await prisma.field.create({
|
||||
data: {
|
||||
envelopeId: options.envelopeId,
|
||||
envelopeItemId: envelopeItem.id,
|
||||
recipientId: options.recipientId,
|
||||
type: FieldType.SIGNATURE,
|
||||
page: 1,
|
||||
positionX: 5,
|
||||
positionY: 10,
|
||||
width: 20,
|
||||
height: 5,
|
||||
customText: '',
|
||||
inserted: false,
|
||||
fieldMeta: FIELD_SIGNATURE_META_DEFAULT_VALUES,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
test('[TEMPLATE_USE]: shows missing signature fields error when sending a template without signature fields', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
// seedTemplate creates one SIGNER recipient and no fields.
|
||||
await seedTemplate({
|
||||
title: 'Template missing signature fields',
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
await apiSignin({
|
||||
page,
|
||||
email: user.email,
|
||||
redirectPath: `/t/${team.url}/templates`,
|
||||
});
|
||||
|
||||
await page.getByRole('button', { name: 'Use Template' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Create document from template' })).toBeVisible();
|
||||
|
||||
// Enable distribution so the document is sent on creation.
|
||||
await page.locator('#distributeDocument').click();
|
||||
await page.getByRole('button', { name: 'Create and send' }).click();
|
||||
|
||||
await expectToastTextToBeVisible(page, 'Missing signature fields');
|
||||
await expectToastTextToBeVisible(
|
||||
page,
|
||||
'The document could not be sent because some signers do not have a signature field',
|
||||
);
|
||||
});
|
||||
|
||||
test('[TEMPLATE_USE]: creates and sends a document when signers have signature fields', async ({ page }) => {
|
||||
const { user, team } = await seedUser();
|
||||
|
||||
const template = await seedTemplate({
|
||||
title: 'Template with signature fields',
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
await seedSignatureFieldForRecipient({
|
||||
envelopeId: template.id,
|
||||
recipientId: template.recipients[0].id,
|
||||
});
|
||||
|
||||
await apiSignin({
|
||||
page,
|
||||
email: user.email,
|
||||
redirectPath: `/t/${team.url}/templates`,
|
||||
});
|
||||
|
||||
await page.getByRole('button', { name: 'Use Template' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Create document from template' })).toBeVisible();
|
||||
|
||||
await page.locator('#distributeDocument').click();
|
||||
await page.getByRole('button', { name: 'Create and send' }).click();
|
||||
|
||||
await page.waitForURL(new RegExp(`/t/${team.url}/documents/envelope_.*`));
|
||||
|
||||
const envelopeId = page.url().split('/').pop()?.split('?')[0];
|
||||
|
||||
const envelope = await prisma.envelope.findFirstOrThrow({
|
||||
where: { id: envelopeId },
|
||||
});
|
||||
|
||||
expect(envelope.status).toBe(DocumentStatus.PENDING);
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import { INTERNAL_CLAIM_ID } from '@documenso/lib/types/subscription';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { OrganisationType, type Prisma, SubscriptionStatus } from '@prisma/client';
|
||||
import { match } from 'ts-pattern';
|
||||
import { reconcileSeatBasedPlans } from './update-subscription-item-quantity';
|
||||
|
||||
const LIVE_SUBSCRIPTION_STATUSES: Stripe.Subscription.Status[] = ['active', 'trialing', 'past_due'];
|
||||
|
||||
@@ -230,19 +229,6 @@ const handleLiveSubscription = async ({
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Detect a billing-period roll by comparing the persisted period end with
|
||||
// the freshly-fetched one — the convergent equivalent of the old
|
||||
// `previous_attributes.current_period_start` signal. On renewal, reconcile
|
||||
// the seat quantity and claim down to the actual member count. The reconcile
|
||||
// itself no-ops for non-seat/unlimited plans and inactive subscriptions.
|
||||
const previousPeriodEnd = organisation.subscription?.periodEnd ?? null;
|
||||
|
||||
const hasPeriodAdvanced = previousPeriodEnd !== null && periodEnd.getTime() > previousPeriodEnd.getTime();
|
||||
|
||||
if (hasPeriodAdvanced && !bypassClaimUpdate) {
|
||||
await reconcileSeatBasedPlans(organisation.id);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,6 @@ import { stripe } from '@documenso/lib/server-only/stripe';
|
||||
import { appLog } from '@documenso/lib/utils/debugger';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import type { OrganisationClaim, Subscription } from '@prisma/client';
|
||||
import { SubscriptionStatus } from '@prisma/client';
|
||||
import type Stripe from 'stripe';
|
||||
|
||||
import { isPriceSeatsBased } from './is-price-seats-based';
|
||||
@@ -12,14 +11,12 @@ export type UpdateSubscriptionItemQuantityOptions = {
|
||||
subscriptionId: string;
|
||||
quantity: number;
|
||||
priceId: string;
|
||||
prorationBehaviour: 'always_invoice' | 'none';
|
||||
};
|
||||
|
||||
export const updateSubscriptionItemQuantity = async ({
|
||||
subscriptionId,
|
||||
quantity,
|
||||
priceId,
|
||||
prorationBehaviour,
|
||||
}: UpdateSubscriptionItemQuantityOptions) => {
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
|
||||
@@ -29,6 +26,7 @@ export const updateSubscriptionItemQuantity = async ({
|
||||
throw new Error('Subscription does not contain required item');
|
||||
}
|
||||
|
||||
const hasYearlyItem = items.find((item) => item.price.recurring?.interval === 'year');
|
||||
const oldQuantity = items[0].quantity;
|
||||
|
||||
if (oldQuantity === quantity) {
|
||||
@@ -40,12 +38,13 @@ export const updateSubscriptionItemQuantity = async ({
|
||||
id: item.id,
|
||||
quantity,
|
||||
})),
|
||||
proration_behavior: prorationBehaviour,
|
||||
// Need to "off_session" updates since adding 3DS will have payments
|
||||
// not pass through for these immediate invoices.
|
||||
off_session: true,
|
||||
};
|
||||
|
||||
// Only invoice immediately when changing the quantity of yearly item.
|
||||
if (hasYearlyItem) {
|
||||
subscriptionUpdatePayload.proration_behavior = 'always_invoice';
|
||||
}
|
||||
|
||||
await stripe.subscriptions.update(subscriptionId, subscriptionUpdatePayload);
|
||||
};
|
||||
|
||||
@@ -56,19 +55,15 @@ export const updateSubscriptionItemQuantity = async ({
|
||||
* via Stripe rather than enforcing a hard cap. A `memberCount` of `0` on the
|
||||
* organisation claim represents unlimited seats.
|
||||
*
|
||||
* Organisations without a subscription (e.g. after being downgraded to the
|
||||
* free plan) can pass `null`, in which case the claim cap is enforced
|
||||
* directly without the seats-based exemption.
|
||||
*
|
||||
* Should only be called from grow paths (invite/add). Reducing operations
|
||||
* must never be gated by this check.
|
||||
*
|
||||
* @param subscription - The organisation's Stripe subscription, if any.
|
||||
* @param subscription - The organisation's Stripe subscription.
|
||||
* @param organisationClaim - The organisation claim.
|
||||
* @param quantity - The proposed total member count.
|
||||
* @param quantity - The proposed total member + pending invite count.
|
||||
*/
|
||||
export const assertMemberCountWithinCap = async (
|
||||
subscription: Subscription | null,
|
||||
subscription: Subscription,
|
||||
organisationClaim: OrganisationClaim,
|
||||
quantity: number,
|
||||
) => {
|
||||
@@ -80,12 +75,10 @@ export const assertMemberCountWithinCap = async (
|
||||
}
|
||||
|
||||
// Seats-based plans don't have a hard cap; Stripe meters the usage.
|
||||
if (subscription) {
|
||||
const isSeatsBased = await isPriceSeatsBased(subscription.priceId);
|
||||
const isSeatsBased = await isPriceSeatsBased(subscription.priceId);
|
||||
|
||||
if (isSeatsBased) {
|
||||
return;
|
||||
}
|
||||
if (isSeatsBased) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (quantity > maximumMemberCount) {
|
||||
@@ -96,134 +89,48 @@ export const assertMemberCountWithinCap = async (
|
||||
};
|
||||
|
||||
/**
|
||||
* Syncs the Stripe subscription quantity with the organisation's member count.
|
||||
* Syncs the organisation's member count with the Stripe subscription quantity.
|
||||
*
|
||||
* This is a Stripe <-> Database sync operation.
|
||||
*
|
||||
* Note: `organisationClaim.memberCount` is the paid seat high-water mark for the
|
||||
* current billing period — the highest count we've already billed for.
|
||||
* No-ops for plans that are not seats-based, and for organisations with
|
||||
* unlimited seats (`organisationClaim.memberCount === 0`). Safe to call from
|
||||
* both grow and shrink paths.
|
||||
*
|
||||
* @param subscription - The subscription to sync the member count with.
|
||||
* @param organisationClaim - The organisation claim.
|
||||
* @param quantity - The new total member count to sync.
|
||||
* @param mode - The member-count change that triggered the sync.
|
||||
* @param quantity - The new total member + pending invite count to sync.
|
||||
*/
|
||||
export const syncMemberCountWithStripeSeatPlan = async (
|
||||
subscription: Subscription,
|
||||
organisationClaim: OrganisationClaim,
|
||||
quantity: number,
|
||||
mode: 'grow' | 'shrink',
|
||||
) => {
|
||||
// Unlimited seats — nothing to meter.
|
||||
// Infinite seats means no sync needed.
|
||||
if (organisationClaim.memberCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isSeatsBased = await isPriceSeatsBased(subscription.priceId);
|
||||
|
||||
// Only seat-based plans support seat syncing.
|
||||
if (!isSeatsBased) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Whether to immediately invoice for new seats if the quantity is greater than
|
||||
// the high-water mark.
|
||||
const billsForNewSeats = mode === 'grow' && quantity > organisationClaim.memberCount;
|
||||
|
||||
appLog('BILLING', `Syncing seat based plan (${mode}, quantity ${quantity})`);
|
||||
appLog('BILLING', 'Updating seat based plan');
|
||||
|
||||
await updateSubscriptionItemQuantity({
|
||||
priceId: subscription.priceId,
|
||||
subscriptionId: subscription.planId,
|
||||
quantity,
|
||||
prorationBehaviour: billsForNewSeats ? 'always_invoice' : 'none',
|
||||
});
|
||||
|
||||
// Advance the high-water mark when billing for new seats; it is reset to the
|
||||
// actual member count when the billing period rolls over. Re-adds and shrinks
|
||||
// deliberately leave it untouched so a seat already paid for this period is
|
||||
// never re-charged.
|
||||
if (billsForNewSeats) {
|
||||
await prisma.organisationClaim.update({
|
||||
where: {
|
||||
id: organisationClaim.id,
|
||||
},
|
||||
data: {
|
||||
memberCount: quantity,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reconciles the organisation claim seat counter, and the stripe quantity with the
|
||||
* actual member count.
|
||||
*
|
||||
* Uses the member count as the authoritative source of truth. Meaning:
|
||||
* - Update the organisation claim with the member count
|
||||
* - Update the Stripe subscription quantity to the member count
|
||||
*
|
||||
* This should only be called when the billing period rolls over.
|
||||
*/
|
||||
export const reconcileSeatBasedPlans = async (organisationId: string) => {
|
||||
const organisation = await prisma.organisation.findFirst({
|
||||
where: {
|
||||
id: organisationId,
|
||||
},
|
||||
include: {
|
||||
organisationClaim: true,
|
||||
subscription: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!organisation || !organisation.subscription) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { subscription, organisationClaim } = organisation;
|
||||
|
||||
// Stripe rejects quantity updates on canceled subscriptions. PAST_DUE is
|
||||
// still live and a no-proration sync is safe, so it's allowed through.
|
||||
if (subscription.status === SubscriptionStatus.INACTIVE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Unlimited seats — nothing to meter.
|
||||
if (organisationClaim.memberCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isSeatsBased = await isPriceSeatsBased(subscription.priceId);
|
||||
|
||||
// Only seat-based plans support seat syncing.
|
||||
if (!isSeatsBased) {
|
||||
return;
|
||||
}
|
||||
|
||||
const memberCount = await prisma.organisationMember.count({
|
||||
where: {
|
||||
organisationId,
|
||||
},
|
||||
});
|
||||
|
||||
// An organisation always retains its owner; never write the unlimited sentinel.
|
||||
if (memberCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await updateSubscriptionItemQuantity({
|
||||
priceId: subscription.priceId,
|
||||
subscriptionId: subscription.planId,
|
||||
quantity: memberCount,
|
||||
prorationBehaviour: 'none',
|
||||
});
|
||||
|
||||
// This should be automatically updated after the Stripe webhook is fired
|
||||
// but we just manually adjust it here as well to avoid any race conditions.
|
||||
await prisma.organisationClaim.update({
|
||||
where: {
|
||||
id: organisationClaim.id,
|
||||
},
|
||||
data: {
|
||||
memberCount,
|
||||
memberCount: quantity,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
|
||||
import type { Stripe } from '@documenso/lib/server-only/stripe';
|
||||
import { stripe } from '@documenso/lib/server-only/stripe';
|
||||
import { env } from '@documenso/lib/utils/env';
|
||||
|
||||
import { syncStripeCustomerSubscription } from '../sync-stripe-customer-subscription';
|
||||
|
||||
type StripeWebhookResponse = {
|
||||
|
||||
@@ -7,10 +7,9 @@ import { DocumentSigningOrder, RecipientRole } from '@prisma/client';
|
||||
import { useId } from 'react';
|
||||
import type { UseFormReturn } from 'react-hook-form';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { prop, sortBy } from 'remeda';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { isCcRecipient, normalizeRecipientSigningOrders, sortRecipientsForSigningOrder } from '../../utils/recipients';
|
||||
|
||||
const LocalRecipientSchema = z.object({
|
||||
formId: z.string().min(1),
|
||||
id: z.number().optional(),
|
||||
@@ -95,13 +94,13 @@ export const useEditorRecipients = ({ envelope }: EditorRecipientsProps): UseEdi
|
||||
name: recipient.name,
|
||||
email: recipient.email,
|
||||
role: recipient.role,
|
||||
signingOrder: isCcRecipient(recipient) ? undefined : (recipient.signingOrder ?? index + 1),
|
||||
signingOrder: recipient.signingOrder ?? index + 1,
|
||||
actionAuth: ZRecipientAuthOptionsSchema.parse(recipient.authOptions)?.actionAuth ?? undefined,
|
||||
}));
|
||||
|
||||
const signers: TLocalRecipient[] =
|
||||
formRecipients.length > 0
|
||||
? normalizeRecipientSigningOrders(sortRecipientsForSigningOrder(formRecipients))
|
||||
? sortBy(formRecipients, [prop('signingOrder'), 'asc'], [prop('id'), 'asc'])
|
||||
: [
|
||||
{
|
||||
formId: initialId,
|
||||
|
||||
@@ -36,13 +36,6 @@ export enum AppErrorCode {
|
||||
*/
|
||||
ENVELOPE_TSP_LOCKED = 'ENVELOPE_TSP_LOCKED',
|
||||
|
||||
/**
|
||||
* A signer recipient does not have a signature field assigned. Thrown when
|
||||
* distributing an envelope or using a direct template where at least one
|
||||
* signer has no signature field.
|
||||
*/
|
||||
MISSING_SIGNATURE_FIELD = 'MISSING_SIGNATURE_FIELD',
|
||||
|
||||
/**
|
||||
* CSC (Cloud Signature Consortium) error codes. See the CSC QES V1 spec
|
||||
* for the recovery taxonomy.
|
||||
@@ -91,7 +84,6 @@ export const genericErrorCodeToTrpcErrorCodeMap: Record<string, { code: string;
|
||||
[AppErrorCode.ENVELOPE_CANCELLED]: { code: 'BAD_REQUEST', status: 400 },
|
||||
[AppErrorCode.ENVELOPE_LEGACY]: { code: 'BAD_REQUEST', status: 400 },
|
||||
[AppErrorCode.ENVELOPE_TSP_LOCKED]: { code: 'BAD_REQUEST', status: 400 },
|
||||
[AppErrorCode.MISSING_SIGNATURE_FIELD]: { code: 'BAD_REQUEST', status: 400 },
|
||||
[AppErrorCode.CSC_INSTANCE_MODE_MISMATCH]: { code: 'BAD_REQUEST', status: 400 },
|
||||
[AppErrorCode.CSC_UNLICENSED]: { code: 'FORBIDDEN', status: 403 },
|
||||
[AppErrorCode.CSC_PROVIDER_INFO_FAILED]: { code: 'INTERNAL_SERVER_ERROR', status: 500 },
|
||||
@@ -299,7 +291,6 @@ export class AppError extends Error {
|
||||
AppErrorCode.ENVELOPE_CANCELLED,
|
||||
AppErrorCode.ENVELOPE_LEGACY,
|
||||
AppErrorCode.ENVELOPE_TSP_LOCKED,
|
||||
AppErrorCode.MISSING_SIGNATURE_FIELD,
|
||||
AppErrorCode.CSC_INSTANCE_MODE_MISMATCH,
|
||||
AppErrorCode.CSC_CREDENTIAL_LIST_EMPTY,
|
||||
AppErrorCode.CSC_CERT_INVALID,
|
||||
|
||||
@@ -17,7 +17,6 @@ import { SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION } from './definitions/emai
|
||||
import { SEND_SIGNING_EMAIL_JOB_DEFINITION } from './definitions/emails/send-signing-email';
|
||||
import { SEND_TEAM_DELETED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-deleted-email';
|
||||
import { ADMIN_DELETE_ORGANISATION_JOB_DEFINITION } from './definitions/internal/admin-delete-organisation';
|
||||
import { ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION } from './definitions/internal/alert-organisation-seat-drift';
|
||||
import { BACKPORT_SUBSCRIPTION_CLAIM_JOB_DEFINITION } from './definitions/internal/backport-subscription-claims';
|
||||
import { BULK_SEND_TEMPLATE_JOB_DEFINITION } from './definitions/internal/bulk-send-template';
|
||||
import { CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION } from './definitions/internal/cancel-organisation-subscription';
|
||||
@@ -30,7 +29,6 @@ import { SEAL_DOCUMENT_JOB_DEFINITION } from './definitions/internal/seal-docume
|
||||
import { SEAL_DOCUMENT_SWEEP_JOB_DEFINITION } from './definitions/internal/seal-document-sweep';
|
||||
import { SEND_SIGNING_REMINDERS_SWEEP_JOB_DEFINITION } from './definitions/internal/send-signing-reminders-sweep';
|
||||
import { SYNC_EMAIL_DOMAINS_JOB_DEFINITION } from './definitions/internal/sync-email-domains';
|
||||
import { SYNC_ORGANISATION_SEATS_JOB_DEFINITION } from './definitions/internal/sync-organisation-seats';
|
||||
|
||||
/**
|
||||
* The `as const` assertion is load bearing as it provides the correct level of type inference for
|
||||
@@ -66,9 +64,7 @@ export const jobsClient = new JobClient([
|
||||
CLEANUP_RATE_LIMITS_JOB_DEFINITION,
|
||||
SYNC_EMAIL_DOMAINS_JOB_DEFINITION,
|
||||
ADMIN_DELETE_ORGANISATION_JOB_DEFINITION,
|
||||
ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION,
|
||||
CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION,
|
||||
SYNC_ORGANISATION_SEATS_JOB_DEFINITION,
|
||||
] as const);
|
||||
|
||||
export const jobs = jobsClient;
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { mailer } from '@documenso/email/mailer';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { IS_BILLING_ENABLED, SUPPORT_EMAIL } from '../../../constants/app';
|
||||
import { DOCUMENSO_INTERNAL_EMAIL } from '../../../constants/email';
|
||||
import type { JobRunIO } from '../../client/_internal/job';
|
||||
import type { TAlertOrganisationSeatDriftJobDefinition } from './alert-organisation-seat-drift';
|
||||
|
||||
/**
|
||||
* Daily check for organisations whose member count exceeds their paid seat
|
||||
* count (`organisationClaim.memberCount`, where `0` means unlimited).
|
||||
*/
|
||||
export const run = async ({ io }: { payload: TAlertOrganisationSeatDriftJobDefinition; io: JobRunIO }) => {
|
||||
if (!IS_BILLING_ENABLED()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const organisations = await prisma.organisation.findMany({
|
||||
where: {
|
||||
// Exclude unlimited-seat plans (memberCount === 0).
|
||||
organisationClaim: {
|
||||
memberCount: {
|
||||
not: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
organisationClaim: {
|
||||
select: {
|
||||
memberCount: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const driftedOrganisations = organisations.filter(
|
||||
(organisation) =>
|
||||
organisation.organisationClaim !== null &&
|
||||
organisation._count.members > organisation.organisationClaim.memberCount,
|
||||
);
|
||||
|
||||
if (driftedOrganisations.length === 0) {
|
||||
io.logger.info('No organisations exceed their paid seat count');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await mailer.sendMail({
|
||||
to: SUPPORT_EMAIL,
|
||||
from: DOCUMENSO_INTERNAL_EMAIL,
|
||||
subject: `[Billing] ${driftedOrganisations.length} organisation(s) exceed their paid seat count`,
|
||||
text: [
|
||||
`${driftedOrganisations.length} organisation(s) have more members than their paid seat count:`,
|
||||
'',
|
||||
...driftedOrganisations.map(
|
||||
(organisation) =>
|
||||
`- ${organisation.name} (${organisation.id}): ${organisation._count.members} members vs ${organisation.organisationClaim?.memberCount ?? 0} paid seats`,
|
||||
),
|
||||
].join('\n'),
|
||||
});
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { JobDefinition } from '../../client/_internal/job';
|
||||
|
||||
const ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_ID = 'internal.alert-organisation-seat-drift';
|
||||
|
||||
const ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_SCHEMA = z.object({});
|
||||
|
||||
export type TAlertOrganisationSeatDriftJobDefinition = z.infer<
|
||||
typeof ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_SCHEMA
|
||||
>;
|
||||
|
||||
export const ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION = {
|
||||
id: ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_ID,
|
||||
name: 'Alert Organisation Seat Drift',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
name: ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_ID,
|
||||
schema: ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_SCHEMA,
|
||||
cron: '0 0 * * *', // Once a day at midnight.
|
||||
},
|
||||
handler: async ({ payload, io }) => {
|
||||
const handler = await import('./alert-organisation-seat-drift.handler');
|
||||
|
||||
await handler.run({ payload, io });
|
||||
},
|
||||
} as const satisfies JobDefinition<
|
||||
typeof ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION_ID,
|
||||
TAlertOrganisationSeatDriftJobDefinition
|
||||
>;
|
||||
@@ -1,54 +0,0 @@
|
||||
import { syncMemberCountWithStripeSeatPlan } from '@documenso/ee/server-only/stripe/update-subscription-item-quantity';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { SubscriptionStatus } from '@prisma/client';
|
||||
import { IS_BILLING_ENABLED } from '../../../constants/app';
|
||||
import type { JobRunIO } from '../../client/_internal/job';
|
||||
import type { TSyncOrganisationSeatsJobDefinition } from './sync-organisation-seats';
|
||||
|
||||
export const run = async ({ payload }: { payload: TSyncOrganisationSeatsJobDefinition; io: JobRunIO }) => {
|
||||
const { organisationId } = payload;
|
||||
|
||||
if (!IS_BILLING_ENABLED()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const organisation = await prisma.organisation.findUnique({
|
||||
where: {
|
||||
id: organisationId,
|
||||
},
|
||||
include: {
|
||||
subscription: true,
|
||||
organisationClaim: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!organisation || !organisation.subscription) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip canceled/terminal subscriptions — Stripe rejects quantity updates on a
|
||||
// canceled subscription. PAST_DUE is still live and a no-proration shrink is
|
||||
// safe, so it's allowed through.
|
||||
if (organisation.subscription.status === SubscriptionStatus.INACTIVE) {
|
||||
return;
|
||||
}
|
||||
|
||||
const memberCount = await prisma.organisationMember.count({
|
||||
where: {
|
||||
organisationId,
|
||||
},
|
||||
});
|
||||
|
||||
// An organisation always retains its owner; guarding zero avoids writing the
|
||||
// unlimited sentinel to the claim.
|
||||
if (memberCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await syncMemberCountWithStripeSeatPlan(
|
||||
organisation.subscription,
|
||||
organisation.organisationClaim,
|
||||
memberCount,
|
||||
'shrink',
|
||||
);
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { JobDefinition } from '../../client/_internal/job';
|
||||
|
||||
const SYNC_ORGANISATION_SEATS_JOB_DEFINITION_ID = 'internal.sync-organisation-seats';
|
||||
|
||||
const SYNC_ORGANISATION_SEATS_JOB_DEFINITION_SCHEMA = z.object({
|
||||
organisationId: z.string(),
|
||||
});
|
||||
|
||||
export type TSyncOrganisationSeatsJobDefinition = z.infer<typeof SYNC_ORGANISATION_SEATS_JOB_DEFINITION_SCHEMA>;
|
||||
|
||||
export const SYNC_ORGANISATION_SEATS_JOB_DEFINITION = {
|
||||
id: SYNC_ORGANISATION_SEATS_JOB_DEFINITION_ID,
|
||||
name: 'Sync Organisation Seats',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
name: SYNC_ORGANISATION_SEATS_JOB_DEFINITION_ID,
|
||||
schema: SYNC_ORGANISATION_SEATS_JOB_DEFINITION_SCHEMA,
|
||||
},
|
||||
handler: async ({ payload, io }) => {
|
||||
const handler = await import('./sync-organisation-seats.handler');
|
||||
|
||||
await handler.run({ payload, io });
|
||||
},
|
||||
} as const satisfies JobDefinition<
|
||||
typeof SYNC_ORGANISATION_SEATS_JOB_DEFINITION_ID,
|
||||
TSyncOrganisationSeatsJobDefinition
|
||||
>;
|
||||
@@ -1,372 +0,0 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { EnvelopeType } from '@prisma/client';
|
||||
|
||||
export const ADMIN_SEARCH_RESULTS_PER_TYPE = 5;
|
||||
|
||||
const MAX_POSTGRES_INT = 2147483647;
|
||||
|
||||
const GROUP_ORDER = ['document', 'user', 'organisation', 'team', 'recipient', 'subscription'] as const;
|
||||
|
||||
export type AdminGlobalSearchResultType = (typeof GROUP_ORDER)[number];
|
||||
|
||||
export type AdminGlobalSearchResult = {
|
||||
label: string;
|
||||
sublabel?: string;
|
||||
path: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type AdminGlobalSearchGroup = {
|
||||
type: AdminGlobalSearchResultType;
|
||||
results: AdminGlobalSearchResult[];
|
||||
};
|
||||
|
||||
export type AdminGlobalSearchOptions = {
|
||||
query: string;
|
||||
};
|
||||
|
||||
type PartialResults = Partial<Record<AdminGlobalSearchResultType, AdminGlobalSearchResult[]>>;
|
||||
|
||||
export const adminGlobalSearch = async ({ query }: AdminGlobalSearchOptions): Promise<AdminGlobalSearchGroup[]> => {
|
||||
const trimmedQuery = query.trim();
|
||||
|
||||
if (trimmedQuery.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const resultsByType = await resolveSearch(trimmedQuery);
|
||||
|
||||
return GROUP_ORDER.map((type) => ({
|
||||
type,
|
||||
results: (resultsByType[type] ?? []).map((result) => ({
|
||||
...result,
|
||||
// Append the raw query so cmdk's client-side filter never hides
|
||||
// server-verified results.
|
||||
value: `${result.value} ${trimmedQuery}`,
|
||||
})),
|
||||
})).filter((group) => group.results.length > 0);
|
||||
};
|
||||
|
||||
const resolveSearch = async (query: string): Promise<PartialResults> => {
|
||||
// Recognized ID prefixes resolve to a single exact lookup.
|
||||
if (query.startsWith('envelope_')) {
|
||||
return { document: await findDocumentsByExactId({ id: query }) };
|
||||
}
|
||||
|
||||
if (query.startsWith('document_')) {
|
||||
return { document: await findDocumentsByExactId({ secondaryId: query }) };
|
||||
}
|
||||
|
||||
if (query.startsWith('org_')) {
|
||||
return { organisation: await findOrganisationsByIdOrUrl(query) };
|
||||
}
|
||||
|
||||
// Bare numbers are treated as verified ID lookups only. Oversized numbers
|
||||
// fall through to text search.
|
||||
const numericId = Number(query);
|
||||
|
||||
if (/^\d+$/.test(query) && numericId <= MAX_POSTGRES_INT) {
|
||||
const [document, user, team, recipient, subscription] = await Promise.all([
|
||||
findDocumentsByExactId({ secondaryId: `document_${numericId}` }),
|
||||
findUsersById(numericId),
|
||||
findTeamsById(numericId),
|
||||
findRecipientsById(numericId),
|
||||
findSubscriptionsById(numericId),
|
||||
]);
|
||||
|
||||
return { document, user, team, recipient, subscription };
|
||||
}
|
||||
|
||||
// Free text searches all resource types in parallel.
|
||||
const [document, user, organisation, team, recipient, subscription] = await Promise.all([
|
||||
findDocumentsByText(query),
|
||||
findUsersByText(query),
|
||||
findOrganisationsByText(query),
|
||||
findTeamsByText(query),
|
||||
findRecipientsByText(query),
|
||||
findSubscriptionsByText(query),
|
||||
]);
|
||||
|
||||
return {
|
||||
document,
|
||||
user,
|
||||
organisation,
|
||||
team,
|
||||
recipient,
|
||||
subscription,
|
||||
};
|
||||
};
|
||||
|
||||
const joinSublabel = (parts: Array<string | null | undefined>) =>
|
||||
parts.filter((part) => part && part.length > 0).join(' · ') || undefined;
|
||||
|
||||
// ─── Documents ────────────────────────────────────────────────────────────────
|
||||
|
||||
const documentSelect = {
|
||||
id: true,
|
||||
title: true,
|
||||
secondaryId: true,
|
||||
user: { select: { email: true } },
|
||||
} as const;
|
||||
|
||||
type DocumentRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
secondaryId: string;
|
||||
user: { email: string };
|
||||
};
|
||||
|
||||
const mapDocument = (envelope: DocumentRow): AdminGlobalSearchResult => ({
|
||||
label: envelope.title,
|
||||
sublabel: joinSublabel([envelope.secondaryId, envelope.user.email]),
|
||||
path: `/admin/documents/${envelope.id}`,
|
||||
value: `document ${envelope.id} ${envelope.secondaryId} ${envelope.title} ${envelope.user.email}`,
|
||||
});
|
||||
|
||||
const findDocumentsByExactId = async (where: { id: string } | { secondaryId: string }) => {
|
||||
const envelope = await prisma.envelope.findFirst({
|
||||
where: { ...where, type: EnvelopeType.DOCUMENT },
|
||||
select: documentSelect,
|
||||
});
|
||||
|
||||
return envelope ? [mapDocument(envelope)] : [];
|
||||
};
|
||||
|
||||
const findDocumentsByText = async (query: string) => {
|
||||
const envelopes = await prisma.envelope.findMany({
|
||||
where: {
|
||||
type: EnvelopeType.DOCUMENT,
|
||||
title: { contains: query, mode: 'insensitive' },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: documentSelect,
|
||||
});
|
||||
|
||||
return envelopes.map(mapDocument);
|
||||
};
|
||||
|
||||
// ─── Users ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const userSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
} as const;
|
||||
|
||||
type UserRow = { id: number; name: string | null; email: string };
|
||||
|
||||
const mapUser = (user: UserRow): AdminGlobalSearchResult => ({
|
||||
label: user.name || user.email,
|
||||
sublabel: joinSublabel([`#${user.id}`, user.email]),
|
||||
path: `/admin/users/${user.id}`,
|
||||
value: `user ${user.id} ${user.name ?? ''} ${user.email}`,
|
||||
});
|
||||
|
||||
const findUsersById = async (id: number) => {
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { id },
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return user ? [mapUser(user)] : [];
|
||||
};
|
||||
|
||||
const findUsersByText = async (query: string) => {
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
OR: [{ name: { contains: query, mode: 'insensitive' } }, { email: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: userSelect,
|
||||
});
|
||||
|
||||
return users.map(mapUser);
|
||||
};
|
||||
|
||||
// ─── Organisations ────────────────────────────────────────────────────────────
|
||||
|
||||
const organisationSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
owner: { select: { email: true } },
|
||||
} as const;
|
||||
|
||||
type OrganisationRow = { id: string; name: string; owner: { email: string } };
|
||||
|
||||
const mapOrganisation = (organisation: OrganisationRow): AdminGlobalSearchResult => ({
|
||||
label: organisation.name,
|
||||
sublabel: joinSublabel([organisation.id, organisation.owner.email]),
|
||||
path: `/admin/organisations/${organisation.id}`,
|
||||
value: `organisation ${organisation.id} ${organisation.name} ${organisation.owner.email}`,
|
||||
});
|
||||
|
||||
const findOrganisationsByIdOrUrl = async (query: string) => {
|
||||
const organisations = await prisma.organisation.findMany({
|
||||
where: {
|
||||
OR: [{ id: query }, { url: query }],
|
||||
},
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: organisationSelect,
|
||||
});
|
||||
|
||||
return organisations.map(mapOrganisation);
|
||||
};
|
||||
|
||||
const findOrganisationsByText = async (query: string) => {
|
||||
const organisations = await prisma.organisation.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ name: { contains: query, mode: 'insensitive' } },
|
||||
{ url: { contains: query, mode: 'insensitive' } },
|
||||
{ customerId: { contains: query, mode: 'insensitive' } },
|
||||
{ owner: { email: { contains: query, mode: 'insensitive' } } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: organisationSelect,
|
||||
});
|
||||
|
||||
return organisations.map(mapOrganisation);
|
||||
};
|
||||
|
||||
// ─── Teams ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const teamSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
url: true,
|
||||
organisation: { select: { name: true } },
|
||||
} as const;
|
||||
|
||||
type TeamRow = { id: number; name: string; url: string; organisation: { name: string } };
|
||||
|
||||
const mapTeam = (team: TeamRow): AdminGlobalSearchResult => ({
|
||||
label: team.name,
|
||||
sublabel: joinSublabel([`#${team.id}`, `/${team.url}`, team.organisation.name]),
|
||||
path: `/admin/teams/${team.id}`,
|
||||
value: `team ${team.id} ${team.name} ${team.url} ${team.organisation.name}`,
|
||||
});
|
||||
|
||||
const findTeamsById = async (id: number) => {
|
||||
const team = await prisma.team.findFirst({
|
||||
where: { id },
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
return team ? [mapTeam(team)] : [];
|
||||
};
|
||||
|
||||
const findTeamsByText = async (query: string) => {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
OR: [{ name: { contains: query, mode: 'insensitive' } }, { url: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
return teams.map(mapTeam);
|
||||
};
|
||||
|
||||
// ─── Recipients ───────────────────────────────────────────────────────────────
|
||||
|
||||
const recipientSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
envelope: { select: { id: true, title: true } },
|
||||
} as const;
|
||||
|
||||
type RecipientRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
envelope: { id: string; title: string };
|
||||
};
|
||||
|
||||
const mapRecipient = (recipient: RecipientRow): AdminGlobalSearchResult => ({
|
||||
label: recipient.email,
|
||||
sublabel: joinSublabel([`#${recipient.id}`, recipient.name, recipient.envelope.title]),
|
||||
path: `/admin/documents/${recipient.envelope.id}`,
|
||||
value: `recipient ${recipient.id} ${recipient.name} ${recipient.email} ${recipient.envelope.title}`,
|
||||
});
|
||||
|
||||
const findRecipientsById = async (id: number) => {
|
||||
const recipient = await prisma.recipient.findFirst({
|
||||
where: {
|
||||
id,
|
||||
envelope: { type: EnvelopeType.DOCUMENT },
|
||||
},
|
||||
select: recipientSelect,
|
||||
});
|
||||
|
||||
return recipient ? [mapRecipient(recipient)] : [];
|
||||
};
|
||||
|
||||
const findRecipientsByText = async (query: string) => {
|
||||
const recipients = await prisma.recipient.findMany({
|
||||
where: {
|
||||
envelope: { type: EnvelopeType.DOCUMENT },
|
||||
OR: [{ email: { contains: query, mode: 'insensitive' } }, { name: { contains: query, mode: 'insensitive' } }],
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: recipientSelect,
|
||||
});
|
||||
|
||||
return recipients.map(mapRecipient);
|
||||
};
|
||||
|
||||
// ─── Subscriptions ────────────────────────────────────────────────────────────
|
||||
|
||||
const subscriptionSelect = {
|
||||
id: true,
|
||||
status: true,
|
||||
planId: true,
|
||||
customerId: true,
|
||||
organisationId: true,
|
||||
} as const;
|
||||
|
||||
type SubscriptionRow = {
|
||||
id: number;
|
||||
status: string;
|
||||
planId: string;
|
||||
customerId: string;
|
||||
organisationId: string;
|
||||
};
|
||||
|
||||
const mapSubscription = (subscription: SubscriptionRow): AdminGlobalSearchResult => ({
|
||||
label: `Subscription #${subscription.id}`,
|
||||
sublabel: joinSublabel([subscription.status, subscription.planId]),
|
||||
path: `/admin/organisations/${subscription.organisationId}`,
|
||||
value: `subscription ${subscription.id} ${subscription.planId} ${subscription.customerId}`,
|
||||
});
|
||||
|
||||
const findSubscriptionsById = async (id: number) => {
|
||||
const subscription = await prisma.subscription.findFirst({
|
||||
where: { id },
|
||||
select: subscriptionSelect,
|
||||
});
|
||||
|
||||
return subscription ? [mapSubscription(subscription)] : [];
|
||||
};
|
||||
|
||||
const findSubscriptionsByText = async (query: string) => {
|
||||
const subscriptions = await prisma.subscription.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ planId: { contains: query, mode: 'insensitive' } },
|
||||
{ customerId: { contains: query, mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: ADMIN_SEARCH_RESULTS_PER_TYPE,
|
||||
select: subscriptionSelect,
|
||||
});
|
||||
|
||||
return subscriptions.map(mapSubscription);
|
||||
};
|
||||
@@ -194,7 +194,7 @@ export const sendDocument = async ({ id, userId, teamId, sendEmail, requestMetad
|
||||
.map((r) => (r.name ? `${r.name} (${r.email}, id: ${r.id})` : `${r.email} (id: ${r.id})`))
|
||||
.join(', ');
|
||||
|
||||
throw new AppError(AppErrorCode.MISSING_SIGNATURE_FIELD, {
|
||||
throw new AppError(AppErrorCode.INVALID_REQUEST, {
|
||||
message: `The following recipients are missing required fields: ${missingRecipientDescriptions}. Signers must have at least one signature field.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,7 +57,10 @@ export const UNSAFE_createEnvelopeItems = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: file.name,
|
||||
});
|
||||
|
||||
const { documentData } = await putPdfFileServerSide({
|
||||
name: file.name,
|
||||
|
||||
@@ -85,7 +85,10 @@ export const UNSAFE_replaceEnvelopeItemPdf = async ({
|
||||
flattenForm: envelope.type !== 'TEMPLATE',
|
||||
});
|
||||
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized);
|
||||
const { cleanedPdf, placeholders } = await extractPdfPlaceholders(normalized, {
|
||||
envelopeId: envelope.id,
|
||||
fileName: data.file.name,
|
||||
});
|
||||
|
||||
// Upload the new PDF and get a new DocumentData record.
|
||||
const { documentData: newDocumentData, filePageCount } = await putPdfFileServerSide({
|
||||
|
||||
@@ -5,7 +5,6 @@ import { match } from 'ts-pattern';
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import { DocumentAccessAuth, type TDocumentAuthMethods } from '../../types/document-auth';
|
||||
import { extractDocumentAuthMethods } from '../../utils/document-auth';
|
||||
import { getRecipientsWithMissingFields } from '../../utils/recipients';
|
||||
import { extractFieldAutoInsertValues } from '../document/send-document';
|
||||
import { getTeamSettings } from '../team/get-team-settings';
|
||||
import type { EnvelopeForSigningResponse } from './get-envelope-for-recipient-signing';
|
||||
@@ -126,17 +125,6 @@ export const getEnvelopeForDirectTemplateSigning = async ({
|
||||
});
|
||||
}
|
||||
|
||||
const recipientsWithMissingFields = getRecipientsWithMissingFields(
|
||||
envelope.recipients,
|
||||
envelope.recipients.flatMap((envelopeRecipient) => envelopeRecipient.fields),
|
||||
);
|
||||
|
||||
if (recipientsWithMissingFields.length > 0) {
|
||||
throw new AppError(AppErrorCode.MISSING_SIGNATURE_FIELD, {
|
||||
message: 'One or more signers on this direct template are missing a signature field',
|
||||
});
|
||||
}
|
||||
|
||||
const settings = await getTeamSettings({ teamId: envelope.teamId });
|
||||
|
||||
const sender = settings.includeSenderDetails
|
||||
|
||||
@@ -5,7 +5,7 @@ import EnvelopeSchema from '@documenso/prisma/generated/zod/modelSchema/Envelope
|
||||
import SignatureSchema from '@documenso/prisma/generated/zod/modelSchema/SignatureSchema';
|
||||
import TeamSchema from '@documenso/prisma/generated/zod/modelSchema/TeamSchema';
|
||||
import UserSchema from '@documenso/prisma/generated/zod/modelSchema/UserSchema';
|
||||
import { DocumentSigningOrder, DocumentStatus, EnvelopeType, RecipientRole, SigningStatus } from '@prisma/client';
|
||||
import { DocumentSigningOrder, DocumentStatus, EnvelopeType, SigningStatus } from '@prisma/client';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
@@ -266,11 +266,6 @@ export const getEnvelopeForRecipientSigning = async ({
|
||||
|
||||
if (envelope.documentMeta.signingOrder === DocumentSigningOrder.SEQUENTIAL && currentRecipientIndex !== -1) {
|
||||
for (let i = 0; i < currentRecipientIndex; i++) {
|
||||
// CC recipients have no action to take, so they can never block the flow.
|
||||
if (envelope.recipients[i].role === RecipientRole.CC) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (envelope.recipients[i].signingStatus !== SigningStatus.SIGNED) {
|
||||
isRecipientsTurn = false;
|
||||
break;
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import {
|
||||
assertMemberCountWithinCap,
|
||||
syncMemberCountWithStripeSeatPlan,
|
||||
} from '@documenso/ee/server-only/stripe/update-subscription-item-quantity';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import type { OrganisationGroup, OrganisationMemberRole } from '@prisma/client';
|
||||
import { OrganisationGroupType, OrganisationMemberInviteStatus, SubscriptionStatus } from '@prisma/client';
|
||||
import { OrganisationGroupType, OrganisationMemberInviteStatus } from '@prisma/client';
|
||||
|
||||
import { IS_BILLING_ENABLED } from '../../constants/app';
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import { jobs } from '../../jobs/client';
|
||||
import { generateDatabaseId } from '../../universal/id';
|
||||
@@ -27,13 +22,6 @@ export const acceptOrganisationInvitation = async ({ token }: AcceptOrganisation
|
||||
organisation: {
|
||||
include: {
|
||||
groups: true,
|
||||
organisationClaim: true,
|
||||
subscription: true,
|
||||
members: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -78,35 +66,6 @@ export const acceptOrganisationInvitation = async ({ token }: AcceptOrganisation
|
||||
return;
|
||||
}
|
||||
|
||||
const newMemberCount = organisation.members.length + 1;
|
||||
|
||||
// Billing occurs when a user accepts an invite.
|
||||
// Assert that the new member count is within the cap and sync the seat plan with Stripe.
|
||||
if (IS_BILLING_ENABLED()) {
|
||||
const { subscription, organisationClaim } = organisation;
|
||||
|
||||
// A canceled subscription cannot have its seat quantity updated in Stripe,
|
||||
// and an organisation with lapsed billing should not gain new members.
|
||||
// Throw a deliberate error so the invite page can render an accurate
|
||||
// message instead of an opaque Stripe failure.
|
||||
if (subscription && subscription.status === SubscriptionStatus.INACTIVE) {
|
||||
throw new AppError('SUBSCRIPTION_INACTIVE', {
|
||||
message: 'The organisation subscription is inactive',
|
||||
});
|
||||
}
|
||||
|
||||
// Organisations can exist without a subscription (e.g. after being
|
||||
// downgraded to the free plan). The claim cap remains authoritative in
|
||||
// that case, surfacing LIMIT_EXCEEDED instead of an opaque "subscription
|
||||
// not found" error.
|
||||
await assertMemberCountWithinCap(subscription, organisationClaim, newMemberCount);
|
||||
|
||||
if (subscription) {
|
||||
await syncMemberCountWithStripeSeatPlan(subscription, organisationClaim, newMemberCount, 'grow');
|
||||
}
|
||||
}
|
||||
|
||||
// Todo: Logging
|
||||
await addUserToOrganisation({
|
||||
userId: user.id,
|
||||
organisationId: organisation.id,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
assertMemberCountWithinCap,
|
||||
syncMemberCountWithStripeSeatPlan,
|
||||
} from '@documenso/ee/server-only/stripe/update-subscription-item-quantity';
|
||||
import { OrganisationInviteEmailTemplate } from '@documenso/email/templates/organisation-invite';
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
|
||||
import { ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP } from '@documenso/lib/constants/organisations';
|
||||
@@ -13,6 +17,7 @@ import { createElement } from 'react';
|
||||
|
||||
import { getI18nInstance } from '../../client-only/providers/i18n-server';
|
||||
import { generateDatabaseId } from '../../universal/id';
|
||||
import { validateIfSubscriptionIsRequired } from '../../utils/billing';
|
||||
import { buildOrganisationWhereQuery } from '../../utils/organisations';
|
||||
import { renderEmailWithI18N } from '../../utils/render-email-with-i18n';
|
||||
import { getEmailContext } from '../email/get-email-context';
|
||||
@@ -57,6 +62,8 @@ export const createOrganisationMemberInvites = async ({
|
||||
},
|
||||
},
|
||||
organisationGlobalSettings: true,
|
||||
organisationClaim: true,
|
||||
subscription: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -64,6 +71,10 @@ export const createOrganisationMemberInvites = async ({
|
||||
throw new AppError(AppErrorCode.NOT_FOUND);
|
||||
}
|
||||
|
||||
const { organisationClaim } = organisation;
|
||||
|
||||
const subscription = validateIfSubscriptionIsRequired(organisation.subscription);
|
||||
|
||||
const currentOrganisationMemberRole = await getMemberOrganisationRole({
|
||||
organisationId: organisation.id,
|
||||
reference: {
|
||||
@@ -109,6 +120,19 @@ export const createOrganisationMemberInvites = async ({
|
||||
}),
|
||||
);
|
||||
|
||||
const numberOfCurrentMembers = organisation.members.length;
|
||||
const numberOfCurrentInvites = organisation.invites.length;
|
||||
const numberOfNewInvites = organisationMemberInvites.length;
|
||||
|
||||
const totalMemberCountWithInvites = numberOfCurrentMembers + numberOfCurrentInvites + numberOfNewInvites;
|
||||
|
||||
// Enforce the seat cap and sync billing for seat based plans.
|
||||
if (subscription) {
|
||||
await assertMemberCountWithinCap(subscription, organisationClaim, totalMemberCountWithInvites);
|
||||
|
||||
await syncMemberCountWithStripeSeatPlan(subscription, organisationClaim, totalMemberCountWithInvites);
|
||||
}
|
||||
|
||||
await prisma.organisationMemberInvite.createMany({
|
||||
data: organisationMemberInvites,
|
||||
});
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { type TFieldAndMeta, ZEnvelopeFieldAndMetaSchema } from '@documenso/lib/types/field-meta';
|
||||
import { logger } from '@documenso/lib/utils/logger';
|
||||
import { PDF, rgb } from '@libpdf/core';
|
||||
import type { FieldType, Recipient } from '@prisma/client';
|
||||
|
||||
import { parseFieldMetaFromPlaceholder, parseFieldTypeFromPlaceholder } from './helpers';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const PLACEHOLDER_REGEX = /\{\{([^}]+)\}\}/g;
|
||||
const DEFAULT_FIELD_HEIGHT_PERCENT = 2;
|
||||
@@ -61,7 +68,15 @@ export type FieldToCreate = TFieldAndMeta & {
|
||||
height: number;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<PlaceholderInfo[]> => {
|
||||
type ExtractPlaceholdersLogContext = {
|
||||
envelopeId?: string;
|
||||
fileName?: string;
|
||||
};
|
||||
|
||||
export const extractPlaceholdersFromPDF = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<PlaceholderInfo[]> => {
|
||||
const pdfDoc = await PDF.load(new Uint8Array(pdf));
|
||||
|
||||
const placeholders: PlaceholderInfo[] = [];
|
||||
@@ -85,7 +100,7 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
continue;
|
||||
}
|
||||
|
||||
const placeholderData = innerMatch[1].split(',').map((property) => property.trim());
|
||||
const placeholderData = parsePlaceholderData(innerMatch[1]);
|
||||
const [fieldTypeString, recipientOrMeta, ...fieldMetaData] = placeholderData;
|
||||
|
||||
let fieldType: FieldType;
|
||||
@@ -109,14 +124,51 @@ export const extractPlaceholdersFromPDF = async (pdf: Buffer): Promise<Placehold
|
||||
|
||||
const recipient = recipientOrMeta;
|
||||
|
||||
const rawFieldMeta = Object.fromEntries(fieldMetaData.map((property) => property.split('=')));
|
||||
/*
|
||||
Parse and validate the field metadata. A malformed selection placeholder
|
||||
(e.g. an unknown validation rule or a default value that doesn't match an
|
||||
option) is skipped like an invalid field type rather than aborting the whole
|
||||
upload, which may contain other valid placeholders and files.
|
||||
*/
|
||||
let fieldAndMeta: TFieldAndMeta;
|
||||
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
try {
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsedFieldMeta = parseFieldMetaFromPlaceholder(rawFieldMeta, fieldType);
|
||||
|
||||
const fieldAndMeta: TFieldAndMeta = ZEnvelopeFieldAndMetaSchema.parse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
const parsedFieldAndMeta = ZEnvelopeFieldAndMetaSchema.safeParse({
|
||||
type: fieldType,
|
||||
fieldMeta: parsedFieldMeta,
|
||||
});
|
||||
|
||||
/*
|
||||
Surface schema failures as INVALID_BODY (400) instead of letting the raw
|
||||
ZodError bubble up to the caller as an INTERNAL_SERVER_ERROR (500).
|
||||
*/
|
||||
if (!parsedFieldAndMeta.success) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid field metadata for placeholder "${placeholder}": ${parsedFieldAndMeta.error.message}`,
|
||||
});
|
||||
}
|
||||
|
||||
fieldAndMeta = parsedFieldAndMeta.data;
|
||||
} catch (error) {
|
||||
const appError = AppError.parseError(error);
|
||||
|
||||
logger.warn(
|
||||
{
|
||||
envelopeId: logContext?.envelopeId,
|
||||
fileName: logContext?.fileName,
|
||||
placeholder,
|
||||
page: page.index + 1,
|
||||
code: appError.code,
|
||||
message: appError.message,
|
||||
},
|
||||
'Skipping placeholder with invalid field metadata',
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
LibPDF returns bbox in points with bottom-left origin.
|
||||
@@ -182,8 +234,9 @@ export const removePlaceholdersFromPDF = async (pdf: Buffer, placeholders?: Plac
|
||||
*/
|
||||
export const extractPdfPlaceholders = async (
|
||||
pdf: Buffer,
|
||||
logContext?: ExtractPlaceholdersLogContext,
|
||||
): Promise<{ cleanedPdf: Buffer; placeholders: PlaceholderInfo[] }> => {
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf);
|
||||
const placeholders = await extractPlaceholdersFromPDF(pdf, logContext);
|
||||
|
||||
if (placeholders.length === 0) {
|
||||
return { cleanedPdf: pdf, placeholders: [] };
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { FieldType } from '@prisma/client';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import {
|
||||
parseFieldMetaFromPlaceholder,
|
||||
parseFieldTypeFromPlaceholder,
|
||||
parsePlaceholderData,
|
||||
parseRawFieldMetaFromPlaceholder,
|
||||
} from './helpers';
|
||||
|
||||
const expectInvalidBody = (fn: () => unknown) => {
|
||||
try {
|
||||
fn();
|
||||
expect.unreachable('Expected an AppError to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AppError);
|
||||
expect((error as AppError).code).toBe(AppErrorCode.INVALID_BODY);
|
||||
}
|
||||
};
|
||||
|
||||
describe('parseFieldTypeFromPlaceholder function', () => {
|
||||
it('maps known field type strings to the FieldType enum', () => {
|
||||
expect(parseFieldTypeFromPlaceholder('signature')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('radio')).toBe(FieldType.RADIO);
|
||||
expect(parseFieldTypeFromPlaceholder('checkbox')).toBe(FieldType.CHECKBOX);
|
||||
expect(parseFieldTypeFromPlaceholder('dropdown')).toBe(FieldType.DROPDOWN);
|
||||
});
|
||||
|
||||
it('is case-insensitive and trims surrounding whitespace', () => {
|
||||
expect(parseFieldTypeFromPlaceholder(' SiGnAtUrE ')).toBe(FieldType.SIGNATURE);
|
||||
expect(parseFieldTypeFromPlaceholder('RADIO')).toBe(FieldType.RADIO);
|
||||
});
|
||||
|
||||
it('throws INVALID_BODY for an unknown field type', () => {
|
||||
expectInvalidBody(() => parseFieldTypeFromPlaceholder('FILE'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsePlaceholderData function', () => {
|
||||
it('splits top-level parts on commas and trims each token', () => {
|
||||
expect(parsePlaceholderData('SIGNATURE, r1, required=true')).toEqual(['SIGNATURE', 'r1', 'required=true']);
|
||||
});
|
||||
|
||||
it('does not split on escaped commas', () => {
|
||||
expect(parsePlaceholderData('dropdown, r1, options=Legal\\, Compliance|Sales')).toEqual([
|
||||
'dropdown',
|
||||
'r1',
|
||||
'options=Legal\\, Compliance|Sales',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseRawFieldMetaFromPlaceholder function', () => {
|
||||
it('splits each token into a key/value entry', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required=true', 'fontSize=12'])).toEqual({
|
||||
required: 'true',
|
||||
fontSize: '12',
|
||||
});
|
||||
});
|
||||
|
||||
it('only splits on the first unescaped equals sign', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['label=a=b'])).toEqual({ label: 'a=b' });
|
||||
});
|
||||
|
||||
it('drops tokens without a value and overwrites duplicate keys with the last', () => {
|
||||
expect(parseRawFieldMetaFromPlaceholder(['required', 'fontSize=12', 'fontSize=14'])).toEqual({
|
||||
fontSize: '14',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseFieldMetaFromPlaceholder function', () => {
|
||||
describe('non-field-meta cases', () => {
|
||||
it('returns undefined for signature and free signature fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'true' }, FieldType.SIGNATURE)).toBeUndefined();
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.FREE_SIGNATURE)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when there is no metadata', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({}, FieldType.TEXT)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generic metadata', () => {
|
||||
it('coerces required/readOnly to booleans (case-insensitive)', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ required: 'TRUE', readOnly: 'false' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
required: true,
|
||||
readOnly: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('coerces numeric properties to numbers', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ fontSize: '14' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
fontSize: 14,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops numeric properties that are not a number', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ fontSize: 'abc' }, FieldType.TEXT);
|
||||
|
||||
expect(parsed).toEqual({ type: 'text' });
|
||||
expect(parsed).not.toHaveProperty('fontSize');
|
||||
});
|
||||
|
||||
it('keeps label/placeholder for non-selection fields', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ label: 'Company Name', placeholder: 'Acme' }, FieldType.TEXT)).toEqual({
|
||||
type: 'text',
|
||||
label: 'Company Name',
|
||||
placeholder: 'Acme',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('radio fields', () => {
|
||||
it('builds stable values from options', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe' }, FieldType.RADIO)).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: false, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('marks only the selected option as checked', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder({ options: 'Yes|No|Maybe', selected: 'No' }, FieldType.RADIO);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'radio',
|
||||
values: [
|
||||
{ id: 1, checked: false, value: 'Yes' },
|
||||
{ id: 2, checked: true, value: 'No' },
|
||||
{ id: 3, checked: false, value: 'Maybe' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when a default value is provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ selected: 'No' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'Yes|No', selected: 'Maybe' }, FieldType.RADIO));
|
||||
});
|
||||
|
||||
it('throws when options is empty', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: '' }, FieldType.RADIO));
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkbox fields', () => {
|
||||
it('builds values with checked state, validation rule alias and length', () => {
|
||||
const parsed = parseFieldMetaFromPlaceholder(
|
||||
{
|
||||
options: 'Email|SMS|Phone',
|
||||
checked: 'Email|Phone',
|
||||
validationRule: 'atLeast',
|
||||
validationLength: '1',
|
||||
},
|
||||
FieldType.CHECKBOX,
|
||||
);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'checkbox',
|
||||
validationRule: 'Select at least',
|
||||
validationLength: 1,
|
||||
values: [
|
||||
{ id: 1, checked: true, value: 'Email' },
|
||||
{ id: 2, checked: false, value: 'SMS' },
|
||||
{ id: 3, checked: true, value: 'Phone' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for an unknown validation rule', () => {
|
||||
expectInvalidBody(() =>
|
||||
parseFieldMetaFromPlaceholder({ options: 'A|B', validationRule: 'nope' }, FieldType.CHECKBOX),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when checked values are provided without options', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ checked: 'A' }, FieldType.CHECKBOX));
|
||||
});
|
||||
|
||||
it('throws when a checked value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', checked: 'C' }, FieldType.CHECKBOX));
|
||||
});
|
||||
});
|
||||
|
||||
describe('dropdown fields', () => {
|
||||
it('builds values and sets a matching default value', () => {
|
||||
expect(
|
||||
parseFieldMetaFromPlaceholder(
|
||||
{ options: 'United States|Canada|United Kingdom', defaultValue: 'Canada' },
|
||||
FieldType.DROPDOWN,
|
||||
),
|
||||
).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'United States' }, { value: 'Canada' }, { value: 'United Kingdom' }],
|
||||
defaultValue: 'Canada',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when the default value does not match an option', () => {
|
||||
expectInvalidBody(() => parseFieldMetaFromPlaceholder({ options: 'A|B', defaultValue: 'C' }, FieldType.DROPDOWN));
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection field options parsing', () => {
|
||||
it('trims option values and drops empty entries', () => {
|
||||
expect(parseFieldMetaFromPlaceholder({ options: ' A || B ' }, FieldType.DROPDOWN)).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'A' }, { value: 'B' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('parses escaped delimiters through the full placeholder pipeline', () => {
|
||||
const [, , ...fieldMetaData] = parsePlaceholderData(
|
||||
'dropdown, r1, options=Sales\\|Ops|Legal\\, Compliance|A\\=B',
|
||||
);
|
||||
|
||||
const rawFieldMeta = parseRawFieldMetaFromPlaceholder(fieldMetaData);
|
||||
const parsed = parseFieldMetaFromPlaceholder(rawFieldMeta, FieldType.DROPDOWN);
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: 'dropdown',
|
||||
values: [{ value: 'Sales|Ops' }, { value: 'Legal, Compliance' }, { value: 'A=B' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,134 @@ type RecipientPlaceholderInfo = {
|
||||
recipientIndex: number;
|
||||
};
|
||||
|
||||
const CHECKBOX_VALIDATION_RULE_BY_ALIAS: Record<string, string> = {
|
||||
atLeast: 'Select at least',
|
||||
exactly: 'Select exactly',
|
||||
atMost: 'Select at most',
|
||||
};
|
||||
|
||||
/*
|
||||
Split a string on a delimiter, treating `\` as an escape for the next character.
|
||||
Delimiters preceded by `\` are kept in the output instead of splitting (e.g. `\,`, `\=`, `\|`).
|
||||
|
||||
With delimiter ',' (top-level placeholder parts):
|
||||
'radio, r1, options=Card/Check|Bank Transfer, selected=Bank Transfer'
|
||||
-> ['radio', ' r1', ' options=Card/Check|Bank Transfer', ' selected=Bank Transfer']
|
||||
|
||||
With delimiter '=' (split one field metadata token into key + value):
|
||||
'options=Card/Check|Bank Transfer'
|
||||
-> ['options', 'Card/Check|Bank Transfer']
|
||||
|
||||
With delimiter '|' (split option list inside 'options='):
|
||||
'Card/Check|Bank Transfer'
|
||||
-> ['Card/Check', 'Bank Transfer']
|
||||
*/
|
||||
const splitPlaceholderToken = (value: string, delimiter: string): string[] => {
|
||||
const parts: string[] = [];
|
||||
let currentPart = '';
|
||||
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const char = value[index];
|
||||
const nextChar = value[index + 1];
|
||||
|
||||
if (char === '\\' && nextChar) {
|
||||
currentPart += char + nextChar;
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === delimiter) {
|
||||
parts.push(currentPart);
|
||||
currentPart = '';
|
||||
continue;
|
||||
}
|
||||
|
||||
currentPart += char;
|
||||
}
|
||||
|
||||
parts.push(currentPart);
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
/*
|
||||
Removes the escape backslashes left over after splitting, so \,=, \|, \\ become their literal characters.
|
||||
|
||||
E.g.
|
||||
'Legal\, Compliance' -> 'Legal, Compliance'
|
||||
'Card\|Check' -> 'Card|Check'
|
||||
'A\=B' -> 'A=B'
|
||||
'C\D' -> 'C\D'
|
||||
*/
|
||||
const unescapePlaceholderValue = (value: string): string => {
|
||||
return value.replace(/\\([,=|\\])/g, '$1');
|
||||
};
|
||||
|
||||
/*
|
||||
Cleans up a selection option/default after splitting:
|
||||
unescapes literal delimiters, collapses repeated whitespace, and trims the ends.
|
||||
|
||||
E.g.
|
||||
' Legal\, Compliance ' -> 'Legal, Compliance'
|
||||
*/
|
||||
const normalizePlaceholderSelectionValue = (value: string): string => {
|
||||
return unescapePlaceholderValue(value).replace(/\s+/g, ' ').trim();
|
||||
};
|
||||
|
||||
/*
|
||||
Split an options string into individual choices.
|
||||
Splits on unescaped '|', then unescapes, trims, and drops empty entries.
|
||||
|
||||
E.g.
|
||||
'Card/Check|Bank Transfer' -> ['Card/Check', 'Bank Transfer']
|
||||
'Card\\|Check|Bank Transfer' -> ['Card|Check', 'Bank Transfer']
|
||||
*/
|
||||
const parsePlaceholderOptions = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, '|')
|
||||
.map((option) => normalizePlaceholderSelectionValue(option))
|
||||
.filter((option) => option.length > 0);
|
||||
};
|
||||
|
||||
/*
|
||||
Split a placeholder string into top-level parts (field type, recipient, metadata).
|
||||
Splits on unescaped commas, then trims whitespace.
|
||||
|
||||
E.g.
|
||||
'SIGNATURE, r1, required=true'
|
||||
-> ['SIGNATURE', 'r1', 'required=true']
|
||||
*/
|
||||
export const parsePlaceholderData = (value: string): string[] => {
|
||||
return splitPlaceholderToken(value, ',').map((token) => token.trim());
|
||||
};
|
||||
|
||||
/*
|
||||
Transforms the field metadata string array into a record of key/value pairs.
|
||||
Each token is split on the first unescaped '='; tokens with no key or no '=' are dropped.
|
||||
|
||||
E.g.
|
||||
['required=true', 'fontSize=12', 'label=a=b']
|
||||
-> { required: 'true', fontSize: '12', label: 'a=b' }
|
||||
*/
|
||||
export const parseRawFieldMetaFromPlaceholder = (fieldMetaData: string[]): Record<string, string> => {
|
||||
const rawFieldMeta: Record<string, string> = {};
|
||||
|
||||
for (const fieldMeta of fieldMetaData) {
|
||||
// Split on the first '=' only; any further '=' stays part of the value (e.g. 'label=a=b').
|
||||
const [rawKey, ...valueParts] = splitPlaceholderToken(fieldMeta, '=');
|
||||
|
||||
if (!rawKey || valueParts.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = rawKey.trim();
|
||||
const value = valueParts.join('=').trim();
|
||||
|
||||
rawFieldMeta[key] = value;
|
||||
}
|
||||
|
||||
return rawFieldMeta;
|
||||
};
|
||||
|
||||
/*
|
||||
Parse field type string to FieldType enum.
|
||||
Normalizes the input (uppercase, trim) and validates it's a valid field type.
|
||||
@@ -72,6 +200,169 @@ export const parseFieldTypeFromPlaceholder = (fieldTypeString: string): FieldTyp
|
||||
});
|
||||
};
|
||||
|
||||
const getDefaultFieldMetaValue = (rawFieldMeta: Record<string, string>) => {
|
||||
const defaultValue = rawFieldMeta.defaultValue ?? rawFieldMeta.default ?? rawFieldMeta.selected;
|
||||
|
||||
return defaultValue ? normalizePlaceholderSelectionValue(defaultValue) : undefined;
|
||||
};
|
||||
|
||||
const parseCheckboxValidationRule = (value: string): string => {
|
||||
const validationRule = CHECKBOX_VALIDATION_RULE_BY_ALIAS[value];
|
||||
|
||||
if (!validationRule) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Invalid checkbox placeholder validation rule: ${value}`,
|
||||
});
|
||||
}
|
||||
|
||||
return validationRule;
|
||||
};
|
||||
|
||||
const parseSelectionFieldOptions = (
|
||||
rawFieldMeta: Record<string, string>,
|
||||
fieldType: FieldType,
|
||||
): string[] | undefined => {
|
||||
const rawOptions = rawFieldMeta.options;
|
||||
|
||||
if (rawOptions === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedOptions = parsePlaceholderOptions(rawOptions);
|
||||
|
||||
if (parsedOptions.length === 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `${fieldType} placeholder options must contain at least one value`,
|
||||
});
|
||||
}
|
||||
|
||||
return parsedOptions;
|
||||
};
|
||||
|
||||
const applyRadioFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.RADIO);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Radio placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedOptionIndex = defaultValue ? options.findIndex((option) => option === defaultValue) : -1;
|
||||
|
||||
if (defaultValue && selectedOptionIndex === -1) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Radio placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: index === selectedOptionIndex,
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyCheckboxFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.CHECKBOX);
|
||||
const checkedValues = rawFieldMeta.checked ? parsePlaceholderOptions(rawFieldMeta.checked) : [];
|
||||
|
||||
if (!options && checkedValues.length > 0) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Checkbox placeholder checked values require options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unmatchedCheckedValues = checkedValues.filter((checkedValue) => !options.includes(checkedValue));
|
||||
|
||||
if (unmatchedCheckedValues.length > 0) {
|
||||
const unmatchedCheckedValue = unmatchedCheckedValues[0];
|
||||
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: [`Checkbox placeholder checked value "${unmatchedCheckedValue}"`, 'must match one of the options'].join(
|
||||
' ',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option, index) => ({
|
||||
id: index + 1,
|
||||
checked: checkedValues.includes(option),
|
||||
value: option,
|
||||
}));
|
||||
};
|
||||
|
||||
const applyDropdownFieldOptions = (parsedFieldMeta: Record<string, unknown>, rawFieldMeta: Record<string, string>) => {
|
||||
const options = parseSelectionFieldOptions(rawFieldMeta, FieldType.DROPDOWN);
|
||||
const defaultValue = getDefaultFieldMetaValue(rawFieldMeta);
|
||||
|
||||
if (!options && defaultValue) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: 'Dropdown placeholder default value requires options',
|
||||
});
|
||||
}
|
||||
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (defaultValue && !options.includes(defaultValue)) {
|
||||
throw new AppError(AppErrorCode.INVALID_BODY, {
|
||||
message: `Dropdown placeholder default value "${defaultValue}" must match one of the options`,
|
||||
});
|
||||
}
|
||||
|
||||
parsedFieldMeta.values = options.map((option) => ({
|
||||
value: option,
|
||||
}));
|
||||
|
||||
if (defaultValue) {
|
||||
parsedFieldMeta.defaultValue = defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Generic field metadata properties are simple properties consisting of a key and a value.
|
||||
E.g. 'required=true', 'fontSize=12', 'textAlign=left'
|
||||
They don't require special handling.
|
||||
|
||||
Special field metadata properties are complex properties consisting of a key and a value with multiple parts.
|
||||
E.g. 'options=Card/Check|Bank Transfer', 'checked=Card|Check', 'selected=Bank Transfer'
|
||||
They require special handling.
|
||||
*/
|
||||
const shouldSkipGenericFieldMetaParsing = (property: string, fieldType: FieldType): boolean => {
|
||||
if (property === 'options' || property === 'default' || property === 'selected') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const isSelectionField =
|
||||
fieldType === FieldType.CHECKBOX || fieldType === FieldType.RADIO || fieldType === FieldType.DROPDOWN;
|
||||
|
||||
if (!isSelectionField) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
property === 'label' ||
|
||||
property === 'placeholder' ||
|
||||
property === 'defaultValue' ||
|
||||
(fieldType === FieldType.CHECKBOX && property === 'checked')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/*
|
||||
Transform raw field metadata from placeholder format to schema format.
|
||||
Users should provide properly capitalized property names (e.g., readOnly, fontSize, textAlign).
|
||||
@@ -91,7 +382,7 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
|
||||
const fieldTypeString = String(fieldType).toLowerCase();
|
||||
|
||||
const parsedFieldMeta: Record<string, boolean | number | string> = {
|
||||
const parsedFieldMeta: Record<string, unknown> = {
|
||||
type: fieldTypeString,
|
||||
};
|
||||
|
||||
@@ -104,24 +395,39 @@ export const parseFieldMetaFromPlaceholder = (
|
||||
const rawFieldMetaEntries = Object.entries(rawFieldMeta);
|
||||
|
||||
for (const [property, value] of rawFieldMetaEntries) {
|
||||
if (shouldSkipGenericFieldMetaParsing(property, fieldType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const unescapedValue = unescapePlaceholderValue(value);
|
||||
|
||||
if (property === 'readOnly' || property === 'required') {
|
||||
parsedFieldMeta[property] = value === 'true';
|
||||
parsedFieldMeta[property] = unescapedValue.toLowerCase() === 'true';
|
||||
} else if (property === 'validationRule' && fieldType === FieldType.CHECKBOX) {
|
||||
parsedFieldMeta[property] = parseCheckboxValidationRule(unescapedValue);
|
||||
} else if (
|
||||
property === 'fontSize' ||
|
||||
property === 'maxValue' ||
|
||||
property === 'minValue' ||
|
||||
property === 'characterLimit'
|
||||
property === 'characterLimit' ||
|
||||
property === 'validationLength'
|
||||
) {
|
||||
const numValue = Number(value);
|
||||
const numValue = Number(unescapedValue);
|
||||
|
||||
if (!Number.isNaN(numValue)) {
|
||||
parsedFieldMeta[property] = numValue;
|
||||
}
|
||||
} else {
|
||||
parsedFieldMeta[property] = value;
|
||||
parsedFieldMeta[property] = unescapedValue;
|
||||
}
|
||||
}
|
||||
|
||||
match(fieldType)
|
||||
.with(FieldType.RADIO, () => applyRadioFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.CHECKBOX, () => applyCheckboxFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.with(FieldType.DROPDOWN, () => applyDropdownFieldOptions(parsedFieldMeta, rawFieldMeta))
|
||||
.otherwise(() => undefined);
|
||||
|
||||
return parsedFieldMeta;
|
||||
};
|
||||
|
||||
|
||||
@@ -84,13 +84,13 @@ export const syncSubscriptionRateLimit = createRateLimit({
|
||||
|
||||
export const apiV1RateLimit = createRateLimit({
|
||||
action: 'api.v1',
|
||||
max: 1000,
|
||||
max: 100,
|
||||
window: '1m',
|
||||
});
|
||||
|
||||
export const apiV2RateLimit = createRateLimit({
|
||||
action: 'api.v2',
|
||||
max: 1000,
|
||||
max: 100,
|
||||
window: '1m',
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { DocumentSigningOrder, EnvelopeType, RecipientRole, SigningStatus } from '@prisma/client';
|
||||
import { DocumentSigningOrder, EnvelopeType, SigningStatus } from '@prisma/client';
|
||||
|
||||
export type GetIsRecipientTurnOptions = {
|
||||
token: string;
|
||||
@@ -38,11 +38,6 @@ export async function getIsRecipientsTurnToSign({ token }: GetIsRecipientTurnOpt
|
||||
}
|
||||
|
||||
for (let i = 0; i < currentRecipientIndex; i++) {
|
||||
// CC recipients have no action to take, so they can never block the flow.
|
||||
if (recipients[i].role === RecipientRole.CC) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (recipients[i].signingStatus !== SigningStatus.SIGNED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { EnvelopeType, RecipientRole } from '@prisma/client';
|
||||
import { EnvelopeType } from '@prisma/client';
|
||||
|
||||
import { mapDocumentIdToSecondaryId } from '../../utils/envelope';
|
||||
|
||||
@@ -16,11 +16,6 @@ export const getNextPendingRecipient = async ({
|
||||
type: EnvelopeType.DOCUMENT,
|
||||
secondaryId: mapDocumentIdToSecondaryId(documentId),
|
||||
},
|
||||
// CC recipients are informational only and never take part in signing,
|
||||
// so they must never be offered as the next pending recipient.
|
||||
role: {
|
||||
not: RecipientRole.CC,
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
extractDocumentAuthMethods,
|
||||
} from '../../utils/document-auth';
|
||||
import { mapSecondaryIdToTemplateId } from '../../utils/envelope';
|
||||
import { getRecipientsWithMissingFields } from '../../utils/recipients';
|
||||
import { sendDocument } from '../document/send-document';
|
||||
import { validateFieldAuth } from '../document/validate-field-auth';
|
||||
import { incrementDocumentId } from '../envelope/increment-id';
|
||||
@@ -173,17 +172,6 @@ export const createDocumentFromDirectTemplate = async ({
|
||||
});
|
||||
}
|
||||
|
||||
const recipientsWithMissingFields = getRecipientsWithMissingFields(
|
||||
recipients,
|
||||
recipients.flatMap((recipient) => recipient.fields),
|
||||
);
|
||||
|
||||
if (recipientsWithMissingFields.length > 0) {
|
||||
throw new AppError(AppErrorCode.MISSING_SIGNATURE_FIELD, {
|
||||
message: 'One or more signers on this direct template are missing a signature field',
|
||||
});
|
||||
}
|
||||
|
||||
if (directTemplateEnvelope.updatedAt.getTime() !== templateUpdatedAt.getTime()) {
|
||||
throw new AppError(AppErrorCode.INVALID_REQUEST, { message: 'Template no longer matches' });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
|
||||
import { AppError, AppErrorCode } from '../../errors/app-error';
|
||||
import { jobs } from '../../jobs/client';
|
||||
import { deleteOrganisation } from '../organisation/delete-organisation';
|
||||
|
||||
export type DeleteUserOptions = {
|
||||
@@ -60,13 +59,6 @@ export const deleteUser = async ({ id }: DeleteUserOptions) => {
|
||||
})),
|
||||
);
|
||||
|
||||
// Organisations the user is a member of (but not owner). Owned organisations
|
||||
// are fully torn down below (including subscription cancellation), so only
|
||||
// these need a seat sync after the user's memberships cascade away.
|
||||
const memberOrganisationIds = user.organisationMember
|
||||
.filter((member) => member.organisation.ownerUserId !== user.id)
|
||||
.map((member) => member.organisationId);
|
||||
|
||||
// For organisations the user owns - fully tear them down (orphan envelopes,
|
||||
// delete the organisation, and cancel any Stripe subscription). Without this
|
||||
// the organisations would only cascade away when the user row is deleted,
|
||||
@@ -90,21 +82,9 @@ export const deleteUser = async ({ id }: DeleteUserOptions) => {
|
||||
}),
|
||||
);
|
||||
|
||||
const deletedUser = await prisma.user.delete({
|
||||
return await prisma.user.delete({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
});
|
||||
|
||||
// The user's memberships were cascade-deleted with the user row — queue a
|
||||
// seat sync for each organisation they belonged to so the Stripe quantity
|
||||
// trues down to the new member count (no proration, no credit).
|
||||
for (const organisationId of memberOrganisationIds) {
|
||||
await jobs.triggerJob({
|
||||
name: 'internal.sync-organisation-seats',
|
||||
payload: { organisationId },
|
||||
});
|
||||
}
|
||||
|
||||
return deletedUser;
|
||||
};
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { RecipientRole } from '@prisma/client';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { isAssistantLastSigner, normalizeRecipientSigningOrders, sortRecipientsForSigningOrder } from './recipients';
|
||||
|
||||
describe('recipient signing order helpers', () => {
|
||||
it('sorts CC recipients after ordered active recipients', () => {
|
||||
const recipients = [
|
||||
{ id: 1, role: RecipientRole.CC, signingOrder: 1 },
|
||||
{ id: 2, role: RecipientRole.SIGNER, signingOrder: 2 },
|
||||
{ id: 3, role: RecipientRole.APPROVER, signingOrder: 1 },
|
||||
];
|
||||
|
||||
expect(sortRecipientsForSigningOrder(recipients).map((recipient) => recipient.id)).toEqual([3, 2, 1]);
|
||||
});
|
||||
|
||||
it('keeps original order when recipients have the same signing order', () => {
|
||||
const recipients = [
|
||||
{ id: 2, role: RecipientRole.SIGNER, signingOrder: 1 },
|
||||
{ id: 1, role: RecipientRole.APPROVER, signingOrder: 1 },
|
||||
];
|
||||
|
||||
expect(sortRecipientsForSigningOrder(recipients).map((recipient) => recipient.id)).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('sorts and normalizes active recipient signing order and removes it from CC recipients', () => {
|
||||
const recipients = [
|
||||
{ id: 1, role: RecipientRole.CC, signingOrder: 1 },
|
||||
{ id: 2, role: RecipientRole.SIGNER, signingOrder: 4 },
|
||||
{ id: 3, role: RecipientRole.APPROVER, signingOrder: 2 },
|
||||
];
|
||||
|
||||
expect(normalizeRecipientSigningOrders(sortRecipientsForSigningOrder(recipients))).toEqual([
|
||||
{ id: 3, role: RecipientRole.APPROVER, signingOrder: 1 },
|
||||
{ id: 2, role: RecipientRole.SIGNER, signingOrder: 2 },
|
||||
{ id: 1, role: RecipientRole.CC, signingOrder: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves caller order while normalizing signing order', () => {
|
||||
const recipients = [
|
||||
{ id: 2, role: RecipientRole.ASSISTANT, signingOrder: 2 },
|
||||
{ id: 1, role: RecipientRole.SIGNER, signingOrder: 1 },
|
||||
{ id: 3, role: RecipientRole.CC, signingOrder: 1 },
|
||||
];
|
||||
|
||||
expect(normalizeRecipientSigningOrders(recipients)).toEqual([
|
||||
{ id: 2, role: RecipientRole.ASSISTANT, signingOrder: 1 },
|
||||
{ id: 1, role: RecipientRole.SIGNER, signingOrder: 2 },
|
||||
{ id: 3, role: RecipientRole.CC, signingOrder: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it('checks whether the last non-CC recipient is an assistant', () => {
|
||||
expect(
|
||||
isAssistantLastSigner([
|
||||
{ role: RecipientRole.SIGNER },
|
||||
{ role: RecipientRole.ASSISTANT },
|
||||
{ role: RecipientRole.CC },
|
||||
]),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
isAssistantLastSigner([
|
||||
{ role: RecipientRole.ASSISTANT },
|
||||
{ role: RecipientRole.SIGNER },
|
||||
{ role: RecipientRole.CC },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { isSignatureFieldType } from '@documenso/prisma/guards/is-signature-field';
|
||||
import type { Envelope, Field, Recipient } from '@prisma/client';
|
||||
import { RecipientRole, SigningStatus } from '@prisma/client';
|
||||
import type { Envelope } from '@prisma/client';
|
||||
import { type Field, RecipientRole, SigningStatus } from '@prisma/client';
|
||||
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '../constants/app';
|
||||
import { AppError, AppErrorCode } from '../errors/app-error';
|
||||
@@ -15,58 +15,6 @@ import { zEmail } from './zod';
|
||||
*/
|
||||
export const RECIPIENT_ROLES_THAT_REQUIRE_FIELDS = [RecipientRole.SIGNER] as const;
|
||||
|
||||
// signingOrder isn't required when submitting the recipient form (Zod: z.number().optional())
|
||||
type RecipientWithSigningOrder = Pick<Recipient, 'role'> & Partial<Pick<Recipient, 'signingOrder'>>;
|
||||
|
||||
export const isCcRecipient = (recipient: Pick<Recipient, 'role'>) => {
|
||||
return recipient.role === RecipientRole.CC;
|
||||
};
|
||||
|
||||
export const isAssistantLastSigner = (recipients: Pick<Recipient, 'role'>[]) => {
|
||||
const nonCcRecipients = recipients.filter((recipient) => !isCcRecipient(recipient));
|
||||
const lastNonCcRecipient = nonCcRecipients[nonCcRecipients.length - 1];
|
||||
|
||||
return lastNonCcRecipient?.role === RecipientRole.ASSISTANT;
|
||||
};
|
||||
|
||||
export const sortRecipientsForSigningOrder = <T extends RecipientWithSigningOrder>(recipients: T[]): T[] => {
|
||||
return [...recipients].sort((r1, r2) => {
|
||||
const r1IsCcRecipient = isCcRecipient(r1);
|
||||
const r2IsCcRecipient = isCcRecipient(r2);
|
||||
|
||||
// CC recipients always sort after non-CC recipients.
|
||||
if (r1IsCcRecipient !== r2IsCcRecipient) {
|
||||
return r1IsCcRecipient ? 1 : -1;
|
||||
}
|
||||
|
||||
// Order by signing order; missing orders sort last.
|
||||
const r1SigningOrder = r1.signingOrder ?? Number.MAX_SAFE_INTEGER;
|
||||
const r2SigningOrder = r2.signingOrder ?? Number.MAX_SAFE_INTEGER;
|
||||
|
||||
return r1SigningOrder - r2SigningOrder;
|
||||
});
|
||||
};
|
||||
|
||||
export const normalizeRecipientSigningOrders = <T extends RecipientWithSigningOrder>(
|
||||
recipients: T[],
|
||||
canUpdateRecipient: (recipient: T) => boolean = () => true,
|
||||
): Array<T & { signingOrder?: number }> => {
|
||||
const nonCcRecipients = recipients.filter((recipient) => !isCcRecipient(recipient));
|
||||
const ccRecipients = recipients.filter((recipient) => isCcRecipient(recipient));
|
||||
|
||||
const normalizedNonCcRecipients = nonCcRecipients.map((recipient, index) => ({
|
||||
...recipient,
|
||||
signingOrder: canUpdateRecipient(recipient) ? index + 1 : (recipient.signingOrder ?? index + 1),
|
||||
}));
|
||||
|
||||
const normalizedCcRecipients = ccRecipients.map((recipient) => ({
|
||||
...recipient,
|
||||
signingOrder: undefined,
|
||||
}));
|
||||
|
||||
return [...normalizedNonCcRecipients, ...normalizedCcRecipients];
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns recipients who are missing required fields for their role.
|
||||
*
|
||||
|
||||
@@ -361,9 +361,9 @@ export const seedAlignmentTestDocument = async ({
|
||||
const { id, recipients, envelopeItems } = createdEnvelope;
|
||||
|
||||
if (isDirectTemplate) {
|
||||
const directTemplateRecipient = recipients.find((recipient) => recipient.email === DIRECT_TEMPLATE_RECIPIENT_EMAIL);
|
||||
const directTemplateRecpient = recipients.find((recipient) => recipient.email === DIRECT_TEMPLATE_RECIPIENT_EMAIL);
|
||||
|
||||
if (!directTemplateRecipient) {
|
||||
if (!directTemplateRecpient) {
|
||||
throw new Error('Need to create a direct template recipient');
|
||||
}
|
||||
|
||||
@@ -372,7 +372,7 @@ export const seedAlignmentTestDocument = async ({
|
||||
envelopeId: id,
|
||||
enabled: true,
|
||||
token: directTemplateToken ?? Math.random().toString(),
|
||||
directTemplateRecipientId: directTemplateRecipient.id,
|
||||
directTemplateRecipientId: directTemplateRecpient.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
DIRECT_TEMPLATE_RECIPIENT_NAME,
|
||||
} from '@documenso/lib/constants/direct-templates';
|
||||
import { incrementTemplateId } from '@documenso/lib/server-only/envelope/increment-id';
|
||||
import { FIELD_SIGNATURE_META_DEFAULT_VALUES } from '@documenso/lib/types/field-meta';
|
||||
import { SignatureLevel } from '@documenso/lib/types/signature-level';
|
||||
import { prefixedId } from '@documenso/lib/universal/id';
|
||||
|
||||
@@ -16,7 +15,6 @@ import {
|
||||
DocumentDataType,
|
||||
DocumentSource,
|
||||
EnvelopeType,
|
||||
FieldType,
|
||||
ReadStatus,
|
||||
RecipientRole,
|
||||
SendStatus,
|
||||
@@ -31,11 +29,6 @@ type SeedTemplateOptions = {
|
||||
teamId: number;
|
||||
internalVersion?: 1 | 2;
|
||||
createTemplateOptions?: Partial<Prisma.EnvelopeUncheckedCreateInput>;
|
||||
/**
|
||||
* Only used by seedDirectTemplate. Creates a signature field for the direct
|
||||
* recipient so the seeded direct template is valid. Defaults to true.
|
||||
*/
|
||||
createDirectRecipientSignatureField?: boolean;
|
||||
};
|
||||
|
||||
type CreateTemplateOptions = {
|
||||
@@ -205,11 +198,11 @@ export const seedDirectTemplate = async (options: SeedTemplateOptions) => {
|
||||
},
|
||||
});
|
||||
|
||||
const directTemplateRecipient = template.recipients.find(
|
||||
const directTemplateRecpient = template.recipients.find(
|
||||
(recipient) => recipient.email === DIRECT_TEMPLATE_RECIPIENT_EMAIL,
|
||||
);
|
||||
|
||||
if (!directTemplateRecipient) {
|
||||
if (!directTemplateRecpient) {
|
||||
throw new Error('Need to create a direct template recipient');
|
||||
}
|
||||
|
||||
@@ -218,35 +211,10 @@ export const seedDirectTemplate = async (options: SeedTemplateOptions) => {
|
||||
envelopeId: template.id,
|
||||
enabled: true,
|
||||
token: Math.random().toString(),
|
||||
directTemplateRecipientId: directTemplateRecipient.id,
|
||||
directTemplateRecipientId: directTemplateRecpient.id,
|
||||
},
|
||||
});
|
||||
|
||||
const { createDirectRecipientSignatureField = true } = options;
|
||||
|
||||
if (createDirectRecipientSignatureField) {
|
||||
const envelopeItem = await prisma.envelopeItem.findFirstOrThrow({
|
||||
where: { envelopeId: template.id },
|
||||
});
|
||||
|
||||
await prisma.field.create({
|
||||
data: {
|
||||
envelopeId: template.id,
|
||||
envelopeItemId: envelopeItem.id,
|
||||
recipientId: directTemplateRecipient.id,
|
||||
type: FieldType.SIGNATURE,
|
||||
page: 1,
|
||||
positionX: 5,
|
||||
positionY: 10,
|
||||
width: 20,
|
||||
height: 5,
|
||||
customText: '',
|
||||
inserted: false,
|
||||
fieldMeta: FIELD_SIGNATURE_META_DEFAULT_VALUES,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return await prisma.envelope.findFirstOrThrow({
|
||||
where: {
|
||||
id: template.id,
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { adminGlobalSearch } from '@documenso/lib/server-only/admin/admin-global-search';
|
||||
|
||||
import { adminProcedure } from '../trpc';
|
||||
import { ZAdminSearchRequestSchema, ZAdminSearchResponseSchema } from './admin-search.types';
|
||||
|
||||
export const adminSearchRoute = adminProcedure
|
||||
.input(ZAdminSearchRequestSchema)
|
||||
.output(ZAdminSearchResponseSchema)
|
||||
.query(async ({ input }) => {
|
||||
const { query } = input;
|
||||
|
||||
const groups = await adminGlobalSearch({ query });
|
||||
|
||||
return { groups };
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ZAdminSearchResultTypeSchema = z.enum([
|
||||
'document',
|
||||
'user',
|
||||
'organisation',
|
||||
'team',
|
||||
'recipient',
|
||||
'subscription',
|
||||
]);
|
||||
|
||||
export const ZAdminSearchResultSchema = z.object({
|
||||
label: z.string(),
|
||||
sublabel: z.string().optional(),
|
||||
path: z.string(),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
export const ADMIN_SEARCH_MAX_QUERY_LENGTH = 100;
|
||||
|
||||
export const ZAdminSearchRequestSchema = z.object({
|
||||
query: z.string().trim().min(1).max(ADMIN_SEARCH_MAX_QUERY_LENGTH),
|
||||
});
|
||||
|
||||
export const ZAdminSearchResponseSchema = z.object({
|
||||
groups: z.array(
|
||||
z.object({
|
||||
type: ZAdminSearchResultTypeSchema,
|
||||
results: ZAdminSearchResultSchema.array(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export type TAdminSearchResultType = z.infer<typeof ZAdminSearchResultTypeSchema>;
|
||||
export type TAdminSearchResult = z.infer<typeof ZAdminSearchResultSchema>;
|
||||
export type TAdminSearchRequest = z.infer<typeof ZAdminSearchRequestSchema>;
|
||||
export type TAdminSearchResponse = z.infer<typeof ZAdminSearchResponseSchema>;
|
||||
@@ -1,6 +1,8 @@
|
||||
import { syncMemberCountWithStripeSeatPlan } from '@documenso/ee/server-only/stripe/update-subscription-item-quantity';
|
||||
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
|
||||
import { jobs } from '@documenso/lib/jobs/client';
|
||||
import { prisma } from '@documenso/prisma';
|
||||
import { OrganisationMemberInviteStatus } from '@prisma/client';
|
||||
|
||||
import { adminProcedure } from '../trpc';
|
||||
import {
|
||||
@@ -26,6 +28,8 @@ export const deleteAdminOrganisationMemberRoute = adminProcedure
|
||||
id: organisationId,
|
||||
},
|
||||
include: {
|
||||
subscription: true,
|
||||
organisationClaim: true,
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -37,6 +41,14 @@ export const deleteAdminOrganisationMemberRoute = adminProcedure
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
invites: {
|
||||
where: {
|
||||
status: OrganisationMemberInviteStatus.PENDING,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -60,6 +72,18 @@ export const deleteAdminOrganisationMemberRoute = adminProcedure
|
||||
});
|
||||
}
|
||||
|
||||
const newMemberCount = organisation.members.length + organisation.invites.length - 1;
|
||||
|
||||
// Removing a member is a reducing operation, so we don't gate it on the
|
||||
// subscription being present. Sync Stripe only when one exists.
|
||||
if (organisation.subscription) {
|
||||
await syncMemberCountWithStripeSeatPlan(
|
||||
organisation.subscription,
|
||||
organisation.organisationClaim,
|
||||
newMemberCount,
|
||||
);
|
||||
}
|
||||
|
||||
const teamIds = organisation.teams.map((team) => team.id);
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
@@ -89,13 +113,6 @@ export const deleteAdminOrganisationMemberRoute = adminProcedure
|
||||
});
|
||||
});
|
||||
|
||||
// A member was removed — queue a seat sync to true the Stripe quantity down
|
||||
// to the new count (no proration, no credit).
|
||||
await jobs.triggerJob({
|
||||
name: 'internal.sync-organisation-seats',
|
||||
payload: { organisationId },
|
||||
});
|
||||
|
||||
await jobs.triggerJob({
|
||||
name: 'send.organisation-member-left.email',
|
||||
payload: {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { router } from '../trpc';
|
||||
import { adminSearchRoute } from './admin-search';
|
||||
import { createAdminOrganisationRoute } from './create-admin-organisation';
|
||||
import { createStripeCustomerRoute } from './create-stripe-customer';
|
||||
import { createSubscriptionClaimRoute } from './create-subscription-claim';
|
||||
@@ -119,6 +118,5 @@ export const adminRouter = router({
|
||||
teamMember: {
|
||||
delete: deleteAdminTeamMemberRoute,
|
||||
},
|
||||
search: adminSearchRoute,
|
||||
updateSiteSetting: updateSiteSettingRoute,
|
||||
});
|
||||
|
||||
@@ -12,10 +12,8 @@ export const createAttachmentRoute = authenticatedProcedure
|
||||
method: 'POST',
|
||||
path: '/document/attachment/create',
|
||||
summary: 'Create attachment',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. Create a new attachment for a document',
|
||||
description: 'Create a new attachment for a document',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
})
|
||||
.input(ZCreateAttachmentRequestSchema)
|
||||
|
||||
@@ -10,10 +10,8 @@ export const deleteAttachmentRoute = authenticatedProcedure
|
||||
method: 'POST',
|
||||
path: '/document/attachment/delete',
|
||||
summary: 'Delete attachment',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. Delete an attachment from a document',
|
||||
description: 'Delete an attachment from a document',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
})
|
||||
.input(ZDeleteAttachmentRequestSchema)
|
||||
|
||||
@@ -12,10 +12,8 @@ export const findAttachmentsRoute = authenticatedProcedure
|
||||
method: 'GET',
|
||||
path: '/document/attachment',
|
||||
summary: 'Find attachments',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. Find all attachments for a document',
|
||||
description: 'Find all attachments for a document',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
})
|
||||
.input(ZFindAttachmentsRequestSchema)
|
||||
|
||||
@@ -10,10 +10,8 @@ export const updateAttachmentRoute = authenticatedProcedure
|
||||
method: 'POST',
|
||||
path: '/document/attachment/update',
|
||||
summary: 'Update attachment',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. Update an existing attachment',
|
||||
description: 'Update an existing attachment',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
})
|
||||
.input(ZUpdateAttachmentRequestSchema)
|
||||
|
||||
@@ -27,7 +27,7 @@ export const createDocumentTemporaryMeta: TrpcRouteMeta = {
|
||||
path: '/document/create/beta',
|
||||
summary: 'Create document',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. You will need to upload the PDF to the provided URL returned. This endpoint will be removed since we will allow direct uploads, instead of using an upload URL.',
|
||||
'You will need to upload the PDF to the provided URL returned. Note: Once V2 API is released, this will be removed since we will allow direct uploads, instead of using an upload URL.',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
|
||||
@@ -25,10 +25,8 @@ export const createDocumentMeta: TrpcRouteMeta = {
|
||||
path: '/document/create',
|
||||
contentTypes: ['multipart/form-data'],
|
||||
summary: 'Create document',
|
||||
description:
|
||||
'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide.',
|
||||
description: 'Create a document using form data.',
|
||||
tags: ['Document'],
|
||||
deprecated: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user