Compare commits

...

30 Commits

Author SHA1 Message Date
b176ff884f fix: merge conflicts 2025-01-30 11:28:05 +00:00
667b8f1a85 chore: add access token to all seal-document 2025-01-30 11:26:05 +00:00
00429038ac fix: qr code link undefined 2025-01-30 11:17:18 +00:00
810d194cfd feat: return the necessary information for document preview and download 2025-01-30 10:29:22 +00:00
6743a108c0 chore: use correct link for qrcode 2025-01-30 10:17:59 +00:00
d82a759acd feat: add document view page 2025-01-30 10:12:25 +00:00
edfb1f2157 feat: add document access token model 2025-01-30 05:38:03 +00:00
7cc85ca6bc chore: extract translations 2025-01-30 16:03:36 +11:00
bc19fa0cbd feat: add Polish and Italian (#1618) 2025-01-30 15:21:37 +11:00
a60f58e20b chore: add translations (#1617) 2025-01-30 15:09:35 +11:00
aca902b5ff chore: add translations (#1585)
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2025-01-30 13:24:46 +11:00
2f866c41b4 fix: create global settings on team creation (#1601)
The global team settings weren't created when creating a new team.

## Changes Made

The global team settings are now created when a new team is created.
2025-01-28 16:16:18 +11:00
7e4faef95f chore: add cancelled webhook event (#1608)
https://github.com/user-attachments/assets/9f2ff975-6688-4150-b4e3-0eb21e2b5503
2025-01-28 15:34:22 +11:00
bcef84787d feat: bulk send templates via csv (#1578)
Implements a bulk send feature allowing users to upload a CSV file to
create multiple documents from a template. Includes CSV template
generation, background processing, and email notifications.

<img width="563" alt="image"
src="https://github.com/user-attachments/assets/658cee71-6508-4a00-87da-b17c6762b7d8"
/>
<img width="578" alt="image"
src="https://github.com/user-attachments/assets/bbfac70b-c6a0-466a-be98-99ca4c4eb1b9"
/>
<img width="635" alt="image"
src="https://github.com/user-attachments/assets/65b2f55d-d491-45ac-84d6-1a31afe953dd"
/>


## Changes Made

- Added `TemplateBulkSendDialog` with CSV upload/download functionality
- Implemented bulk send job handler using background task system
- Created email template for completion notifications
- Added bulk send option to template view and actions dropdown
- Added CSV parsing with email/name validation

## Testing Performed

- CSV upload with valid/invalid data
- Bulk send with/without immediate sending
- Email notifications and error handling
- Team context integration
- File size and row count limits

Resolves #1550
2025-01-28 15:33:32 +11:00
70a3ac0525 fix: tidy document invite email render logic (#1597)
Updates one of our confusing ternaries to use `ts-pattern` for rendering
the conditional blocks making it easy to follow the logic occurring.

## Related Issue

N/A

## Changes Made

- Swapped ternary for `ts-pattern`

## Testing Performed

- Manually created a bunch of documents in configurations matching those
required to exhaust the `match` conditions.
2025-01-28 15:18:12 +11:00
c6fb101a99 fix: admin leaderboard query sorting (#1548) 2025-01-28 13:05:40 +11:00
2984af769c feat: add text align option to fields (#1610)
## Description

Adds the ability to align text to the left, center or right for relevant
fields.

Previously text was always centered which can be less desirable.

See attached debug document which has left, center and right text
alignments set for fields.

<img width="614" alt="image"
src="https://github.com/user-attachments/assets/361a030e-813d-458b-9c7a-ff4c9fa5e33c"
/>


## Related Issue

N/A

## Changes Made

- Added text align option
- Update the insert in pdf method to support different alignments
- Added a debug mode to field insertion

## Testing Performed

- Ran manual tests using the debug mode
2025-01-28 12:29:38 +11:00
9183f668d3 chore: bump node version for docker 2025-01-27 12:20:04 +11:00
54ea96391a fix: correct redirect after document duplication (#1595) 2025-01-23 16:34:22 +11:00
42d24fd1a1 feat: copy, paste, duplicate template fields (#1594) 2025-01-23 14:28:26 +11:00
dc36a8182c v1.9.0-rc.11 2025-01-21 09:49:22 +11:00
0ef85b47b1 fix: handle empty object as fieldMeta 2025-01-21 09:46:54 +11:00
058d9dd0ba v1.9.0-rc.10 2025-01-20 19:54:39 +11:00
74bb230247 fix: add empty success responses (#1600) 2025-01-20 19:47:39 +11:00
04e5244a5a chore: update styling 2025-01-09 14:38:00 +11:00
e367894218 Merge branch 'main' into feat/document-qrcode 2025-01-09 13:15:15 +11:00
99b0b80635 chore: use uqr 2025-01-07 13:05:52 +00:00
1b1cd0ba3d Merge branch 'main' into feat/document-qrcode 2025-01-07 12:59:21 +00:00
1fe5cda0ed Merge branch 'main' into feat/document-qrcode 2025-01-03 03:07:05 +00:00
f82e71f11c feat: qr code 2025-01-03 03:05:01 +00:00
62 changed files with 10519 additions and 1412 deletions

View File

@ -21,6 +21,7 @@ Documenso supports Webhooks and allows you to subscribe to the following events:
- `document.signed`
- `document.completed`
- `document.rejected`
- `document.cancelled`
## Create a webhook subscription
@ -37,7 +38,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:
- 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`.
- Select the event(s) you want to subscribe to: `document.created`, `document.sent`, `document.opened`, `document.signed`, `document.completed`, `document.rejected`, `document.cancelled`.
- 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)
@ -528,6 +529,96 @@ 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
Webhooks are available to individual users and teams.

View File

@ -1,6 +1,6 @@
{
"name": "@documenso/web",
"version": "1.9.0-rc.9",
"version": "1.9.0-rc.11",
"private": true,
"license": "AGPL-3.0",
"scripts": {

View File

@ -0,0 +1,19 @@
<svg width="58" height="58" viewBox="0 0 58 58" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M24.07 6.25832C23.333 6.92796 22.5176 7.71453 21.5857 8.63408C20.9957 9.09732 20.2682 9.35873 19.5117 9.37328L16.3896 9.43332L17.2992 8.52369C22.815 3.0079 25.5729 0.25 29 0.25C32.4271 0.25 35.185 3.00789 40.7008 8.52368L41.6087 9.43166L38.5937 9.37486C37.7437 9.35885 36.9292 9.03109 36.3051 8.45388L34.4972 6.78198C34.3255 6.6212 34.1581 6.46631 33.9946 6.31712L33.897 6.22687L33.8953 6.22687C33.2778 5.667 32.7153 5.18958 32.1851 4.78508C30.6538 3.6167 29.7624 3.35263 29 3.35263C28.2376 3.35263 27.3462 3.6167 25.8149 4.78508C25.2783 5.19451 24.7085 5.67864 24.0821 6.24737L24.0814 6.24737L24.07 6.25832Z" fill="black"/>
<path d="M51.6826 24.0051C51.5337 23.8419 51.3791 23.6748 51.2187 23.5035L49.5459 21.6946C48.9691 21.0709 48.6413 20.2571 48.6249 19.4077L48.5667 16.3896L49.4763 17.2992C54.9921 22.815 57.75 25.5729 57.75 29C57.75 32.4271 54.9921 35.185 49.4763 40.7008L48.5667 41.6104L48.6249 38.5923C48.6413 37.7429 48.9691 36.9291 49.5459 36.3054L51.2185 34.4968C51.379 34.3253 51.5337 34.1581 51.6827 33.9948L51.7731 33.897V33.8953C52.333 33.2778 52.8104 32.7153 53.2149 32.1851C54.3833 30.6538 54.6474 29.7624 54.6474 29C54.6474 28.2376 54.3833 27.3462 53.2149 25.8149C52.8104 25.2847 52.333 24.7222 51.7731 24.1047V24.103L51.6826 24.0051Z" fill="black"/>
<path d="M33.9601 51.7143C34.1446 51.5464 34.334 51.3711 34.5289 51.1883L36.3054 49.5457C36.9294 48.9687 37.7435 48.6411 38.5932 48.6249L41.6096 48.5675L40.7008 49.4763C35.185 54.9921 32.4271 57.75 29 57.75C25.5729 57.75 22.815 54.9921 17.2992 49.4763L16.3896 48.5667L19.4141 48.6248C20.2599 48.641 21.0705 48.9659 21.6934 49.5383L22.9131 50.6592C24.0267 51.726 24.9626 52.5647 25.8149 53.2149C27.3462 54.3833 28.2376 54.6474 29 54.6474C29.7624 54.6474 30.6538 54.3833 32.1851 53.2149C32.7217 52.8055 33.2915 52.3214 33.9179 51.7526H33.9187L33.9601 51.7143Z" fill="black"/>
<path d="M6.26202 33.9341C6.44675 34.1373 6.64036 34.3465 6.8432 34.5625L8.4547 36.3051C9.03166 36.929 9.35938 37.7431 9.37562 38.5927L9.43332 41.6104L8.52369 40.7008C3.0079 35.185 0.25 32.4271 0.25 29C0.25 25.5729 3.00789 22.815 8.52368 17.2992L9.43249 16.3904L9.37539 19.4067C9.3593 20.2567 9.03143 21.0711 8.45413 21.6952L6.79271 23.4913C6.62762 23.6675 6.46871 23.8392 6.3158 24.0069L6.22687 24.103L6.22687 24.1047C5.66699 24.7222 5.18958 25.2847 4.78508 25.8149C3.6167 27.3462 3.35263 28.2376 3.35263 29C3.35263 29.7624 3.6167 30.6538 4.78508 32.1851C5.1946 32.7219 5.67887 33.2918 6.24777 33.9184L6.24777 33.9187L6.26202 33.9341Z" fill="black"/>
<path d="M6.24777 24.0804L8.45413 21.6952C8.96576 21.1421 9.28147 20.4395 9.35788 19.6951C9.36697 18.4688 9.38705 17.3991 9.43129 16.4536L9.43374 16.3242L9.43774 16.3202C9.47846 15.5034 9.53816 14.7805 9.62565 14.1297C9.88231 12.2207 10.3259 11.4037 10.865 10.8646C11.4041 10.3255 12.2211 9.88195 14.1301 9.62529C14.7929 9.53618 15.5306 9.4759 16.3661 9.43513L16.3675 9.43374L16.4131 9.43287C17.3923 9.38614 18.5054 9.36574 19.7886 9.35686C20.5626 9.2798 21.2914 8.94412 21.8545 8.39979L24.0813 6.24742H22.7951C14.9946 6.24742 11.0944 6.24742 8.67108 8.67072C6.24777 11.094 6.24777 14.9943 6.24777 22.7948V24.0804Z" fill="black"/>
<path d="M6.24777 33.9187V35.2053C6.24777 43.0058 6.24777 46.9061 8.67108 49.3294C11.0944 51.7527 14.9946 51.7527 22.7951 51.7527H35.2057C43.0062 51.7527 46.9064 51.7527 49.3297 49.3294C51.753 46.9061 51.753 43.0058 51.753 35.2053V33.9187L49.5459 36.3054C49.0356 36.8571 48.7203 37.5577 48.643 38.3C48.6337 39.5529 48.613 40.6424 48.5668 41.603L48.5663 41.6325L48.5654 41.6334C48.5246 42.4693 48.4643 43.2073 48.3752 43.8704C48.1185 45.7794 47.6749 46.5964 47.1358 47.1355C46.5967 47.6746 45.7797 48.1181 43.8707 48.3748C43.2197 48.4623 42.4965 48.522 41.6793 48.5628L41.6758 48.5663L41.5626 48.5684C40.6127 48.6132 39.5373 48.6334 38.3032 48.6426C37.5597 48.7193 36.858 49.0347 36.3054 49.5457L33.9187 51.7526L24.103 51.7526L21.6934 49.5383C21.1424 49.032 20.4445 48.7193 19.7052 48.6426C18.4558 48.6334 17.3688 48.6129 16.4101 48.5671L16.3675 48.5663L16.3662 48.565C15.5307 48.5242 14.7929 48.4639 14.1301 48.3748C12.2211 48.1181 11.4041 47.6746 10.865 47.1355C10.3259 46.5964 9.88231 45.7794 9.62565 43.8704C9.53653 43.2075 9.47625 42.4698 9.43548 41.6342L9.43374 41.6325L9.43265 41.5753C9.38742 40.6221 9.36703 39.5422 9.35786 38.3022C9.281 37.559 8.96554 36.8575 8.4547 36.3051L6.24777 33.9187Z" fill="black"/>
<path d="M48.643 19.7C48.7203 20.4423 49.0356 21.1428 49.5459 21.6946L51.753 24.0813V22.7948C51.753 14.9943 51.753 11.094 49.3297 8.67072C46.9064 6.24742 43.0062 6.24742 35.2057 6.24742H33.9192L36.3051 8.45388C36.8586 8.96577 37.5618 9.28147 38.3067 9.35754C39.5257 9.36658 40.5898 9.38648 41.531 9.4302L41.7192 9.43374L41.725 9.43963C42.5235 9.4803 43.2319 9.5394 43.8707 9.62529C45.7797 9.88195 46.5967 10.3255 47.1358 10.8646C47.6749 11.4037 48.1185 12.2207 48.3752 14.1297C48.4643 14.7928 48.5246 15.5307 48.5654 16.3666L48.5663 16.3675L48.5668 16.3971C48.613 17.3577 48.6337 18.4471 48.643 19.7Z" fill="black"/>
<path d="M26.6453 15.2538L24.5526 17.0299C24.1792 17.3469 23.7112 17.5312 23.2219 17.554L19.7195 17.7172L21.5458 15.8909C25.071 12.3656 26.8336 10.603 29.0239 10.603C31.2142 10.603 32.9768 12.3656 36.502 15.8909L38.3172 17.706L34.7657 17.5521C34.2678 17.5305 33.7917 17.3417 33.4143 17.0162L31.8345 15.6533C31.2799 15.1314 30.8096 14.7189 30.3805 14.3915C29.5014 13.7207 29.168 13.7055 29.0239 13.7055C28.8799 13.7055 28.5465 13.7207 27.6674 14.3915C27.6533 14.4022 27.6393 14.413 27.6252 14.4239L27.6232 14.4238L27.6024 14.4414C27.3079 14.6698 26.9934 14.9381 26.6453 15.2538Z" fill="black"/>
<path d="M43.4935 27.471C42.8957 26.7152 42.0376 25.8229 40.7954 24.5736C40.5923 24.2491 40.4753 23.8751 40.4596 23.4874L40.306 19.6948L42.1106 21.4994C45.6358 25.0247 47.3985 26.7873 47.3985 28.9776C47.3985 31.1678 45.6358 32.9304 42.1106 36.4557L40.2963 38.27L40.4711 34.6452C40.4954 34.1415 40.6908 33.6612 41.025 33.2835L42.352 31.784C42.7709 31.3388 43.1192 30.9479 43.4095 30.589L43.573 30.4043V30.3824C43.5854 30.3662 43.5978 30.3502 43.61 30.3341C44.2808 29.455 44.296 29.1216 44.296 28.9776C44.296 28.8335 44.2808 28.5001 43.61 27.621C43.5978 27.6049 43.5854 27.5889 43.573 27.5727V27.5545L43.4935 27.471Z" fill="black"/>
<path d="M14.4826 27.5691L16.902 24.9381C17.2447 24.5655 17.4494 24.0868 17.4821 23.5816L17.616 21.5163C17.6363 20.8624 17.6699 20.31 17.7254 19.8285L17.7349 19.682L17.7445 19.6725C17.7466 19.6559 17.7488 19.6394 17.751 19.6229C17.8983 18.527 18.1233 18.2805 18.2251 18.1786C18.327 18.0767 18.5736 17.8518 19.6695 17.7044C20.0213 17.6571 20.4118 17.6233 20.8544 17.5991L23.8259 17.3059C24.3027 17.2589 24.7513 17.0586 25.1046 16.7352L27.6159 14.4361H25.0583C20.0729 14.4361 17.5802 14.4361 16.0314 15.9848C14.712 17.3043 14.5166 19.3088 14.4877 22.9561C14.4826 23.59 14.4826 24.2735 14.4826 25.0117L14.4826 27.5627V27.5691Z" fill="black"/>
<path d="M14.4826 30.386V30.3952L14.4826 32.9434C14.4826 33.6816 14.4826 34.3651 14.4877 34.999C14.5166 38.6463 14.7119 40.6509 16.0314 41.9703C17.3509 43.2898 19.3554 43.4851 23.0028 43.5141C23.6366 43.5191 24.3201 43.5191 25.0583 43.5191H27.6059H30.4384H32.99C33.728 43.5191 34.4114 43.5191 35.0451 43.5141C38.6927 43.4852 40.6974 43.2898 42.0169 41.9703C43.5657 40.4216 43.5657 37.9289 43.5657 32.9434V30.3783L40.9873 33.1741C40.7295 33.4537 40.5498 33.7928 40.462 34.1575C40.457 35.9697 40.4324 37.2297 40.3142 38.1998L40.313 38.2515L40.3071 38.2574C40.3039 38.2825 40.3006 38.3075 40.2973 38.3322C40.15 39.4282 39.925 39.6747 39.8231 39.7766C39.7213 39.8784 39.4747 40.1034 38.3788 40.2507C38.3541 40.2541 38.3291 40.2573 38.304 40.2605L38.2979 40.2666L38.2111 40.2719C37.6594 40.3374 37.0141 40.3733 36.2282 40.3929L34.4602 40.5008C33.9569 40.5316 33.4791 40.7331 33.1058 41.072L30.4107 43.5191H27.5938L24.8997 41.0003C24.5451 40.6688 24.0925 40.4638 23.612 40.4147C23.4039 40.4139 23.2033 40.4127 23.0098 40.4112C21.5576 40.3995 20.5048 40.363 19.6695 40.2507C18.5736 40.1034 18.327 39.8784 18.2251 39.7766C18.1233 39.6747 17.8983 39.4282 17.751 38.3322C17.7488 38.3158 17.7466 38.2993 17.7445 38.2828L17.7349 38.2732L17.734 38.2524L17.7304 38.1697C17.6321 37.3441 17.6002 36.3092 17.5899 34.9063L17.5744 34.5469C17.5703 34.4505 17.5598 34.355 17.5434 34.2608C17.4714 33.8486 17.2836 33.463 16.9993 33.1507L14.4826 30.386Z" fill="black"/>
<path d="M40.4361 21.6459L40.5814 23.6165C40.6181 24.1136 40.8212 24.5837 41.158 24.9511L43.5657 27.5768V25.0117C43.5657 20.0263 43.5657 17.5336 42.0169 15.9848C40.4681 14.4361 37.9754 14.4361 32.99 14.4361H30.4104L32.9941 16.7897C33.3562 17.1196 33.8173 17.3201 34.3055 17.3601L37.3018 17.6052C37.5881 17.6223 37.8522 17.6436 38.098 17.6704L38.3195 17.6885L38.3288 17.6978C38.3455 17.7 38.3622 17.7022 38.3788 17.7044C39.4747 17.8518 39.7213 18.0767 39.8231 18.1786C39.925 18.2805 40.15 18.527 40.2973 19.6229C40.3724 20.1817 40.4136 20.8379 40.4361 21.6459Z" fill="black"/>
<path d="M17.7437 38.2621L17.734 38.2524L17.7349 38.2732L17.7445 38.2828L17.7437 38.2621Z" fill="black"/>
<path d="M19.7418 40.2602L23.0098 40.4112C21.5992 40.3998 20.5654 40.3651 19.7418 40.2602Z" fill="black"/>
<path d="M17.6049 34.6945C17.5987 34.5474 17.578 34.4022 17.5434 34.2608C17.5598 34.355 17.5703 34.4505 17.5744 34.5469L17.5899 34.9063C17.6002 36.3092 17.6321 37.3441 17.7304 38.1697L17.734 38.2524L17.7437 38.2621L17.6049 34.6945Z" fill="black"/>
<path d="M10.6494 28.9776C10.6494 30.8436 11.9288 32.3993 14.4877 34.999C14.4826 34.3651 14.4826 33.6816 14.4826 32.9434L14.4826 30.3952L14.4772 30.389L14.4772 30.3854C14.464 30.3682 14.4508 30.3511 14.4379 30.3341C13.7671 29.455 13.7518 29.1216 13.7518 28.9776C13.7518 28.8335 13.7671 28.5001 14.4379 27.621C14.4526 27.6016 14.4675 27.5822 14.4826 27.5627L14.4826 25.0117C14.4826 24.2735 14.4826 23.59 14.4877 22.9561C11.9288 25.5558 10.6494 27.1115 10.6494 28.9776Z" fill="black"/>
<path d="M27.6674 43.5636C27.6549 43.5541 27.6425 43.5446 27.63 43.5349H27.6232L27.6059 43.5191H25.0583C24.3201 43.5191 23.6366 43.5191 23.0028 43.5141C25.6023 46.0727 27.1579 47.3521 29.0239 47.3521C30.8899 47.3521 32.4455 46.0727 35.0451 43.5141C34.4114 43.5191 33.728 43.5191 32.99 43.5191H30.4384C30.419 43.5341 30.3997 43.5489 30.3805 43.5636C29.5014 44.2344 29.168 44.2496 29.0239 44.2496C28.8799 44.2496 28.5465 44.2344 27.6674 43.5636Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

View File

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

View File

@ -23,8 +23,8 @@ import { useSession } from 'next-auth/react';
import { downloadPDF } from '@documenso/lib/client-only/download-pdf';
import { formatDocumentsPath } from '@documenso/lib/utils/teams';
import { DocumentStatus, RecipientRole } from '@documenso/prisma/client';
import type { Document, Recipient, Team, User } from '@documenso/prisma/client';
import { DocumentStatus, RecipientRole } from '@documenso/prisma/client';
import { trpc as trpcClient } from '@documenso/trpc/client';
import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';
import {
@ -233,14 +233,12 @@ export const DataTableActionDropdown = ({ row, team }: DataTableActionDropdownPr
onOpenChange={setMoveDialogOpen}
/>
{isDuplicateDialogOpen && (
<DuplicateDocumentDialog
id={row.id}
open={isDuplicateDialogOpen}
onOpenChange={setDuplicateDialogOpen}
team={team}
/>
)}
<DuplicateDocumentDialog
id={row.id}
open={isDuplicateDialogOpen}
onOpenChange={setDuplicateDialogOpen}
team={team}
/>
</DropdownMenu>
);
};

View File

@ -50,8 +50,8 @@ export const DuplicateDocumentDialog = ({
const { mutateAsync: duplicateDocument, isPending: isDuplicateLoading } =
trpcReact.document.duplicateDocument.useMutation({
onSuccess: (newId) => {
router.push(`${documentsPath}/${newId}/edit`);
onSuccess: ({ documentId }) => {
router.push(`${documentsPath}/${documentId}/edit`);
toast({
title: _(msg`Document Duplicated`),

View File

@ -14,6 +14,7 @@ import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
import { DocumentReadOnlyFields } from '~/components/document/document-read-only-fields';
import { TemplateType } from '~/components/formatter/template-type';
import { TemplateBulkSendDialog } from '~/components/templates/template-bulk-send-dialog';
import { DataTableActionDropdown } from '../data-table-action-dropdown';
import { TemplateDirectLinkBadge } from '../template-direct-link-badge';
@ -111,6 +112,8 @@ export const TemplatePageView = async ({ params, team }: TemplatePageViewProps)
<div className="mt-2 flex flex-row space-x-4 sm:mt-0 sm:self-end">
<TemplateDirectLinkDialogWrapper template={template} />
<TemplateBulkSendDialog templateId={template.id} recipients={template.recipients} />
<Button className="w-full" asChild>
<Link href={`${templateRootPath}/${template.id}/edit`}>
<LucideEdit className="mr-1.5 h-3.5 w-3.5" />

View File

@ -5,7 +5,7 @@ import { useState } from 'react';
import Link from 'next/link';
import { Trans } from '@lingui/macro';
import { Copy, Edit, MoreHorizontal, MoveRight, Share2Icon, Trash2 } from 'lucide-react';
import { Copy, Edit, MoreHorizontal, MoveRight, Share2Icon, Trash2, Upload } from 'lucide-react';
import { useSession } from 'next-auth/react';
import type { Recipient, Template, TemplateDirectLink } from '@documenso/prisma/client';
@ -17,6 +17,8 @@ import {
DropdownMenuTrigger,
} from '@documenso/ui/primitives/dropdown-menu';
import { TemplateBulkSendDialog } from '~/components/templates/template-bulk-send-dialog';
import { DeleteTemplateDialog } from './delete-template-dialog';
import { DuplicateTemplateDialog } from './duplicate-template-dialog';
import { MoveTemplateDialog } from './move-template-dialog';
@ -86,6 +88,17 @@ export const DataTableActionDropdown = ({
</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
disabled={!isOwner && !isTeamTemplate}
onClick={() => setDeleteDialogOpen(true)}

View File

@ -1,5 +1,3 @@
import React from 'react';
import { redirect } from 'next/navigation';
import { msg } from '@lingui/macro';
@ -7,8 +5,10 @@ import { useLingui } from '@lingui/react';
import { DateTime } from 'luxon';
import { match } from 'ts-pattern';
import { UAParser } from 'ua-parser-js';
import { renderSVG } from 'uqr';
import { setupI18nSSR } from '@documenso/lib/client-only/providers/i18n.server';
import { WEBAPP_BASE_URL } from '@documenso/lib/constants/app';
import { APP_I18N_OPTIONS, ZSupportedLanguageCodeSchema } from '@documenso/lib/constants/i18n';
import {
RECIPIENT_ROLES_DESCRIPTION,
@ -73,6 +73,8 @@ export default async function SigningCertificate({ searchParams }: SigningCertif
id: documentId,
}).catch(() => null);
const documentAccessToken = document?.documentAccessToken?.token;
if (!document) {
return redirect('/');
}
@ -305,17 +307,27 @@ export default async function SigningCertificate({ searchParams }: SigningCertif
</TableBody>
</Table>
</CardContent>
</Card>
<div className="my-8 flex flex-row-reverse items-end justify-between px-8">
<div className="flex items-end justify-end gap-x-4">
<div
className="flex h-24 w-24 justify-center"
dangerouslySetInnerHTML={{
__html: renderSVG(`${WEBAPP_BASE_URL}/q/${documentAccessToken}`, {
ecc: 'Q',
}),
}}
/>
</div>
<div className="my-8 flex-row-reverse">
<div className="flex items-end justify-end gap-x-4">
<p className="flex-shrink-0 text-sm font-medium print:text-xs">
{_(msg`Signing certificate provided by`)}:
</p>
<div>
<p className="flex-shrink-0 text-sm print:text-xs">
{_(msg`Signing certificate provided by`)}:
</p>
<Logo className="max-h-6 print:max-h-4" />
<Logo className="mt-2 max-h-6 print:max-h-4" />
</div>
</div>
</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,44 @@
'use client';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { Download } from 'lucide-react';
import { downloadPDF } from '@documenso/lib/client-only/download-pdf';
import type { Document, DocumentData } from '@documenso/prisma/client';
import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast';
export type DocumentDownloadButtonProps = {
document: Pick<Document, 'title'> & {
documentData: DocumentData;
};
};
export const DocumentDownloadButton = ({ document }: DocumentDownloadButtonProps) => {
const { toast } = useToast();
const { _ } = useLingui();
const onDownloadClick = async () => {
try {
if (!document) {
throw new Error('No document available');
}
await downloadPDF({ documentData: document.documentData, fileName: document.title });
} catch (err) {
toast({
title: _(msg`Something went wrong`),
description: _(msg`An error occurred while downloading your document.`),
variant: 'destructive',
});
}
};
return (
<Button className="w-full" onClick={onDownloadClick}>
<Download className="-ml-1 mr-2 inline h-4 w-4" />
<Trans>Download</Trans>
</Button>
);
};

View File

@ -0,0 +1,35 @@
import React from 'react';
import { setupI18nSSR } from '@documenso/lib/client-only/providers/i18n.server';
import { getServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
import type { TGetTeamsResponse } from '@documenso/lib/server-only/team/get-teams';
import { getTeams } from '@documenso/lib/server-only/team/get-teams';
import { Header as AuthenticatedHeader } from '~/components/(dashboard)/layout/header';
import { NextAuthProvider } from '~/providers/next-auth';
export type SigningLayoutProps = {
children: React.ReactNode;
};
export default async function SigningLayout({ children }: SigningLayoutProps) {
await setupI18nSSR();
const { user, session } = await getServerComponentSession();
let teams: TGetTeamsResponse = [];
if (user && session) {
teams = await getTeams({ userId: user.id });
}
return (
<NextAuthProvider session={session}>
<div className="min-h-screen">
{user && <AuthenticatedHeader user={user} teams={teams} />}
<main className="mb-8 mt-8 px-4 md:mb-12 md:mt-12 md:px-8">{children}</main>
</div>
</NextAuthProvider>
);
}

View File

@ -0,0 +1,68 @@
import { notFound } from 'next/navigation';
import { setupI18nSSR } from '@documenso/lib/client-only/providers/i18n.server';
import { getDocumentByAccessToken } from '@documenso/lib/server-only/document/get-document-by-access-token';
import { Card, CardContent } from '@documenso/ui/primitives/card';
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
import { DocumentDownloadButton } from './document-download-button';
export type DocumentAccessPageProps = {
params: {
token?: string;
};
};
export default async function DocumentAccessPage({ params: { token } }: DocumentAccessPageProps) {
await setupI18nSSR();
if (!token) {
return notFound();
}
const { document } = await getDocumentByAccessToken({ token });
const { documentData, documentMeta } = document;
return (
<div className="mx-auto w-full max-w-screen-xl md:px-8">
<h1
className="mt-4 block max-w-[20rem] truncate text-2xl font-semibold md:max-w-[30rem] md:text-3xl"
title={document.title}
>
{document.title}
</h1>
<div className="mt-8 grid grid-cols-12 gap-y-8 lg:gap-x-8 lg:gap-y-0">
<Card
className="col-span-12 rounded-xl before:rounded-xl lg:col-span-7 xl:col-span-8"
gradient
>
<CardContent className="p-2">
<LazyPDFViewer
key={documentData.id}
documentData={documentData}
document={document}
password={documentMeta?.password}
/>
</CardContent>
</Card>
<div className="col-span-12 lg:col-span-5 xl:col-span-4">
<section className="border-border bg-widget flex flex-col rounded-xl border pb-4 pt-6">
<div className="flex flex-row items-center justify-between px-4">
<h3 className="text-foreground text-2xl font-semibold">Download document</h3>
</div>
<p className="text-muted-foreground mt-2 px-4 text-sm">
Download the document as a PDF file.
</p>
<div className="mt-4 border-t px-4 pt-4">
<DocumentDownloadButton document={document} />
</div>
</section>
</div>
</div>
</div>
);
}

View File

@ -16,6 +16,7 @@ import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones'
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import { ZDateFieldMeta } from '@documenso/lib/types/field-meta';
import type { Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
@ -23,6 +24,7 @@ import type {
TRemovedSignedFieldWithTokenMutationSchema,
TSignFieldWithTokenMutationSchema,
} from '@documenso/trpc/server/field-router/schema';
import { cn } from '@documenso/ui/lib/utils';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { SigningFieldContainer } from './signing-field-container';
@ -59,6 +61,9 @@ export const DateField = ({
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const safeFieldMeta = ZDateFieldMeta.safeParse(field.fieldMeta);
const parsedFieldMeta = safeFieldMeta.success ? safeFieldMeta.data : null;
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const localDateString = convertToLocalSystemFormat(field.customText, dateFormat, timezone);
@ -150,9 +155,21 @@ export const DateField = ({
)}
{field.inserted && (
<p className="text-muted-foreground dark:text-background/80 text-[clamp(0.425rem,25cqw,0.825rem)] duration-200">
{localDateString}
</p>
<div className="flex h-full w-full items-center">
<p
className={cn(
'text-muted-foreground dark:text-background/80 w-full text-[clamp(0.425rem,25cqw,0.825rem)] duration-200',
{
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
},
)}
>
{localDateString}
</p>
</div>
)}
</SigningFieldContainer>
);

View File

@ -11,6 +11,7 @@ import { Loader } from 'lucide-react';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import { ZEmailFieldMeta } from '@documenso/lib/types/field-meta';
import type { Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
@ -18,6 +19,7 @@ import type {
TRemovedSignedFieldWithTokenMutationSchema,
TSignFieldWithTokenMutationSchema,
} from '@documenso/trpc/server/field-router/schema';
import { cn } from '@documenso/ui/lib/utils';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useRequiredSigningContext } from './provider';
@ -48,6 +50,9 @@ export const EmailField = ({ field, recipient, onSignField, onUnsignField }: Ema
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const safeFieldMeta = ZEmailFieldMeta.safeParse(field.fieldMeta);
const parsedFieldMeta = safeFieldMeta.success ? safeFieldMeta.data : null;
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const onSign = async (authOptions?: TRecipientActionAuth) => {
@ -128,9 +133,21 @@ export const EmailField = ({ field, recipient, onSignField, onUnsignField }: Ema
)}
{field.inserted && (
<p className="text-muted-foreground dark:text-background/80 text-[clamp(0.425rem,25cqw,0.825rem)] duration-200">
{field.customText}
</p>
<div className="flex h-full w-full items-center">
<p
className={cn(
'text-muted-foreground dark:text-background/80 w-full text-[clamp(0.425rem,25cqw,0.825rem)] duration-200',
{
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
},
)}
>
{field.customText}
</p>
</div>
)}
</SigningFieldContainer>
);

View File

@ -11,6 +11,7 @@ import { Loader } from 'lucide-react';
import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import { ZNameFieldMeta } from '@documenso/lib/types/field-meta';
import { type Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
@ -18,6 +19,7 @@ import type {
TRemovedSignedFieldWithTokenMutationSchema,
TSignFieldWithTokenMutationSchema,
} from '@documenso/trpc/server/field-router/schema';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import { Dialog, DialogContent, DialogFooter, DialogTitle } from '@documenso/ui/primitives/dialog';
import { Input } from '@documenso/ui/primitives/input';
@ -56,6 +58,9 @@ export const NameField = ({ field, recipient, onSignField, onUnsignField }: Name
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const safeFieldMeta = ZNameFieldMeta.safeParse(field.fieldMeta);
const parsedFieldMeta = safeFieldMeta.success ? safeFieldMeta.data : null;
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const [showFullNameModal, setShowFullNameModal] = useState(false);
@ -172,9 +177,21 @@ export const NameField = ({ field, recipient, onSignField, onUnsignField }: Name
)}
{field.inserted && (
<p className="text-muted-foreground dark:text-background/80 text-[clamp(0.425rem,25cqw,0.825rem)] duration-200">
{field.customText}
</p>
<div className="flex h-full w-full items-center">
<p
className={cn(
'text-muted-foreground dark:text-background/80 w-full text-[clamp(0.425rem,25cqw,0.825rem)] duration-200',
{
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
},
)}
>
{field.customText}
</p>
</div>
)}
<Dialog open={showFullNameModal} onOpenChange={setShowFullNameModal}>

View File

@ -52,8 +52,19 @@ export const NumberField = ({ field, recipient, onSignField, onUnsignField }: Nu
const [isPending, startTransition] = useTransition();
const [showRadioModal, setShowRadioModal] = useState(false);
const parsedFieldMeta = field.fieldMeta ? ZNumberFieldMeta.parse(field.fieldMeta) : null;
const isReadOnly = parsedFieldMeta?.readOnly;
const { mutateAsync: signFieldWithToken, isPending: isSignFieldWithTokenLoading } =
trpc.field.signFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const {
mutateAsync: removeSignedFieldWithToken,
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const safeFieldMeta = ZNumberFieldMeta.safeParse(field.fieldMeta);
const parsedFieldMeta = safeFieldMeta.success ? safeFieldMeta.data : null;
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const defaultValue = parsedFieldMeta?.value;
const [localNumber, setLocalNumber] = useState(
parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0',
@ -71,16 +82,6 @@ export const NumberField = ({ field, recipient, onSignField, onUnsignField }: Nu
const { executeActionAuthProcedure } = useRequiredDocumentAuthContext();
const { mutateAsync: signFieldWithToken, isPending: isSignFieldWithTokenLoading } =
trpc.field.signFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const {
mutateAsync: removeSignedFieldWithToken,
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const text = e.target.value;
setLocalNumber(text);
@ -208,7 +209,7 @@ export const NumberField = ({ field, recipient, onSignField, onUnsignField }: Nu
useEffect(() => {
if (
(!field.inserted && defaultValue && localNumber) ||
(!field.inserted && isReadOnly && defaultValue)
(!field.inserted && parsedFieldMeta?.readOnly && defaultValue)
) {
void executeActionAuthProcedure({
onReauthFormSubmit: async (authOptions) => await onSign(authOptions),
@ -260,9 +261,21 @@ export const NumberField = ({ field, recipient, onSignField, onUnsignField }: Nu
)}
{field.inserted && (
<p className="text-muted-foreground dark:text-background/80 text-[clamp(0.425rem,25cqw,0.825rem)] duration-200">
{field.customText}
</p>
<div className="flex h-full w-full items-center">
<p
className={cn(
'text-muted-foreground dark:text-background/80 w-full text-[clamp(0.425rem,25cqw,0.825rem)] duration-200',
{
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
},
)}
>
{field.customText}
</p>
</div>
)}
<Dialog open={showRadioModal} onOpenChange={setShowRadioModal}>

View File

@ -62,7 +62,8 @@ export const TextField = ({ field, recipient, onSignField, onUnsignField }: Text
isPending: isRemoveSignedFieldWithTokenLoading,
} = trpc.field.removeSignedFieldWithToken.useMutation(DO_NOT_INVALIDATE_QUERY_ON_MUTATION);
const parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;
const safeFieldMeta = ZTextFieldMeta.safeParse(field.fieldMeta);
const parsedFieldMeta = safeFieldMeta.success ? safeFieldMeta.data : null;
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const shouldAutoSignField =
@ -261,11 +262,23 @@ export const TextField = ({ field, recipient, onSignField, onUnsignField }: Text
)}
{field.inserted && (
<p className="text-muted-foreground dark:text-background/80 flex items-center justify-center gap-x-1 text-[clamp(0.425rem,25cqw,0.825rem)] duration-200">
{field.customText.length < 20
? field.customText
: field.customText.substring(0, 15) + '...'}
</p>
<div className="flex h-full w-full items-center">
<p
className={cn(
'text-muted-foreground dark:text-background/80 w-full text-[clamp(0.425rem,25cqw,0.825rem)] duration-200',
{
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
},
)}
>
{field.customText.length < 20
? field.customText
: field.customText.substring(0, 15) + '...'}
</p>
</div>
)}
<Dialog open={showCustomTextModal} onOpenChange={setShowCustomTextModal}>
@ -281,6 +294,10 @@ export const TextField = ({ field, recipient, onSignField, onUnsignField }: Text
className={cn('mt-2 w-full rounded-md', {
'border-2 border-red-300 ring-2 ring-red-200 ring-offset-2 ring-offset-red-200 focus-visible:border-red-400 focus-visible:ring-4 focus-visible:ring-red-200 focus-visible:ring-offset-2 focus-visible:ring-offset-red-200':
userInputHasErrors,
'text-left': parsedFieldMeta?.textAlign === 'left',
'text-center':
!parsedFieldMeta?.textAlign || parsedFieldMeta?.textAlign === 'center',
'text-right': parsedFieldMeta?.textAlign === 'right',
})}
value={localText}
onChange={handleTextChange}

View File

@ -0,0 +1,275 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { File as FileIcon, Upload, X } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { trpc } from '@documenso/trpc/react';
import { Button } from '@documenso/ui/primitives/button';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { Form, FormControl, FormField, FormItem } from '@documenso/ui/primitives/form/form';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useOptionalCurrentTeam } from '~/providers/team';
const ZBulkSendFormSchema = z.object({
file: z.instanceof(File),
sendImmediately: z.boolean().default(false),
});
type TBulkSendFormSchema = z.infer<typeof ZBulkSendFormSchema>;
export type TemplateBulkSendDialogProps = {
templateId: number;
recipients: Array<{ email: string; name?: string | null }>;
trigger?: React.ReactNode;
onSuccess?: () => void;
};
export const TemplateBulkSendDialog = ({
templateId,
recipients,
trigger,
onSuccess,
}: TemplateBulkSendDialogProps) => {
const { _ } = useLingui();
const { toast } = useToast();
const team = useOptionalCurrentTeam();
const form = useForm<TBulkSendFormSchema>({
resolver: zodResolver(ZBulkSendFormSchema),
defaultValues: {
sendImmediately: false,
},
});
const { mutateAsync: uploadBulkSend } = trpc.template.uploadBulkSend.useMutation();
const onDownloadTemplate = () => {
const headers = recipients.flatMap((_, index) => [
`recipient_${index + 1}_email`,
`recipient_${index + 1}_name`,
]);
const exampleRow = recipients.flatMap((recipient) => [recipient.email, recipient.name || '']);
const csv = [headers.join(','), exampleRow.join(',')].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'), {
href: url,
download: 'template.csv',
});
a.click();
window.URL.revokeObjectURL(url);
};
const onSubmit = async (values: TBulkSendFormSchema) => {
try {
const csv = await values.file.text();
await uploadBulkSend({
templateId,
teamId: team?.id,
csv: csv,
sendImmediately: values.sendImmediately,
});
toast({
title: _(msg`Success`),
description: _(
msg`Your bulk send has been initiated. You will receive an email notification upon completion.`,
),
});
form.reset();
onSuccess?.();
} catch (err) {
console.error(err);
toast({
title: 'Error',
description: 'Failed to upload CSV. Please check the file format and try again.',
variant: 'destructive',
});
}
};
return (
<Dialog>
<DialogTrigger asChild>
{trigger ?? (
<Button>
<Upload className="mr-2 h-4 w-4" />
<Trans>Bulk Send via CSV</Trans>
</Button>
)}
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
<Trans>Bulk Send Template via CSV</Trans>
</DialogTitle>
<DialogDescription>
<Trans>
Upload a CSV file to create multiple documents from this template. Each row represents
one document with its recipient details.
</Trans>
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-y-4">
<div className="bg-muted/70 rounded-lg border p-4">
<h3 className="text-sm font-medium">
<Trans>CSV Structure</Trans>
</h3>
<p className="text-muted-foreground mt-1 text-sm">
<Trans>
For each recipient, provide their email (required) and name (optional) in separate
columns. Download the template CSV below for the correct format.
</Trans>
</p>
<p className="mt-4 text-sm">
<Trans>Current recipients:</Trans>
</p>
<ul className="text-muted-foreground mt-2 list-inside list-disc text-sm">
{recipients.map((recipient, index) => (
<li key={index}>
{recipient.name ? `${recipient.name} (${recipient.email})` : recipient.email}
</li>
))}
</ul>
</div>
<div className="flex flex-col gap-y-2">
<Button onClick={onDownloadTemplate} variant="outline" type="button">
<Trans>Download Template CSV</Trans>
</Button>
<p className="text-muted-foreground text-xs">
<Trans>Pre-formatted CSV template with example data.</Trans>
</p>
</div>
<FormField
control={form.control}
name="file"
render={({ field: { onChange, value }, fieldState: { error } }) => (
<FormItem>
<FormControl>
{!value ? (
<Button asChild variant="outline" className="w-full">
<label className="cursor-pointer">
<input
type="file"
accept=".csv"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
onChange(file);
}
}}
disabled={form.formState.isSubmitting}
/>
<Upload className="mr-2 h-4 w-4" />
<Trans>Upload CSV</Trans>
</label>
</Button>
) : (
<div className="flex h-10 items-center rounded-md border px-3">
<div className="flex flex-1 items-center gap-2">
<FileIcon className="text-muted-foreground h-4 w-4" />
<span className="flex-1 truncate text-sm">{value.name}</span>
</div>
<Button
type="button"
variant="link"
className="text-destructive hover:text-destructive p-0 text-xs"
onClick={() => onChange(null)}
disabled={form.formState.isSubmitting}
>
<X className="h-4 w-4" />
<span className="sr-only">
<Trans>Remove</Trans>
</span>
</Button>
</div>
)}
</FormControl>
{error && <p className="text-destructive text-sm">{error.message}</p>}
<p className="text-muted-foreground text-xs">
<Trans>
Maximum file size: 4MB. Maximum 100 rows per upload. Blank values will use
template defaults.
</Trans>
</p>
</FormItem>
)}
/>
<FormField
control={form.control}
name="sendImmediately"
render={({ field }) => (
<FormItem className="flex items-center space-x-2">
<FormControl>
<div className="flex items-center">
<Checkbox
id="send-immediately"
checked={field.value}
onCheckedChange={field.onChange}
/>
<label
htmlFor="send-immediately"
className="text-muted-foreground ml-2 flex items-center text-sm"
>
<Trans>Send documents to recipients immediately</Trans>
</label>
</div>
</FormControl>
</FormItem>
)}
/>
<DialogFooter className="mt-4">
<Button variant="secondary" onClick={() => form.reset()} type="button">
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
<Trans>Upload and Process</Trans>
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
};

View File

@ -1,7 +1,10 @@
###########################
# BASE CONTAINER #
###########################
FROM node:18-alpine AS base
FROM node:22-alpine3.20 AS base
RUN apk add --no-cache openssl
###########################
# BUILDER CONTAINER #
@ -30,7 +33,7 @@ FROM base AS installer
RUN apk add --no-cache libc6-compat
RUN apk add --no-cache jq
# Required for node_modules/aws-crt
RUN apk add --no-cache make cmake g++
RUN apk add --no-cache make cmake g++ openssl
WORKDIR /app

View File

@ -4,4 +4,4 @@ set -x
npx prisma migrate deploy --schema ./packages/prisma/schema.prisma
node apps/web/server.js
HOSTNAME=0.0.0.0 node apps/web/server.js

16
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@documenso/root",
"version": "1.9.0-rc.9",
"version": "1.9.0-rc.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@documenso/root",
"version": "1.9.0-rc.9",
"version": "1.9.0-rc.11",
"workspaces": [
"apps/*",
"packages/*"
@ -106,7 +106,7 @@
},
"apps/web": {
"name": "@documenso/web",
"version": "1.9.0-rc.9",
"version": "1.9.0-rc.11",
"license": "AGPL-3.0",
"dependencies": {
"@documenso/api": "*",
@ -13836,6 +13836,12 @@
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.2.tgz",
"integrity": "sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ=="
},
"node_modules/csv-parse": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-5.6.0.tgz",
"integrity": "sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q==",
"license": "MIT"
},
"node_modules/cytoscape": {
"version": "3.28.1",
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.28.1.tgz",
@ -32559,7 +32565,8 @@
"node_modules/uqr": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.2.tgz",
"integrity": "sha512-MJu7ypHq6QasgF5YRTjqscSzQp/W11zoUk6kvmlH+fmWEs63Y0Eib13hYFwAzagRJcVY8WVnlV+eBDUGMJ5IbA=="
"integrity": "sha512-MJu7ypHq6QasgF5YRTjqscSzQp/W11zoUk6kvmlH+fmWEs63Y0Eib13hYFwAzagRJcVY8WVnlV+eBDUGMJ5IbA==",
"license": "MIT"
},
"node_modules/uri-js": {
"version": "4.4.1",
@ -35031,6 +35038,7 @@
"@trigger.dev/sdk": "^2.3.18",
"@upstash/redis": "^1.20.6",
"@vvo/tzdb": "^6.117.0",
"csv-parse": "^5.6.0",
"inngest": "^3.19.13",
"kysely": "^0.26.3",
"luxon": "^3.4.0",

View File

@ -1,6 +1,6 @@
{
"private": true,
"version": "1.9.0-rc.9",
"version": "1.9.0-rc.11",
"scripts": {
"build": "turbo run build",
"build:web": "turbo run build --filter=@documenso/web",

View File

@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { Trans } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { match } from 'ts-pattern';
import { P, match } from 'ts-pattern';
import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
import { RecipientRole } from '@documenso/prisma/client';
@ -40,11 +40,9 @@ export const TemplateDocumentInvite = ({
const rejectDocumentLink = useMemo(() => {
const url = new URL(signDocumentLink);
url.searchParams.set('reject', 'true');
return url.toString();
}, []);
}, [signDocumentLink]);
return (
<>
@ -52,31 +50,32 @@ export const TemplateDocumentInvite = ({
<Section>
<Text className="text-primary mx-auto mb-0 max-w-[80%] text-center text-lg font-semibold">
{selfSigner ? (
<Trans>
Please {_(actionVerb).toLowerCase()} your document
<br />"{documentName}"
</Trans>
) : isTeamInvite ? (
<>
{includeSenderDetails ? (
<Trans>
{inviterName} on behalf of "{teamName}" has invited you to{' '}
{_(actionVerb).toLowerCase()}
</Trans>
) : (
<Trans>
{teamName} has invited you to {_(actionVerb).toLowerCase()}
</Trans>
)}
<br />"{documentName}"
</>
) : (
<Trans>
{inviterName} has invited you to {_(actionVerb).toLowerCase()}
<br />"{documentName}"
</Trans>
)}
{match({ selfSigner, isTeamInvite, includeSenderDetails, teamName })
.with({ selfSigner: true }, () => (
<Trans>
Please {_(actionVerb).toLowerCase()} your document
<br />"{documentName}"
</Trans>
))
.with({ isTeamInvite: true, includeSenderDetails: true, teamName: P.string }, () => (
<Trans>
{inviterName} on behalf of "{teamName}" has invited you to{' '}
{_(actionVerb).toLowerCase()}
<br />"{documentName}"
</Trans>
))
.with({ isTeamInvite: true, teamName: P.string }, () => (
<Trans>
{teamName} has invited you to {_(actionVerb).toLowerCase()}
<br />"{documentName}"
</Trans>
))
.otherwise(() => (
<Trans>
{inviterName} has invited you to {_(actionVerb).toLowerCase()}
<br />"{documentName}"
</Trans>
))}
</Text>
<Text className="my-1 text-center text-base text-slate-400">

View File

@ -0,0 +1,91 @@
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { Body, Container, Head, Html, Preview, Section, Text } from '../components';
import { TemplateFooter } from '../template-components/template-footer';
export interface BulkSendCompleteEmailProps {
userName: string;
templateName: string;
totalProcessed: number;
successCount: number;
failedCount: number;
errors: string[];
assetBaseUrl?: string;
}
export const BulkSendCompleteEmail = ({
userName,
templateName,
totalProcessed,
successCount,
failedCount,
errors,
}: BulkSendCompleteEmailProps) => {
const { _ } = useLingui();
return (
<Html>
<Head />
<Preview>{_(msg`Bulk send operation complete for template "${templateName}"`)}</Preview>
<Body className="mx-auto my-auto bg-white font-sans">
<Section>
<Container className="mx-auto mb-2 mt-8 max-w-xl rounded-lg border border-solid border-slate-200 p-4 backdrop-blur-sm">
<Section>
<Text className="text-sm">
<Trans>Hi {userName},</Trans>
</Text>
<Text className="text-sm">
<Trans>Your bulk send operation for template "{templateName}" has completed.</Trans>
</Text>
<Text className="text-lg font-semibold">
<Trans>Summary:</Trans>
</Text>
<ul className="my-2 ml-4 list-inside list-disc">
<li>
<Trans>Total rows processed: {totalProcessed}</Trans>
</li>
<li className="mt-1">
<Trans>Successfully created: {successCount}</Trans>
</li>
<li className="mt-1">
<Trans>Failed: {failedCount}</Trans>
</li>
</ul>
{failedCount > 0 && (
<Section className="mt-4">
<Text className="text-lg font-semibold">
<Trans>The following errors occurred:</Trans>
</Text>
<ul className="my-2 ml-4 list-inside list-disc">
{errors.map((error, index) => (
<li key={index} className="text-destructive mt-1 text-sm text-slate-400">
{error}
</li>
))}
</ul>
</Section>
)}
<Text className="text-sm">
<Trans>
You can view the created documents in your dashboard under the "Documents created
from template" section.
</Trans>
</Text>
</Section>
</Container>
<Container className="mx-auto max-w-xl">
<TemplateFooter isDocument={false} />
</Container>
</Section>
</Body>
</Html>
);
};

View File

@ -1,6 +1,6 @@
import { z } from 'zod';
export const SUPPORTED_LANGUAGE_CODES = ['de', 'en', 'fr', 'es'] as const;
export const SUPPORTED_LANGUAGE_CODES = ['de', 'en', 'fr', 'es', 'it', 'pl'] as const;
export const ZSupportedLanguageCodeSchema = z.enum(SUPPORTED_LANGUAGE_CODES).catch('en');
@ -46,6 +46,14 @@ export const SUPPORTED_LANGUAGES: Record<string, SupportedLanguage> = {
full: 'Spanish',
short: 'es',
},
it: {
full: 'Italian',
short: 'it',
},
pl: {
short: 'pl',
full: 'Polish',
},
} satisfies Record<SupportedLanguageCodes, SupportedLanguage>;
export const isValidLanguageCode = (code: unknown): code is SupportedLanguageCodes =>

View File

@ -6,6 +6,7 @@ import { SEND_SIGNING_EMAIL_JOB_DEFINITION } from './definitions/emails/send-sig
import { SEND_TEAM_DELETED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-deleted-email';
import { SEND_TEAM_MEMBER_JOINED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-member-joined-email';
import { SEND_TEAM_MEMBER_LEFT_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-member-left-email';
import { BULK_SEND_TEMPLATE_JOB_DEFINITION } from './definitions/internal/bulk-send-template';
import { SEAL_DOCUMENT_JOB_DEFINITION } from './definitions/internal/seal-document';
/**
@ -21,6 +22,7 @@ export const jobsClient = new JobClient([
SEAL_DOCUMENT_JOB_DEFINITION,
SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION,
SEND_RECIPIENT_SIGNED_EMAIL_JOB_DEFINITION,
BULK_SEND_TEMPLATE_JOB_DEFINITION,
] as const);
export const jobs = jobsClient;

View File

@ -0,0 +1,39 @@
import { z } from 'zod';
import { ZRequestMetadataSchema } from '../../../universal/extract-request-metadata';
import { type JobDefinition } from '../../client/_internal/job';
const SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_ID = 'send.bulk.complete.email';
const SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_SCHEMA = z.object({
userId: z.number(),
templateId: z.number(),
templateName: z.string(),
totalProcessed: z.number(),
successCount: z.number(),
failedCount: z.number(),
errors: z.array(z.string()),
requestMetadata: ZRequestMetadataSchema.optional(),
});
export type TSendBulkCompleteEmailJobDefinition = z.infer<
typeof SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_SCHEMA
>;
export const SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION = {
id: SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_ID,
name: 'Send Bulk Complete Email',
version: '1.0.0',
trigger: {
name: SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_ID,
schema: SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_SCHEMA,
},
handler: async ({ payload, io }) => {
const handler = await import('./send-bulk-complete-email.handler');
await handler.run({ payload, io });
},
} as const satisfies JobDefinition<
typeof SEND_BULK_COMPLETE_EMAIL_JOB_DEFINITION_ID,
TSendBulkCompleteEmailJobDefinition
>;

View File

@ -0,0 +1,208 @@
import { createElement } from 'react';
import { msg } from '@lingui/macro';
import { parse } from 'csv-parse/sync';
import { z } from 'zod';
import { mailer } from '@documenso/email/mailer';
import { BulkSendCompleteEmail } from '@documenso/email/templates/bulk-send-complete';
import { sendDocument } from '@documenso/lib/server-only/document/send-document';
import { createDocumentFromTemplate } from '@documenso/lib/server-only/template/create-document-from-template';
import { getTemplateById } from '@documenso/lib/server-only/template/get-template-by-id';
import { prisma } from '@documenso/prisma';
import type { TeamGlobalSettings } from '@documenso/prisma/client';
import { getI18nInstance } from '../../../client-only/providers/i18n.server';
import { NEXT_PUBLIC_WEBAPP_URL } from '../../../constants/app';
import { FROM_ADDRESS, FROM_NAME } from '../../../constants/email';
import { AppError } from '../../../errors/app-error';
import { renderEmailWithI18N } from '../../../utils/render-email-with-i18n';
import { teamGlobalSettingsToBranding } from '../../../utils/team-global-settings-to-branding';
import type { JobRunIO } from '../../client/_internal/job';
import type { TBulkSendTemplateJobDefinition } from './bulk-send-template';
const ZRecipientRowSchema = z.object({
name: z.string().optional(),
email: z.union([
z.string().email({ message: 'Value must be a valid email or empty string' }),
z.string().max(0, { message: 'Value must be a valid email or empty string' }),
]),
});
export const run = async ({
payload,
io,
}: {
payload: TBulkSendTemplateJobDefinition;
io: JobRunIO;
}) => {
const { userId, teamId, templateId, csvContent, sendImmediately, requestMetadata } = payload;
const template = await getTemplateById({
id: templateId,
userId,
teamId,
});
if (!template) {
throw new Error('Template not found');
}
const rows = parse(csvContent, { columns: true, skip_empty_lines: true });
if (rows.length > 100) {
throw new Error('Maximum 100 rows allowed per upload');
}
const { recipients } = template;
// Validate CSV structure
const csvHeaders = Object.keys(rows[0]);
const requiredHeaders = recipients.map((_, index) => `recipient_${index + 1}_email`);
for (const header of requiredHeaders) {
if (!csvHeaders.includes(header)) {
throw new Error(`Missing required column: ${header}`);
}
}
const user = await prisma.user.findFirstOrThrow({
where: {
id: userId,
},
select: {
email: true,
name: true,
},
});
const results = {
success: 0,
failed: 0,
errors: Array<string>(),
};
// Process each row
for (const [rowIndex, row] of rows.entries()) {
try {
for (const [recipientIndex] of recipients.entries()) {
const nameKey = `recipient_${recipientIndex + 1}_name`;
const emailKey = `recipient_${recipientIndex + 1}_email`;
const parsed = ZRecipientRowSchema.safeParse({
name: row[nameKey],
email: row[emailKey],
});
if (!parsed.success) {
throw new Error(
`Invalid recipient data provided for ${emailKey}, ${nameKey}: ${parsed.error.issues?.[0]?.message}`,
);
}
}
const document = await io.runTask(`create-document-${rowIndex}`, async () => {
return await createDocumentFromTemplate({
templateId: template.id,
userId,
teamId,
recipients: recipients.map((recipient, index) => {
return {
id: recipient.id,
email: row[`recipient_${index + 1}_email`] || recipient.email,
name: row[`recipient_${index + 1}_name`] || recipient.name,
role: recipient.role,
signingOrder: recipient.signingOrder,
};
}),
requestMetadata: {
source: 'app',
auth: 'session',
requestMetadata: requestMetadata || {},
},
});
});
if (sendImmediately) {
await io.runTask(`send-document-${rowIndex}`, async () => {
await sendDocument({
documentId: document.id,
userId,
teamId,
requestMetadata: {
source: 'app',
auth: 'session',
requestMetadata: requestMetadata || {},
},
}).catch((err) => {
console.error(err);
throw new AppError('DOCUMENT_SEND_FAILED');
});
});
}
results.success += 1;
} catch (error) {
results.failed += 1;
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
results.errors.push(`Row ${rowIndex + 1}: Was unable to be processed - ${errorMessage}`);
}
}
await io.runTask('send-completion-email', async () => {
const completionTemplate = createElement(BulkSendCompleteEmail, {
userName: user.name || user.email,
templateName: template.title,
totalProcessed: rows.length,
successCount: results.success,
failedCount: results.failed,
errors: results.errors,
assetBaseUrl: NEXT_PUBLIC_WEBAPP_URL(),
});
let teamGlobalSettings: TeamGlobalSettings | undefined | null;
if (template.teamId) {
teamGlobalSettings = await prisma.teamGlobalSettings.findUnique({
where: {
teamId: template.teamId,
},
});
}
const branding = teamGlobalSettings
? teamGlobalSettingsToBranding(teamGlobalSettings)
: undefined;
const i18n = await getI18nInstance(teamGlobalSettings?.documentLanguage);
const [html, text] = await Promise.all([
renderEmailWithI18N(completionTemplate, {
lang: teamGlobalSettings?.documentLanguage,
branding,
}),
renderEmailWithI18N(completionTemplate, {
lang: teamGlobalSettings?.documentLanguage,
branding,
plainText: true,
}),
]);
await mailer.sendMail({
to: {
name: user.name || '',
address: user.email,
},
from: {
name: FROM_NAME,
address: FROM_ADDRESS,
},
subject: i18n._(msg`Bulk Send Complete: ${template.title}`),
html,
text,
});
});
};

View File

@ -0,0 +1,37 @@
import { z } from 'zod';
import { ZRequestMetadataSchema } from '../../../universal/extract-request-metadata';
import { type JobDefinition } from '../../client/_internal/job';
const BULK_SEND_TEMPLATE_JOB_DEFINITION_ID = 'internal.bulk-send-template';
const BULK_SEND_TEMPLATE_JOB_DEFINITION_SCHEMA = z.object({
userId: z.number(),
teamId: z.number().optional(),
templateId: z.number(),
csvContent: z.string(),
sendImmediately: z.boolean(),
requestMetadata: ZRequestMetadataSchema.optional(),
});
export type TBulkSendTemplateJobDefinition = z.infer<
typeof BULK_SEND_TEMPLATE_JOB_DEFINITION_SCHEMA
>;
export const BULK_SEND_TEMPLATE_JOB_DEFINITION = {
id: BULK_SEND_TEMPLATE_JOB_DEFINITION_ID,
name: 'Bulk Send Template',
version: '1.0.0',
trigger: {
name: BULK_SEND_TEMPLATE_JOB_DEFINITION_ID,
schema: BULK_SEND_TEMPLATE_JOB_DEFINITION_SCHEMA,
},
handler: async ({ payload, io }) => {
const handler = await import('./bulk-send-template.handler');
await handler.run({ payload, io });
},
} as const satisfies JobDefinition<
typeof BULK_SEND_TEMPLATE_JOB_DEFINITION_ID,
TBulkSendTemplateJobDefinition
>;

View File

@ -119,6 +119,21 @@ export const run = async ({
documentData.data = documentData.initialData;
}
const existingDocumentAccessToken = await prisma.documentAccessToken.findUnique({
where: {
documentId: document.id,
},
});
if (!existingDocumentAccessToken) {
await prisma.documentAccessToken.create({
data: {
token: nanoid(),
documentId: document.id,
},
});
}
const pdfData = await getFile(documentData);
const certificateData =

View File

@ -40,6 +40,7 @@
"@trigger.dev/sdk": "^2.3.18",
"@upstash/redis": "^1.20.6",
"@vvo/tzdb": "^6.117.0",
"csv-parse": "^5.6.0",
"inngest": "^3.19.13",
"kysely": "^0.26.3",
"luxon": "^3.4.0",

View File

@ -11,6 +11,7 @@ export const getEntireDocument = async ({ id }: GetEntireDocumentOptions) => {
},
include: {
documentMeta: true,
documentAccessToken: true,
user: {
select: {
id: true,

View File

@ -1,5 +1,5 @@
import { prisma } from '@documenso/prisma';
import { DocumentStatus, Prisma } from '@documenso/prisma/client';
import { kyselyPrisma, sql } from '@documenso/prisma';
import { DocumentStatus, SubscriptionStatus } from '@documenso/prisma/client';
export type SigningVolume = {
id: number;
@ -24,92 +24,78 @@ export async function getSigningVolume({
sortBy = 'signingVolume',
sortOrder = 'desc',
}: GetSigningVolumeOptions) {
const whereClause = Prisma.validator<Prisma.SubscriptionWhereInput>()({
status: 'ACTIVE',
OR: [
{
user: {
OR: [
{ name: { contains: search, mode: 'insensitive' } },
{ email: { contains: search, mode: 'insensitive' } },
],
},
},
{
team: {
name: { contains: search, mode: 'insensitive' },
},
},
],
});
const offset = Math.max(page - 1, 0) * perPage;
const [subscriptions, totalCount] = await Promise.all([
prisma.subscription.findMany({
where: whereClause,
include: {
user: {
select: {
name: true,
email: true,
documents: {
where: {
status: DocumentStatus.COMPLETED,
deletedAt: null,
teamId: null,
},
},
},
},
team: {
select: {
name: true,
documents: {
where: {
status: DocumentStatus.COMPLETED,
deletedAt: null,
},
},
},
},
},
orderBy:
sortBy === 'name'
? [{ user: { name: sortOrder } }, { team: { name: sortOrder } }, { createdAt: 'desc' }]
: sortBy === 'createdAt'
? [{ createdAt: sortOrder }]
: undefined,
skip: Math.max(page - 1, 0) * perPage,
take: perPage,
}),
prisma.subscription.count({
where: whereClause,
}),
]);
let findQuery = kyselyPrisma.$kysely
.selectFrom('Subscription as s')
.leftJoin('User as u', 's.userId', 'u.id')
.leftJoin('Team as t', 's.teamId', 't.id')
.leftJoin('Document as ud', (join) =>
join
.onRef('u.id', '=', 'ud.userId')
.on('ud.status', '=', sql.lit(DocumentStatus.COMPLETED))
.on('ud.deletedAt', 'is', null)
.on('ud.teamId', 'is', null),
)
.leftJoin('Document as td', (join) =>
join
.onRef('t.id', '=', 'td.teamId')
.on('td.status', '=', sql.lit(DocumentStatus.COMPLETED))
.on('td.deletedAt', 'is', null),
)
// @ts-expect-error - Raw SQL enum casting not properly typed by Kysely
.where(sql`s.status = ${SubscriptionStatus.ACTIVE}::"SubscriptionStatus"`)
.where((eb) =>
eb.or([
eb('u.name', 'ilike', `%${search}%`),
eb('u.email', 'ilike', `%${search}%`),
eb('t.name', 'ilike', `%${search}%`),
]),
)
.select([
's.id as id',
's.createdAt as createdAt',
's.planId as planId',
sql<string>`COALESCE(u.name, t.name, u.email, 'Unknown')`.as('name'),
sql<number>`COUNT(DISTINCT ud.id) + COUNT(DISTINCT td.id)`.as('signingVolume'),
])
.groupBy(['s.id', 'u.name', 't.name', 'u.email']);
const leaderboardWithVolume: SigningVolume[] = subscriptions.map((subscription) => {
const name =
subscription.user?.name || subscription.team?.name || subscription.user?.email || 'Unknown';
const userSignedDocs = subscription.user?.documents?.length || 0;
const teamSignedDocs = subscription.team?.documents?.length || 0;
return {
id: subscription.id,
name,
signingVolume: userSignedDocs + teamSignedDocs,
createdAt: subscription.createdAt,
planId: subscription.planId,
};
});
if (sortBy === 'signingVolume') {
leaderboardWithVolume.sort((a, b) => {
return sortOrder === 'desc'
? b.signingVolume - a.signingVolume
: a.signingVolume - b.signingVolume;
});
switch (sortBy) {
case 'name':
findQuery = findQuery.orderBy('name', sortOrder);
break;
case 'createdAt':
findQuery = findQuery.orderBy('createdAt', sortOrder);
break;
case 'signingVolume':
findQuery = findQuery.orderBy('signingVolume', sortOrder);
break;
default:
findQuery = findQuery.orderBy('signingVolume', 'desc');
}
findQuery = findQuery.limit(perPage).offset(offset);
const countQuery = kyselyPrisma.$kysely
.selectFrom('Subscription as s')
.leftJoin('User as u', 's.userId', 'u.id')
.leftJoin('Team as t', 's.teamId', 't.id')
// @ts-expect-error - Raw SQL enum casting not properly typed by Kysely
.where(sql`s.status = ${SubscriptionStatus.ACTIVE}::"SubscriptionStatus"`)
.where((eb) =>
eb.or([
eb('u.name', 'ilike', `%${search}%`),
eb('u.email', 'ilike', `%${search}%`),
eb('t.name', 'ilike', `%${search}%`),
]),
)
.select(({ fn }) => [fn.countAll().as('count')]);
const [results, [{ count }]] = await Promise.all([findQuery.execute(), countQuery.execute()]);
return {
leaderboard: leaderboardWithVolume,
totalPages: Math.ceil(totalCount / perPage),
leaderboard: results,
totalPages: Math.ceil(Number(count) / perPage),
};
}

View File

@ -15,7 +15,7 @@ import type {
TeamGlobalSettings,
User,
} from '@documenso/prisma/client';
import { DocumentStatus, SendStatus } from '@documenso/prisma/client';
import { DocumentStatus, SendStatus, WebhookTriggerEvents } from '@documenso/prisma/client';
import { getI18nInstance } from '../../client-only/providers/i18n.server';
import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';
@ -23,10 +23,15 @@ import { FROM_ADDRESS, FROM_NAME } from '../../constants/email';
import { AppError, AppErrorCode } from '../../errors/app-error';
import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs';
import { extractDerivedDocumentEmailSettings } from '../../types/document-email';
import {
ZWebhookDocumentSchema,
mapDocumentToWebhookDocumentPayload,
} from '../../types/webhook-payload';
import type { ApiRequestMetadata } from '../../universal/extract-request-metadata';
import { createDocumentAuditLogData } from '../../utils/document-audit-logs';
import { renderEmailWithI18N } from '../../utils/render-email-with-i18n';
import { teamGlobalSettingsToBranding } from '../../utils/team-global-settings-to-branding';
import { triggerWebhook } from '../webhooks/trigger/trigger-webhook';
export type DeleteDocumentOptions = {
id: number;
@ -112,6 +117,13 @@ export const deleteDocument = async ({
});
}
await triggerWebhook({
event: WebhookTriggerEvents.DOCUMENT_CANCELLED,
data: ZWebhookDocumentSchema.parse(mapDocumentToWebhookDocumentPayload(document)),
userId,
teamId,
});
// Return partial document for API v1 response.
return {
id: document.id,

View File

@ -0,0 +1,39 @@
import { prisma } from '@documenso/prisma';
export type GetDocumentByAccessTokenOptions = {
token: string;
};
export const getDocumentByAccessToken = async ({ token }: GetDocumentByAccessTokenOptions) => {
if (!token) {
throw new Error('Missing token');
}
const result = await prisma.documentAccessToken.findFirstOrThrow({
where: {
token,
},
select: {
document: {
select: {
title: true,
documentData: {
select: {
id: true,
type: true,
data: true,
initialData: true,
},
},
documentMeta: {
select: {
password: true,
},
},
},
},
},
});
return result;
};

View File

@ -106,6 +106,21 @@ export const sealDocument = async ({
documentData.data = documentData.initialData;
}
const existingDocumentAccessToken = await prisma.documentAccessToken.findUnique({
where: {
documentId: document.id,
},
});
if (!existingDocumentAccessToken) {
await prisma.documentAccessToken.create({
data: {
token: nanoid(),
documentId: document.id,
},
});
}
// !: Need to write the fields onto the document as a hard copy
const pdfData = await getFile(documentData);

View File

@ -1,7 +1,7 @@
// https://github.com/Hopding/pdf-lib/issues/20#issuecomment-412852821
import fontkit from '@pdf-lib/fontkit';
import type { PDFDocument } from 'pdf-lib';
import { RotationTypes, degrees, radiansToDegrees } from 'pdf-lib';
import { RotationTypes, degrees, radiansToDegrees, rgb } from 'pdf-lib';
import { P, match } from 'ts-pattern';
import {
@ -36,6 +36,9 @@ export const insertFieldInPDF = async (pdf: PDFDocument, field: FieldWithSignatu
);
const isSignatureField = isSignatureFieldType(field.type);
const isDebugMode =
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.DEBUG_PDF_INSERT === '1' || process.env.DEBUG_PDF_INSERT === 'true';
pdf.registerFontkit(fontkit);
@ -83,6 +86,35 @@ export const insertFieldInPDF = async (pdf: PDFDocument, field: FieldWithSignatu
const fieldX = pageWidth * (Number(field.positionX) / 100);
const fieldY = pageHeight * (Number(field.positionY) / 100);
// Draw debug box if debug mode is enabled
if (isDebugMode) {
let debugX = fieldX;
let debugY = pageHeight - fieldY - fieldHeight; // Invert Y for PDF coordinates
if (pageRotationInDegrees !== 0) {
const adjustedPosition = adjustPositionForRotation(
pageWidth,
pageHeight,
debugX,
debugY,
pageRotationInDegrees,
);
debugX = adjustedPosition.xPos;
debugY = adjustedPosition.yPos;
}
page.drawRectangle({
x: debugX,
y: debugY,
width: fieldWidth,
height: fieldHeight,
borderColor: rgb(1, 0, 0), // Red
borderWidth: 1,
rotate: degrees(pageRotationInDegrees),
});
}
const font = await pdf.embedFont(
isSignatureField ? fontCaveat : fontNoto,
isSignatureField ? { features: { calt: false } } : undefined,
@ -278,6 +310,7 @@ export const insertFieldInPDF = async (pdf: PDFDocument, field: FieldWithSignatu
const meta = Parser ? Parser.safeParse(field.fieldMeta) : null;
const customFontSize = meta?.success && meta.data.fontSize ? meta.data.fontSize : null;
const textAlign = meta?.success && meta.data.textAlign ? meta.data.textAlign : 'center';
const longestLineInTextForWidth = field.customText
.split('\n')
.sort((a, b) => b.length - a.length)[0];
@ -293,7 +326,17 @@ export const insertFieldInPDF = async (pdf: PDFDocument, field: FieldWithSignatu
textWidth = font.widthOfTextAtSize(longestLineInTextForWidth, fontSize);
let textX = fieldX + (fieldWidth - textWidth) / 2;
// Add padding similar to web display (roughly 0.5rem equivalent in PDF units)
const padding = 8; // PDF points, roughly equivalent to 0.5rem
// Calculate X position based on text alignment with padding
let textX = fieldX + padding; // Left alignment starts after padding
if (textAlign === 'center') {
textX = fieldX + (fieldWidth - textWidth) / 2; // Center alignment ignores padding
} else if (textAlign === 'right') {
textX = fieldX + fieldWidth - textWidth - padding; // Right alignment respects right padding
}
let textY = fieldY + (fieldHeight - textHeight) / 2;
// Invert the Y axis since PDFs use a bottom-left coordinate system

View File

@ -95,7 +95,7 @@ export const createTeam = async ({
});
}
await tx.team.create({
const team = await tx.team.create({
data: {
name: teamName,
url: teamUrl,
@ -104,13 +104,23 @@ export const createTeam = async ({
members: {
create: [
{
userId,
userId: user.id,
role: TeamMemberRole.ADMIN,
},
],
},
},
});
await tx.teamGlobalSettings.upsert({
where: {
teamId: team.id,
},
update: {},
create: {
teamId: team.id,
},
});
});
return {
@ -225,6 +235,16 @@ export const createTeamFromPendingTeam = async ({
},
});
await tx.teamGlobalSettings.upsert({
where: {
teamId: team.id,
},
update: {},
create: {
teamId: team.id,
},
});
await tx.subscription.upsert(
mapStripeSubscriptionToPrismaUpsertAction(subscription, undefined, team.id),
);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -11,9 +11,14 @@ export const ZBaseFieldMeta = z.object({
export type TBaseFieldMeta = z.infer<typeof ZBaseFieldMeta>;
export const ZFieldTextAlignSchema = z.enum(['left', 'center', 'right']);
export type TFieldTextAlignSchema = z.infer<typeof ZFieldTextAlignSchema>;
export const ZInitialsFieldMeta = ZBaseFieldMeta.extend({
type: z.literal('initials'),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TInitialsFieldMeta = z.infer<typeof ZInitialsFieldMeta>;
@ -21,6 +26,7 @@ export type TInitialsFieldMeta = z.infer<typeof ZInitialsFieldMeta>;
export const ZNameFieldMeta = ZBaseFieldMeta.extend({
type: z.literal('name'),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TNameFieldMeta = z.infer<typeof ZNameFieldMeta>;
@ -28,6 +34,7 @@ export type TNameFieldMeta = z.infer<typeof ZNameFieldMeta>;
export const ZEmailFieldMeta = ZBaseFieldMeta.extend({
type: z.literal('email'),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TEmailFieldMeta = z.infer<typeof ZEmailFieldMeta>;
@ -35,6 +42,7 @@ export type TEmailFieldMeta = z.infer<typeof ZEmailFieldMeta>;
export const ZDateFieldMeta = ZBaseFieldMeta.extend({
type: z.literal('date'),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TDateFieldMeta = z.infer<typeof ZDateFieldMeta>;
@ -44,6 +52,7 @@ export const ZTextFieldMeta = ZBaseFieldMeta.extend({
text: z.string().optional(),
characterLimit: z.number().optional(),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TTextFieldMeta = z.infer<typeof ZTextFieldMeta>;
@ -55,6 +64,7 @@ export const ZNumberFieldMeta = ZBaseFieldMeta.extend({
minValue: z.number().optional(),
maxValue: z.number().optional(),
fontSize: z.number().min(8).max(96).optional(),
textAlign: ZFieldTextAlignSchema.optional(),
});
export type TNumberFieldMeta = z.infer<typeof ZNumberFieldMeta>;
@ -113,7 +123,16 @@ export const ZFieldMetaNotOptionalSchema = z.discriminatedUnion('type', [
export type TFieldMetaNotOptionalSchema = z.infer<typeof ZFieldMetaNotOptionalSchema>;
export const ZFieldMetaSchema = ZFieldMetaNotOptionalSchema.optional();
export const ZFieldMetaSchema = z
.union([
// Handles an empty object being provided as fieldMeta.
z
.object({})
.strict()
.transform(() => undefined),
ZFieldMetaNotOptionalSchema,
])
.optional();
export type TFieldMetaSchema = z.infer<typeof ZFieldMetaSchema>;

View File

@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WebhookTriggerEvents" ADD VALUE 'DOCUMENT_CANCELLED';

View File

@ -0,0 +1,29 @@
-- CreateTable
CREATE TABLE "DocumentAccessToken" (
"id" TEXT NOT NULL,
"token" TEXT NOT NULL,
"documentId" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"expiresAt" TIMESTAMP(3),
"revokedAt" TIMESTAMP(3),
"lastAccessedAt" TIMESTAMP(3),
"accessCount" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "DocumentAccessToken_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "DocumentAccessToken_token_key" ON "DocumentAccessToken"("token");
-- CreateIndex
CREATE UNIQUE INDEX "DocumentAccessToken_documentId_key" ON "DocumentAccessToken"("documentId");
-- CreateIndex
CREATE INDEX "DocumentAccessToken_token_idx" ON "DocumentAccessToken"("token");
-- CreateIndex
CREATE INDEX "DocumentAccessToken_documentId_idx" ON "DocumentAccessToken"("documentId");
-- AddForeignKey
ALTER TABLE "DocumentAccessToken" ADD CONSTRAINT "DocumentAccessToken_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "Document"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -175,6 +175,7 @@ enum WebhookTriggerEvents {
DOCUMENT_SIGNED
DOCUMENT_COMPLETED
DOCUMENT_REJECTED
DOCUMENT_CANCELLED
}
model Webhook {
@ -328,7 +329,8 @@ model Document {
template Template? @relation(fields: [templateId], references: [id], onDelete: SetNull)
source DocumentSource
auditLogs DocumentAuditLog[]
auditLogs DocumentAuditLog[]
documentAccessToken DocumentAccessToken?
@@unique([documentDataId])
@@index([userId])
@ -395,6 +397,23 @@ model DocumentMeta {
emailSettings Json? /// [DocumentEmailSettings] @zod.custom.use(ZDocumentEmailSettingsSchema)
}
model DocumentAccessToken {
id String @id @default(cuid())
token String @unique
documentId Int @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime?
revokedAt DateTime?
lastAccessedAt DateTime?
accessCount Int @default(0)
document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
@@index([token])
@@index([documentId])
}
enum ReadStatus {
NOT_OPENED
OPENED

View File

@ -1,6 +1,5 @@
import { TRPCError } from '@trpc/server';
import { DateTime } from 'luxon';
import { z } from 'zod';
import { getServerLimits } from '@documenso/ee/server-only/limits/server';
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
@ -42,6 +41,7 @@ import {
ZFindDocumentAuditLogsQuerySchema,
ZFindDocumentsRequestSchema,
ZFindDocumentsResponseSchema,
ZGenericSuccessResponse,
ZGetDocumentByIdQuerySchema,
ZGetDocumentByTokenQuerySchema,
ZGetDocumentWithDetailsByIdRequestSchema,
@ -52,6 +52,7 @@ import {
ZSearchDocumentsMutationSchema,
ZSetPasswordForDocumentMutationSchema,
ZSetSigningOrderForDocumentMutationSchema,
ZSuccessResponseSchema,
ZUpdateDocumentRequestSchema,
ZUpdateDocumentResponseSchema,
} from './schema';
@ -326,7 +327,7 @@ export const documentRouter = router({
},
})
.input(ZDeleteDocumentMutationSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { documentId } = input;
@ -339,6 +340,8 @@ export const documentRouter = router({
teamId,
requestMetadata: ctx.metadata,
});
return ZGenericSuccessResponse;
}),
/**
@ -481,18 +484,20 @@ export const documentRouter = router({
},
})
.input(ZResendDocumentMutationSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { documentId, recipients } = input;
return await resendDocument({
await resendDocument({
userId: ctx.user.id,
teamId,
documentId,
recipients,
requestMetadata: ctx.metadata,
});
return ZGenericSuccessResponse;
}),
/**

View File

@ -34,6 +34,19 @@ import {
import { ZCreateRecipientSchema } from '../recipient-router/schema';
/**
* Required for empty responses since we currently can't 201 requests for our openapi setup.
*
* Without this it will throw an error in Speakeasy SDK when it tries to parse an empty response.
*/
export const ZSuccessResponseSchema = z.object({
success: z.literal(true),
});
export const ZGenericSuccessResponse = {
success: true,
} satisfies z.infer<typeof ZSuccessResponseSchema>;
export const ZDocumentTitleSchema = z
.string()
.trim()

View File

@ -1,5 +1,3 @@
import { z } from 'zod';
import { createDocumentFields } from '@documenso/lib/server-only/field/create-document-fields';
import { createTemplateFields } from '@documenso/lib/server-only/field/create-template-fields';
import { deleteDocumentField } from '@documenso/lib/server-only/field/delete-document-field';
@ -13,6 +11,7 @@ import { updateDocumentFields } from '@documenso/lib/server-only/field/update-do
import { updateTemplateFields } from '@documenso/lib/server-only/field/update-template-fields';
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../document-router/schema';
import { authenticatedProcedure, procedure, router } from '../trpc';
import {
ZCreateDocumentFieldRequestSchema,
@ -200,7 +199,7 @@ export const fieldRouter = router({
},
})
.input(ZDeleteDocumentFieldRequestSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { fieldId } = input;
@ -211,6 +210,8 @@ export const fieldRouter = router({
fieldId,
requestMetadata: ctx.metadata,
});
return ZGenericSuccessResponse;
}),
/**
@ -396,7 +397,7 @@ export const fieldRouter = router({
},
})
.input(ZDeleteTemplateFieldRequestSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { fieldId } = input;
@ -406,6 +407,8 @@ export const fieldRouter = router({
teamId,
fieldId,
});
return ZGenericSuccessResponse;
}),
/**

View File

@ -1,5 +1,3 @@
import { z } from 'zod';
import { completeDocumentWithToken } from '@documenso/lib/server-only/document/complete-document-with-token';
import { rejectDocumentWithToken } from '@documenso/lib/server-only/document/reject-document-with-token';
import { createDocumentRecipients } from '@documenso/lib/server-only/recipient/create-document-recipients';
@ -13,6 +11,7 @@ import { updateDocumentRecipients } from '@documenso/lib/server-only/recipient/u
import { updateTemplateRecipients } from '@documenso/lib/server-only/recipient/update-template-recipients';
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../document-router/schema';
import { authenticatedProcedure, procedure, router } from '../trpc';
import {
ZCompleteDocumentWithTokenMutationSchema,
@ -200,7 +199,7 @@ export const recipientRouter = router({
},
})
.input(ZDeleteDocumentRecipientRequestSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { recipientId } = input;
@ -211,6 +210,8 @@ export const recipientRouter = router({
recipientId,
requestMetadata: ctx.metadata,
});
return ZGenericSuccessResponse;
}),
/**
@ -391,7 +392,7 @@ export const recipientRouter = router({
},
})
.input(ZDeleteTemplateRecipientRequestSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { recipientId } = input;
@ -401,6 +402,8 @@ export const recipientRouter = router({
userId: ctx.user.id,
teamId,
});
return ZGenericSuccessResponse;
}),
/**

View File

@ -1,7 +1,8 @@
import { z } from 'zod';
import { TRPCError } from '@trpc/server';
import { getServerLimits } from '@documenso/ee/server-only/limits/server';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { jobs } from '@documenso/lib/jobs/client';
import { getDocumentWithDetailsById } from '@documenso/lib/server-only/document/get-document-with-details-by-id';
import { sendDocument } from '@documenso/lib/server-only/document/send-document';
import {
@ -24,8 +25,10 @@ import { toggleTemplateDirectLink } from '@documenso/lib/server-only/template/to
import { updateTemplate } from '@documenso/lib/server-only/template/update-template';
import type { Document } from '@documenso/prisma/client';
import { ZGenericSuccessResponse, ZSuccessResponseSchema } from '../document-router/schema';
import { authenticatedProcedure, maybeAuthenticatedProcedure, router } from '../trpc';
import {
ZBulkSendTemplateMutationSchema,
ZCreateDocumentFromDirectTemplateRequestSchema,
ZCreateDocumentFromTemplateRequestSchema,
ZCreateDocumentFromTemplateResponseSchema,
@ -195,7 +198,7 @@ export const templateRouter = router({
},
})
.input(ZDeleteTemplateMutationSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { templateId } = input;
@ -203,6 +206,8 @@ export const templateRouter = router({
const userId = ctx.user.id;
await deleteTemplate({ userId, id: templateId, teamId });
return ZGenericSuccessResponse;
}),
/**
@ -352,7 +357,7 @@ export const templateRouter = router({
},
})
.input(ZDeleteTemplateDirectLinkRequestSchema)
.output(z.void())
.output(ZSuccessResponseSchema)
.mutation(async ({ input, ctx }) => {
const { teamId } = ctx;
const { templateId } = input;
@ -360,6 +365,8 @@ export const templateRouter = router({
const userId = ctx.user.id;
await deleteTemplateDirectLink({ userId, teamId, templateId });
return ZGenericSuccessResponse;
}),
/**
@ -411,4 +418,48 @@ export const templateRouter = router({
userId,
});
}),
/**
* @private
*/
uploadBulkSend: authenticatedProcedure
.input(ZBulkSendTemplateMutationSchema)
.mutation(async ({ ctx, input }) => {
const { templateId, teamId, csv, sendImmediately } = input;
const { user } = ctx;
if (csv.length > 4 * 1024 * 1024) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'File size exceeds 4MB limit',
});
}
const template = await getTemplateById({
id: templateId,
teamId,
userId: user.id,
});
if (!template) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Template not found',
});
}
await jobs.triggerJob({
name: 'internal.bulk-send-template',
payload: {
userId: user.id,
teamId,
templateId,
csvContent: csv,
sendImmediately,
requestMetadata: ctx.metadata.requestMetadata,
},
});
return { success: true };
}),
});

View File

@ -188,6 +188,14 @@ export const ZMoveTemplateToTeamRequestSchema = z.object({
export const ZMoveTemplateToTeamResponseSchema = ZTemplateLiteSchema;
export const ZBulkSendTemplateMutationSchema = z.object({
templateId: z.number(),
teamId: z.number().optional(),
csv: z.string().min(1),
sendImmediately: z.boolean(),
});
export type TCreateTemplateMutationSchema = z.infer<typeof ZCreateTemplateMutationSchema>;
export type TDuplicateTemplateMutationSchema = z.infer<typeof ZDuplicateTemplateMutationSchema>;
export type TDeleteTemplateMutationSchema = z.infer<typeof ZDeleteTemplateMutationSchema>;
export type TBulkSendTemplateMutationSchema = z.infer<typeof ZBulkSendTemplateMutationSchema>;

View File

@ -71,21 +71,25 @@ const getDefaultState = (fieldType: FieldType): FieldMeta => {
return {
type: 'initials',
fontSize: 14,
textAlign: 'left',
};
case FieldType.NAME:
return {
type: 'name',
fontSize: 14,
textAlign: 'left',
};
case FieldType.EMAIL:
return {
type: 'email',
fontSize: 14,
textAlign: 'left',
};
case FieldType.DATE:
return {
type: 'date',
fontSize: 14,
textAlign: 'left',
};
case FieldType.TEXT:
return {
@ -97,6 +101,7 @@ const getDefaultState = (fieldType: FieldType): FieldMeta => {
fontSize: 14,
required: false,
readOnly: false,
textAlign: 'left',
};
case FieldType.NUMBER:
return {
@ -110,6 +115,7 @@ const getDefaultState = (fieldType: FieldType): FieldMeta => {
required: false,
readOnly: false,
fontSize: 14,
textAlign: 'left',
};
case FieldType.RADIO:
return {

View File

@ -5,6 +5,13 @@ import { validateFields as validateDateFields } from '@documenso/lib/advanced-fi
import { type TDateFieldMeta as DateFieldMeta } from '@documenso/lib/types/field-meta';
import { Input } from '@documenso/ui/primitives/input';
import { Label } from '@documenso/ui/primitives/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
type DateFieldAdvancedSettingsProps = {
fieldState: DateFieldMeta;
@ -66,6 +73,27 @@ export const DateFieldAdvancedSettings = ({
max={96}
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
</div>
);
};

View File

@ -5,6 +5,13 @@ import { validateFields as validateEmailFields } from '@documenso/lib/advanced-f
import { type TEmailFieldMeta as EmailFieldMeta } from '@documenso/lib/types/field-meta';
import { Input } from '@documenso/ui/primitives/input';
import { Label } from '@documenso/ui/primitives/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
type EmailFieldAdvancedSettingsProps = {
fieldState: EmailFieldMeta;
@ -48,6 +55,27 @@ export const EmailFieldAdvancedSettings = ({
max={96}
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
</div>
);
};

View File

@ -6,6 +6,8 @@ import { type TInitialsFieldMeta as InitialsFieldMeta } from '@documenso/lib/typ
import { Input } from '@documenso/ui/primitives/input';
import { Label } from '@documenso/ui/primitives/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../select';
type InitialsFieldAdvancedSettingsProps = {
fieldState: InitialsFieldMeta;
handleFieldChange: (key: keyof InitialsFieldMeta, value: string | boolean) => void;
@ -48,6 +50,27 @@ export const InitialsFieldAdvancedSettings = ({
max={96}
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
</div>
);
};

View File

@ -5,6 +5,13 @@ import { validateFields as validateNameFields } from '@documenso/lib/advanced-fi
import { type TNameFieldMeta as NameFieldMeta } from '@documenso/lib/types/field-meta';
import { Input } from '@documenso/ui/primitives/input';
import { Label } from '@documenso/ui/primitives/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
type NameFieldAdvancedSettingsProps = {
fieldState: NameFieldMeta;
@ -48,6 +55,27 @@ export const NameFieldAdvancedSettings = ({
max={96}
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
</div>
);
};

View File

@ -38,12 +38,12 @@ export const NumberFieldAdvancedSettings = ({
const [showValidation, setShowValidation] = useState(false);
const handleInput = (field: keyof NumberFieldMeta, value: string | boolean) => {
const userValue = field === 'value' ? value : fieldState.value ?? 0;
const userValue = field === 'value' ? value : (fieldState.value ?? 0);
const userMinValue = field === 'minValue' ? Number(value) : Number(fieldState.minValue ?? 0);
const userMaxValue = field === 'maxValue' ? Number(value) : Number(fieldState.maxValue ?? 0);
const readOnly = field === 'readOnly' ? Boolean(value) : Boolean(fieldState.readOnly);
const required = field === 'required' ? Boolean(value) : Boolean(fieldState.required);
const numberFormat = field === 'numberFormat' ? String(value) : fieldState.numberFormat ?? '';
const numberFormat = field === 'numberFormat' ? String(value) : (fieldState.numberFormat ?? '');
const fontSize = field === 'fontSize' ? Number(value) : Number(fieldState.fontSize ?? 14);
const valueErrors = validateNumberField(String(userValue), {
@ -135,6 +135,27 @@ export const NumberFieldAdvancedSettings = ({
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="mt-2 flex flex-col gap-4">
<div className="flex flex-row items-center gap-2">
<Switch

View File

@ -5,6 +5,13 @@ import { validateTextField } from '@documenso/lib/advanced-fields-validation/val
import { type TTextFieldMeta as TextFieldMeta } from '@documenso/lib/types/field-meta';
import { Input } from '@documenso/ui/primitives/input';
import { Label } from '@documenso/ui/primitives/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
import { Switch } from '@documenso/ui/primitives/switch';
import { Textarea } from '@documenso/ui/primitives/textarea';
@ -22,7 +29,7 @@ export const TextFieldAdvancedSettings = ({
const { _ } = useLingui();
const handleInput = (field: keyof TextFieldMeta, value: string | boolean) => {
const text = field === 'text' ? String(value) : fieldState.text ?? '';
const text = field === 'text' ? String(value) : (fieldState.text ?? '');
const limit =
field === 'characterLimit' ? Number(value) : Number(fieldState.characterLimit ?? 0);
const fontSize = field === 'fontSize' ? Number(value) : Number(fieldState.fontSize ?? 14);
@ -112,6 +119,27 @@ export const TextFieldAdvancedSettings = ({
/>
</div>
<div>
<Label>
<Trans>Text Align</Trans>
</Label>
<Select
value={fieldState.textAlign}
onValueChange={(value) => handleInput('textAlign', value)}
>
<SelectTrigger className="bg-background mt-2">
<SelectValue placeholder="Select text align" />
</SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="center">Center</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="mt-4 flex flex-col gap-4">
<div className="flex flex-row items-center gap-2">
<Switch

View File

@ -19,6 +19,7 @@ import {
User,
} from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-client-rect';
import { useDocumentElement } from '@documenso/lib/client-only/hooks/use-document-element';
@ -53,6 +54,7 @@ import { FieldItem } from '@documenso/ui/primitives/document-flow/field-item';
import type { DocumentFlowStep } from '@documenso/ui/primitives/document-flow/types';
import { FRIENDLY_FIELD_TYPE } from '@documenso/ui/primitives/document-flow/types';
import { Popover, PopoverContent, PopoverTrigger } from '@documenso/ui/primitives/popover';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { getSignerColorStyles, useSignerColors } from '../../lib/signer-colors';
import { Checkbox } from '../checkbox';
@ -95,12 +97,19 @@ export const AddTemplateFieldsFormPartial = ({
typedSignatureEnabled,
}: AddTemplateFieldsFormProps) => {
const { _ } = useLingui();
const { toast } = useToast();
const { isWithinPageBounds, getFieldPosition, getPage } = useDocumentElement();
const { currentStep, totalSteps, previousStep } = useStep();
const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
const [currentField, setCurrentField] = useState<FieldFormType>();
const [activeFieldId, setActiveFieldId] = useState<string | null>(null);
const [lastActiveField, setLastActiveField] = useState<
TAddTemplateFieldsFormSchema['fields'][0] | null
>(null);
const [fieldClipboard, setFieldClipboard] = useState<
TAddTemplateFieldsFormSchema['fields'][0] | null
>(null);
const form = useForm<TAddTemplateFieldsFormSchema>({
defaultValues: {
@ -126,25 +135,6 @@ export const AddTemplateFieldsFormPartial = ({
const onFormSubmit = form.handleSubmit(onSubmit);
const handleSavedFieldSettings = (fieldState: FieldMeta) => {
const initialValues = form.getValues();
const updatedFields = initialValues.fields.map((field) => {
if (field.formId === currentField?.formId) {
const parsedFieldMeta = ZFieldMetaSchema.parse(fieldState);
return {
...field,
fieldMeta: parsedFieldMeta,
};
}
return field;
});
form.setValue('fields', updatedFields);
};
const {
append,
remove,
@ -164,6 +154,72 @@ export const AddTemplateFieldsFormPartial = ({
selectedSignerIndex === -1 ? 0 : selectedSignerIndex,
);
const onFieldCopy = useCallback(
(event?: KeyboardEvent | null, options?: { duplicate?: boolean }) => {
const { duplicate = false } = options ?? {};
if (lastActiveField) {
event?.preventDefault();
if (!duplicate) {
setFieldClipboard(lastActiveField);
toast({
title: 'Copied field',
description: 'Copied field to clipboard',
});
return;
}
const newField: TAddTemplateFieldsFormSchema['fields'][0] = {
...structuredClone(lastActiveField),
formId: nanoid(12),
signerEmail: selectedSigner?.email ?? lastActiveField.signerEmail,
signerId: selectedSigner?.id ?? lastActiveField.signerId,
signerToken: selectedSigner?.token ?? lastActiveField.signerToken,
pageX: lastActiveField.pageX + 3,
pageY: lastActiveField.pageY + 3,
};
append(newField);
}
},
[
append,
lastActiveField,
selectedSigner?.email,
selectedSigner?.id,
selectedSigner?.token,
toast,
],
);
const onFieldPaste = useCallback(
(event: KeyboardEvent) => {
if (fieldClipboard) {
event.preventDefault();
const copiedField = structuredClone(fieldClipboard);
append({
...copiedField,
formId: nanoid(12),
signerEmail: selectedSigner?.email ?? copiedField.signerEmail,
signerId: selectedSigner?.id ?? copiedField.signerId,
signerToken: selectedSigner?.token ?? copiedField.signerToken,
pageX: copiedField.pageX + 3,
pageY: copiedField.pageY + 3,
});
}
},
[append, fieldClipboard, selectedSigner?.email, selectedSigner?.id, selectedSigner?.token],
);
useHotkeys(['ctrl+c', 'meta+c'], (evt) => onFieldCopy(evt));
useHotkeys(['ctrl+v', 'meta+v'], (evt) => onFieldPaste(evt));
useHotkeys(['ctrl+d', 'meta+d'], (evt) => onFieldCopy(evt, { duplicate: true }));
const filterFieldsWithEmptyValues = (fields: typeof localFields, fieldType: string) =>
fields
.filter((field) => field.type === fieldType)
@ -402,6 +458,25 @@ export const AddTemplateFieldsFormPartial = ({
setShowAdvancedSettings((prev) => !prev);
};
const handleSavedFieldSettings = (fieldState: FieldMeta) => {
const initialValues = form.getValues();
const updatedFields = initialValues.fields.map((field) => {
if (field.formId === currentField?.formId) {
const parsedFieldMeta = ZFieldMetaSchema.parse(fieldState);
return {
...field,
fieldMeta: parsedFieldMeta,
};
}
return field;
});
form.setValue('fields', updatedFields);
};
const isTypedSignatureEnabled = form.watch('typedSignatureEnabled');
const handleTypedSignatureChange = (value: boolean) => {
@ -468,9 +543,12 @@ export const AddTemplateFieldsFormPartial = ({
defaultHeight={DEFAULT_HEIGHT_PX}
defaultWidth={DEFAULT_WIDTH_PX}
passive={isFieldWithinBounds && !!selectedField}
onFocus={() => setLastActiveField(field)}
onBlur={() => setLastActiveField(null)}
onResize={(options) => onFieldResize(options, index)}
onMove={(options) => onFieldMove(options, index)}
onRemove={() => remove(index)}
onDuplicate={() => onFieldCopy(null, { duplicate: true })}
onAdvancedSettings={() => {
setCurrentField(field);
handleAdvancedSettings();