Compare commits

..

2 Commits

Author SHA1 Message Date
David Nguyen
071ce70292 wip: test 2025-01-05 15:45:51 +11:00
Mythie
866b036484 wip 2025-01-02 15:33:37 +11:00
404 changed files with 12643 additions and 25253 deletions

View File

@@ -10,7 +10,7 @@ on:
jobs: jobs:
analyze: analyze:
name: Analyze name: Analyze
runs-on: ubuntu-22.04 runs-on: ubuntu-latest
permissions: permissions:
actions: read actions: read
contents: read contents: read

View File

@@ -8,7 +8,7 @@ jobs:
e2e_tests: e2e_tests:
name: 'E2E Tests' name: 'E2E Tests'
timeout-minutes: 60 timeout-minutes: 60
runs-on: warp-ubuntu-2204-x64-16x runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

View File

@@ -1,4 +1,4 @@
> 🚨 We are live on Product Hunt 🎉 Check out our latest launch: <a href="https://documen.so/sign-everywhere">The Platform Plan</a>! > 🚨 We are live on Product Hunt 🎉 Check out our latest launch: <a href="documen.so/sign-everywhere">The Platform Plan</a>!
<a href="https://www.producthunt.com/posts/documenso-platform-plan?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-documenso&#0045;platform&#0045;plan" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=670576&theme=light" alt="Documenso&#0032;Platform&#0032;Plan - Whitelabeled&#0032;signing&#0032;flows&#0032;in&#0032;your&#0032;product | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a> <a href="https://www.producthunt.com/posts/documenso-platform-plan?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-documenso&#0045;platform&#0045;plan" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=670576&theme=light" alt="Documenso&#0032;Platform&#0032;Plan - Whitelabeled&#0032;signing&#0032;flows&#0032;in&#0032;your&#0032;product | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>

View File

@@ -27,6 +27,6 @@
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"typescript": "5.6.2" "typescript": "^5"
} }
} }

View File

@@ -5,7 +5,5 @@
"svelte": "Svelte Integration", "svelte": "Svelte Integration",
"solid": "Solid Integration", "solid": "Solid Integration",
"preact": "Preact Integration", "preact": "Preact Integration",
"angular": "Angular Integration", "css-variables": "CSS Variables"
"css-variables": "CSS Variables",
"web-components": "Web Components"
} }

View File

@@ -1,90 +0,0 @@
---
title: Angular Integration
description: Learn how to use our embedding SDK within your Angular application.
---
# Angular Integration
Our Angular SDK provides a simple way to embed a signing experience within your Angular application. It supports both direct link templates and signing tokens.
## Installation
To install the SDK, run the following command:
```bash
npm install @documenso/embed-angular
```
## Usage
To embed a signing experience, you'll need to provide the token for the document you want to embed. This can be done in a few different ways, depending on your use case.
### Direct Link Template
If you have a direct link template, you can simply provide the token for the template to the `EmbedDirectTemplate` component.
```typescript
import { Component } from '@angular/core';
import { EmbedDirectTemplate } from '@documenso/embed-angular';
@Component({
selector: 'app-embedding',
template: `
<embed-direct-template [token]="token" />
`,
standalone: true,
imports: [EmbedDirectTemplate],
})
export class EmbeddingComponent {
token = 'YOUR_TOKEN_HERE'; // Replace with the actual token
}
```
#### Props
| Prop | Type | Description |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------ |
| token | string | The token for the document you want to embed |
| host | string (optional) | The host to be used for the signing experience, relevant for self-hosters |
| name | string (optional) | The name the signer that will be used by default for signing |
| lockName | boolean (optional) | Whether or not the name field should be locked disallowing modifications |
| email | string (optional) | The email the signer that will be used by default for signing |
| lockEmail | boolean (optional) | Whether or not the email field should be locked disallowing modifications |
| onDocumentReady | function (optional) | A callback function that will be called when the document is loaded and ready to be signed |
| onDocumentCompleted | function (optional) | A callback function that will be called when the document has been completed |
| onDocumentError | function (optional) | A callback function that will be called when an error occurs with the document |
| onFieldSigned | function (optional) | A callback function that will be called when a field is signed |
| onFieldUnsigned | function (optional) | A callback function that will be called when a field is unsigned |
### Signing Token
If you have a signing token, you can provide it to the `EmbedSignDocument` component.
```typescript
import { Component } from '@angular/core';
import { EmbedSignDocument } from '@documenso/embed-angular';
@Component({
selector: 'app-embedding',
template: `
<embed-sign-document [token]="token" />
`,
standalone: true,
imports: [EmbedSignDocument],
})
export class EmbeddingComponent {
token = 'YOUR_TOKEN_HERE'; // Replace with the actual token
}
```
#### Props
| Prop | Type | Description |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------ |
| token | string | The token for the document you want to embed |
| host | string (optional) | The host to be used for the signing experience, relevant for self-hosters |
| name | string (optional) | The name the signer that will be used by default for signing |
| lockName | boolean (optional) | Whether or not the name field should be locked disallowing modifications |
| onDocumentReady | function (optional) | A callback function that will be called when the document is loaded and ready to be signed |
| onDocumentCompleted | function (optional) | A callback function that will be called when the document has been completed |
| onDocumentError | function (optional) | A callback function that will be called when an error occurs with the document |

View File

@@ -111,83 +111,6 @@ The colors will be automatically converted to the appropriate format internally.
4. **Consistent Radius**: Use a consistent border radius value that matches your application's design system. 4. **Consistent Radius**: Use a consistent border radius value that matches your application's design system.
## CSS Class Targets
In addition to CSS variables, specific components in the embedded experience can be targeted using CSS classes for more granular styling:
### Component Classes
| Class Name | Description |
| --------------------------------- | ----------------------------------------------------------------------- |
| `.embed--Root` | Main container for the embedded signing experience |
| `.embed--DocumentContainer` | Container for the document and signing widget |
| `.embed--DocumentViewer` | Container for the document viewer |
| `.embed--DocumentWidget` | The signing widget container |
| `.embed--DocumentWidgetContainer` | Outer container for the signing widget, handles positioning |
| `.embed--DocumentWidgetHeader` | Header section of the signing widget |
| `.embed--DocumentWidgetContent` | Main content area of the signing widget |
| `.embed--DocumentWidgetForm` | Form section within the signing widget |
| `.embed--DocumentWidgetFooter` | Footer section of the signing widget |
| `.embed--WaitingForTurn` | Container for the waiting screen when it's not the user's turn to sign |
| `.embed--DocumentCompleted` | Container for the completion screen after signing |
| `.field--FieldRootContainer` | Base container for document fields (signatures, text, checkboxes, etc.) |
Field components also expose several data attributes that can be used for styling different states:
| Data Attribute | Values | Description |
| ------------------- | ---------------------------------------------- | ------------------------------------ |
| `[data-field-type]` | `SIGNATURE`, `TEXT`, `CHECKBOX`, `RADIO`, etc. | The type of field |
| `[data-inserted]` | `true`, `false` | Whether the field has been filled |
| `[data-validate]` | `true`, `false` | Whether the field is being validated |
### Field Styling Example
```css
/* Style all field containers */
.field--FieldRootContainer {
transition: all 200ms ease;
}
/* Style specific field types */
.field--FieldRootContainer[data-field-type='SIGNATURE'] {
background-color: rgba(0, 0, 0, 0.02);
}
/* Style inserted fields */
.field--FieldRootContainer[data-inserted='true'] {
background-color: var(--primary);
opacity: 0.2;
}
/* Style fields being validated */
.field--FieldRootContainer[data-validate='true'] {
border-color: orange;
}
```
### Example Usage
```css
/* Custom styles for the document widget */
.embed--DocumentWidget {
background-color: #ffffff;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}
/* Custom styles for the waiting screen */
.embed--WaitingForTurn {
background-color: #f9fafb;
padding: 2rem;
}
/* Responsive adjustments for the document container */
@media (min-width: 768px) {
.embed--DocumentContainer {
gap: 2rem;
}
}
```
## Related ## Related
- [React Integration](/developers/embedding/react) - [React Integration](/developers/embedding/react)

View File

@@ -5,7 +5,7 @@ description: Learn how to use embedding to bring signing to your own website or
# Embedding # Embedding
Our embedding feature lets you integrate our document signing experience into your own application or website. Whether you're building with React, Preact, Vue, Svelte, Solid, Angular, or using generalized web components, this guide will help you get started with embedding Documenso. Our embedding feature lets you integrate our document signing experience into your own application or website. Whether you're building with React, Preact, Vue, Svelte, Solid, or using generalized web components, this guide will help you get started with embedding Documenso.
## Availability ## Availability
@@ -52,9 +52,9 @@ Platform customers have access to advanced styling options to customize the embe
<EmbedDirectTemplate <EmbedDirectTemplate
token={token} token={token}
cssVars={{ cssVars={{
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}} }}
/> />
``` ```
@@ -73,15 +73,13 @@ These customization options are available for both Direct Templates and Signing
We support embedding across a range of popular JavaScript frameworks, including: We support embedding across a range of popular JavaScript frameworks, including:
| Framework | Package | | Framework | Package |
| --------- | ---------------------------------------------------------------------------------- | | --------- | -------------------------------------------------------------------------------- |
| React | [@documenso/embed-react](https://www.npmjs.com/package/@documenso/embed-react) | | React | [@documenso/embed-react](https://www.npmjs.com/package/@documenso/embed-react) |
| Preact | [@documenso/embed-preact](https://www.npmjs.com/package/@documenso/embed-preact) | | Preact | [@documenso/embed-preact](https://www.npmjs.com/package/@documenso/embed-preact) |
| Vue | [@documenso/embed-vue](https://www.npmjs.com/package/@documenso/embed-vue) | | Vue | [@documenso/embed-vue](https://www.npmjs.com/package/@documenso/embed-vue) |
| Svelte | [@documenso/embed-svelte](https://www.npmjs.com/package/@documenso/embed-svelte) | | Svelte | [@documenso/embed-svelte](https://www.npmjs.com/package/@documenso/embed-svelte) |
| Solid | [@documenso/embed-solid](https://www.npmjs.com/package/@documenso/embed-solid) | | Solid | [@documenso/embed-solid](https://www.npmjs.com/package/@documenso/embed-solid) |
| Angular | [@documenso/embed-angular](https://www.npmjs.com/package/@documenso/embed-angular) |
| Web Components | [@documenso/embed-webcomponent](https://www.npmjs.com/package/@documenso/embed-webcomponent) |
Additionally, we provide **web components** for more generalized use. However, please note that web components are still in their early stages and haven't been extensively tested. Additionally, we provide **web components** for more generalized use. However, please note that web components are still in their early stages and haven't been extensively tested.
@@ -129,7 +127,7 @@ This will show a dialog which will ask you to configure which recipient should b
## Embedding with Signing Tokens ## Embedding with Signing Tokens
To embed the signing process for an ordinary document, you'll need a **document signing token** for the recipient. This token provides the necessary access to load the document and facilitate the signing process securely. To embed the signing process for an ordinary document, youll need a **document signing token** for the recipient. This token provides the necessary access to load the document and facilitate the signing process securely.
#### Instructions #### Instructions
@@ -166,8 +164,6 @@ Once you've obtained the appropriate tokens, you can integrate the signing exper
- [Vue](/developers/embedding/vue) - [Vue](/developers/embedding/vue)
- [Svelte](/developers/embedding/svelte) - [Svelte](/developers/embedding/svelte)
- [Solid](/developers/embedding/solid) - [Solid](/developers/embedding/solid)
- [Angular](/developers/embedding/angular)
- [Web Components](/developers/embedding/web-components)
If you're using **web components**, the integration process is slightly different. Keep in mind that web components are currently less tested but can still provide flexibility for general use cases. If you're using **web components**, the integration process is slightly different. Keep in mind that web components are currently less tested but can still provide flexibility for general use cases.
@@ -178,6 +174,4 @@ If you're using **web components**, the integration process is slightly differen
- [Svelte Integration](/developers/embedding/svelte) - [Svelte Integration](/developers/embedding/svelte)
- [Solid Integration](/developers/embedding/solid) - [Solid Integration](/developers/embedding/solid)
- [Preact Integration](/developers/embedding/preact) - [Preact Integration](/developers/embedding/preact)
- [Angular Integration](/developers/embedding/angular)
- [Web Components](/developers/embedding/web-components)
- [CSS Variables](/developers/embedding/css-variables) - [CSS Variables](/developers/embedding/css-variables)

View File

@@ -95,9 +95,9 @@ const MyEmbeddingComponent = () => {
} }
`; `;
const cssVars = { const cssVars = {
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}; };
return ( return (

View File

@@ -99,9 +99,9 @@ const MyEmbeddingComponent = () => {
`} `}
// CSS Variables // CSS Variables
cssVars={{ cssVars={{
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}} }}
// Dark Mode Control // Dark Mode Control
darkModeDisabled={true} darkModeDisabled={true}

View File

@@ -95,9 +95,9 @@ const MyEmbeddingComponent = () => {
} }
`; `;
const cssVars = { const cssVars = {
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}; };
return ( return (

View File

@@ -97,9 +97,9 @@ Platform customers have access to advanced styling options:
} }
`; `;
const cssVars = { const cssVars = {
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}; };
</script> </script>

View File

@@ -97,9 +97,9 @@ Platform customers have access to advanced styling options:
} }
`; `;
const cssVars = { const cssVars = {
primary: '#0000FF', colorPrimary: '#0000FF',
background: '#F5F5F5', colorBackground: '#F5F5F5',
radius: '8px', borderRadius: '8px',
}; };
</script> </script>

View File

@@ -1,89 +0,0 @@
---
title: Web Components Integration
description: Learn how to use our embedding SDK via Web Components on a framework-less web application.
---
# Web Components Integration
Our Web Components SDK provides a simple way to embed a signing experience within your framework-less web application. It supports both direct link templates and signing tokens.
## Installation
To install the SDK, run the following command:
```bash
npm install @documenso/embed-webcomponent
```
Then in your html file, add the following to add the script, replacing the path with the proper path to the web component script.
```html
<script src="YOUR_PATH_HERE"></script>
```
## Usage
To embed a signing experience, you'll need to provide the token for the document you want to embed. This can be done in a few different ways, depending on your use case.
### Direct Link Template
If you have a direct link template, you can simply provide the token for the template to the `documenso-embed-direct-template` tag.
```html
<documenso-embed-direct-template
token="YOUR_TOKEN_HERE"
</documenso-embed-direct-template>
```
#### Attributes
| Attribute | Type | Description |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------ |
| token | string | The token for the document you want to embed |
| host | string (optional) | The host to be used for the signing experience, relevant for self-hosters |
| name | string (optional) | The name the signer that will be used by default for signing |
| lockName | boolean (optional) | Whether or not the name field should be locked disallowing modifications |
| email | string (optional) | The email the signer that will be used by default for signing |
| lockEmail | boolean (optional) | Whether or not the email field should be locked disallowing modifications |
| onDocumentReady | function (optional) | A callback function that will be called when the document is loaded and ready to be signed |
| onDocumentCompleted | function (optional) | A callback function that will be called when the document has been completed |
| onDocumentError | function (optional) | A callback function that will be called when an error occurs with the document |
| onFieldSigned | function (optional) | A callback function that will be called when a field is signed |
| onFieldUnsigned | function (optional) | A callback function that will be called when a field is unsigned |
### Signing Token
If you have a signing token, you can provide it to the `documenso-embed-sign-document` tag.
```html
<documenso-embed-sign-document
token="YOUR_TOKEN_HERE"
</documenso-embed-sign-document>
```
#### Attributes
| Attribute | Type | Description |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------ |
| token | string | The token for the document you want to embed |
| host | string (optional) | The host to be used for the signing experience, relevant for self-hosters |
| name | string (optional) | The name the signer that will be used by default for signing |
| lockName | boolean (optional) | Whether or not the name field should be locked disallowing modifications |
| onDocumentReady | function (optional) | A callback function that will be called when the document is loaded and ready to be signed |
| onDocumentCompleted | function (optional) | A callback function that will be called when the document has been completed |
| onDocumentError | function (optional) | A callback function that will be called when an error occurs with the document |
### Creating via JavaScript
You can also create the tag element using javascript, for dynamic generation of either modes. For example, this would add the sign document embed to the DOM.
```javascript
document.getElementById('my-wrapper-here').innerHTML = '';
const tag = document.createElement('documenso-embed-sign-document');
tag.setAttribute('token', data.token);
tag.style.width = '100%';
tag.style.height = '100%';
document.getElementById('my-wrapper-here').appendChild(tag);
```

View File

@@ -3,8 +3,6 @@ title: Public API
description: Learn how to interact with your documents programmatically using the Documenso public API. description: Learn how to interact with your documents programmatically using the Documenso public API.
--- ---
import { Callout, Steps } from 'nextra/components';
# Public API # Public API
Documenso provides a public REST API enabling you to interact with your documents programmatically. The API exposes various HTTP endpoints that allow you to perform operations such as: Documenso provides a public REST API enabling you to interact with your documents programmatically. The API exposes various HTTP endpoints that allow you to perform operations such as:
@@ -15,35 +13,10 @@ Documenso provides a public REST API enabling you to interact with your document
The documentation walks you through creating API keys and using them to authenticate your API requests. You'll also learn about the available endpoints, request and response formats, and how to use the API. The documentation walks you through creating API keys and using them to authenticate your API requests. You'll also learn about the available endpoints, request and response formats, and how to use the API.
## API V1 - Stable ## Swagger Documentation
Check out the [API V1 documentation](https://app.documenso.com/api/v1/openapi) for details about the API endpoints, request parameters, response formats, and authentication methods. The [Swagger documentation](https://app.documenso.com/api/v1/openapi) also provides information about the API endpoints, request parameters, response formats, and authentication methods.
## API V2 - Beta
<Callout type="warning">API V2 is currently beta, and will be subject to breaking changes</Callout>
Check out the [API V2 documentation](https://documen.so/api-v2-docs) for details about the API endpoints, request parameters, response formats, and authentication methods.
Our new API V2 supports the following typed SDKs:
- [TypeScript](https://github.com/documenso/sdk-typescript)
- [Python](https://github.com/documenso/sdk-python)
- [Go](https://github.com/documenso/sdk-go)
<Callout type="info">
For the staging API, please use the following base URL:
`https://stg-app.documenso.dev/api/v2-beta/`
</Callout>
🚀 [V2 Announcement](https://documen.so/sdk-blog)
📖 [Documentation](https://documen.so/api-v2-docs)
💬 [Leave Feedback](https://documen.so/sdk-feedback)
🔔 [Breaking Changes](https://documen.so/sdk-breaking)
## Availability ## Availability
The API is available to individual users, teams and higher plans. [Fair Use](https://documen.so/fair) applies. The API is available to individual users and teams.

View File

@@ -532,93 +532,3 @@ Replace the `text` value with the corresponding field type:
- For the `SELECT` field it should be `select`. (check this before merge) - For the `SELECT` field it should be `select`. (check this before merge)
You must pass this property at all times, even if you don't need to set any other properties. If you don't, the endpoint will throw an error. You must pass this property at all times, even if you don't need to set any other properties. If you don't, the endpoint will throw an error.
## Pre-fill Fields On Document Creation
The API allows you to pre-fill fields on document creation. This is useful when you want to create a document from an existing template and pre-fill the fields with specific values.
To pre-fill a field, you need to make a `POST` request to the `/api/v1/templates/{templateId}/generate-document` endpoint with the field information. Here's an example:
```json
{
"title": "my-document.pdf",
"recipients": [
{
"id": 3,
"name": "Example User",
"email": "example@documenso.com",
"signingOrder": 1,
"role": "SIGNER"
}
],
"prefillFields": [
{
"id": 21,
"type": "text",
"label": "my-label",
"placeholder": "my-placeholder",
"value": "my-value"
},
{
"id": 22,
"type": "number",
"label": "my-label",
"placeholder": "my-placeholder",
"value": "123"
},
{
"id": 23,
"type": "checkbox",
"label": "my-label",
"placeholder": "my-placeholder",
"value": ["option-1", "option-2"]
}
]
}
```
Check out the endpoint in the [API V1 documentation](https://app.documenso.com/api/v1/openapi#:~:text=/%7BtemplateId%7D/-,generate,-%2Ddocument).
### API V2
For API V2, you need to make a `POST` request to the `/api/v2-beta/template/use` endpoint with the field(s) information. Here's an example:
```json
{
"templateId": 111,
"recipients": [
{
"id": 3,
"name": "Example User",
"email": "example@documenso.com",
"signingOrder": 1,
"role": "SIGNER"
}
],
"prefillFields": [
{
"id": 21,
"type": "text",
"label": "my-label",
"placeholder": "my-placeholder",
"value": "my-value"
},
{
"id": 22,
"type": "number",
"label": "my-label",
"placeholder": "my-placeholder",
"value": "123"
},
{
"id": 23,
"type": "checkbox",
"label": "my-label",
"placeholder": "my-placeholder",
"value": ["option-1", "option-2"]
}
]
}
```
Check out the endpoint in the [API V2 documentation](https://openapi.documenso.com/reference#tag/template/POST/template/use).

View File

@@ -21,7 +21,6 @@ Documenso supports Webhooks and allows you to subscribe to the following events:
- `document.signed` - `document.signed`
- `document.completed` - `document.completed`
- `document.rejected` - `document.rejected`
- `document.cancelled`
## Create a webhook subscription ## Create a webhook subscription
@@ -38,7 +37,7 @@ Clicking on the "**Create Webhook**" button opens a modal to create a new webhoo
To create a new webhook subscription, you need to provide the following information: To create a new webhook subscription, you need to provide the following information:
- Enter the webhook URL that will receive the event payload. - Enter the webhook URL that will receive the event payload.
- Select the event(s) you want to subscribe to: `document.created`, `document.sent`, `document.opened`, `document.signed`, `document.completed`, `document.rejected`, `document.cancelled`. - Select the event(s) you want to subscribe to: `document.created`, `document.sent`, `document.opened`, `document.signed`, `document.completed`, `document.rejected`.
- Optionally, you can provide a secret key that will be used to sign the payload. This key will be included in the `X-Documenso-Secret` header of the request. - Optionally, you can provide a secret key that will be used to sign the payload. This key will be included in the `X-Documenso-Secret` header of the request.
![A screenshot of the Create Webhook modal that shows the URL input field and the event checkboxes](/webhook-images/webhooks-page-create-webhook-modal.webp) ![A screenshot of the Create Webhook modal that shows the URL input field and the event checkboxes](/webhook-images/webhooks-page-create-webhook-modal.webp)
@@ -529,96 +528,6 @@ Example payload for the `document.rejected` event:
} }
``` ```
Example payload for the `document.rejected` event:
```json
{
"event": "DOCUMENT_CANCELLED",
"payload": {
"id": 7,
"externalId": null,
"userId": 3,
"authOptions": null,
"formValues": null,
"visibility": "EVERYONE",
"title": "documenso.pdf",
"status": "PENDING",
"documentDataId": "cm6exvn93006hi02ru90a265a",
"createdAt": "2025-01-27T11:02:14.393Z",
"updatedAt": "2025-01-27T11:03:16.387Z",
"completedAt": null,
"deletedAt": null,
"teamId": null,
"templateId": null,
"source": "DOCUMENT",
"documentMeta": {
"id": "cm6exvn96006ji02rqvzjvwoy",
"subject": "",
"message": "",
"timezone": "Etc/UTC",
"password": null,
"dateFormat": "yyyy-MM-dd hh:mm a",
"redirectUrl": "",
"signingOrder": "PARALLEL",
"typedSignatureEnabled": true,
"language": "en",
"distributionMethod": "EMAIL",
"emailSettings": {
"documentDeleted": true,
"documentPending": true,
"recipientSigned": true,
"recipientRemoved": true,
"documentCompleted": true,
"ownerDocumentCompleted": true,
"recipientSigningRequest": true
}
},
"recipients": [
{
"id": 7,
"documentId": 7,
"templateId": null,
"email": "mybirihix@mailinator.com",
"name": "Zorita Baird",
"token": "XkKx1HCs6Znm2UBJA2j6o",
"documentDeletedAt": null,
"expired": null,
"signedAt": null,
"authOptions": { "accessAuth": null, "actionAuth": null },
"signingOrder": 1,
"rejectionReason": null,
"role": "SIGNER",
"readStatus": "NOT_OPENED",
"signingStatus": "NOT_SIGNED",
"sendStatus": "SENT"
}
],
"Recipient": [
{
"id": 7,
"documentId": 7,
"templateId": null,
"email": "signer@documenso.com",
"name": "Signer",
"token": "XkKx1HCs6Znm2UBJA2j6o",
"documentDeletedAt": null,
"expired": null,
"signedAt": null,
"authOptions": { "accessAuth": null, "actionAuth": null },
"signingOrder": 1,
"rejectionReason": null,
"role": "SIGNER",
"readStatus": "NOT_OPENED",
"signingStatus": "NOT_SIGNED",
"sendStatus": "SENT"
}
]
},
"createdAt": "2025-01-27T11:03:27.730Z",
"webhookEndpoint": "https://mywebhooksite.com/mywebhook"
}
```
## Availability ## Availability
Webhooks are available to individual users and teams. Webhooks are available to individual users and teams.

View File

@@ -85,13 +85,12 @@ You can also set the recipient's role, which determines their actions and permis
Documenso has 4 roles for recipients with different permissions and actions. Documenso has 4 roles for recipients with different permissions and actions.
| Role | Function | Action required | Signature | | Role | Function | Action required | Signature |
| :-------: | :-----------------------------------------------------------------------------: | :-------------: | :-------: | | :------: | :-----------------------------------------------------------------------------: | :-------------: | :-------: |
| Signer | Needs to sign signatures fields assigned to them. | Yes | Yes | | Signer | Needs to sign signatures fields assigned to them. | Yes | Yes |
| Approver | Needs to approve the document as a whole. Signature optional. | Yes | Optional | | Approver | Needs to approve the document as a whole. Signature optional. | Yes | Optional |
| Viewer | Needs to confirm they viewed the document. | Yes | No | | Viewer | Needs to confirm they viewed the document. | Yes | No |
| Assistant | Can help prepare the document by filling in fields on behalf of other signers. | Yes | No | | BCC | Receives a copy of the signed document after completion. No action is required. | No | No |
| CC | Receives a copy of the signed document after completion. No action is required. | No | No |
### Fields ### Fields

View File

@@ -16,8 +16,8 @@
"next": "14.2.6" "next": "14.2.6"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^20", "@types/node": "20.16.5",
"@types/react": "18.3.5", "@types/react": "18.3.5",
"typescript": "5.6.2" "typescript": "5.5.4"
} }
} }

4
apps/remix/.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
.react-router
build
node_modules
README.md

9
apps/remix/.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
.DS_Store
/node_modules/
# React Router
/.react-router/
/build/
# Vite
vite.config.ts.timestamp*

22
apps/remix/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:20-alpine AS development-dependencies-env
COPY . /app
WORKDIR /app
RUN npm ci
FROM node:20-alpine AS production-dependencies-env
COPY ./package.json package-lock.json /app/
WORKDIR /app
RUN npm ci --omit=dev
FROM node:20-alpine AS build-env
COPY . /app/
COPY --from=development-dependencies-env /app/node_modules /app/node_modules
WORKDIR /app
RUN npm run build
FROM node:20-alpine
COPY ./package.json package-lock.json /app/
COPY --from=production-dependencies-env /app/node_modules /app/node_modules
COPY --from=build-env /app/build /app/build
WORKDIR /app
CMD ["npm", "run", "start"]

25
apps/remix/Dockerfile.bun Normal file
View File

@@ -0,0 +1,25 @@
FROM oven/bun:1 AS dependencies-env
COPY . /app
FROM dependencies-env AS development-dependencies-env
COPY ./package.json bun.lockb /app/
WORKDIR /app
RUN bun i --frozen-lockfile
FROM dependencies-env AS production-dependencies-env
COPY ./package.json bun.lockb /app/
WORKDIR /app
RUN bun i --production
FROM dependencies-env AS build-env
COPY ./package.json bun.lockb /app/
COPY --from=development-dependencies-env /app/node_modules /app/node_modules
WORKDIR /app
RUN bun run build
FROM dependencies-env
COPY ./package.json bun.lockb /app/
COPY --from=production-dependencies-env /app/node_modules /app/node_modules
COPY --from=build-env /app/build /app/build
WORKDIR /app
CMD ["bun", "run", "start"]

View File

@@ -0,0 +1,26 @@
FROM node:20-alpine AS dependencies-env
RUN npm i -g pnpm
COPY . /app
FROM dependencies-env AS development-dependencies-env
COPY ./package.json pnpm-lock.yaml /app/
WORKDIR /app
RUN pnpm i --frozen-lockfile
FROM dependencies-env AS production-dependencies-env
COPY ./package.json pnpm-lock.yaml /app/
WORKDIR /app
RUN pnpm i --prod --frozen-lockfile
FROM dependencies-env AS build-env
COPY ./package.json pnpm-lock.yaml /app/
COPY --from=development-dependencies-env /app/node_modules /app/node_modules
WORKDIR /app
RUN pnpm build
FROM dependencies-env
COPY ./package.json pnpm-lock.yaml /app/
COPY --from=production-dependencies-env /app/node_modules /app/node_modules
COPY --from=build-env /app/build /app/build
WORKDIR /app
CMD ["pnpm", "start"]

100
apps/remix/README.md Normal file
View File

@@ -0,0 +1,100 @@
# Welcome to React Router!
A modern, production-ready template for building full-stack React applications using React Router.
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/remix-run/react-router-templates/tree/main/default)
## Features
- 🚀 Server-side rendering
- ⚡️ Hot Module Replacement (HMR)
- 📦 Asset bundling and optimization
- 🔄 Data loading and mutations
- 🔒 TypeScript by default
- 🎉 TailwindCSS for styling
- 📖 [React Router docs](https://reactrouter.com/)
## Getting Started
### Installation
Install the dependencies:
```bash
npm install
```
### Development
Start the development server with HMR:
```bash
npm run dev
```
Your application will be available at `http://localhost:5173`.
## Building for Production
Create a production build:
```bash
npm run build
```
## Deployment
### Docker Deployment
This template includes three Dockerfiles optimized for different package managers:
- `Dockerfile` - for npm
- `Dockerfile.pnpm` - for pnpm
- `Dockerfile.bun` - for bun
To build and run using Docker:
```bash
# For npm
docker build -t my-app .
# For pnpm
docker build -f Dockerfile.pnpm -t my-app .
# For bun
docker build -f Dockerfile.bun -t my-app .
# Run the container
docker run -p 3000:3000 my-app
```
The containerized application can be deployed to any platform that supports Docker, including:
- AWS ECS
- Google Cloud Run
- Azure Container Apps
- Digital Ocean App Platform
- Fly.io
- Railway
### DIY Deployment
If you're familiar with deploying Node applications, the built-in app server is production-ready.
Make sure to deploy the output of `npm run build`
```
├── package.json
├── package-lock.json (or pnpm-lock.yaml, or bun.lockb)
├── build/
│ ├── client/ # Static assets
│ └── server/ # Server-side code
```
## Styling
This template comes with [Tailwind CSS](https://tailwindcss.com/) already configured for a simple default starting experience. You can use whatever CSS framework you prefer.
---
Built with ❤️ using React Router.

1
apps/remix/app/app.css Normal file
View File

@@ -0,0 +1 @@
@import '@documenso/ui/styles/theme.css';

View File

@@ -0,0 +1,13 @@
import { twoFactor } from 'better-auth/plugins';
import { createAuthClient } from 'better-auth/react';
import { passkeyClientPlugin } from './auth/passkey-plugin/client';
// make sure to import from better-auth/react
export const authClient = createAuthClient({
baseURL: 'http://localhost:3000',
plugins: [twoFactor(), passkeyClientPlugin()],
});
export const { signIn, signOut, useSession } = authClient;

View File

@@ -0,0 +1,112 @@
import { compare, hash } from '@node-rs/bcrypt';
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { twoFactor } from 'better-auth/plugins';
import { getAuthenticatorOptions } from '@documenso/lib/utils/authenticator';
import { prisma } from '@documenso/prisma';
import { passkeyPlugin } from './auth/passkey-plugin';
// todo: import from @documenso/lib/constants/auth
export const SALT_ROUNDS = 12;
const passkeyOptions = getAuthenticatorOptions();
export const auth = betterAuth({
appName: 'Documenso',
plugins: [
twoFactor({
issuer: 'Documenso',
skipVerificationOnEnable: true,
// totpOptions: {
// },
schema: {
twoFactor: {
modelName: 'TwoFactor',
fields: {
userId: 'userId',
secret: 'secret',
backupCodes: 'backupCodes',
},
},
},
// todo: add options
}),
passkeyPlugin(),
// passkey({
// rpID: passkeyOptions.rpId,
// rpName: passkeyOptions.rpName,
// origin: passkeyOptions.origin,
// schema: {
// passkey: {
// fields: {
// publicKey: 'credentialPublicKey',
// credentialID: 'credentialId',
// deviceType: 'credentialDeviceType',
// backedUp: 'credentialBackedUp',
// // transports: '',
// },
// },
// },
// }),
],
secret: 'secret', // todo
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
databaseHooks: {
account: {
create: {
before: (session) => {
return {
data: {
...session,
accountId: session.accountId.toString(),
},
};
},
},
},
},
session: {
fields: {
token: 'sessionToken',
expiresAt: 'expires',
},
},
user: {
fields: {
emailVerified: 'isEmailVerified',
},
},
account: {
fields: {
providerId: 'provider',
accountId: 'providerAccountId',
refreshToken: 'refresh_token',
accessToken: 'access_token',
idToken: 'id_token',
},
},
advanced: {
generateId: false,
},
socialProviders: {
google: {
clientId: '',
clientSecret: '',
},
},
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
// maxPasswordLength: 128,
// minPasswordLength: 8,
password: {
hash: async (password) => hash(password, SALT_ROUNDS),
verify: async ({ hash, password }) => compare(password, hash),
},
},
});

View File

@@ -0,0 +1,24 @@
import type { BetterAuthClientPlugin } from 'better-auth';
import type { passkeyPlugin } from './index';
type PasskeyPlugin = typeof passkeyPlugin;
export const passkeyClientPlugin = () => {
const passkeySignin = () => {
//
// credential: JSON.stringify(credential),
// callbackUrl,
};
return {
id: 'passkeyPlugin',
getActions: () => ({
signIn: {
passkey: () => passkeySignin,
},
}),
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
$InferServerPlugin: {} as ReturnType<PasskeyPlugin>,
} satisfies BetterAuthClientPlugin;
};

View File

@@ -0,0 +1,165 @@
import type { BetterAuthPlugin } from 'better-auth';
import { createAuthEndpoint, createAuthMiddleware } from 'better-auth/plugins';
export const passkeyPlugin = () =>
({
id: 'passkeyPlugin',
schema: {
user: {
fields: {
// twoFactorEnabled: {
// type: 'boolean',
// required: false,
// },
// twoFactorBackupCodes: {
// type: 'string',
// required: false,
// },
// twoFactorSecret: {
// type: 'string',
// required: false,
// },
// birthday: {
// type: 'date', // string, number, boolean, date
// required: true, // if the field should be required on a new record. (default: false)
// unique: false, // if the field should be unique. (default: false)
// reference: null, // if the field is a reference to another table. (default: null)
// },
},
},
},
endpoints: {
authorize: createAuthEndpoint(
'/passkey/authorize',
{
method: 'POST',
// use: [],
},
async (ctx) => {
const csrfToken = credentials?.csrfToken;
if (typeof csrfToken !== 'string' || csrfToken.length === 0) {
throw new AppError(AppErrorCode.INVALID_REQUEST);
}
let requestBodyCrediential: TAuthenticationResponseJSONSchema | null = null;
try {
const parsedBodyCredential = JSON.parse(req.body?.credential);
requestBodyCrediential = ZAuthenticationResponseJSONSchema.parse(parsedBodyCredential);
} catch {
throw new AppError(AppErrorCode.INVALID_REQUEST);
}
const challengeToken = await prisma.anonymousVerificationToken
.delete({
where: {
id: csrfToken,
},
})
.catch(() => null);
if (!challengeToken) {
return null;
}
if (challengeToken.expiresAt < new Date()) {
throw new AppError(AppErrorCode.EXPIRED_CODE);
}
const passkey = await prisma.passkey.findFirst({
where: {
credentialId: Buffer.from(requestBodyCrediential.id, 'base64'),
},
include: {
User: {
select: {
id: true,
email: true,
name: true,
emailVerified: true,
},
},
},
});
if (!passkey) {
throw new AppError(AppErrorCode.NOT_SETUP);
}
const user = passkey.User;
const { rpId, origin } = getAuthenticatorOptions();
const verification = await verifyAuthenticationResponse({
response: requestBodyCrediential,
expectedChallenge: challengeToken.token,
expectedOrigin: origin,
expectedRPID: rpId,
authenticator: {
credentialID: new Uint8Array(Array.from(passkey.credentialId)),
credentialPublicKey: new Uint8Array(passkey.credentialPublicKey),
counter: Number(passkey.counter),
},
}).catch(() => null);
const requestMetadata = extractNextAuthRequestMetadata(req);
if (!verification?.verified) {
await prisma.userSecurityAuditLog.create({
data: {
userId: user.id,
ipAddress: requestMetadata.ipAddress,
userAgent: requestMetadata.userAgent,
type: UserSecurityAuditLogType.SIGN_IN_PASSKEY_FAIL,
},
});
return null;
}
await prisma.passkey.update({
where: {
id: passkey.id,
},
data: {
lastUsedAt: new Date(),
counter: verification.authenticationInfo.newCounter,
},
});
return {
id: Number(user.id),
email: user.email,
name: user.name,
emailVerified: user.emailVerified?.toISOString() ?? null,
} satisfies User;
},
),
},
hooks: {
before: [
{
matcher: (context) => context.path.startsWith('/sign-in/email'),
handler: createAuthMiddleware(async (ctx) => {
console.log('here...');
const { birthday } = ctx.body;
if ((!birthday) instanceof Date) {
throw new APIError('BAD_REQUEST', { message: 'Birthday must be of type Date.' });
}
const today = new Date();
const fiveYearsAgo = new Date(today.setFullYear(today.getFullYear() - 5));
if (birthday >= fiveYearsAgo) {
throw new APIError('BAD_REQUEST', { message: 'User must be above 5 years old.' });
}
return { context: ctx };
}),
},
],
},
}) satisfies BetterAuthPlugin;

74
apps/remix/app/root.tsx Normal file
View File

@@ -0,0 +1,74 @@
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
isRouteErrorResponse,
} from 'react-router';
import type { Route } from './+types/root';
import stylesheet from './app.css?url';
export const links: Route.LinksFunction = () => [
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' },
{
rel: 'preconnect',
href: 'https://fonts.gstatic.com',
crossOrigin: 'anonymous',
},
{
rel: 'stylesheet',
href: 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap',
},
{ rel: 'stylesheet', href: stylesheet },
];
export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}
export default function App() {
return <Outlet />;
}
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
let message = 'Oops!';
let details = 'An unexpected error occurred.';
let stack: string | undefined;
if (isRouteErrorResponse(error)) {
message = error.status === 404 ? '404' : 'Error';
details =
error.status === 404 ? 'The requested page could not be found.' : error.statusText || details;
} else if (import.meta.env.DEV && error && error instanceof Error) {
details = error.message;
stack = error.stack;
}
return (
<main className="container mx-auto p-4 pt-16">
<h1>{message}</h1>
<p>{details}</p>
{stack && (
<pre className="w-full overflow-x-auto p-4">
<code>{stack}</code>
</pre>
)}
</main>
);
}

4
apps/remix/app/routes.ts Normal file
View File

@@ -0,0 +1,4 @@
import { type RouteConfig } from '@react-router/dev/routes';
import { flatRoutes } from '@react-router/fs-routes';
export default flatRoutes() satisfies RouteConfig;

View File

@@ -0,0 +1,193 @@
import { useState } from 'react';
import { Button } from '@documenso/ui/primitives/button';
import { authClient, signOut, useSession } from '~/lib/auth-client';
import { auth } from '~/lib/auth.server';
import type { Route } from '../+types/root';
export function meta({}: Route.MetaArgs) {
return [
{ title: 'New React Router App' },
{ name: 'description', content: 'Welcome to React Router!' },
];
}
export async function loader({ params, request, context }: Route.LoaderArgs) {
const session = await auth.api.getSession({
query: {
disableCookieCache: true,
},
headers: request.headers, // pass the headers
});
return {
session,
};
}
export function clientLoader({ params }: Route.ClientLoaderArgs) {
return {
session: authClient.getSession(),
};
}
export default function Home({ loaderData }: Route.ComponentProps) {
const { data } = useSession();
const [email, setEmail] = useState('deepfriedcoconut@gmail.com');
const [password, setPassword] = useState('password');
const signIn = async () => {
await authClient.signIn.email(
{
email,
password,
},
{
onRequest: (ctx) => {
// show loading state
},
onSuccess: (ctx) => {
console.log('success');
// redirect to home
},
onError: (ctx) => {
console.log(ctx.error);
alert(ctx.error);
},
},
);
};
const signUp = async () => {
await authClient.signUp.email(
{
email,
password,
name: '',
},
{
onRequest: (ctx) => {
// show loading state
},
onSuccess: (ctx) => {
console.log(ctx);
// redirect to home
},
onError: (ctx) => {
console.log(ctx.error);
alert(ctx.error);
},
},
);
};
return (
<main className="flex flex-col items-center justify-center pb-4 pt-16">
<h1>Status: {data ? 'Authenticated' : 'Not Authenticated'}</h1>
{data ? (
<>
<div>
<p>Session data</p>
<p className="mt-2 max-w-2xl text-xs">{JSON.stringify(data, null, 2)}</p>
</div>
<div className="space-x-2">
<Button
onClick={() => {
authClient.twoFactor
.enable({
password: 'password', // user password required
})
.catch((e) => {
console.log(e);
});
}}
>
Enable 2FA
</Button>
<Button
variant="destructive"
onClick={() => {
authClient.twoFactor.disable({
password: 'password',
});
}}
>
Disable 2FA
</Button>
</div>
<button onClick={() => signOut()}>signout</button>
</>
) : (
<>
<div className="">
<h2>Sign In</h2>
<input
className="border border-blue-500"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
className="border border-blue-500"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" onClick={signIn}>
Sign In
</button>
</div>
<div className="mt-8">
<h2>Sign Up</h2>
<input
type="email"
className="border border-blue-500"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
className="border border-blue-500"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit" onClick={signUp}>
Sign Up
</button>
</div>
<button
onClick={() => {
authClient.signIn.social({
provider: 'google',
});
}}
>
google
</button>
<button
onClick={async () => {
const response = await authClient.signIn.passkey();
console.log(response);
}}
>
passkey
</button>
</>
)}
</main>
);
}

View File

@@ -0,0 +1,12 @@
// Adjust the path as necessary
import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node';
import { auth } from '~/lib/auth.server';
export function loader({ request }: LoaderFunctionArgs) {
return auth.handler(request);
}
export function action({ request }: ActionFunctionArgs) {
return auth.handler(request);
}

View File

@@ -0,0 +1,40 @@
import { useState } from 'react';
import { authClient } from '~/lib/auth-client';
export default function SignIn() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const signIn = async () => {
await authClient.signIn.email(
{
email,
password,
},
{
onRequest: (ctx) => {
// show loading state
},
onSuccess: (ctx) => {
// redirect to home
},
onError: (ctx) => {
alert(ctx.error);
},
},
);
};
return (
<div>
<h2>Sign In</h2>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit" onClick={signIn}>
Sign In
</button>
</div>
);
}

43
apps/remix/package.json Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "@documenso/remix",
"type": "module",
"private": true,
"scripts": {
"build": "cross-env NODE_ENV=production react-router build",
"dev": "tsx watch --ignore \"vite.config.ts*\" server/main.ts",
"start": "cross-env NODE_ENV=production node dist/server/index.js",
"typecheck": "react-router typegen && tsc"
},
"dependencies": {
"@documenso/api": "*",
"@documenso/assets": "*",
"@documenso/ee": "*",
"@documenso/lib": "*",
"@documenso/prisma": "*",
"@documenso/trpc": "*",
"@documenso/ui": "*",
"@epic-web/remember": "^1.1.0",
"@hono/node-server": "^1.13.7",
"@react-router/fs-routes": "^7.1.1",
"@react-router/node": "^7.1.1",
"@react-router/serve": "^7.1.1",
"better-auth": "^1.1.9",
"hono": "^4.6.15",
"isbot": "^5.1.17",
"react": "^18",
"react-dom": "^18",
"react-router": "^7.1.1",
"remix-hono": "^0.0.18"
},
"devDependencies": {
"@react-router/dev": "^7.1.1",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"cross-env": "^7.0.3",
"tsx": "^4.11.0",
"typescript": "5.7.2",
"vite": "^5.4.11",
"vite-tsconfig-paths": "^5.1.4"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,7 @@
import type { Config } from '@react-router/dev/config';
export default {
appDirectory: 'app',
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
} satisfies Config;

45
apps/remix/server/app.ts Normal file
View File

@@ -0,0 +1,45 @@
import { remember } from '@epic-web/remember';
import { type HttpBindings } from '@hono/node-server';
import { Hono } from 'hono';
import { reactRouter } from 'remix-hono/handler';
type Bindings = HttpBindings;
const app = new Hono<{ Bindings: Bindings }>();
const isProduction = process.env.NODE_ENV === 'production';
const viteDevServer = isProduction
? undefined
: await import('vite').then(async (vite) =>
vite.createServer({
server: { middlewareMode: true },
}),
);
const reactRouterMiddleware = remember('reactRouterMiddleware', async () =>
reactRouter({
mode: isProduction ? 'production' : 'development',
build: isProduction
? // @ts-expect-error build/server/index.js is a build artifact
await import('../build/server/index.js')
: async () => viteDevServer!.ssrLoadModule('virtual:react-router/server-build'),
}),
);
// app.get('/', (c) => c.text('Hello, world!'));
if (viteDevServer) {
app.use('*', async (c, next) => {
return new Promise((resolve) => {
viteDevServer.middlewares(c.env.incoming, c.env.outgoing, () => resolve(next()));
});
});
}
app.use('*', async (c, next) => {
const middleware = await reactRouterMiddleware;
return middleware(c, next);
});
export default app;

View File

@@ -0,0 +1,7 @@
import { serve } from '@hono/node-server';
import app from './app';
serve(app, (info) => {
console.log(`Server is running on http://localhost:${info.port}`);
});

View File

@@ -0,0 +1,18 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const baseConfig = require('@documenso/tailwind-config');
const path = require('path');
module.exports = {
...baseConfig,
content: [
...baseConfig.content,
'./app/**/*.{ts,tsx}',
`${path.join(require.resolve('@documenso/ui'), '..')}/components/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/ui'), '..')}/icons/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/ui'), '..')}/lib/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/ui'), '..')}/primitives/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/email'), '..')}/templates/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/email'), '..')}/template-components/**/*.{ts,tsx}`,
`${path.join(require.resolve('@documenso/email'), '..')}/providers/**/*.{ts,tsx}`,
],
};

27
apps/remix/tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"include": [
"**/*",
"**/.server/**/*",
"**/.client/**/*",
".react-router/types/**/*"
],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["node", "vite/client"],
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"rootDirs": [".", "./.react-router/types"],
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true
}
}

17
apps/remix/vite.config.ts Normal file
View File

@@ -0,0 +1,17 @@
import { reactRouter } from '@react-router/dev/vite';
import autoprefixer from 'autoprefixer';
import tailwindcss from 'tailwindcss';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
css: {
postcss: {
plugins: [tailwindcss, autoprefixer],
},
},
plugins: [reactRouter(), tsconfigPaths()],
optimizeDeps: {
exclude: ['@node-rs/bcrypt'],
},
});

View File

@@ -1,6 +1,6 @@
{ {
"name": "@documenso/web", "name": "@documenso/web",
"version": "1.9.1-rc.9", "version": "1.9.0-rc.5",
"private": true, "private": true,
"license": "AGPL-3.0", "license": "AGPL-3.0",
"scripts": { "scripts": {
@@ -26,6 +26,7 @@
"@lingui/react": "^4.11.3", "@lingui/react": "^4.11.3",
"@simplewebauthn/browser": "^9.0.1", "@simplewebauthn/browser": "^9.0.1",
"@simplewebauthn/server": "^9.0.3", "@simplewebauthn/server": "^9.0.3",
"@tanstack/react-query": "^4.29.5",
"colord": "^2.9.3", "colord": "^2.9.3",
"cookie-es": "^1.0.0", "cookie-es": "^1.0.0",
"formidable": "^2.1.1", "formidable": "^2.1.1",
@@ -54,7 +55,7 @@
"recharts": "^2.7.2", "recharts": "^2.7.2",
"remeda": "^2.17.3", "remeda": "^2.17.3",
"sharp": "0.32.6", "sharp": "0.32.6",
"trpc-to-openapi": "2.0.4", "trpc-openapi": "^1.2.0",
"ts-pattern": "^5.0.5", "ts-pattern": "^5.0.5",
"ua-parser-js": "^1.0.37", "ua-parser-js": "^1.0.37",
"uqr": "^0.1.2", "uqr": "^0.1.2",
@@ -67,11 +68,11 @@
"@simplewebauthn/types": "^9.0.1", "@simplewebauthn/types": "^9.0.1",
"@types/formidable": "^2.0.6", "@types/formidable": "^2.0.6",
"@types/luxon": "^3.3.1", "@types/luxon": "^3.3.1",
"@types/node": "^20", "@types/node": "20.1.0",
"@types/papaparse": "^5.3.14", "@types/papaparse": "^5.3.14",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"@types/ua-parser-js": "^0.7.39", "@types/ua-parser-js": "^0.7.39",
"typescript": "5.6.2" "typescript": "5.7.2"
} }
} }

View File

@@ -28,7 +28,7 @@ export const AdminActions = ({ className, document, recipients }: AdminActionsPr
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
const { mutate: resealDocument, isPending: isResealDocumentLoading } = const { mutate: resealDocument, isLoading: isResealDocumentLoading } =
trpc.admin.resealDocument.useMutation({ trpc.admin.resealDocument.useMutation({
onSuccess: () => { onSuccess: () => {
toast({ toast({

View File

@@ -59,7 +59,7 @@ export default async function AdminDocumentDetailsPage({ params }: AdminDocument
<Trans>Admin Actions</Trans> <Trans>Admin Actions</Trans>
</h2> </h2>
<AdminActions className="mt-2" document={document} recipients={document.recipients} /> <AdminActions className="mt-2" document={document} recipients={document.Recipient} />
<hr className="my-4" /> <hr className="my-4" />
<h2 className="text-lg font-semibold"> <h2 className="text-lg font-semibold">
@@ -68,7 +68,7 @@ export default async function AdminDocumentDetailsPage({ params }: AdminDocument
<div className="mt-4"> <div className="mt-4">
<Accordion type="multiple" className="space-y-4"> <Accordion type="multiple" className="space-y-4">
{document.recipients.map((recipient) => ( {document.Recipient.map((recipient) => (
<AccordionItem <AccordionItem
key={recipient.id} key={recipient.id}
value={recipient.id.toString()} value={recipient.id.toString()}

View File

@@ -39,9 +39,9 @@ type TAdminUpdateRecipientFormSchema = z.infer<typeof ZAdminUpdateRecipientFormS
export type RecipientItemProps = { export type RecipientItemProps = {
recipient: Recipient & { recipient: Recipient & {
fields: Array< Field: Array<
Field & { Field & {
signature: Signature | null; Signature: Signature | null;
} }
>; >;
}; };
@@ -89,13 +89,13 @@ export const RecipientItem = ({ recipient }: RecipientItemProps) => {
accessorKey: 'signature', accessorKey: 'signature',
cell: ({ row }) => ( cell: ({ row }) => (
<div> <div>
{row.original.signature?.typedSignature && ( {row.original.Signature?.typedSignature && (
<span>{row.original.signature.typedSignature}</span> <span>{row.original.Signature.typedSignature}</span>
)} )}
{row.original.signature?.signatureImageAsBase64 && ( {row.original.Signature?.signatureImageAsBase64 && (
<img <img
src={row.original.signature.signatureImageAsBase64} src={row.original.Signature.signatureImageAsBase64}
alt="Signature" alt="Signature"
className="h-12 w-full dark:invert" className="h-12 w-full dark:invert"
/> />
@@ -103,7 +103,7 @@ export const RecipientItem = ({ recipient }: RecipientItemProps) => {
</div> </div>
), ),
}, },
] satisfies DataTableColumnDef<(typeof recipient)['fields'][number]>[]; ] satisfies DataTableColumnDef<(typeof recipient)['Field'][number]>[];
}, []); }, []);
const onUpdateRecipientFormSubmit = async ({ name, email }: TAdminUpdateRecipientFormSchema) => { const onUpdateRecipientFormSubmit = async ({ name, email }: TAdminUpdateRecipientFormSchema) => {
@@ -190,7 +190,7 @@ export const RecipientItem = ({ recipient }: RecipientItemProps) => {
<Trans>Fields</Trans> <Trans>Fields</Trans>
</h2> </h2>
<DataTable columns={columns} data={recipient.fields} /> <DataTable columns={columns} data={recipient.Field} />
</div> </div>
); );
}; };

View File

@@ -8,6 +8,7 @@ import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react'; import { useLingui } from '@lingui/react';
import type { Document } from '@documenso/prisma/client'; import type { Document } from '@documenso/prisma/client';
import { TRPCClientError } from '@documenso/trpc/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert'; import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button'; import { Button } from '@documenso/ui/primitives/button';
@@ -35,7 +36,7 @@ export const SuperDeleteDocumentDialog = ({ document }: SuperDeleteDocumentDialo
const [reason, setReason] = useState(''); const [reason, setReason] = useState('');
const { mutateAsync: deleteDocument, isPending: isDeletingDocument } = const { mutateAsync: deleteDocument, isLoading: isDeletingDocument } =
trpc.admin.deleteDocument.useMutation(); trpc.admin.deleteDocument.useMutation();
const handleDeleteDocument = async () => { const handleDeleteDocument = async () => {
@@ -54,12 +55,21 @@ export const SuperDeleteDocumentDialog = ({ document }: SuperDeleteDocumentDialo
router.push('/admin/documents'); router.push('/admin/documents');
} catch (err) { } catch (err) {
toast({ if (err instanceof TRPCClientError && err.data?.code === 'BAD_REQUEST') {
title: _(msg`An unknown error occurred`), toast({
variant: 'destructive', title: _(msg`An error occurred`),
description: description: err.message,
'We encountered an unknown error while attempting to delete your document. Please try again later.', variant: 'destructive',
}); });
} else {
toast({
title: _(msg`An unknown error occurred`),
variant: 'destructive',
description:
err.message ??
'We encountered an unknown error while attempting to delete your document. Please try again later.',
});
}
} }
}; };
@@ -67,7 +77,7 @@ export const SuperDeleteDocumentDialog = ({ document }: SuperDeleteDocumentDialo
<div> <div>
<div> <div>
<Alert <Alert
className="flex flex-col items-center justify-between gap-4 p-6 md:flex-row" className="flex flex-col items-center justify-between gap-4 p-6 md:flex-row "
variant="neutral" variant="neutral"
> >
<div> <div>

View File

@@ -37,7 +37,7 @@ export const AdminDocumentResults = () => {
const page = searchParams?.get?.('page') ? Number(searchParams.get('page')) : undefined; const page = searchParams?.get?.('page') ? Number(searchParams.get('page')) : undefined;
const perPage = searchParams?.get?.('perPage') ? Number(searchParams.get('perPage')) : undefined; const perPage = searchParams?.get?.('perPage') ? Number(searchParams.get('perPage')) : undefined;
const { data: findDocumentsData, isPending: isFindDocumentsLoading } = const { data: findDocumentsData, isLoading: isFindDocumentsLoading } =
trpc.admin.findDocuments.useQuery( trpc.admin.findDocuments.useQuery(
{ {
query: debouncedTerm, query: debouncedTerm,
@@ -45,7 +45,7 @@ export const AdminDocumentResults = () => {
perPage: perPage || 20, perPage: perPage || 20,
}, },
{ {
placeholderData: (previousData) => previousData, keepPreviousData: true,
}, },
); );
@@ -86,14 +86,14 @@ export const AdminDocumentResults = () => {
header: _(msg`Owner`), header: _(msg`Owner`),
accessorKey: 'owner', accessorKey: 'owner',
cell: ({ row }) => { cell: ({ row }) => {
const avatarFallbackText = row.original.user.name const avatarFallbackText = row.original.User.name
? extractInitials(row.original.user.name) ? extractInitials(row.original.User.name)
: row.original.user.email.slice(0, 1).toUpperCase(); : row.original.User.email.slice(0, 1).toUpperCase();
return ( return (
<Tooltip delayDuration={200}> <Tooltip delayDuration={200}>
<TooltipTrigger> <TooltipTrigger>
<Link href={`/admin/users/${row.original.user.id}`}> <Link href={`/admin/users/${row.original.User.id}`}>
<Avatar className="dark:border-border h-12 w-12 border-2 border-solid border-white"> <Avatar className="dark:border-border h-12 w-12 border-2 border-solid border-white">
<AvatarFallback className="text-xs text-gray-400"> <AvatarFallback className="text-xs text-gray-400">
{avatarFallbackText} {avatarFallbackText}
@@ -110,8 +110,8 @@ export const AdminDocumentResults = () => {
</Avatar> </Avatar>
<div className="text-muted-foreground flex flex-col text-sm"> <div className="text-muted-foreground flex flex-col text-sm">
<span>{row.original.user.name}</span> <span>{row.original.User.name}</span>
<span>{row.original.user.email}</span> <span>{row.original.User.email}</span>
</div> </div>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>

View File

@@ -4,7 +4,7 @@ import { useEffect, useMemo, useState, useTransition } from 'react';
import { msg } from '@lingui/macro'; import { msg } from '@lingui/macro';
import { useLingui } from '@lingui/react'; import { useLingui } from '@lingui/react';
import { ChevronDownIcon, ChevronUpIcon, ChevronsUpDown, Loader } from 'lucide-react'; import { ChevronDownIcon as CaretSortIcon, Loader } from 'lucide-react';
import { useDebouncedValue } from '@documenso/lib/client-only/hooks/use-debounced-value'; import { useDebouncedValue } from '@documenso/lib/client-only/hooks/use-debounced-value';
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params'; import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
@@ -54,15 +54,7 @@ export const LeaderboardTable = ({
onClick={() => handleColumnSort('name')} onClick={() => handleColumnSort('name')}
> >
{_(msg`Name`)} {_(msg`Name`)}
{sortBy === 'name' ? ( <CaretSortIcon className="ml-2 h-4 w-4" />
sortOrder === 'asc' ? (
<ChevronUpIcon className="ml-2 h-4 w-4" />
) : (
<ChevronDownIcon className="ml-2 h-4 w-4" />
)
) : (
<ChevronsUpDown className="ml-2 h-4 w-4" />
)}
</div> </div>
), ),
accessorKey: 'name', accessorKey: 'name',
@@ -88,15 +80,7 @@ export const LeaderboardTable = ({
onClick={() => handleColumnSort('signingVolume')} onClick={() => handleColumnSort('signingVolume')}
> >
{_(msg`Signing Volume`)} {_(msg`Signing Volume`)}
{sortBy === 'signingVolume' ? ( <CaretSortIcon className="ml-2 h-4 w-4" />
sortOrder === 'asc' ? (
<ChevronUpIcon className="ml-2 h-4 w-4" />
) : (
<ChevronDownIcon className="ml-2 h-4 w-4" />
)
) : (
<ChevronsUpDown className="ml-2 h-4 w-4" />
)}
</div> </div>
), ),
accessorKey: 'signingVolume', accessorKey: 'signingVolume',
@@ -110,15 +94,7 @@ export const LeaderboardTable = ({
onClick={() => handleColumnSort('createdAt')} onClick={() => handleColumnSort('createdAt')}
> >
{_(msg`Created`)} {_(msg`Created`)}
{sortBy === 'createdAt' ? ( <CaretSortIcon className="ml-2 h-4 w-4" />
sortOrder === 'asc' ? (
<ChevronUpIcon className="ml-2 h-4 w-4" />
) : (
<ChevronDownIcon className="ml-2 h-4 w-4" />
)
) : (
<ChevronsUpDown className="ml-2 h-4 w-4" />
)}
</div> </div>
); );
}, },
@@ -126,7 +102,7 @@ export const LeaderboardTable = ({
cell: ({ row }) => i18n.date(row.original.createdAt), cell: ({ row }) => i18n.date(row.original.createdAt),
}, },
] satisfies DataTableColumnDef<SigningVolume>[]; ] satisfies DataTableColumnDef<SigningVolume>[];
}, [sortOrder, sortBy]); }, [sortOrder]);
useEffect(() => { useEffect(() => {
startTransition(() => { startTransition(() => {
@@ -157,9 +133,6 @@ export const LeaderboardTable = ({
const handleColumnSort = (column: 'name' | 'createdAt' | 'signingVolume') => { const handleColumnSort = (column: 'name' | 'createdAt' | 'signingVolume') => {
startTransition(() => { startTransition(() => {
updateSearchParams({ updateSearchParams({
search: debouncedSearchString,
page,
perPage,
sortBy: column, sortBy: column,
sortOrder: sortBy === column && sortOrder === 'asc' ? 'desc' : 'asc', sortOrder: sortBy === column && sortOrder === 'asc' ? 'desc' : 'asc',
}); });

View File

@@ -13,6 +13,7 @@ import {
SITE_SETTINGS_BANNER_ID, SITE_SETTINGS_BANNER_ID,
ZSiteSettingsBannerSchema, ZSiteSettingsBannerSchema,
} from '@documenso/lib/server-only/site-settings/schemas/banner'; } from '@documenso/lib/server-only/site-settings/schemas/banner';
import { TRPCClientError } from '@documenso/trpc/client';
import { trpc as trpcReact } from '@documenso/trpc/react'; import { trpc as trpcReact } from '@documenso/trpc/react';
import { Button } from '@documenso/ui/primitives/button'; import { Button } from '@documenso/ui/primitives/button';
import { ColorPicker } from '@documenso/ui/primitives/color-picker'; import { ColorPicker } from '@documenso/ui/primitives/color-picker';
@@ -58,7 +59,7 @@ export function BannerForm({ banner }: BannerFormProps) {
const enabled = form.watch('enabled'); const enabled = form.watch('enabled');
const { mutateAsync: updateSiteSetting, isPending: isUpdateSiteSettingLoading } = const { mutateAsync: updateSiteSetting, isLoading: isUpdateSiteSettingLoading } =
trpcReact.admin.updateSiteSetting.useMutation(); trpcReact.admin.updateSiteSetting.useMutation();
const onBannerUpdate = async ({ id, enabled, data }: TBannerFormSchema) => { const onBannerUpdate = async ({ id, enabled, data }: TBannerFormSchema) => {
@@ -77,13 +78,21 @@ export function BannerForm({ banner }: BannerFormProps) {
router.refresh(); router.refresh();
} catch (err) { } catch (err) {
toast({ if (err instanceof TRPCClientError && err.data?.code === 'BAD_REQUEST') {
title: _(msg`An unknown error occurred`), toast({
variant: 'destructive', title: _(msg`An error occurred`),
description: _( description: err.message,
msg`We encountered an unknown error while attempting to update the banner. Please try again later.`, variant: 'destructive',
), });
}); } else {
toast({
title: _(msg`An unknown error occurred`),
variant: 'destructive',
description: _(
msg`We encountered an unknown error while attempting to update the banner. Please try again later.`,
),
});
}
} }
}; };

View File

@@ -6,10 +6,9 @@ import { useRouter } from 'next/navigation';
import { Trans, msg } from '@lingui/macro'; import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react'; import { useLingui } from '@lingui/react';
import { match } from 'ts-pattern';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { User } from '@documenso/prisma/client'; import type { User } from '@documenso/prisma/client';
import { TRPCClientError } from '@documenso/trpc/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert'; import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button'; import { Button } from '@documenso/ui/primitives/button';
@@ -38,7 +37,7 @@ export const DeleteUserDialog = ({ className, user }: DeleteUserDialogProps) =>
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const { mutateAsync: deleteUser, isPending: isDeletingUser } = const { mutateAsync: deleteUser, isLoading: isDeletingUser } =
trpc.admin.deleteUser.useMutation(); trpc.admin.deleteUser.useMutation();
const onDeleteAccount = async () => { const onDeleteAccount = async () => {
@@ -55,19 +54,23 @@ export const DeleteUserDialog = ({ className, user }: DeleteUserDialogProps) =>
router.push('/admin/users'); router.push('/admin/users');
} catch (err) { } catch (err) {
const error = AppError.parseError(err); if (err instanceof TRPCClientError && err.data?.code === 'BAD_REQUEST') {
toast({
const errorMessage = match(error.code) title: _(msg`An error occurred`),
.with(AppErrorCode.NOT_FOUND, () => msg`User not found.`) description: err.message,
.with(AppErrorCode.UNAUTHORIZED, () => msg`You are not authorized to delete this user.`) variant: 'destructive',
.otherwise(() => msg`An error occurred while deleting the user.`); });
} else {
toast({ toast({
title: _(msg`Error`), title: _(msg`An unknown error occurred`),
description: _(errorMessage), variant: 'destructive',
variant: 'destructive', description:
duration: 7500, err.message ??
}); _(
msg`We encountered an unknown error while attempting to delete your account. Please try again later.`,
),
});
}
} }
}; };

View File

@@ -34,7 +34,7 @@ export const DisableUserDialog = ({ className, userToDisable }: DisableUserDialo
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const { mutateAsync: disableUser, isPending: isDisablingUser } = const { mutateAsync: disableUser, isLoading: isDisablingUser } =
trpc.admin.disableUser.useMutation(); trpc.admin.disableUser.useMutation();
const onDisableAccount = async () => { const onDisableAccount = async () => {

View File

@@ -34,7 +34,7 @@ export const EnableUserDialog = ({ className, userToEnable }: EnableUserDialogPr
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const { mutateAsync: enableUser, isPending: isEnablingUser } = const { mutateAsync: enableUser, isLoading: isEnablingUser } =
trpc.admin.enableUser.useMutation(); trpc.admin.enableUser.useMutation();
const onEnableAccount = async () => { const onEnableAccount = async () => {

View File

@@ -22,8 +22,8 @@ type UserData = {
name: string | null; name: string | null;
email: string; email: string;
roles: Role[]; roles: Role[];
subscriptions?: SubscriptionLite[] | null; Subscription?: SubscriptionLite[] | null;
documents: DocumentLite[]; Document: DocumentLite[];
}; };
type SubscriptionLite = Pick< type SubscriptionLite = Pick<
@@ -81,7 +81,7 @@ export const UsersDataTable = ({
header: _(msg`Subscription`), header: _(msg`Subscription`),
accessorKey: 'subscription', accessorKey: 'subscription',
cell: ({ row }) => { cell: ({ row }) => {
const foundIndividualSubscription = (row.original.subscriptions ?? []).find((sub) => const foundIndividualSubscription = (row.original.Subscription ?? []).find((sub) =>
individualPriceIds.includes(sub.priceId), individualPriceIds.includes(sub.priceId),
); );
@@ -92,7 +92,7 @@ export const UsersDataTable = ({
header: _(msg`Documents`), header: _(msg`Documents`),
accessorKey: 'documents', accessorKey: 'documents',
cell: ({ row }) => { cell: ({ row }) => {
return <div>{row.original.documents?.length}</div>; return <div>{row.original.Document.length}</div>;
}, },
}, },
{ {

View File

@@ -18,14 +18,14 @@ import { useToast } from '@documenso/ui/primitives/use-toast';
export type DocumentPageViewButtonProps = { export type DocumentPageViewButtonProps = {
document: Document & { document: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
recipients: Recipient[]; Recipient: Recipient[];
team: Pick<Team, 'id' | 'url'> | null; team: Pick<Team, 'id' | 'url'> | null;
}; };
team?: Pick<Team, 'id' | 'url'>; team?: Pick<Team, 'id' | 'url'>;
}; };
export const DocumentPageViewButton = ({ document }: DocumentPageViewButtonProps) => { export const DocumentPageViewButton = ({ document, team }: DocumentPageViewButtonProps) => {
const { data: session } = useSession(); const { data: session } = useSession();
const { toast } = useToast(); const { toast } = useToast();
const { _ } = useLingui(); const { _ } = useLingui();
@@ -34,7 +34,7 @@ export const DocumentPageViewButton = ({ document }: DocumentPageViewButtonProps
return null; return null;
} }
const recipient = document.recipients.find((recipient) => recipient.email === session.user.email); const recipient = document.Recipient.find((recipient) => recipient.email === session.user.email);
const isRecipient = !!recipient; const isRecipient = !!recipient;
const isPending = document.status === DocumentStatus.PENDING; const isPending = document.status === DocumentStatus.PENDING;
@@ -46,16 +46,10 @@ export const DocumentPageViewButton = ({ document }: DocumentPageViewButtonProps
const onDownloadClick = async () => { const onDownloadClick = async () => {
try { try {
const documentWithData = await trpcClient.document.getDocumentById.query( const documentWithData = await trpcClient.document.getDocumentById.query({
{ documentId: document.id,
documentId: document.id, teamId: team?.id,
}, });
{
context: {
teamId: document.team?.id?.toString(),
},
},
);
const documentData = documentWithData?.documentData; const documentData = documentWithData?.documentData;

View File

@@ -41,8 +41,8 @@ import { DuplicateDocumentDialog } from '../duplicate-document-dialog';
export type DocumentPageViewDropdownProps = { export type DocumentPageViewDropdownProps = {
document: Document & { document: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
recipients: Recipient[]; Recipient: Recipient[];
team: Pick<Team, 'id' | 'url'> | null; team: Pick<Team, 'id' | 'url'> | null;
}; };
team?: Pick<Team, 'id' | 'url'> & { teamEmail: TeamEmail | null }; team?: Pick<Team, 'id' | 'url'> & { teamEmail: TeamEmail | null };
@@ -60,9 +60,9 @@ export const DocumentPageViewDropdown = ({ document, team }: DocumentPageViewDro
return null; return null;
} }
const recipient = document.recipients.find((recipient) => recipient.email === session.user.email); const recipient = document.Recipient.find((recipient) => recipient.email === session.user.email);
const isOwner = document.user.id === session.user.id; const isOwner = document.User.id === session.user.id;
const isDraft = document.status === DocumentStatus.DRAFT; const isDraft = document.status === DocumentStatus.DRAFT;
const isPending = document.status === DocumentStatus.PENDING; const isPending = document.status === DocumentStatus.PENDING;
const isDeleted = document.deletedAt !== null; const isDeleted = document.deletedAt !== null;
@@ -74,16 +74,10 @@ export const DocumentPageViewDropdown = ({ document, team }: DocumentPageViewDro
const onDownloadClick = async () => { const onDownloadClick = async () => {
try { try {
const documentWithData = await trpcClient.document.getDocumentById.query( const documentWithData = await trpcClient.document.getDocumentById.query({
{ documentId: document.id,
documentId: document.id, teamId: team?.id,
}, });
{
context: {
teamId: team?.id?.toString(),
},
},
);
const documentData = documentWithData?.documentData; const documentData = documentWithData?.documentData;
@@ -101,7 +95,7 @@ export const DocumentPageViewDropdown = ({ document, team }: DocumentPageViewDro
} }
}; };
const nonSignedRecipients = document.recipients.filter((item) => item.signingStatus !== 'SIGNED'); const nonSignedRecipients = document.Recipient.filter((item) => item.signingStatus !== 'SIGNED');
return ( return (
<DropdownMenu> <DropdownMenu>
@@ -156,7 +150,7 @@ export const DocumentPageViewDropdown = ({ document, team }: DocumentPageViewDro
{canManageDocument && ( {canManageDocument && (
<DocumentRecipientLinkCopyDialog <DocumentRecipientLinkCopyDialog
recipients={document.recipients} recipients={document.Recipient}
trigger={ trigger={
<DropdownMenuItem <DropdownMenuItem
disabled={!isPending || isDeleted} disabled={!isPending || isDeleted}

View File

@@ -12,8 +12,8 @@ import type { Document, Recipient, User } from '@documenso/prisma/client';
export type DocumentPageViewInformationProps = { export type DocumentPageViewInformationProps = {
userId: number; userId: number;
document: Document & { document: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
recipients: Recipient[]; Recipient: Recipient[];
}; };
}; };
@@ -29,8 +29,7 @@ export const DocumentPageViewInformation = ({
return [ return [
{ {
description: msg`Uploaded by`, description: msg`Uploaded by`,
value: value: userId === document.userId ? _(msg`You`) : document.User.name ?? document.User.email,
userId === document.userId ? _(msg`You`) : (document.user.name ?? document.user.email),
}, },
{ {
description: msg`Created`, description: msg`Created`,

View File

@@ -12,14 +12,13 @@ import {
MailOpenIcon, MailOpenIcon,
PenIcon, PenIcon,
PlusIcon, PlusIcon,
UserIcon,
} from 'lucide-react'; } from 'lucide-react';
import { match } from 'ts-pattern'; import { match } from 'ts-pattern';
import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles'; import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
import { formatSigningLink } from '@documenso/lib/utils/recipients'; import { formatSigningLink } from '@documenso/lib/utils/recipients';
import type { Document, Recipient } from '@documenso/prisma/client';
import { DocumentStatus, RecipientRole, SigningStatus } from '@documenso/prisma/client'; import { DocumentStatus, RecipientRole, SigningStatus } from '@documenso/prisma/client';
import type { Document, Recipient } from '@documenso/prisma/client';
import { CopyTextButton } from '@documenso/ui/components/common/copy-text-button'; import { CopyTextButton } from '@documenso/ui/components/common/copy-text-button';
import { SignatureIcon } from '@documenso/ui/icons/signature'; import { SignatureIcon } from '@documenso/ui/icons/signature';
import { AvatarWithText } from '@documenso/ui/primitives/avatar'; import { AvatarWithText } from '@documenso/ui/primitives/avatar';
@@ -29,7 +28,7 @@ import { useToast } from '@documenso/ui/primitives/use-toast';
export type DocumentPageViewRecipientsProps = { export type DocumentPageViewRecipientsProps = {
document: Document & { document: Document & {
recipients: Recipient[]; Recipient: Recipient[];
}; };
documentRootPath: string; documentRootPath: string;
}; };
@@ -41,7 +40,7 @@ export const DocumentPageViewRecipients = ({
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
const recipients = document.recipients; const recipients = document.Recipient;
return ( return (
<section className="dark:bg-background border-border bg-widget flex flex-col rounded-xl border"> <section className="dark:bg-background border-border bg-widget flex flex-col rounded-xl border">
@@ -121,12 +120,6 @@ export const DocumentPageViewRecipients = ({
<Trans>Viewed</Trans> <Trans>Viewed</Trans>
</> </>
)) ))
.with(RecipientRole.ASSISTANT, () => (
<>
<UserIcon className="mr-1 h-3 w-3" />
<Trans>Assisted</Trans>
</>
))
.exhaustive()} .exhaustive()}
</Badge> </Badge>
)} )}

View File

@@ -71,7 +71,7 @@ export const DocumentPageView = async ({ params, team }: DocumentPageViewProps)
const documentVisibility = document?.visibility; const documentVisibility = document?.visibility;
const currentTeamMemberRole = team?.currentTeamMember?.role; const currentTeamMemberRole = team?.currentTeamMember?.role;
const isRecipient = document?.recipients.find((recipient) => recipient.email === user.email); const isRecipient = document?.Recipient.find((recipient) => recipient.email === user.email);
let canAccessDocument = true; let canAccessDocument = true;
if (team && !isRecipient && document?.userId !== user.id) { if (team && !isRecipient && document?.userId !== user.id) {
@@ -125,13 +125,12 @@ export const DocumentPageView = async ({ params, team }: DocumentPageViewProps)
getFieldsForDocument({ getFieldsForDocument({
documentId, documentId,
userId: user.id, userId: user.id,
teamId: team?.id,
}), }),
]); ]);
const documentWithRecipients = { const documentWithRecipients = {
...document, ...document,
recipients, Recipient: recipients,
}; };
return ( return (

View File

@@ -12,7 +12,7 @@ import {
DO_NOT_INVALIDATE_QUERY_ON_MUTATION, DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
SKIP_QUERY_BATCH_META, SKIP_QUERY_BATCH_META,
} from '@documenso/lib/constants/trpc'; } from '@documenso/lib/constants/trpc';
import type { TDocument } from '@documenso/lib/types/document'; import type { TGetDocumentWithDetailsByIdResponse } from '@documenso/lib/server-only/document/get-document-with-details-by-id';
import { DocumentDistributionMethod, DocumentStatus } from '@documenso/prisma/client'; import { DocumentDistributionMethod, DocumentStatus } from '@documenso/prisma/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils'; import { cn } from '@documenso/ui/lib/utils';
@@ -35,7 +35,7 @@ import { useOptionalCurrentTeam } from '~/providers/team';
export type EditDocumentFormProps = { export type EditDocumentFormProps = {
className?: string; className?: string;
initialDocument: TDocument; initialDocument: TGetDocumentWithDetailsByIdResponse;
documentRootPath: string; documentRootPath: string;
isDocumentEnterprise: boolean; isDocumentEnterprise: boolean;
}; };
@@ -64,6 +64,7 @@ export const EditDocumentForm = ({
trpc.document.getDocumentWithDetailsById.useQuery( trpc.document.getDocumentWithDetailsById.useQuery(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
{ {
initialData: initialDocument, initialData: initialDocument,
@@ -71,14 +72,15 @@ export const EditDocumentForm = ({
}, },
); );
const { recipients, fields } = document; const { Recipient: recipients, Field: fields } = document;
const { mutateAsync: updateDocument } = trpc.document.setSettingsForDocument.useMutation({ const { mutateAsync: setSettingsForDocument } = trpc.document.setSettingsForDocument.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION, ...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => { onSuccess: (newData) => {
utils.document.getDocumentWithDetailsById.setData( utils.document.getDocumentWithDetailsById.setData(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
(oldData) => ({ ...(oldData || initialDocument), ...newData }), (oldData) => ({ ...(oldData || initialDocument), ...newData }),
); );
@@ -92,6 +94,7 @@ export const EditDocumentForm = ({
utils.document.getDocumentWithDetailsById.setData( utils.document.getDocumentWithDetailsById.setData(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
(oldData) => ({ ...(oldData || initialDocument), ...newData, id: Number(newData.id) }), (oldData) => ({ ...(oldData || initialDocument), ...newData, id: Number(newData.id) }),
); );
@@ -104,20 +107,40 @@ export const EditDocumentForm = ({
utils.document.getDocumentWithDetailsById.setData( utils.document.getDocumentWithDetailsById.setData(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
(oldData) => ({ ...(oldData || initialDocument), fields: newFields }), (oldData) => ({ ...(oldData || initialDocument), Field: newFields }),
); );
}, },
}); });
const { mutateAsync: setRecipients } = trpc.recipient.setDocumentRecipients.useMutation({ const { mutateAsync: updateTypedSignature } =
trpc.document.updateTypedSignatureSettings.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => {
utils.document.getDocumentWithDetailsById.setData(
{
documentId: initialDocument.id,
teamId: team?.id,
},
(oldData) => ({
...(oldData || initialDocument),
...newData,
id: Number(newData.id),
}),
);
},
});
const { mutateAsync: addSigners } = trpc.recipient.addSigners.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION, ...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: ({ recipients: newRecipients }) => { onSuccess: ({ recipients: newRecipients }) => {
utils.document.getDocumentWithDetailsById.setData( utils.document.getDocumentWithDetailsById.setData(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
(oldData) => ({ ...(oldData || initialDocument), recipients: newRecipients }), (oldData) => ({ ...(oldData || initialDocument), Recipient: newRecipients }),
); );
}, },
}); });
@@ -128,6 +151,7 @@ export const EditDocumentForm = ({
utils.document.getDocumentWithDetailsById.setData( utils.document.getDocumentWithDetailsById.setData(
{ {
documentId: initialDocument.id, documentId: initialDocument.id,
teamId: team?.id,
}, },
(oldData) => ({ ...(oldData || initialDocument), ...newData }), (oldData) => ({ ...(oldData || initialDocument), ...newData }),
); );
@@ -181,8 +205,9 @@ export const EditDocumentForm = ({
try { try {
const { timezone, dateFormat, redirectUrl, language } = data.meta; const { timezone, dateFormat, redirectUrl, language } = data.meta;
await updateDocument({ await setSettingsForDocument({
documentId: document.id, documentId: document.id,
teamId: team?.id,
data: { data: {
title: data.title, title: data.title,
externalId: data.externalId || null, externalId: data.externalId || null,
@@ -221,9 +246,10 @@ export const EditDocumentForm = ({
signingOrder: data.signingOrder, signingOrder: data.signingOrder,
}), }),
setRecipients({ addSigners({
documentId: document.id, documentId: document.id,
recipients: data.signers.map((signer) => ({ teamId: team?.id,
signers: data.signers.map((signer) => ({
...signer, ...signer,
// Explicitly set to null to indicate we want to remove auth if required. // Explicitly set to null to indicate we want to remove auth if required.
actionAuth: signer.actionAuth || null, actionAuth: signer.actionAuth || null,
@@ -253,12 +279,9 @@ export const EditDocumentForm = ({
fields: data.fields, fields: data.fields,
}); });
await updateDocument({ await updateTypedSignature({
documentId: document.id, documentId: document.id,
typedSignatureEnabled: data.typedSignatureEnabled,
meta: {
typedSignatureEnabled: data.typedSignatureEnabled,
},
}); });
// Clear all field data from localStorage // Clear all field data from localStorage
@@ -290,6 +313,7 @@ export const EditDocumentForm = ({
try { try {
await sendDocument({ await sendDocument({
documentId: document.id, documentId: document.id,
teamId: team?.id,
meta: { meta: {
subject, subject,
message, message,

View File

@@ -52,7 +52,7 @@ export const DocumentEditPageView = async ({ params, team }: DocumentEditPageVie
const documentVisibility = document?.visibility; const documentVisibility = document?.visibility;
const currentTeamMemberRole = team?.currentTeamMember?.role; const currentTeamMemberRole = team?.currentTeamMember?.role;
const isRecipient = document?.recipients.find((recipient) => recipient.email === user.email); const isRecipient = document?.Recipient.find((recipient) => recipient.email === user.email);
let canAccessDocument = true; let canAccessDocument = true;
if (!isRecipient && document?.userId !== user.id) { if (!isRecipient && document?.userId !== user.id) {
@@ -78,7 +78,7 @@ export const DocumentEditPageView = async ({ params, team }: DocumentEditPageVie
redirect(`${documentRootPath}/${documentId}`); redirect(`${documentRootPath}/${documentId}`);
} }
const { documentMeta, recipients } = document; const { documentMeta, Recipient: recipients } = document;
if (documentMeta?.password) { if (documentMeta?.password) {
const key = DOCUMENSO_ENCRYPTION_KEY; const key = DOCUMENSO_ENCRYPTION_KEY;

View File

@@ -37,16 +37,17 @@ export const DocumentLogsDataTable = ({ documentId }: DocumentLogsDataTableProps
const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? [])); const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? []));
const { data, isLoading, isLoadingError } = trpc.document.findDocumentAuditLogs.useQuery( const { data, isLoading, isInitialLoading, isLoadingError } =
{ trpc.document.findDocumentAuditLogs.useQuery(
documentId, {
page: parsedSearchParams.page, documentId,
perPage: parsedSearchParams.perPage, page: parsedSearchParams.page,
}, perPage: parsedSearchParams.perPage,
{ },
placeholderData: (previousData) => previousData, {
}, keepPreviousData: true,
); },
);
const onPaginationChange = (page: number, perPage: number) => { const onPaginationChange = (page: number, perPage: number) => {
updateSearchParams({ updateSearchParams({
@@ -131,7 +132,7 @@ export const DocumentLogsDataTable = ({ documentId }: DocumentLogsDataTableProps
enable: isLoadingError, enable: isLoadingError,
}} }}
skeleton={{ skeleton={{
enable: isLoading, enable: isLoading && isInitialLoading,
rows: 3, rows: 3,
component: ( component: (
<> <>

View File

@@ -77,9 +77,9 @@ export const DocumentLogsPageView = async ({ params, team }: DocumentLogsPageVie
}, },
{ {
description: msg`Created by`, description: msg`Created by`,
value: document.user.name value: document.User.name
? `${document.user.name} (${document.user.email})` ? `${document.User.name} (${document.User.email})`
: document.user.email, : document.User.email,
}, },
{ {
description: msg`Date created`, description: msg`Date created`,

View File

@@ -15,16 +15,20 @@ export type DownloadAuditLogButtonProps = {
documentId: number; documentId: number;
}; };
export const DownloadAuditLogButton = ({ className, documentId }: DownloadAuditLogButtonProps) => { export const DownloadAuditLogButton = ({
className,
teamId,
documentId,
}: DownloadAuditLogButtonProps) => {
const { toast } = useToast(); const { toast } = useToast();
const { _ } = useLingui(); const { _ } = useLingui();
const { mutateAsync: downloadAuditLogs, isPending } = const { mutateAsync: downloadAuditLogs, isLoading } =
trpc.document.downloadAuditLogs.useMutation(); trpc.document.downloadAuditLogs.useMutation();
const onDownloadAuditLogsClick = async () => { const onDownloadAuditLogsClick = async () => {
try { try {
const { url } = await downloadAuditLogs({ documentId }); const { url } = await downloadAuditLogs({ teamId, documentId });
const iframe = Object.assign(document.createElement('iframe'), { const iframe = Object.assign(document.createElement('iframe'), {
src: url, src: url,
@@ -70,10 +74,10 @@ export const DownloadAuditLogButton = ({ className, documentId }: DownloadAuditL
return ( return (
<Button <Button
className={cn('w-full sm:w-auto', className)} className={cn('w-full sm:w-auto', className)}
loading={isPending} loading={isLoading}
onClick={() => void onDownloadAuditLogsClick()} onClick={() => void onDownloadAuditLogsClick()}
> >
{!isPending && <DownloadIcon className="mr-1.5 h-4 w-4" />} {!isLoading && <DownloadIcon className="mr-1.5 h-4 w-4" />}
<Trans>Download Audit Logs</Trans> <Trans>Download Audit Logs</Trans>
</Button> </Button>
); );

View File

@@ -26,12 +26,12 @@ export const DownloadCertificateButton = ({
const { toast } = useToast(); const { toast } = useToast();
const { _ } = useLingui(); const { _ } = useLingui();
const { mutateAsync: downloadCertificate, isPending } = const { mutateAsync: downloadCertificate, isLoading } =
trpc.document.downloadCertificate.useMutation(); trpc.document.downloadCertificate.useMutation();
const onDownloadCertificatesClick = async () => { const onDownloadCertificatesClick = async () => {
try { try {
const { url } = await downloadCertificate({ documentId }); const { url } = await downloadCertificate({ documentId, teamId });
const iframe = Object.assign(document.createElement('iframe'), { const iframe = Object.assign(document.createElement('iframe'), {
src: url, src: url,
@@ -77,12 +77,12 @@ export const DownloadCertificateButton = ({
return ( return (
<Button <Button
className={cn('w-full sm:w-auto', className)} className={cn('w-full sm:w-auto', className)}
loading={isPending} loading={isLoading}
variant="outline" variant="outline"
disabled={documentStatus !== DocumentStatus.COMPLETED} disabled={documentStatus !== DocumentStatus.COMPLETED}
onClick={() => void onDownloadCertificatesClick()} onClick={() => void onDownloadCertificatesClick()}
> >
{!isPending && <DownloadIcon className="mr-1.5 h-4 w-4" />} {!isLoading && <DownloadIcon className="mr-1.5 h-4 w-4" />}
<Trans>Download Certificate</Trans> <Trans>Download Certificate</Trans>
</Button> </Button>
); );

View File

@@ -91,7 +91,7 @@ export const ResendDocumentActionItem = ({
const onFormSubmit = async ({ recipients }: TResendDocumentFormSchema) => { const onFormSubmit = async ({ recipients }: TResendDocumentFormSchema) => {
try { try {
await resendDocument({ documentId: document.id, recipients }); await resendDocument({ documentId: document.id, recipients, teamId: team?.id });
toast({ toast({
title: _(msg`Document re-sent`), title: _(msg`Document re-sent`),

View File

@@ -12,14 +12,15 @@ import { downloadPDF } from '@documenso/lib/client-only/download-pdf';
import { formatDocumentsPath } from '@documenso/lib/utils/teams'; import { formatDocumentsPath } from '@documenso/lib/utils/teams';
import type { Document, Recipient, Team, User } from '@documenso/prisma/client'; import type { Document, Recipient, Team, User } from '@documenso/prisma/client';
import { DocumentStatus, RecipientRole, SigningStatus } from '@documenso/prisma/client'; import { DocumentStatus, RecipientRole, SigningStatus } from '@documenso/prisma/client';
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
import { trpc as trpcClient } from '@documenso/trpc/client'; import { trpc as trpcClient } from '@documenso/trpc/client';
import { Button } from '@documenso/ui/primitives/button'; import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast'; import { useToast } from '@documenso/ui/primitives/use-toast';
export type DataTableActionButtonProps = { export type DataTableActionButtonProps = {
row: Document & { row: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
recipients: Recipient[]; Recipient: Recipient[];
team: Pick<Team, 'id' | 'url'> | null; team: Pick<Team, 'id' | 'url'> | null;
}; };
team?: Pick<Team, 'id' | 'url'>; team?: Pick<Team, 'id' | 'url'>;
@@ -34,9 +35,9 @@ export const DataTableActionButton = ({ row, team }: DataTableActionButtonProps)
return null; return null;
} }
const recipient = row.recipients.find((recipient) => recipient.email === session.user.email); const recipient = row.Recipient.find((recipient) => recipient.email === session.user.email);
const isOwner = row.user.id === session.user.id; const isOwner = row.User.id === session.user.id;
const isRecipient = !!recipient; const isRecipient = !!recipient;
const isDraft = row.status === DocumentStatus.DRAFT; const isDraft = row.status === DocumentStatus.DRAFT;
const isPending = row.status === DocumentStatus.PENDING; const isPending = row.status === DocumentStatus.PENDING;
@@ -49,20 +50,18 @@ export const DataTableActionButton = ({ row, team }: DataTableActionButtonProps)
const onDownloadClick = async () => { const onDownloadClick = async () => {
try { try {
const document = !recipient let document: DocumentWithData | null = null;
? await trpcClient.document.getDocumentById.query(
{ if (!recipient) {
documentId: row.id, document = await trpcClient.document.getDocumentById.query({
}, documentId: row.id,
{ teamId: team?.id,
context: { });
teamId: team?.id?.toString(), } else {
}, document = await trpcClient.document.getDocumentByToken.query({
}, token: recipient.token,
) });
: await trpcClient.document.getDocumentByToken.query({ }
token: recipient.token,
});
const documentData = document?.documentData; const documentData = document?.documentData;

View File

@@ -23,8 +23,9 @@ import { useSession } from 'next-auth/react';
import { downloadPDF } from '@documenso/lib/client-only/download-pdf'; import { downloadPDF } from '@documenso/lib/client-only/download-pdf';
import { formatDocumentsPath } from '@documenso/lib/utils/teams'; import { formatDocumentsPath } from '@documenso/lib/utils/teams';
import type { Document, Recipient, Team, User } from '@documenso/prisma/client';
import { DocumentStatus, RecipientRole } from '@documenso/prisma/client'; import { DocumentStatus, RecipientRole } from '@documenso/prisma/client';
import type { Document, Recipient, Team, User } from '@documenso/prisma/client';
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
import { trpc as trpcClient } from '@documenso/trpc/client'; import { trpc as trpcClient } from '@documenso/trpc/client';
import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button'; import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';
import { import {
@@ -45,8 +46,8 @@ import { MoveDocumentDialog } from './move-document-dialog';
export type DataTableActionDropdownProps = { export type DataTableActionDropdownProps = {
row: Document & { row: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
recipients: Recipient[]; Recipient: Recipient[];
team: Pick<Team, 'id' | 'url'> | null; team: Pick<Team, 'id' | 'url'> | null;
}; };
team?: Pick<Team, 'id' | 'url'> & { teamEmail?: string }; team?: Pick<Team, 'id' | 'url'> & { teamEmail?: string };
@@ -65,9 +66,9 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
return null; return null;
} }
const recipient = row.recipients.find((recipient) => recipient.email === session.user.email); const recipient = row.Recipient.find((recipient) => recipient.email === session.user.email);
const isOwner = row.user.id === session.user.id; const isOwner = row.User.id === session.user.id;
// const isRecipient = !!recipient; // const isRecipient = !!recipient;
const isDraft = row.status === DocumentStatus.DRAFT; const isDraft = row.status === DocumentStatus.DRAFT;
const isPending = row.status === DocumentStatus.PENDING; const isPending = row.status === DocumentStatus.PENDING;
@@ -80,13 +81,18 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
const onDownloadClick = async () => { const onDownloadClick = async () => {
try { try {
const document = !recipient let document: DocumentWithData | null = null;
? await trpcClient.document.getDocumentById.query({
documentId: row.id, if (!recipient) {
}) document = await trpcClient.document.getDocumentById.query({
: await trpcClient.document.getDocumentByToken.query({ documentId: row.id,
token: recipient.token, teamId: team?.id,
}); });
} else {
document = await trpcClient.document.getDocumentByToken.query({
token: recipient.token,
});
}
const documentData = document?.documentData; const documentData = document?.documentData;
@@ -104,7 +110,7 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
} }
}; };
const nonSignedRecipients = row.recipients.filter((item) => item.signingStatus !== 'SIGNED'); const nonSignedRecipients = row.Recipient.filter((item) => item.signingStatus !== 'SIGNED');
return ( return (
<DropdownMenu> <DropdownMenu>
@@ -162,7 +168,7 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
</DropdownMenuItem> </DropdownMenuItem>
{/* We don't want to allow teams moving documents across at the moment. */} {/* We don't want to allow teams moving documents across at the moment. */}
{!team && !row.teamId && ( {!team && (
<DropdownMenuItem onClick={() => setMoveDialogOpen(true)}> <DropdownMenuItem onClick={() => setMoveDialogOpen(true)}>
<MoveRight className="mr-2 h-4 w-4" /> <MoveRight className="mr-2 h-4 w-4" />
<Trans>Move to Team</Trans> <Trans>Move to Team</Trans>
@@ -189,7 +195,7 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
{canManageDocument && ( {canManageDocument && (
<DocumentRecipientLinkCopyDialog <DocumentRecipientLinkCopyDialog
recipients={row.recipients} recipients={row.Recipient}
trigger={ trigger={
<DropdownMenuItem disabled={!isPending} asChild onSelect={(e) => e.preventDefault()}> <DropdownMenuItem disabled={!isPending} asChild onSelect={(e) => e.preventDefault()}>
<div> <div>
@@ -233,12 +239,14 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
onOpenChange={setMoveDialogOpen} onOpenChange={setMoveDialogOpen}
/> />
<DuplicateDocumentDialog {isDuplicateDialogOpen && (
id={row.id} <DuplicateDocumentDialog
open={isDuplicateDialogOpen} id={row.id}
onOpenChange={setDuplicateDialogOpen} open={isDuplicateDialogOpen}
team={team} onOpenChange={setDuplicateDialogOpen}
/> team={team}
/>
)}
</DropdownMenu> </DropdownMenu>
); );
}; };

View File

@@ -25,7 +25,7 @@ export const DataTableSenderFilter = ({ teamId }: DataTableSenderFilterProps) =>
const senderIds = parseToIntegerArray(searchParams?.get('senderIds') ?? ''); const senderIds = parseToIntegerArray(searchParams?.get('senderIds') ?? '');
const { data, isLoading } = trpc.team.getTeamMembers.useQuery({ const { data, isInitialLoading } = trpc.team.getTeamMembers.useQuery({
teamId, teamId,
}); });
@@ -61,7 +61,7 @@ export const DataTableSenderFilter = ({ teamId }: DataTableSenderFilterProps) =>
} }
enableClearAllButton={true} enableClearAllButton={true}
inputPlaceholder={msg`Search`} inputPlaceholder={msg`Search`}
loading={!isMounted || isLoading} loading={!isMounted || isInitialLoading}
options={comboBoxOptions} options={comboBoxOptions}
selectedValues={senderIds} selectedValues={senderIds}
onChange={onChange} onChange={onChange}

View File

@@ -10,9 +10,9 @@ import type { Document, Recipient, Team, User } from '@documenso/prisma/client';
export type DataTableTitleProps = { export type DataTableTitleProps = {
row: Document & { row: Document & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
team: Pick<Team, 'url'> | null; team: Pick<Team, 'url'> | null;
recipients: Recipient[]; Recipient: Recipient[];
}; };
teamUrl?: string; teamUrl?: string;
}; };
@@ -24,9 +24,9 @@ export const DataTableTitle = ({ row, teamUrl }: DataTableTitleProps) => {
return null; return null;
} }
const recipient = row.recipients.find((recipient) => recipient.email === session.user.email); const recipient = row.Recipient.find((recipient) => recipient.email === session.user.email);
const isOwner = row.user.id === session.user.id; const isOwner = row.User.id === session.user.id;
const isRecipient = !!recipient; const isRecipient = !!recipient;
const isCurrentTeamDocument = teamUrl && row.team?.url === teamUrl; const isCurrentTeamDocument = teamUrl && row.team?.url === teamUrl;

View File

@@ -9,9 +9,9 @@ import { DateTime } from 'luxon';
import { useSession } from 'next-auth/react'; import { useSession } from 'next-auth/react';
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params'; import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
import type { TFindDocumentsResponse } from '@documenso/lib/server-only/document/find-documents';
import type { Team } from '@documenso/prisma/client'; import type { Team } from '@documenso/prisma/client';
import { ExtendedDocumentStatus } from '@documenso/prisma/types/extended-document-status'; import { ExtendedDocumentStatus } from '@documenso/prisma/types/extended-document-status';
import type { TFindDocumentsResponse } from '@documenso/trpc/server/document-router/schema';
import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table'; import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table';
import { DataTable } from '@documenso/ui/primitives/data-table'; import { DataTable } from '@documenso/ui/primitives/data-table';
import { DataTablePagination } from '@documenso/ui/primitives/data-table-pagination'; import { DataTablePagination } from '@documenso/ui/primitives/data-table-pagination';
@@ -57,14 +57,14 @@ export const DocumentsDataTable = ({
{ {
id: 'sender', id: 'sender',
header: _(msg`Sender`), header: _(msg`Sender`),
cell: ({ row }) => row.original.user.name ?? row.original.user.email, cell: ({ row }) => row.original.User.name ?? row.original.User.email,
}, },
{ {
header: _(msg`Recipient`), header: _(msg`Recipient`),
accessorKey: 'recipient', accessorKey: 'recipient',
cell: ({ row }) => ( cell: ({ row }) => (
<StackAvatarsWithTooltip <StackAvatarsWithTooltip
recipients={row.original.recipients} recipients={row.original.Recipient}
documentStatus={row.original.status} documentStatus={row.original.status}
/> />
), ),

View File

@@ -38,6 +38,7 @@ export const DeleteDocumentDialog = ({
onOpenChange, onOpenChange,
status, status,
documentTitle, documentTitle,
teamId,
canManageDocument, canManageDocument,
}: DeleteDocumentDialogProps) => { }: DeleteDocumentDialogProps) => {
const router = useRouter(); const router = useRouter();
@@ -51,7 +52,7 @@ export const DeleteDocumentDialog = ({
const [inputValue, setInputValue] = useState(''); const [inputValue, setInputValue] = useState('');
const [isDeleteEnabled, setIsDeleteEnabled] = useState(status === DocumentStatus.DRAFT); const [isDeleteEnabled, setIsDeleteEnabled] = useState(status === DocumentStatus.DRAFT);
const { mutateAsync: deleteDocument, isPending } = trpcReact.document.deleteDocument.useMutation({ const { mutateAsync: deleteDocument, isLoading } = trpcReact.document.deleteDocument.useMutation({
onSuccess: () => { onSuccess: () => {
router.refresh(); router.refresh();
void refreshLimits(); void refreshLimits();
@@ -75,7 +76,7 @@ export const DeleteDocumentDialog = ({
const onDelete = async () => { const onDelete = async () => {
try { try {
await deleteDocument({ documentId: id }); await deleteDocument({ documentId: id, teamId });
} catch { } catch {
toast({ toast({
title: _(msg`Something went wrong`), title: _(msg`Something went wrong`),
@@ -92,7 +93,7 @@ export const DeleteDocumentDialog = ({
}; };
return ( return (
<Dialog open={open} onOpenChange={(value) => !isPending && onOpenChange(value)}> <Dialog open={open} onOpenChange={(value) => !isLoading && onOpenChange(value)}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
@@ -193,7 +194,7 @@ export const DeleteDocumentDialog = ({
<Button <Button
type="button" type="button"
loading={isPending} loading={isLoading}
onClick={onDelete} onClick={onDelete}
disabled={!isDeleteEnabled && canManageDocument} disabled={!isDeleteEnabled && canManageDocument}
variant="destructive" variant="destructive"

View File

@@ -37,6 +37,7 @@ export const DuplicateDocumentDialog = ({
const { data: document, isLoading } = trpcReact.document.getDocumentById.useQuery({ const { data: document, isLoading } = trpcReact.document.getDocumentById.useQuery({
documentId: id, documentId: id,
teamId: team?.id,
}); });
const documentData = document?.documentData const documentData = document?.documentData
@@ -48,10 +49,10 @@ export const DuplicateDocumentDialog = ({
const documentsPath = formatDocumentsPath(team?.url); const documentsPath = formatDocumentsPath(team?.url);
const { mutateAsync: duplicateDocument, isPending: isDuplicateLoading } = const { mutateAsync: duplicateDocument, isLoading: isDuplicateLoading } =
trpcReact.document.duplicateDocument.useMutation({ trpcReact.document.duplicateDocument.useMutation({
onSuccess: ({ documentId }) => { onSuccess: (newId) => {
router.push(`${documentsPath}/${documentId}/edit`); router.push(`${documentsPath}/${newId}/edit`);
toast({ toast({
title: _(msg`Document Duplicated`), title: _(msg`Document Duplicated`),
@@ -65,7 +66,7 @@ export const DuplicateDocumentDialog = ({
const onDuplicate = async () => { const onDuplicate = async () => {
try { try {
await duplicateDocument({ documentId: id }); await duplicateDocument({ documentId: id, teamId: team?.id });
} catch { } catch {
toast({ toast({
title: _(msg`Something went wrong`), title: _(msg`Something went wrong`),

View File

@@ -40,9 +40,9 @@ export const MoveDocumentDialog = ({ documentId, open, onOpenChange }: MoveDocum
const [selectedTeamId, setSelectedTeamId] = useState<number | null>(null); const [selectedTeamId, setSelectedTeamId] = useState<number | null>(null);
const { data: teams, isPending: isLoadingTeams } = trpc.team.getTeams.useQuery(); const { data: teams, isLoading: isLoadingTeams } = trpc.team.getTeams.useQuery();
const { mutateAsync: moveDocument, isPending } = trpc.document.moveDocumentToTeam.useMutation({ const { mutateAsync: moveDocument, isLoading } = trpc.document.moveDocumentToTeam.useMutation({
onSuccess: () => { onSuccess: () => {
router.refresh(); router.refresh();
toast({ toast({
@@ -119,8 +119,8 @@ export const MoveDocumentDialog = ({ documentId, open, onOpenChange }: MoveDocum
<Button variant="secondary" onClick={() => onOpenChange(false)}> <Button variant="secondary" onClick={() => onOpenChange(false)}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button onClick={onMove} loading={isPending} disabled={!selectedTeamId || isPending}> <Button onClick={onMove} loading={isLoading} disabled={!selectedTeamId || isLoading}>
{isPending ? <Trans>Moving...</Trans> : <Trans>Move</Trans>} {isLoading ? <Trans>Moving...</Trans> : <Trans>Move</Trans>}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -8,16 +8,16 @@ import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react'; import { useLingui } from '@lingui/react';
import { Loader } from 'lucide-react'; import { Loader } from 'lucide-react';
import { useSession } from 'next-auth/react'; import { useSession } from 'next-auth/react';
import { match } from 'ts-pattern';
import { useLimits } from '@documenso/ee/server-only/limits/provider/client'; import { useLimits } from '@documenso/ee/server-only/limits/provider/client';
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics'; import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app'; import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones'; import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error'; import { AppError } from '@documenso/lib/errors/app-error';
import { createDocumentData } from '@documenso/lib/server-only/document-data/create-document-data'; import { createDocumentData } from '@documenso/lib/server-only/document-data/create-document-data';
import { putPdfFile } from '@documenso/lib/universal/upload/put-file'; import { putPdfFile } from '@documenso/lib/universal/upload/put-file';
import { formatDocumentsPath } from '@documenso/lib/utils/teams'; import { formatDocumentsPath } from '@documenso/lib/utils/teams';
import { TRPCClientError } from '@documenso/trpc/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils'; import { cn } from '@documenso/ui/lib/utils';
import { DocumentDropzone } from '@documenso/ui/primitives/document-dropzone'; import { DocumentDropzone } from '@documenso/ui/primitives/document-dropzone';
@@ -76,6 +76,7 @@ export const UploadDocument = ({ className, team }: UploadDocumentProps) => {
const { id } = await createDocument({ const { id } = await createDocument({
title: file.name, title: file.name,
documentDataId, documentDataId,
teamId: team?.id,
timezone: userTimezone, timezone: userTimezone,
}); });
@@ -99,20 +100,25 @@ export const UploadDocument = ({ className, team }: UploadDocumentProps) => {
console.error(err); console.error(err);
const errorMessage = match(error.code) if (error.code === 'INVALID_DOCUMENT_FILE') {
.with('INVALID_DOCUMENT_FILE', () => msg`You cannot upload encrypted PDFs`) toast({
.with( title: _(msg`Invalid file`),
AppErrorCode.LIMIT_EXCEEDED, description: _(msg`You cannot upload encrypted PDFs`),
() => msg`You have reached your document limit for this month. Please upgrade your plan.`, variant: 'destructive',
) });
.otherwise(() => msg`An error occurred while uploading your document.`); } else if (err instanceof TRPCClientError) {
toast({
toast({ title: _(msg`Error`),
title: _(msg`Error`), description: err.message,
description: _(errorMessage), variant: 'destructive',
variant: 'destructive', });
duration: 7500, } else {
}); toast({
title: _(msg`Error`),
description: _(msg`An error occurred while uploading your document.`),
variant: 'destructive',
});
}
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }

View File

@@ -36,7 +36,7 @@ export const DeleteAccountDialog = ({ className, user }: DeleteAccountDialogProp
const [enteredEmail, setEnteredEmail] = useState<string>(''); const [enteredEmail, setEnteredEmail] = useState<string>('');
const { mutateAsync: deleteAccount, isPending: isDeletingAccount } = const { mutateAsync: deleteAccount, isLoading: isDeletingAccount } =
trpc.profile.deleteAccount.useMutation(); trpc.profile.deleteAccount.useMutation();
const onDeleteAccount = async () => { const onDeleteAccount = async () => {

View File

@@ -5,6 +5,7 @@ import { useEffect, useMemo, useState } from 'react';
import { Trans, msg } from '@lingui/macro'; import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react'; import { useLingui } from '@lingui/react';
import type { FindTemplateRow } from '@documenso/lib/server-only/template/find-templates';
import type { import type {
Team, Team,
TeamProfile, TeamProfile,
@@ -14,7 +15,6 @@ import type {
} from '@documenso/prisma/client'; } from '@documenso/prisma/client';
import { TemplateType } from '@documenso/prisma/client'; import { TemplateType } from '@documenso/prisma/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import type { FindTemplateRow } from '@documenso/trpc/server/template-router/schema';
import { cn } from '@documenso/ui/lib/utils'; import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button'; import { Button } from '@documenso/ui/primitives/button';
import { Switch } from '@documenso/ui/primitives/switch'; import { Switch } from '@documenso/ui/primitives/switch';
@@ -61,12 +61,13 @@ export const PublicProfilePageView = ({ user, team, profile }: PublicProfilePage
const { data } = trpc.template.findTemplates.useQuery({ const { data } = trpc.template.findTemplates.useQuery({
perPage: 100, perPage: 100,
teamId: team?.id,
}); });
const { mutateAsync: updateUserProfile, isPending: isUpdatingUserProfile } = const { mutateAsync: updateUserProfile, isLoading: isUpdatingUserProfile } =
trpc.profile.updatePublicProfile.useMutation(); trpc.profile.updatePublicProfile.useMutation();
const { mutateAsync: updateTeamProfile, isPending: isUpdatingTeamProfile } = const { mutateAsync: updateTeamProfile, isLoading: isUpdatingTeamProfile } =
trpc.team.updateTeamPublicProfile.useMutation(); trpc.team.updateTeamPublicProfile.useMutation();
const isUpdating = isUpdatingUserProfile || isUpdatingTeamProfile; const isUpdating = isUpdatingUserProfile || isUpdatingTeamProfile;

View File

@@ -7,11 +7,11 @@ import { useLingui } from '@lingui/react';
import { EditIcon, FileIcon, LinkIcon, MoreHorizontalIcon, Trash2Icon } from 'lucide-react'; import { EditIcon, FileIcon, LinkIcon, MoreHorizontalIcon, Trash2Icon } from 'lucide-react';
import { useCopyToClipboard } from '@documenso/lib/client-only/hooks/use-copy-to-clipboard'; import { useCopyToClipboard } from '@documenso/lib/client-only/hooks/use-copy-to-clipboard';
import type { FindTemplateRow } from '@documenso/lib/server-only/template/find-templates';
import { formatDirectTemplatePath } from '@documenso/lib/utils/templates'; import { formatDirectTemplatePath } from '@documenso/lib/utils/templates';
import type { TemplateDirectLink } from '@documenso/prisma/client'; import type { TemplateDirectLink } from '@documenso/prisma/client';
import { TemplateType } from '@documenso/prisma/client'; import { TemplateType } from '@documenso/prisma/client';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import type { FindTemplateRow } from '@documenso/trpc/server/template-router/schema';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -23,12 +23,15 @@ import { Skeleton } from '@documenso/ui/primitives/skeleton';
import { useToast } from '@documenso/ui/primitives/use-toast'; import { useToast } from '@documenso/ui/primitives/use-toast';
import { ManagePublicTemplateDialog } from '~/components/templates/manage-public-template-dialog'; import { ManagePublicTemplateDialog } from '~/components/templates/manage-public-template-dialog';
import { useOptionalCurrentTeam } from '~/providers/team';
type DirectTemplate = FindTemplateRow & { type DirectTemplate = FindTemplateRow & {
directLink: Pick<TemplateDirectLink, 'token' | 'enabled'>; directLink: Pick<TemplateDirectLink, 'token' | 'enabled'>;
}; };
export const PublicTemplatesDataTable = () => { export const PublicTemplatesDataTable = () => {
const team = useOptionalCurrentTeam();
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
@@ -39,10 +42,12 @@ export const PublicTemplatesDataTable = () => {
templateId: number; templateId: number;
} | null>(null); } | null>(null);
const { data, isLoading, isLoadingError, refetch } = trpc.template.findTemplates.useQuery( const { data, isInitialLoading, isLoadingError, refetch } = trpc.template.findTemplates.useQuery(
{},
{ {
placeholderData: (previousData) => previousData, teamId: team?.id,
},
{
keepPreviousData: true,
}, },
); );
@@ -80,7 +85,7 @@ export const PublicTemplatesDataTable = () => {
{/* Loading and error handling states. */} {/* Loading and error handling states. */}
{publicDirectTemplates.length === 0 && ( {publicDirectTemplates.length === 0 && (
<> <>
{isLoading && {isInitialLoading &&
Array(3) Array(3)
.fill(0) .fill(0)
.map((_, index) => ( .map((_, index) => (
@@ -115,7 +120,7 @@ export const PublicTemplatesDataTable = () => {
</div> </div>
)} )}
{!isLoading && ( {!isInitialLoading && (
<div className="text-muted-foreground flex h-32 flex-col items-center justify-center text-sm"> <div className="text-muted-foreground flex h-32 flex-col items-center justify-center text-sm">
<Trans>No public profile templates found</Trans> <Trans>No public profile templates found</Trans>
<ManagePublicTemplateDialog <ManagePublicTemplateDialog

View File

@@ -35,15 +35,16 @@ export const UserSecurityActivityDataTable = () => {
const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? [])); const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? []));
const { data, isLoading, isLoadingError } = trpc.profile.findUserSecurityAuditLogs.useQuery( const { data, isLoading, isInitialLoading, isLoadingError } =
{ trpc.profile.findUserSecurityAuditLogs.useQuery(
page: parsedSearchParams.page, {
perPage: parsedSearchParams.perPage, page: parsedSearchParams.page,
}, perPage: parsedSearchParams.perPage,
{ },
placeholderData: (previousData) => previousData, {
}, keepPreviousData: true,
); },
);
const onPaginationChange = (page: number, perPage: number) => { const onPaginationChange = (page: number, perPage: number) => {
updateSearchParams({ updateSearchParams({
@@ -133,7 +134,7 @@ export const UserSecurityActivityDataTable = () => {
enable: isLoadingError, enable: isLoadingError,
}} }}
skeleton={{ skeleton={{
enable: isLoading, enable: isLoading && isInitialLoading,
rows: 3, rows: 3,
component: ( component: (
<> <>

View File

@@ -65,7 +65,7 @@ export const CreatePasskeyDialog = ({ trigger, onSuccess, ...props }: CreatePass
}, },
}); });
const { mutateAsync: createPasskeyRegistrationOptions, isPending } = const { mutateAsync: createPasskeyRegistrationOptions, isLoading } =
trpc.auth.createPasskeyRegistrationOptions.useMutation(); trpc.auth.createPasskeyRegistrationOptions.useMutation();
const { mutateAsync: createPasskey } = trpc.auth.createPasskey.useMutation(); const { mutateAsync: createPasskey } = trpc.auth.createPasskey.useMutation();
@@ -141,7 +141,7 @@ export const CreatePasskeyDialog = ({ trigger, onSuccess, ...props }: CreatePass
> >
<DialogTrigger onClick={(e) => e.stopPropagation()} asChild={true}> <DialogTrigger onClick={(e) => e.stopPropagation()} asChild={true}>
{trigger ?? ( {trigger ?? (
<Button variant="secondary" loading={isPending}> <Button variant="secondary" loading={isLoading}>
<KeyRoundIcon className="-ml-1 mr-1 h-5 w-5" /> <KeyRoundIcon className="-ml-1 mr-1 h-5 w-5" />
<Trans>Add passkey</Trans> <Trans>Add passkey</Trans>
</Button> </Button>

View File

@@ -60,7 +60,7 @@ export const UserPasskeysDataTableActions = ({
}, },
}); });
const { mutateAsync: updatePasskey, isPending: isUpdatingPasskey } = const { mutateAsync: updatePasskey, isLoading: isUpdatingPasskey } =
trpc.auth.updatePasskey.useMutation({ trpc.auth.updatePasskey.useMutation({
onSuccess: () => { onSuccess: () => {
toast({ toast({
@@ -80,7 +80,7 @@ export const UserPasskeysDataTableActions = ({
}, },
}); });
const { mutateAsync: deletePasskey, isPending: isDeletingPasskey } = const { mutateAsync: deletePasskey, isLoading: isDeletingPasskey } =
trpc.auth.deletePasskey.useMutation({ trpc.auth.deletePasskey.useMutation({
onSuccess: () => { onSuccess: () => {
toast({ toast({

View File

@@ -29,13 +29,13 @@ export const UserPasskeysDataTable = () => {
const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? [])); const parsedSearchParams = ZUrlSearchParamsSchema.parse(Object.fromEntries(searchParams ?? []));
const { data, isLoading, isLoadingError } = trpc.auth.findPasskeys.useQuery( const { data, isLoading, isInitialLoading, isLoadingError } = trpc.auth.findPasskeys.useQuery(
{ {
page: parsedSearchParams.page, page: parsedSearchParams.page,
perPage: parsedSearchParams.perPage, perPage: parsedSearchParams.perPage,
}, },
{ {
placeholderData: (previousData) => previousData, keepPreviousData: true,
}, },
); );
@@ -100,7 +100,7 @@ export const UserPasskeysDataTable = () => {
enable: isLoadingError, enable: isLoadingError,
}} }}
skeleton={{ skeleton={{
enable: isLoading, enable: isLoading && isInitialLoading,
rows: 3, rows: 3,
component: ( component: (
<> <>

View File

@@ -17,7 +17,7 @@ export const AcceptTeamInvitationButton = ({ teamId }: AcceptTeamInvitationButto
const { const {
mutateAsync: acceptTeamInvitation, mutateAsync: acceptTeamInvitation,
isPending, isLoading,
isSuccess, isSuccess,
} = trpc.team.acceptTeamInvitation.useMutation({ } = trpc.team.acceptTeamInvitation.useMutation({
onSuccess: () => { onSuccess: () => {
@@ -40,8 +40,8 @@ export const AcceptTeamInvitationButton = ({ teamId }: AcceptTeamInvitationButto
return ( return (
<Button <Button
onClick={async () => acceptTeamInvitation({ teamId })} onClick={async () => acceptTeamInvitation({ teamId })}
loading={isPending} loading={isLoading}
disabled={isPending || isSuccess} disabled={isLoading || isSuccess}
> >
<Trans>Accept</Trans> <Trans>Accept</Trans>
</Button> </Button>

View File

@@ -17,7 +17,7 @@ export const DeclineTeamInvitationButton = ({ teamId }: DeclineTeamInvitationBut
const { const {
mutateAsync: declineTeamInvitation, mutateAsync: declineTeamInvitation,
isPending, isLoading,
isSuccess, isSuccess,
} = trpc.team.declineTeamInvitation.useMutation({ } = trpc.team.declineTeamInvitation.useMutation({
onSuccess: () => { onSuccess: () => {
@@ -40,8 +40,8 @@ export const DeclineTeamInvitationButton = ({ teamId }: DeclineTeamInvitationBut
return ( return (
<Button <Button
onClick={async () => declineTeamInvitation({ teamId })} onClick={async () => declineTeamInvitation({ teamId })}
loading={isPending} loading={isLoading}
disabled={isPending || isSuccess} disabled={isLoading || isSuccess}
variant="ghost" variant="ghost"
> >
<Trans>Decline</Trans> <Trans>Decline</Trans>

View File

@@ -30,7 +30,7 @@ export const TeamEmailUsage = ({ teamEmail }: TeamEmailUsageProps) => {
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
const { mutateAsync: deleteTeamEmail, isPending: isDeletingTeamEmail } = const { mutateAsync: deleteTeamEmail, isLoading: isDeletingTeamEmail } =
trpc.team.deleteTeamEmail.useMutation({ trpc.team.deleteTeamEmail.useMutation({
onSuccess: () => { onSuccess: () => {
toast({ toast({

View File

@@ -23,11 +23,11 @@ import { AcceptTeamInvitationButton } from './accept-team-invitation-button';
import { DeclineTeamInvitationButton } from './decline-team-invitation-button'; import { DeclineTeamInvitationButton } from './decline-team-invitation-button';
export const TeamInvitations = () => { export const TeamInvitations = () => {
const { data, isLoading } = trpc.team.getTeamInvitations.useQuery(); const { data, isInitialLoading } = trpc.team.getTeamInvitations.useQuery();
return ( return (
<AnimatePresence> <AnimatePresence>
{data && data.length > 0 && !isLoading && ( {data && data.length > 0 && !isInitialLoading && (
<AnimateGenericFadeInOut> <AnimateGenericFadeInOut>
<Alert variant="secondary"> <Alert variant="secondary">
<div className="flex h-full flex-row items-center p-2"> <div className="flex h-full flex-row items-center p-2">

View File

@@ -12,7 +12,7 @@ import {
DO_NOT_INVALIDATE_QUERY_ON_MUTATION, DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
SKIP_QUERY_BATCH_META, SKIP_QUERY_BATCH_META,
} from '@documenso/lib/constants/trpc'; } from '@documenso/lib/constants/trpc';
import type { TTemplate } from '@documenso/lib/types/template'; import type { TemplateWithDetails } from '@documenso/prisma/types/template';
import { trpc } from '@documenso/trpc/react'; import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils'; import { cn } from '@documenso/ui/lib/utils';
import { Card, CardContent } from '@documenso/ui/primitives/card'; import { Card, CardContent } from '@documenso/ui/primitives/card';
@@ -32,7 +32,7 @@ import { useOptionalCurrentTeam } from '~/providers/team';
export type EditTemplateFormProps = { export type EditTemplateFormProps = {
className?: string; className?: string;
initialTemplate: TTemplate; initialTemplate: TemplateWithDetails;
isEnterprise: boolean; isEnterprise: boolean;
templateRootPath: string; templateRootPath: string;
}; };
@@ -62,6 +62,7 @@ export const EditTemplateForm = ({
const { data: template, refetch: refetchTemplate } = trpc.template.getTemplateById.useQuery( const { data: template, refetch: refetchTemplate } = trpc.template.getTemplateById.useQuery(
{ {
templateId: initialTemplate.id, templateId: initialTemplate.id,
teamId: initialTemplate.teamId || undefined,
}, },
{ {
initialData: initialTemplate, initialData: initialTemplate,
@@ -69,7 +70,7 @@ export const EditTemplateForm = ({
}, },
); );
const { recipients, fields, templateDocumentData } = template; const { Recipient: recipients, Field: fields, templateDocumentData } = template;
const documentFlow: Record<EditTemplateStep, DocumentFlowStep> = { const documentFlow: Record<EditTemplateStep, DocumentFlowStep> = {
settings: { settings: {
@@ -103,6 +104,19 @@ export const EditTemplateForm = ({
}, },
}); });
const { mutateAsync: setSigningOrderForTemplate } =
trpc.template.setSigningOrderForTemplate.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => {
utils.template.getTemplateById.setData(
{
templateId: initialTemplate.id,
},
(oldData) => ({ ...(oldData || initialTemplate), ...newData }),
);
},
});
const { mutateAsync: addTemplateFields } = trpc.field.addTemplateFields.useMutation({ const { mutateAsync: addTemplateFields } = trpc.field.addTemplateFields.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION, ...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => { onSuccess: (newData) => {
@@ -115,7 +129,7 @@ export const EditTemplateForm = ({
}, },
}); });
const { mutateAsync: setRecipients } = trpc.recipient.setTemplateRecipients.useMutation({ const { mutateAsync: addTemplateSigners } = trpc.recipient.addTemplateSigners.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION, ...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => { onSuccess: (newData) => {
utils.template.getTemplateById.setData( utils.template.getTemplateById.setData(
@@ -127,14 +141,31 @@ export const EditTemplateForm = ({
}, },
}); });
const { mutateAsync: updateTypedSignature } =
trpc.template.updateTemplateTypedSignatureSettings.useMutation({
...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
onSuccess: (newData) => {
utils.template.getTemplateById.setData(
{
templateId: initialTemplate.id,
},
(oldData) => ({
...(oldData || initialTemplate),
...newData,
id: Number(newData.id),
}),
);
},
});
const onAddSettingsFormSubmit = async (data: TAddTemplateSettingsFormSchema) => { const onAddSettingsFormSubmit = async (data: TAddTemplateSettingsFormSchema) => {
try { try {
await updateTemplateSettings({ await updateTemplateSettings({
templateId: template.id, templateId: template.id,
teamId: team?.id,
data: { data: {
title: data.title, title: data.title,
externalId: data.externalId || null, externalId: data.externalId || null,
visibility: data.visibility,
globalAccessAuth: data.globalAccessAuth ?? null, globalAccessAuth: data.globalAccessAuth ?? null,
globalActionAuth: data.globalActionAuth ?? null, globalActionAuth: data.globalActionAuth ?? null,
}, },
@@ -164,16 +195,16 @@ export const EditTemplateForm = ({
) => { ) => {
try { try {
await Promise.all([ await Promise.all([
updateTemplateSettings({ setSigningOrderForTemplate({
templateId: template.id, templateId: template.id,
meta: { teamId: team?.id,
signingOrder: data.signingOrder, signingOrder: data.signingOrder,
},
}), }),
setRecipients({ addTemplateSigners({
templateId: template.id, templateId: template.id,
recipients: data.signers, teamId: team?.id,
signers: data.signers,
}), }),
]); ]);
@@ -197,11 +228,10 @@ export const EditTemplateForm = ({
fields: data.fields, fields: data.fields,
}); });
await updateTemplateSettings({ await updateTypedSignature({
templateId: template.id, templateId: template.id,
meta: { teamId: team?.id,
typedSignatureEnabled: data.typedSignatureEnabled, typedSignatureEnabled: data.typedSignatureEnabled,
},
}); });
// Clear all field data from localStorage // Clear all field data from localStorage
@@ -266,7 +296,6 @@ export const EditTemplateForm = ({
<AddTemplateSettingsFormPartial <AddTemplateSettingsFormPartial
key={recipients.length} key={recipients.length}
template={template} template={template}
currentTeamMemberRole={team?.currentTeamMember?.role}
documentFlow={documentFlow.settings} documentFlow={documentFlow.settings}
recipients={recipients} recipients={recipients}
fields={fields} fields={fields}

View File

@@ -11,7 +11,7 @@ import { Button } from '@documenso/ui/primitives/button';
import { TemplateDirectLinkDialog } from '../template-direct-link-dialog'; import { TemplateDirectLinkDialog } from '../template-direct-link-dialog';
export type TemplateDirectLinkDialogWrapperProps = { export type TemplateDirectLinkDialogWrapperProps = {
template: Template & { directLink?: TemplateDirectLink | null; recipients: Recipient[] }; template: Template & { directLink?: TemplateDirectLink | null; Recipient: Recipient[] };
}; };
export const TemplateDirectLinkDialogWrapper = ({ export const TemplateDirectLinkDialogWrapper = ({

View File

@@ -69,19 +69,21 @@ export const TemplatePageViewDocumentsTable = ({
Object.fromEntries(searchParams ?? []), Object.fromEntries(searchParams ?? []),
); );
const { data, isLoading, isLoadingError } = trpc.document.findDocuments.useQuery( const { data, isLoading, isInitialLoading, isLoadingError } =
{ trpc.document.findDocuments.useQuery(
templateId, {
page: parsedSearchParams.page, templateId,
perPage: parsedSearchParams.perPage, teamId: team?.id,
query: parsedSearchParams.query, page: parsedSearchParams.page,
source: parsedSearchParams.source, perPage: parsedSearchParams.perPage,
status: parsedSearchParams.status, query: parsedSearchParams.query,
}, source: parsedSearchParams.source,
{ status: parsedSearchParams.status,
placeholderData: (previousData) => previousData, },
}, {
); keepPreviousData: true,
},
);
const onPaginationChange = (page: number, perPage: number) => { const onPaginationChange = (page: number, perPage: number) => {
updateSearchParams({ updateSearchParams({
@@ -115,7 +117,7 @@ export const TemplatePageViewDocumentsTable = ({
accessorKey: 'recipient', accessorKey: 'recipient',
cell: ({ row }) => ( cell: ({ row }) => (
<StackAvatarsWithTooltip <StackAvatarsWithTooltip
recipients={row.original.recipients} recipients={row.original.Recipient}
documentStatus={row.original.status} documentStatus={row.original.status}
/> />
), ),
@@ -240,7 +242,7 @@ export const TemplatePageViewDocumentsTable = ({
enable: isLoadingError, enable: isLoadingError,
}} }}
skeleton={{ skeleton={{
enable: isLoading, enable: isLoading && isInitialLoading,
rows: 3, rows: 3,
component: ( component: (
<> <>

View File

@@ -12,7 +12,7 @@ import type { Template, User } from '@documenso/prisma/client';
export type TemplatePageViewInformationProps = { export type TemplatePageViewInformationProps = {
userId: number; userId: number;
template: Template & { template: Template & {
user: Pick<User, 'id' | 'name' | 'email'>; User: Pick<User, 'id' | 'name' | 'email'>;
}; };
}; };
@@ -28,8 +28,7 @@ export const TemplatePageViewInformation = ({
return [ return [
{ {
description: msg`Uploaded by`, description: msg`Uploaded by`,
value: value: userId === template.userId ? _(msg`You`) : template.User.name ?? template.User.email,
userId === template.userId ? _(msg`You`) : (template.user.name ?? template.user.email),
}, },
{ {
description: msg`Created`, description: msg`Created`,

View File

@@ -20,10 +20,12 @@ export type TemplatePageViewRecentActivityProps = {
export const TemplatePageViewRecentActivity = ({ export const TemplatePageViewRecentActivity = ({
templateId, templateId,
teamId,
documentRootPath, documentRootPath,
}: TemplatePageViewRecentActivityProps) => { }: TemplatePageViewRecentActivityProps) => {
const { data, isLoading, isLoadingError, refetch } = trpc.document.findDocuments.useQuery({ const { data, isLoading, isLoadingError, refetch } = trpc.document.findDocuments.useQuery({
templateId, templateId,
teamId,
orderByColumn: 'createdAt', orderByColumn: 'createdAt',
orderByDirection: 'asc', orderByDirection: 'asc',
perPage: 5, perPage: 5,
@@ -123,7 +125,7 @@ export const TemplatePageViewRecentActivity = ({
{match(document.source) {match(document.source)
.with(DocumentSource.DOCUMENT, DocumentSource.TEMPLATE, () => ( .with(DocumentSource.DOCUMENT, DocumentSource.TEMPLATE, () => (
<Trans> <Trans>
Document created by <span className="font-bold">{document.user.name}</span> Document created by <span className="font-bold">{document.User.name}</span>
</Trans> </Trans>
)) ))
.with(DocumentSource.TEMPLATE_DIRECT_LINK, () => ( .with(DocumentSource.TEMPLATE_DIRECT_LINK, () => (

View File

@@ -10,7 +10,7 @@ import { AvatarWithText } from '@documenso/ui/primitives/avatar';
export type TemplatePageViewRecipientsProps = { export type TemplatePageViewRecipientsProps = {
template: Template & { template: Template & {
recipients: Recipient[]; Recipient: Recipient[];
}; };
templateRootPath: string; templateRootPath: string;
}; };
@@ -21,7 +21,7 @@ export const TemplatePageViewRecipients = ({
}: TemplatePageViewRecipientsProps) => { }: TemplatePageViewRecipientsProps) => {
const { _ } = useLingui(); const { _ } = useLingui();
const recipients = template.recipients; const recipients = template.Recipient;
return ( return (
<section className="dark:bg-background border-border bg-widget flex flex-col rounded-xl border"> <section className="dark:bg-background border-border bg-widget flex flex-col rounded-xl border">

View File

@@ -14,7 +14,6 @@ import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
import { DocumentReadOnlyFields } from '~/components/document/document-read-only-fields'; import { DocumentReadOnlyFields } from '~/components/document/document-read-only-fields';
import { TemplateType } from '~/components/formatter/template-type'; import { TemplateType } from '~/components/formatter/template-type';
import { TemplateBulkSendDialog } from '~/components/templates/template-bulk-send-dialog';
import { DataTableActionDropdown } from '../data-table-action-dropdown'; import { DataTableActionDropdown } from '../data-table-action-dropdown';
import { TemplateDirectLinkBadge } from '../template-direct-link-badge'; import { TemplateDirectLinkBadge } from '../template-direct-link-badge';
@@ -55,10 +54,10 @@ export const TemplatePageView = async ({ params, team }: TemplatePageViewProps)
redirect(templateRootPath); redirect(templateRootPath);
} }
const { templateDocumentData, fields, recipients, templateMeta } = template; const { templateDocumentData, Field, Recipient: recipients, templateMeta } = template;
// Remap to fit the DocumentReadOnlyFields component. // Remap to fit the DocumentReadOnlyFields component.
const readOnlyFields = fields.map((field) => { const readOnlyFields = Field.map((field) => {
const recipient = recipients.find((recipient) => recipient.id === field.recipientId) || { const recipient = recipients.find((recipient) => recipient.id === field.recipientId) || {
name: '', name: '',
email: '', email: '',
@@ -67,8 +66,8 @@ export const TemplatePageView = async ({ params, team }: TemplatePageViewProps)
return { return {
...field, ...field,
recipient, Recipient: recipient,
signature: null, Signature: null,
}; };
}); });
@@ -112,8 +111,6 @@ export const TemplatePageView = async ({ params, team }: TemplatePageViewProps)
<div className="mt-2 flex flex-row space-x-4 sm:mt-0 sm:self-end"> <div className="mt-2 flex flex-row space-x-4 sm:mt-0 sm:self-end">
<TemplateDirectLinkDialogWrapper template={template} /> <TemplateDirectLinkDialogWrapper template={template} />
<TemplateBulkSendDialog templateId={template.id} recipients={template.recipients} />
<Button className="w-full" asChild> <Button className="w-full" asChild>
<Link href={`${templateRootPath}/${template.id}/edit`}> <Link href={`${templateRootPath}/${template.id}/edit`}>
<LucideEdit className="mr-1.5 h-3.5 w-3.5" /> <LucideEdit className="mr-1.5 h-3.5 w-3.5" />
@@ -168,7 +165,7 @@ export const TemplatePageView = async ({ params, team }: TemplatePageViewProps)
<UseTemplateDialog <UseTemplateDialog
templateId={template.id} templateId={template.id}
templateSigningOrder={template.templateMeta?.signingOrder} templateSigningOrder={template.templateMeta?.signingOrder}
recipients={template.recipients} recipients={template.Recipient}
documentRootPath={documentRootPath} documentRootPath={documentRootPath}
trigger={ trigger={
<Button className="w-full"> <Button className="w-full">

View File

@@ -5,7 +5,7 @@ import { useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { Trans } from '@lingui/macro'; import { Trans } from '@lingui/macro';
import { Copy, Edit, MoreHorizontal, MoveRight, Share2Icon, Trash2, Upload } from 'lucide-react'; import { Copy, Edit, MoreHorizontal, MoveRight, Share2Icon, Trash2 } from 'lucide-react';
import { useSession } from 'next-auth/react'; import { useSession } from 'next-auth/react';
import type { Recipient, Template, TemplateDirectLink } from '@documenso/prisma/client'; import type { Recipient, Template, TemplateDirectLink } from '@documenso/prisma/client';
@@ -17,8 +17,6 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@documenso/ui/primitives/dropdown-menu'; } from '@documenso/ui/primitives/dropdown-menu';
import { TemplateBulkSendDialog } from '~/components/templates/template-bulk-send-dialog';
import { DeleteTemplateDialog } from './delete-template-dialog'; import { DeleteTemplateDialog } from './delete-template-dialog';
import { DuplicateTemplateDialog } from './duplicate-template-dialog'; import { DuplicateTemplateDialog } from './duplicate-template-dialog';
import { MoveTemplateDialog } from './move-template-dialog'; import { MoveTemplateDialog } from './move-template-dialog';
@@ -27,7 +25,7 @@ import { TemplateDirectLinkDialog } from './template-direct-link-dialog';
export type DataTableActionDropdownProps = { export type DataTableActionDropdownProps = {
row: Template & { row: Template & {
directLink?: Pick<TemplateDirectLink, 'token' | 'enabled'> | null; directLink?: Pick<TemplateDirectLink, 'token' | 'enabled'> | null;
recipients: Recipient[]; Recipient: Recipient[];
}; };
templateRootPath: string; templateRootPath: string;
teamId?: number; teamId?: number;
@@ -81,24 +79,13 @@ export const DataTableActionDropdown = ({
<Trans>Direct link</Trans> <Trans>Direct link</Trans>
</DropdownMenuItem> </DropdownMenuItem>
{!teamId && !row.teamId && ( {!teamId && (
<DropdownMenuItem onClick={() => setMoveDialogOpen(true)}> <DropdownMenuItem onClick={() => setMoveDialogOpen(true)}>
<MoveRight className="mr-2 h-4 w-4" /> <MoveRight className="mr-2 h-4 w-4" />
<Trans>Move to Team</Trans> <Trans>Move to Team</Trans>
</DropdownMenuItem> </DropdownMenuItem>
)} )}
<TemplateBulkSendDialog
templateId={row.id}
recipients={row.recipients}
trigger={
<div className="hover:bg-accent hover:text-accent-foreground relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors">
<Upload className="mr-2 h-4 w-4" />
<Trans>Bulk Send via CSV</Trans>
</div>
}
/>
<DropdownMenuItem <DropdownMenuItem
disabled={!isOwner && !isTeamTemplate} disabled={!isOwner && !isTeamTemplate}
onClick={() => setDeleteDialogOpen(true)} onClick={() => setDeleteDialogOpen(true)}

View File

@@ -10,7 +10,7 @@ import { AlertTriangle, Globe2Icon, InfoIcon, Link2Icon, Loader, LockIcon } from
import { useLimits } from '@documenso/ee/server-only/limits/provider/client'; import { useLimits } from '@documenso/ee/server-only/limits/provider/client';
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params'; import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
import type { FindTemplateRow } from '@documenso/trpc/server/template-router/schema'; import type { FindTemplateRow } from '@documenso/lib/server-only/template/find-templates';
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert'; import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table'; import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table';
import { DataTable } from '@documenso/ui/primitives/data-table'; import { DataTable } from '@documenso/ui/primitives/data-table';
@@ -146,7 +146,7 @@ export const TemplatesDataTable = ({
templateId={row.original.id} templateId={row.original.id}
templateSigningOrder={row.original.templateMeta?.signingOrder} templateSigningOrder={row.original.templateMeta?.signingOrder}
documentDistributionMethod={row.original.templateMeta?.distributionMethod} documentDistributionMethod={row.original.templateMeta?.distributionMethod}
recipients={row.original.recipients} recipients={row.original.Recipient}
documentRootPath={documentRootPath} documentRootPath={documentRootPath}
/> />

View File

@@ -22,13 +22,18 @@ type DeleteTemplateDialogProps = {
onOpenChange: (_open: boolean) => void; onOpenChange: (_open: boolean) => void;
}; };
export const DeleteTemplateDialog = ({ id, open, onOpenChange }: DeleteTemplateDialogProps) => { export const DeleteTemplateDialog = ({
id,
teamId,
open,
onOpenChange,
}: DeleteTemplateDialogProps) => {
const router = useRouter(); const router = useRouter();
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
const { mutateAsync: deleteTemplate, isPending } = trpcReact.template.deleteTemplate.useMutation({ const { mutateAsync: deleteTemplate, isLoading } = trpcReact.template.deleteTemplate.useMutation({
onSuccess: () => { onSuccess: () => {
router.refresh(); router.refresh();
@@ -51,7 +56,7 @@ export const DeleteTemplateDialog = ({ id, open, onOpenChange }: DeleteTemplateD
}); });
return ( return (
<Dialog open={open} onOpenChange={(value) => !isPending && onOpenChange(value)}> <Dialog open={open} onOpenChange={(value) => !isLoading && onOpenChange(value)}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
@@ -70,7 +75,7 @@ export const DeleteTemplateDialog = ({ id, open, onOpenChange }: DeleteTemplateD
<Button <Button
type="button" type="button"
variant="secondary" variant="secondary"
disabled={isPending} disabled={isLoading}
onClick={() => onOpenChange(false)} onClick={() => onOpenChange(false)}
> >
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
@@ -79,8 +84,8 @@ export const DeleteTemplateDialog = ({ id, open, onOpenChange }: DeleteTemplateD
<Button <Button
type="button" type="button"
variant="destructive" variant="destructive"
loading={isPending} loading={isLoading}
onClick={async () => deleteTemplate({ templateId: id })} onClick={async () => deleteTemplate({ templateId: id, teamId })}
> >
<Trans>Delete</Trans> <Trans>Delete</Trans>
</Button> </Button>

View File

@@ -24,6 +24,7 @@ type DuplicateTemplateDialogProps = {
export const DuplicateTemplateDialog = ({ export const DuplicateTemplateDialog = ({
id, id,
teamId,
open, open,
onOpenChange, onOpenChange,
}: DuplicateTemplateDialogProps) => { }: DuplicateTemplateDialogProps) => {
@@ -32,7 +33,7 @@ export const DuplicateTemplateDialog = ({
const { _ } = useLingui(); const { _ } = useLingui();
const { toast } = useToast(); const { toast } = useToast();
const { mutateAsync: duplicateTemplate, isPending } = const { mutateAsync: duplicateTemplate, isLoading } =
trpcReact.template.duplicateTemplate.useMutation({ trpcReact.template.duplicateTemplate.useMutation({
onSuccess: () => { onSuccess: () => {
router.refresh(); router.refresh();
@@ -55,7 +56,7 @@ export const DuplicateTemplateDialog = ({
}); });
return ( return (
<Dialog open={open} onOpenChange={(value) => !isPending && onOpenChange(value)}> <Dialog open={open} onOpenChange={(value) => !isLoading && onOpenChange(value)}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
@@ -70,7 +71,7 @@ export const DuplicateTemplateDialog = ({
<DialogFooter> <DialogFooter>
<Button <Button
type="button" type="button"
disabled={isPending} disabled={isLoading}
variant="secondary" variant="secondary"
onClick={() => onOpenChange(false)} onClick={() => onOpenChange(false)}
> >
@@ -79,10 +80,11 @@ export const DuplicateTemplateDialog = ({
<Button <Button
type="button" type="button"
loading={isPending} loading={isLoading}
onClick={async () => onClick={async () =>
duplicateTemplate({ duplicateTemplate({
templateId: id, templateId: id,
teamId,
}) })
} }
> >

View File

@@ -42,8 +42,8 @@ export const MoveTemplateDialog = ({ templateId, open, onOpenChange }: MoveTempl
const [selectedTeamId, setSelectedTeamId] = useState<number | null>(null); const [selectedTeamId, setSelectedTeamId] = useState<number | null>(null);
const { data: teams, isPending: isLoadingTeams } = trpc.team.getTeams.useQuery(); const { data: teams, isLoading: isLoadingTeams } = trpc.team.getTeams.useQuery();
const { mutateAsync: moveTemplate, isPending } = trpc.template.moveTemplateToTeam.useMutation({ const { mutateAsync: moveTemplate, isLoading } = trpc.template.moveTemplateToTeam.useMutation({
onSuccess: () => { onSuccess: () => {
router.refresh(); router.refresh();
toast({ toast({
@@ -130,8 +130,8 @@ export const MoveTemplateDialog = ({ templateId, open, onOpenChange }: MoveTempl
<Button variant="secondary" onClick={() => onOpenChange(false)}> <Button variant="secondary" onClick={() => onOpenChange(false)}>
<Trans>Cancel</Trans> <Trans>Cancel</Trans>
</Button> </Button>
<Button onClick={onMove} loading={isPending} disabled={!selectedTeamId || isPending}> <Button onClick={onMove} loading={isLoading} disabled={!selectedTeamId || isLoading}>
{isPending ? <Trans>Moving...</Trans> : <Trans>Move</Trans>} {isLoading ? <Trans>Moving...</Trans> : <Trans>Move</Trans>}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -31,7 +31,7 @@ type NewTemplateDialogProps = {
templateRootPath: string; templateRootPath: string;
}; };
export const NewTemplateDialog = ({ templateRootPath }: NewTemplateDialogProps) => { export const NewTemplateDialog = ({ teamId, templateRootPath }: NewTemplateDialogProps) => {
const router = useRouter(); const router = useRouter();
const { data: session } = useSession(); const { data: session } = useSession();
@@ -58,6 +58,7 @@ export const NewTemplateDialog = ({ templateRootPath }: NewTemplateDialogProps)
}); });
const { id } = await createTemplate({ const { id } = await createTemplate({
teamId,
title: file.name, title: file.name,
templateDocumentDataId, templateDocumentDataId,
}); });

Some files were not shown because too many files have changed in this diff Show More