AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(pandadoc): let AI agents create, send and track documents, with signed webhook triggers (#16691)
Odai Ahmada3b5f0e44bd9
diff --git a/bun.lock b/bun.lockindex f2ee16e131f..578bb7e5339 100644--- a/bun.lock+++ b/bun.lock@@ -6893,15 +6893,17 @@},"packages/pieces/community/pandadoc": {"name": "@activepieces/piece-pandadoc",- "version": "0.2.2",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/paperform": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex 3845265c2e3..5da8e6bb242 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,18 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### PandaDoc 0.3.0: seven actions are builder-only, and the triggers now fire++Create Document from Template, Create Attachment, Create or Update Contact, Find Document(s), Get Document Attachment, Get Document and Download Document are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.++The PandaDoc triggers did not fire before this version; after you upgrade and re-enable a flow they start runs. The trigger output is now a flat document (`id`, `name`, `status`, `template_id`, `folder_uuid`, `recipients`, ...) instead of the old sample data's `data` / `template.id` shape. The filter on **Document Updated** is still shown but is ignored, so the trigger runs for every update. **Create Document from Template** now sends template fields by their merge-field key, so a step that used to fail with a 401 now fills the fields. Checkbox template fields are now a Checked / Unchecked dropdown; left empty, the template default is kept.++#### What you need to do++Agents that used these actions switch to their twins: Create Document from Template (AI), Add Document Attachment (AI), Create Contact (AI) or Update Contact (AI), Search Documents (AI), List Document Attachments (AI), Get Document (AI) and Download Document (AI). Flow steps keep running on the version they were built with until you upgrade them.++After upgrading a PandaDoc trigger, turn the flow off and on again so PandaDoc signs its deliveries. If a flow mapped fields from the old trigger sample data, re-map them from the new output (for example `template_id` instead of `template.id`). If a flow used the Document Updated filter, add a Router or Branch step after the trigger to keep only the updates you need.+#### Cognito Forms 0.3.0: Update Entry skips empty fields, and the entry actions move to new AI versionsFrom Cognito Forms 0.3.0 the **Update Entry** action only sends the fields you fill in. Before, empty values (blank text, null, empty lists) were sent too, which cleared the value stored on the entry. Now an empty field keeps its current value, and the step fails with "Fill in at least one field to update." when every field is empty. Yes/No fields in Update Entry are now a **Yes** / **No** dropdown; left empty, the field keeps its current value. Before, an untouched Yes/No checkbox was sent as No and overwrote the entry. **Create Entry** also leaves out empty fields, so the form's own default values apply.diff --git a/packages/pieces/community/pandadoc/package.json b/packages/pieces/community/pandadoc/package.jsonindex 904f56bf0a4..a3c6fb10bb7 100644--- a/packages/pieces/community/pandadoc/package.json+++ b/packages/pieces/community/pandadoc/package.json@@ -1,20 +1,23 @@{"name": "@activepieces/piece-pandadoc",- "version": "0.2.2",+ "version": "0.3.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/pandadoc/src/i18n/translation.json b/packages/pieces/community/pandadoc/src/i18n/translation.jsonindex c054d1e35ba..66cc6411b17 100644--- a/packages/pieces/community/pandadoc/src/i18n/translation.json+++ b/packages/pieces/community/pandadoc/src/i18n/translation.json@@ -1,5 +1,6 @@{- "Your PandaDoc API key. Get it from the Developer Dashboard in your PandaDoc account.": "Your PandaDoc API key. Get it from the Developer Dashboard in your PandaDoc account.",+ "Create, send and track documents, proposals and e-signatures.": "Create, send and track documents, proposals and e-signatures.",+ "Your PandaDoc API key.\n\n1. In PandaDoc, open **Settings > Integrations > API** (the Developer Dashboard).\n2. Copy the **Sandbox** key for testing or the **Production** key for live documents.\n3. Paste it here.\n\nSandbox keys are limited to 10 requests per minute and can only send documents to email addresses in your own domain.": "Your PandaDoc API key.\n\n1. In PandaDoc, open **Settings > Integrations > API** (the Developer Dashboard).\n2. Copy the **Sandbox** key for testing or the **Production** key for live documents.\n3. Paste it here.\n\nSandbox keys are limited to 10 requests per minute and can only send documents to email addresses in your own domain.","Create Document from Template": "Create Document from Template","Create Attachment": "Create Attachment","Create or Update Contact": "Create or Update Contact",@@ -7,14 +8,60 @@"Get Document Attachment": "Get Document Attachment","Get Document": "Get Document","Download Document": "Download Document",+ "Send Document": "Send Document",+ "Create Document from File": "Create Document from File",+ "Create Signing Link": "Create Signing Link",+ "Send Document Reminder": "Send Document Reminder",+ "Update Document Status": "Update Document Status",+ "Delete Document": "Delete Document",+ "Move Document to Folder": "Move Document to Folder",+ "Add Document Recipient": "Add Document Recipient",+ "List Document Fields": "List Document Fields",+ "List Templates": "List Templates",+ "Get Template Details": "Get Template Details",+ "List Document Folders": "List Document Folders",+ "Create Document Folder": "Create Document Folder",+ "Find Contacts": "Find Contacts",+ "Delete Contact": "Delete Contact",+ "Create Document from Template (AI)": "Create Document from Template (AI)",+ "Add Document Attachment (AI)": "Add Document Attachment (AI)",+ "Create Contact (AI)": "Create Contact (AI)",+ "Update Contact (AI)": "Update Contact (AI)",+ "Download Document (AI)": "Download Document (AI)",+ "Search Documents (AI)": "Search Documents (AI)",+ "List Document Attachments (AI)": "List Document Attachments (AI)",+ "Get Document (AI)": "Get Document (AI)","Custom API Call": "Custom API Call","Creates a document from a PandaDoc Template.": "Creates a document from a PandaDoc Template.",- "Adds an attachment to a document.": "Adds an attachment to a document.",+ "Adds an attachment to a document, from a file URL or an uploaded file.": "Adds an attachment to a document, from a file URL or an uploaded file.","Creates a new or update an existing contact.": "Creates a new or update an existing contact.",- "Finds documents based various filter.": "Finds documents based various filter.",+ "Finds documents using filters such as name, status, template, folder, contact and dates.": "Finds documents using filters such as name, status, template, folder, contact and dates.","Retrieves details of a specific attachment from a document.": "Retrieves details of a specific attachment from a document.","Retrieves comprehensive document data.": "Retrieves comprehensive document data.",- "Downloads a document as PDF.": "Downloads a document as PDF.",+ "Downloads a document as PDF (or a zip of PDFs, one per section).": "Downloads a document as PDF (or a zip of PDFs, one per section).",+ "Sends a draft document to its recipients for viewing or signing.": "Sends a draft document to its recipients for viewing or signing.",+ "Creates a document from a PDF (or DOCX) file or a public file URL.": "Creates a document from a PDF (or DOCX) file or a public file URL.",+ "Creates a temporary link a recipient can open to view and sign a sent document.": "Creates a temporary link a recipient can open to view and sign a sent document.",+ "Emails a reminder to recipients who have not yet completed a sent document.": "Emails a reminder to recipients who have not yet completed a sent document.",+ "Manually marks a document as completed, paid, voided or declined.": "Manually marks a document as completed, paid, voided or declined.",+ "Deletes a document.": "Deletes a document.",+ "Moves a document into a folder.": "Moves a document into a folder.",+ "Adds a contact as a recipient of a draft document.": "Adds a contact as a recipient of a draft document.",+ "Lists the fields of a document with their current values.": "Lists the fields of a document with their current values.",+ "Lists or searches templates.": "Lists or searches templates.",+ "Gets a template with its roles, fields and variables.": "Gets a template with its roles, fields and variables.",+ "Lists document folders, optionally inside a parent folder.": "Lists document folders, optionally inside a parent folder.",+ "Creates a folder for documents.": "Creates a folder for documents.",+ "Finds contacts by exact email, or lists all contacts.": "Finds contacts by exact email, or lists all contacts.",+ "Deletes a contact.": "Deletes a contact.",+ "Creates a document from a PandaDoc template by template ID.": "Creates a document from a PandaDoc template by template ID.",+ "Adds an attachment to a document by document ID.": "Adds an attachment to a document by document ID.",+ "Creates a new PandaDoc contact.": "Creates a new PandaDoc contact.",+ "Updates an existing PandaDoc contact by ID.": "Updates an existing PandaDoc contact by ID.",+ "Downloads a document as a PDF file by document ID.": "Downloads a document as a PDF file by document ID.",+ "Searches PandaDoc documents with filters.": "Searches PandaDoc documents with filters.",+ "Lists the attachments of a document.": "Lists the attachments of a document.",+ "Gets the details of a document by ID.": "Gets the details of a document by ID.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Template": "Template","Document Name": "Document Name",@@ -24,8 +71,10 @@"Folder": "Folder","Tags": "Tags","Metadata": "Metadata",+ "Wait Until Ready to Send": "Wait Until Ready to Send","Document": "Document","File URL": "File URL",+ "File": "File","Attachment Name": "Attachment Name","Contact ID (for Update)": "Contact ID (for Update)","Email": "Email",@@ -59,12 +108,13 @@"Completed To": "Completed To","Modified From": "Modified From","Modified To": "Modified To",- "Show Deleted Documents": "Show Deleted Documents",+ "Only Deleted Documents": "Only Deleted Documents","Results Count": "Results Count","Page Number": "Page Number","Order By": "Order By","Metadata Filters": "Metadata Filters","Attachment": "Attachment",+ "Download Protected (Completed) Copy": "Download Protected (Completed) Copy","Download as Separate Files": "Download as Separate Files","Watermark Text": "Watermark Text","Custom Watermark Text": "Custom Watermark Text",@@ -72,6 +122,29 @@"Custom Watermark Color": "Custom Watermark Color","Watermark Font Size": "Watermark Font Size","Watermark Opacity": "Watermark Opacity",+ "Email Subject": "Email Subject",+ "Email Message": "Email Message",+ "Silent (No Email)": "Silent (No Email)",+ "Sender Email": "Sender Email",+ "Field Values": "Field Values",+ "Parse Form Fields": "Parse Form Fields",+ "Folder ID": "Folder ID",+ "Recipient Email": "Recipient Email",+ "Lifetime (Seconds)": "Lifetime (Seconds)",+ "Recipient IDs": "Recipient IDs",+ "New Status": "New Status",+ "Private Note": "Private Note",+ "Notify Recipients": "Notify Recipients",+ "Contact ID": "Contact ID",+ "Search Text": "Search Text",+ "Results per Page": "Results per Page",+ "Page": "Page",+ "Template ID": "Template ID",+ "Parent Folder ID": "Parent Folder ID",+ "Folder Name": "Folder Name",+ "Variables": "Variables",+ "State": "State",+ "Protected Copy": "Protected Copy","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -81,15 +154,18 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "Select a template from your PandaDoc workspace": "Select a template from your PandaDoc workspace",+ "Select a template from your PandaDoc workspace. Type to search by name.": "Select a template from your PandaDoc workspace. Type to search by name.","Name the document you are creating": "Name the document you are creating",- "List of recipients to whom the document will be sent": "List of recipients to whom the document will be sent",+ "People who will receive the document. Use the role names defined in the template so they get the right fields.": "People who will receive the document. Use the role names defined in the template so they get the right fields.",+ "Values for the template fields that have a merge field name. Leave a field empty to keep its default.": "Values for the template fields that have a merge field name. Leave a field empty to keep its default.","Pass values for the variables in the template": "Pass values for the variables in the template","Select a folder from your PandaDoc workspace": "Select a folder from your PandaDoc workspace","Tag the document for filtering and organization": "Tag the document for filtering and organization","Additional data in key-value format to associate with document": "Additional data in key-value format to associate with document",- "Select a document from your PandaDoc workspace": "Select a document from your PandaDoc workspace",- "URL link to the file to be attached to the document": "URL link to the file to be attached to the document",+ "PandaDoc prepares new documents in the background. Turn this on to wait (up to 90 seconds) until the document is in draft, so a following Send Document step does not fail.": "PandaDoc prepares new documents in the background. Turn this on to wait (up to 90 seconds) until the document is in draft, so a following Send Document step does not fail.",+ "Select a document. The newest documents are listed first; type to search by name.": "Select a document. The newest documents are listed first; type to search by name.",+ "Public URL of the file to attach. Leave empty when you use the File field instead.": "Public URL of the file to attach. Leave empty when you use the File field instead.",+ "A file from a previous step to attach. Used instead of the File URL when both are set.": "A file from a previous step to attach. Used instead of the File URL when both are set.","Optional name to set for the uploaded file.": "Optional name to set for the uploaded file.","Select a contact to update. Leave empty to create a new contact.": "Select a contact to update. Leave empty to create a new contact.","An email address of the contact": "An email address of the contact",@@ -124,12 +200,13 @@"Include only documents completed before this date": "Include only documents completed before this date","Include only documents modified on or after this date": "Include only documents modified on or after this date","Include only documents modified before this date": "Include only documents modified before this date",- "Return only deleted documents": "Return only deleted documents",+ "When on, returns only deleted documents instead of active ones.": "When on, returns only deleted documents instead of active ones.","Number of documents to return (default: 50, max: 100)": "Number of documents to return (default: 50, max: 100)","Page number for pagination (starts with 1)": "Page number for pagination (starts with 1)","Sort results by field": "Sort results by field","Filter by metadata key-value pairs. Use format: {\"key\": \"value\"}": "Filter by metadata key-value pairs. Use format: {\"key\": \"value\"}","Select an attachment from the document": "Select an attachment from the document",+ "Download the certified, tamper-protected PDF of a completed document. Only works for completed documents; watermark options are ignored.": "Download the certified, tamper-protected PDF of a completed document. Only works for completed documents; watermark options are ignored.","Download document bundle as a zip archive of separate PDFs (1 file per section)": "Download document bundle as a zip archive of separate PDFs (1 file per section)","Select common watermark text or choose \"Custom\" to enter your own": "Select common watermark text or choose \"Custom\" to enter your own","Enter custom watermark text (only used if \"Custom\" is selected above)": "Enter custom watermark text (only used if \"Custom\" is selected above)",@@ -137,6 +214,29 @@"Enter a custom HEX color code (e.g., #FF5733). Only used if \"Custom HEX Code\" is selected above.": "Enter a custom HEX color code (e.g., #FF5733). Only used if \"Custom HEX Code\" is selected above.","Font size of the watermark text": "Font size of the watermark text","Opacity of the watermark (0.0 to 1.0)": "Opacity of the watermark (0.0 to 1.0)",+ "The PandaDoc document ID, for example from Search Documents or a create step.": "The PandaDoc document ID, for example from Search Documents or a create step.",+ "Send without emailing recipients, for example when you share a signing link yourself.": "Send without emailing recipients, for example when you share a signing link yourself.",+ "Email of a workspace member to send as. Leave empty to send as the API key owner.": "Email of a workspace member to send as. Leave empty to send as the API key owner.",+ "A PDF or DOCX file. Used instead of File URL when both are set.": "A PDF or DOCX file. Used instead of File URL when both are set.",+ "Public URL of a PDF or DOCX file.": "Public URL of a PDF or DOCX file.",+ "People who will receive the document. Each needs an email (or phone). Role must match a role name in the template or file.": "People who will receive the document. Each needs an email (or phone). Role must match a role name in the template or file.",+ "Values for fields, keyed by merge field name, for example {\"client_name\": \"Jane Doe\", \"agree\": true}. Get merge field names from Get Template Details.": "Values for fields, keyed by merge field name, for example {\"client_name\": \"Jane Doe\", \"agree\": true}. Get merge field names from Get Template Details.",+ "Turn on for PDFs with fillable form fields; leave off for PDFs with PandaDoc field tags.": "Turn on for PDFs with fillable form fields; leave off for PDFs with PandaDoc field tags.",+ "Wait (up to 90 seconds) until PandaDoc finishes preparing the document, so it can be sent right away.": "Wait (up to 90 seconds) until PandaDoc finishes preparing the document, so it can be sent right away.",+ "Must be a recipient of the document.": "Must be a recipient of the document.",+ "How long the link stays valid. Default 3600 (1 hour).": "How long the link stays valid. Default 3600 (1 hour).",+ "Leave empty to remind all pending recipients.": "Leave empty to remind all pending recipients.",+ "Matches template name.": "Matches template name.",+ "1 to 100, default 50.": "1 to 100, default 50.",+ "Starts at 1.": "Starts at 1.",+ "Leave empty for top-level folders.": "Leave empty for top-level folders.",+ "Leave empty to create a top-level folder.": "Leave empty to create a top-level folder.",+ "Exact email to match. Leave empty to list all contacts.": "Exact email to match. Leave empty to list all contacts.",+ "Template variables as name/value pairs, for example {\"Client.Company\": \"Acme\"}.": "Template variables as name/value pairs, for example {\"Client.Company\": \"Acme\"}.",+ "Key-value pairs stored on the document.": "Key-value pairs stored on the document.",+ "Public URL of the file. Leave empty when passing File.": "Public URL of the file. Leave empty when passing File.",+ "Matches document name or reference number.": "Matches document name or reference number.",+ "Match documents whose metadata has these key-value pairs.": "Match documents whose metadata has these key-value pairs.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",@@ -325,6 +425,7 @@"Voided": "Voided","Declined": "Declined","External Review": "External Review",+ "Signed (Notarization Pending)": "Signed (Notarization Pending)","contract": "contract","proposal": "proposal","quote": "quote",@@ -376,6 +477,20 @@"Orange (#FF7F00)": "Orange (#FF7F00)","Purple (#800080)": "Purple (#800080)","Custom HEX Code": "Custom HEX Code",+ "sent": "sent",+ "completed": "completed",+ "uploaded": "uploaded",+ "error": "error",+ "viewed": "viewed",+ "waiting_approval": "waiting_approval",+ "approved": "approved",+ "rejected": "rejected",+ "waiting_pay": "waiting_pay",+ "paid": "paid",+ "voided": "voided",+ "declined": "declined",+ "external_review": "external_review",+ "signed": "signed","GET": "GET","POST": "POST","PATCH": "PATCH",@@ -387,17 +502,23 @@"Document Completed": "Document Completed","Document State Changed": "Document State Changed","Document Updated": "Document Updated",- "Triggers when a document is completed.": "Triggers when a document is completed.",+ "Recipient Completed": "Recipient Completed",+ "Document Deleted": "Document Deleted",+ "Document Creation Failed": "Document Creation Failed",+ "Triggers when a document is completed (all recipients have signed or approved).": "Triggers when a document is completed (all recipients have signed or approved).","Triggers when a document status changes.": "Triggers when a document status changes.",- "Triggers when a document is updated.": "Triggers when a document is updated.",+ "Triggers when a sent document is moved back to draft so it can be edited.": "Triggers when a sent document is moved back to draft so it can be edited.",+ "Triggers when one recipient finishes their part of a document (signs or approves).": "Triggers when one recipient finishes their part of a document (signs or approves).",+ "Triggers when a document is deleted.": "Triggers when a document is deleted.",+ "Triggers when PandaDoc fails to create a document requested through the API (for example a bad file or missing field values).": "Triggers when PandaDoc fails to create a document requested through the API (for example a bad file or missing field values).","Filter by Templates": "Filter by Templates","Filter by Folders": "Filter by Folders","Filter by Status": "Filter by Status",- "Filter by Update Type": "Filter by Update Type",- "Only trigger for documents created from specific templates (leave empty for all)": "Only trigger for documents created from specific templates (leave empty for all)",- "Only trigger for documents in specific folders (leave empty for all)": "Only trigger for documents in specific folders (leave empty for all)",- "Only trigger for specific status changes (leave empty for all)": "Only trigger for specific status changes (leave empty for all)",- "Only trigger for specific types of updates (leave empty for all)": "Only trigger for specific types of updates (leave empty for all)",+ "Filter by Update Type (no longer used)": "Filter by Update Type (no longer used)",+ "Only trigger for documents created from these templates (leave empty for all).": "Only trigger for documents created from these templates (leave empty for all).",+ "Only trigger for documents stored in these folders (leave empty for all).": "Only trigger for documents stored in these folders (leave empty for all).",+ "Only trigger when the document moves into one of these statuses (leave empty for all).": "Only trigger when the document moves into one of these statuses (leave empty for all).",+ "PandaDoc does not report which part of a document changed, so this filter is ignored. Leave it empty.": "PandaDoc does not report which part of a document changed, so this filter is ignored. Leave it empty.","Content Changes": "Content Changes","Recipient Changes": "Recipient Changes","Settings Changes": "Settings Changes",diff --git a/packages/pieces/community/pandadoc/src/index.ts b/packages/pieces/community/pandadoc/src/index.tsindex 8ac1a5f2e43..0513ec8db74 100644--- a/packages/pieces/community/pandadoc/src/index.ts+++ b/packages/pieces/community/pandadoc/src/index.ts@@ -1,6 +1,6 @@-import { createPiece } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';-+import { pandadocAuth } from './lib/common/auth';import { createDocumentFromTemplate } from './lib/actions/create-document-from-template';import { createAttachment } from './lib/actions/create-attachment';import { createOrUpdateContact } from './lib/actions/create-or-update-contact';@@ -8,21 +8,44 @@ import { findDocument } from './lib/actions/find-document';import { getDocumentAttachments } from './lib/actions/get-document-attachments';import { getDocumentDetails } from './lib/actions/get-document-details';import { downloadDocument } from './lib/actions/download-document';-+import { sendDocument } from './lib/actions/send-document';+import { createDocumentFromFile } from './lib/actions/create-document-from-file';+import { createSigningLink } from './lib/actions/create-signing-link';+import { sendDocumentReminder } from './lib/actions/send-document-reminder';+import { updateDocumentStatus } from './lib/actions/update-document-status';+import { deleteDocument } from './lib/actions/delete-document';+import { moveDocumentToFolder } from './lib/actions/move-document-to-folder';+import { addDocumentRecipient } from './lib/actions/add-document-recipient';+import { listDocumentFields } from './lib/actions/list-document-fields';+import { listTemplates } from './lib/actions/list-templates';+import { getTemplateDetails } from './lib/actions/get-template-details';+import { listDocumentFolders } from './lib/actions/list-document-folders';+import { createDocumentFolder } from './lib/actions/create-document-folder';+import { findContacts } from './lib/actions/find-contacts';+import { deleteContact } from './lib/actions/delete-contact';+import { createDocumentFromTemplateAi } from './lib/actions/ai/create-document-from-template';+import { addDocumentAttachmentAi } from './lib/actions/ai/add-document-attachment';+import { createContactAi } from './lib/actions/ai/create-contact';+import { updateContactAi } from './lib/actions/ai/update-contact';+import { downloadDocumentAi } from './lib/actions/ai/download-document';+import { searchDocumentsAi } from './lib/actions/ai/search-documents';+import { listDocumentAttachmentsAi } from './lib/actions/ai/list-document-attachments';+import { getDocumentAi } from './lib/actions/ai/get-document';import { documentCompleted } from './lib/triggers/document-completed';import { documentStateChanged } from './lib/triggers/document-state-changed';import { documentUpdated } from './lib/triggers/document-updated';--import { pandadocAuth } from './lib/common';-import { PieceCategory } from '@activepieces/pieces-framework';+import { recipientCompleted } from './lib/triggers/recipient-completed';+import { documentDeleted } from './lib/triggers/document-deleted';+import { documentCreationFailed } from './lib/triggers/document-creation-failed';export const pandadoc = createPiece({displayName: 'PandaDoc',+ description: 'Create, send and track documents, proposals and e-signatures.',auth: pandadocAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/pandadoc.png',- categories:[PieceCategory.CONTENT_AND_FILES,PieceCategory.PRODUCTIVITY],- authors: ['onyedikachi-david'],+ categories: [PieceCategory.CONTENT_AND_FILES, PieceCategory.PRODUCTIVITY],+ authors: ['onyedikachi-david', 'OdaiAhmed99'],actions: [createDocumentFromTemplate,createAttachment,@@ -31,17 +54,36 @@ export const pandadoc = createPiece({getDocumentAttachments,getDocumentDetails,downloadDocument,+ sendDocument,+ createDocumentFromFile,+ createSigningLink,+ sendDocumentReminder,+ updateDocumentStatus,+ deleteDocument,+ moveDocumentToFolder,+ addDocumentRecipient,+ listDocumentFields,+ listTemplates,+ getTemplateDetails,+ listDocumentFolders,+ createDocumentFolder,+ findContacts,+ deleteContact,+ createDocumentFromTemplateAi,+ addDocumentAttachmentAi,+ createContactAi,+ updateContactAi,+ downloadDocumentAi,+ searchDocumentsAi,+ listDocumentAttachmentsAi,+ getDocumentAi,createCustomApiCallAction({baseUrl: () => 'https://api.pandadoc.com/public/v1',auth: pandadocAuth,authMapping: async (auth) => ({- Authorization: `API-Key ${(auth.secret_text)}`,+ Authorization: `API-Key ${auth.secret_text}`,}),}),],- triggers: [- documentCompleted,- documentStateChanged,- documentUpdated,- ],+ triggers: [documentCompleted, documentStateChanged, documentUpdated, recipientCompleted, documentDeleted, documentCreationFailed],});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/add-document-recipient.ts b/packages/pieces/community/pandadoc/src/lib/actions/add-document-recipient.tsnew file mode 100644index 00000000000..269daac05d1--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/add-document-recipient.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const addDocumentRecipient = createAction({+ auth: pandadocAuth,+ name: 'add_document_recipient',+ classification: 'WRITE',+ displayName: 'Add Document Recipient',+ description: 'Adds a contact as a recipient of a draft document.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Add an existing PandaDoc contact (by contact ID from Find Contacts or Create Contact) as a recipient of a document that is still in draft. Not idempotent: adding the same contact twice can create a duplicate recipient.',+ idempotent: false,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),+ },+ outputSchema: pandadocSchemas['recipientAdded'],+ async run({ auth, propsValue }) {+ return pandadocApi.addRecipient({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ contactId: pandadocInputs.requiredString({ value: propsValue.contact_id, label: 'Contact ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/add-document-attachment.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/add-document-attachment.tsnew file mode 100644index 00000000000..68d7438cff2--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/add-document-attachment.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocAiProps } from '../../common/ai-props';+import { pandadocFiles } from '../../common/files';+import { pandadocInputs } from '../../common/inputs';+import { pandadocNormalize } from '../../common/normalize';+import { pandadocSchemas } from '../../common/schemas';++export const addDocumentAttachmentAi = createAction({+ auth: pandadocAuth,+ name: 'add_document_attachment',+ classification: 'WRITE',+ displayName: 'Add Document Attachment (AI)',+ description: 'Adds an attachment to a document by document ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Attach a file to a PandaDoc document, either from a public URL or from a file produced by an earlier step. Attachments are extra files shown with the document, not pages of it. Not idempotent: each call adds another attachment.',+ idempotent: false,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ url: Property.ShortText({ displayName: 'File URL', description: 'Public URL of the file. Leave empty when passing File.', required: false }),+ file: Property.File({ displayName: 'File', required: false }),+ name: Property.ShortText({ displayName: 'Attachment Name', required: false }),+ },+ outputSchema: pandadocSchemas['attachment'],+ async run({ auth, propsValue }) {+ const raw = await pandadocApi.createAttachmentRaw({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ url: pandadocInputs.optionalString(propsValue.url),+ file: pandadocFiles.readUploadFile({ value: propsValue.file, label: 'File' }),+ name: pandadocInputs.optionalString(propsValue.name),+ });+ return pandadocNormalize.attachment(raw);+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/contact-props.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/contact-props.tsnew file mode 100644index 00000000000..17abd54aecc--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/contact-props.ts@@ -0,0 +1,26 @@+import { Property } from '@activepieces/pieces-framework';+import { pandadocInputs } from '../../common/inputs';++export function contactBody(values: Record<string, unknown>): Record<string, string> {+ return Object.fromEntries(+ CONTACT_KEYS.flatMap((key) => {+ const value = pandadocInputs.optionalString(values[key]);+ return value === undefined ? [] : [[key, value]];+ }),+ );+}++export const contactProps = {+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),+ company: Property.ShortText({ displayName: 'Company', required: false }),+ job_title: Property.ShortText({ displayName: 'Job Title', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ street_address: Property.ShortText({ displayName: 'Street Address', required: false }),+ city: Property.ShortText({ displayName: 'City', required: false }),+ state: Property.ShortText({ displayName: 'State', required: false }),+ postal_code: Property.ShortText({ displayName: 'Postal Code', required: false }),+ country: Property.ShortText({ displayName: 'Country', required: false }),+};++const CONTACT_KEYS = ['first_name', 'last_name', 'company', 'job_title', 'phone', 'street_address', 'city', 'state', 'postal_code', 'country'];diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/create-contact.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/create-contact.tsnew file mode 100644index 00000000000..1392851195c--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/create-contact.ts@@ -0,0 +1,30 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocInputs } from '../../common/inputs';+import { pandadocNormalize } from '../../common/normalize';+import { pandadocSchemas } from '../../common/schemas';+import { contactProps, contactBody } from './contact-props';++export const createContactAi = createAction({+ auth: pandadocAuth,+ name: 'create_contact',+ classification: 'WRITE',+ displayName: 'Create Contact (AI)',+ description: 'Creates a new PandaDoc contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a new contact in the PandaDoc address book. Check Find Contacts by email first: this always creates a new record and is not idempotent. To change an existing contact use Update Contact.',+ idempotent: false,+ },+ props: {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ ...contactProps,+ },+ outputSchema: pandadocSchemas['contact'],+ async run({ auth, propsValue }) {+ const body = { email: pandadocInputs.requiredString({ value: propsValue.email, label: 'Email' }), ...contactBody(propsValue) };+ return pandadocNormalize.contact(await pandadocApi.createContactRaw({ apiKey: auth.secret_text, body }));+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/create-document-from-template.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/create-document-from-template.tsnew file mode 100644index 00000000000..c205300e97d--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/create-document-from-template.ts@@ -0,0 +1,61 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocAiProps } from '../../common/ai-props';+import { pandadocInputs } from '../../common/inputs';+import { pandadocSchemas } from '../../common/schemas';++export const createDocumentFromTemplateAi = createAction({+ auth: pandadocAuth,+ name: 'create_document_from_template',+ classification: 'WRITE',+ displayName: 'Create Document from Template (AI)',+ description: 'Creates a document from a PandaDoc template by template ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Create a PandaDoc document from a template ID (find it with List Templates). Recipients need an email and a role that exists in the template (see Get Template Details); field values are keyed by merge field name; tokens fill template variables. By default waits until the document is in draft so Send Document can follow. Not idempotent: every call creates a new document.',+ idempotent: false,+ },+ props: {+ template_id: Property.ShortText({ displayName: 'Template ID', required: true }),+ name: Property.ShortText({ displayName: 'Document Name', required: true }),+ recipients: pandadocAiProps.recipients({ required: true }),+ fields: pandadocAiProps.fieldValues(),+ tokens: Property.Object({+ displayName: 'Variables',+ description: 'Template variables as name/value pairs, for example {"Client.Company": "Acme"}.',+ required: false,+ }),+ folder_id: Property.ShortText({ displayName: 'Folder ID', required: false }),+ tags: Property.Array({ displayName: 'Tags', required: false }),+ metadata: Property.Object({ displayName: 'Metadata', description: 'Key-value pairs stored on the document.', required: false }),+ wait_until_ready: pandadocAiProps.waitUntilReady(),+ },+ outputSchema: pandadocSchemas['createdDocument'],+ async run({ auth, propsValue }) {+ const fields = pandadocInputs.fieldValues(propsValue.fields);+ const tokens = pandadocInputs.tokenList(propsValue.tokens);+ const tags = pandadocInputs.stringList(propsValue.tags);+ const metadata = pandadocInputs.stringRecord(propsValue.metadata);+ const folderId = pandadocInputs.optionalString(propsValue.folder_id);+ const recipients = pandadocInputs.recipients(propsValue.recipients);+ if (recipients.length === 0) {+ throw new Error('Add at least one recipient.');+ }+ return pandadocApi.createDocument({+ apiKey: auth.secret_text,+ waitForDraft: propsValue.wait_until_ready !== false,+ body: {+ template_uuid: pandadocInputs.requiredString({ value: propsValue.template_id, label: 'Template ID' }),+ name: pandadocInputs.requiredString({ value: propsValue.name, label: 'Document Name' }),+ recipients,+ ...(Object.keys(fields).length > 0 ? { fields } : {}),+ ...(tokens.length > 0 ? { tokens } : {}),+ ...(folderId === undefined ? {} : { folder_uuid: folderId }),+ ...(tags.length > 0 ? { tags } : {}),+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),+ },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/download-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/download-document.tsnew file mode 100644index 00000000000..25a07c4f374--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/download-document.ts@@ -0,0 +1,36 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocAiProps } from '../../common/ai-props';+import { pandadocInputs } from '../../common/inputs';+import { pandadocSchemas } from '../../common/schemas';++export const downloadDocumentAi = createAction({+ auth: pandadocAuth,+ name: 'download_document',+ classification: 'READ',+ displayName: 'Download Document (AI)',+ description: 'Downloads a document as a PDF file by document ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Download a PandaDoc document as a PDF file that later steps can use. Set Protected Copy for the certified PDF of a completed document (fails if it is not completed). Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ protected_copy: Property.Checkbox({ displayName: 'Protected Copy', required: false, defaultValue: false }),+ },+ outputSchema: pandadocSchemas['aiDownloadedFile'],+ async run({ auth, propsValue, files }) {+ const documentId = pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' });+ const protectedCopy = propsValue.protected_copy === true;+ const result = await pandadocApi.downloadDocument({ apiKey: auth.secret_text, documentId, protectedCopy, query: {} });+ return {+ file: await files.write({ fileName: result.fileName, data: result.data }),+ file_name: result.fileName,+ protected: protectedCopy,+ document_id: documentId,+ };+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/get-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/get-document.tsnew file mode 100644index 00000000000..946e7af7623--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/get-document.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocAiProps } from '../../common/ai-props';+import { pandadocInputs } from '../../common/inputs';+import { pandadocSchemas } from '../../common/schemas';++export const getDocumentAi = createAction({+ auth: pandadocAuth,+ name: 'get_document',+ classification: 'READ',+ displayName: 'Get Document (AI)',+ description: 'Gets the details of a document by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Get one PandaDoc document by ID: status, dates, recipients (with who has completed), fields with values, tokens, tags, metadata and totals. Use it to check whether a document is ready, sent or signed. Read-only.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ },+ outputSchema: pandadocSchemas['documentDetails'],+ async run({ auth, propsValue }) {+ return pandadocApi.getDocumentDetails({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/list-document-attachments.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/list-document-attachments.tsnew file mode 100644index 00000000000..7040f3f6419--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/list-document-attachments.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocAiProps } from '../../common/ai-props';+import { pandadocInputs } from '../../common/inputs';+import { pandadocSchemas } from '../../common/schemas';++export const listDocumentAttachmentsAi = createAction({+ auth: pandadocAuth,+ name: 'list_document_attachments',+ classification: 'READ',+ displayName: 'List Document Attachments (AI)',+ description: 'Lists the attachments of a document.',+ audience: 'ai',+ aiMetadata: {+ description: 'List every attachment on one PandaDoc document with its ID, name, type, creator and creation date. Read-only.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ },+ outputSchema: pandadocSchemas['attachmentList'],+ async run({ auth, propsValue }) {+ return pandadocApi.listAttachments({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/search-documents.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/search-documents.tsnew file mode 100644index 00000000000..ce83c05dd7f--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/search-documents.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { metadataQuery, pandadocInputs } from '../../common/inputs';+import { pandadocSchemas } from '../../common/schemas';+import { DOCUMENT_STATUS_CODES } from '../../common/statuses';++export const searchDocumentsAi = createAction({+ auth: pandadocAuth,+ name: 'search_documents',+ classification: 'SEARCH',+ displayName: 'Search Documents (AI)',+ description: 'Searches PandaDoc documents with filters.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Find PandaDoc documents by name or reference number, status (draft, sent, viewed, completed, voided, declined, paid...), template ID, folder ID, contact ID, tag, created/modified dates or metadata. Newest first. Returns up to 100 per page; use Page for more. Read-only.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({ displayName: 'Search Text', description: 'Matches document name or reference number.', required: false }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ options: { options: Object.keys(DOCUMENT_STATUS_CODES).map((value) => ({ label: value, value })) },+ }),+ template_id: Property.ShortText({ displayName: 'Template ID', required: false }),+ folder_id: Property.ShortText({ displayName: 'Folder ID', required: false }),+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: false }),+ tag: Property.ShortText({ displayName: 'Tag', required: false }),+ created_from: Property.DateTime({ displayName: 'Created From', required: false }),+ created_to: Property.DateTime({ displayName: 'Created To', required: false }),+ modified_from: Property.DateTime({ displayName: 'Modified From', required: false }),+ modified_to: Property.DateTime({ displayName: 'Modified To', required: false }),+ metadata: Property.Object({ displayName: 'Metadata', description: 'Match documents whose metadata has these key-value pairs.', required: false }),+ count: Property.Number({ displayName: 'Results per Page', description: '1 to 100, default 50.', required: false }),+ page: Property.Number({ displayName: 'Page', description: 'Starts at 1.', required: false }),+ },+ outputSchema: pandadocSchemas['documentList'],+ async run({ auth, propsValue }) {+ const statusName = pandadocInputs.optionalString(propsValue.status);+ const status = statusName === undefined ? undefined : DOCUMENT_STATUS_CODES[statusName.replace('document.', '').toLowerCase()];+ if (statusName !== undefined && status === undefined) {+ throw new Error(`Unknown status "${statusName}". Use one of: ${Object.keys(DOCUMENT_STATUS_CODES).join(', ')}.`);+ }+ return pandadocApi.listDocuments({+ apiKey: auth.secret_text,+ query: {+ q: pandadocInputs.optionalString(propsValue.query),+ status,+ template_id: pandadocInputs.optionalString(propsValue.template_id),+ folder_uuid: pandadocInputs.optionalString(propsValue.folder_id),+ contact_id: pandadocInputs.optionalString(propsValue.contact_id),+ tag: pandadocInputs.optionalString(propsValue.tag),+ created_from: pandadocInputs.optionalString(propsValue.created_from),+ created_to: pandadocInputs.optionalString(propsValue.created_to),+ modified_from: pandadocInputs.optionalString(propsValue.modified_from),+ modified_to: pandadocInputs.optionalString(propsValue.modified_to),+ count: pandadocInputs.boundedCount({ value: propsValue.count, label: 'Results per Page' }),+ page: pandadocInputs.positivePage(propsValue.page),+ order_by: '-date_modified',+ ...metadataQuery(propsValue.metadata),+ },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/ai/update-contact.ts b/packages/pieces/community/pandadoc/src/lib/actions/ai/update-contact.tsnew file mode 100644index 00000000000..fb1deac4281--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/ai/update-contact.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../../common/auth';+import { pandadocApi } from '../../common/api';+import { pandadocInputs } from '../../common/inputs';+import { pandadocNormalize } from '../../common/normalize';+import { pandadocSchemas } from '../../common/schemas';+import { contactProps, contactBody } from './contact-props';++export const updateContactAi = createAction({+ auth: pandadocAuth,+ name: 'update_contact',+ classification: 'WRITE',+ displayName: 'Update Contact (AI)',+ description: 'Updates an existing PandaDoc contact by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change fields of an existing PandaDoc contact by contact ID (get it from Find Contacts). Only the fields you pass are changed; empty values are ignored. Idempotent: repeating the same update gives the same result.',+ idempotent: true,+ },+ props: {+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),+ email: Property.ShortText({ displayName: 'Email', required: false }),+ ...contactProps,+ },+ outputSchema: pandadocSchemas['contact'],+ async run({ auth, propsValue }) {+ const email = pandadocInputs.optionalString(propsValue.email);+ const body = { ...(email === undefined ? {} : { email }), ...contactBody(propsValue) };+ if (Object.keys(body).length === 0) {+ throw new Error('Pass at least one field to update.');+ }+ const raw = await pandadocApi.updateContactRaw({+ apiKey: auth.secret_text,+ contactId: pandadocInputs.requiredString({ value: propsValue.contact_id, label: 'Contact ID' }),+ body,+ });+ return pandadocNormalize.contact(raw);+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-attachment.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-attachment.tsindex 8619d6a90d6..825ceb05670 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/create-attachment.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-attachment.ts@@ -1,25 +1,33 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocFiles } from '../common/files';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import { documentDropdown } from '../common/dynamic-dropdowns';export const createAttachment = createAction({+ auth: pandadocAuth,name: 'createAttachment',classification: 'WRITE',displayName: 'Create Attachment',- description: 'Adds an attachment to a document.',- audience: 'both',+ description: 'Adds an attachment to a document, from a file URL or an uploaded file.',+ audience: 'human',aiMetadata: {- description: 'Attach a file (fetched from a public file URL) to an existing PandaDoc document, with an optional display name. Requires the target document ID and a reachable source URL. Not idempotent — each call appends another attachment.',+ description: 'Attach a file to an existing PandaDoc document, from a public URL or a file. Not idempotent: each call adds another attachment.',idempotent: false,},- auth: pandadocAuth,props: {document_id: documentDropdown,source: Property.ShortText({displayName: 'File URL',- description: 'URL link to the file to be attached to the document',- required: true,+ description: 'Public URL of the file to attach. Leave empty when you use the File field instead.',+ required: false,+ }),+ file: Property.File({+ displayName: 'File',+ description: 'A file from a previous step to attach. Used instead of the File URL when both are set.',+ required: false,}),name: Property.ShortText({displayName: 'Attachment Name',@@ -27,20 +35,14 @@ export const createAttachment = createAction({required: false,}),},+ outputSchema: pandadocSchemas['rawAttachment'],async run({ auth, propsValue }) {- const body: any = {- source: propsValue.source,- };-- if (propsValue.name) {- body.name = propsValue.name;- }-- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.POST,- `/documents/${propsValue.document_id}/attachments`,- body- );+ return pandadocApi.createAttachmentRaw({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document' }),+ url: pandadocInputs.optionalString(propsValue.source),+ file: pandadocFiles.readUploadFile({ value: propsValue.file, label: 'File' }),+ name: pandadocInputs.optionalString(propsValue.name),+ });},});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-document-folder.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-document-folder.tsnew file mode 100644index 00000000000..2c0b5ffad77--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-document-folder.ts@@ -0,0 +1,30 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const createDocumentFolder = createAction({+ auth: pandadocAuth,+ name: 'create_document_folder',+ classification: 'WRITE',+ displayName: 'Create Document Folder',+ description: 'Creates a folder for documents.',+ audience: 'both',+ aiMetadata: {+ description: 'Create a PandaDoc documents folder, at the top level or inside a parent folder ID. Check List Document Folders first: PandaDoc allows duplicate names, so this is not idempotent.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({ displayName: 'Folder Name', required: true }),+ parent_folder_id: Property.ShortText({ displayName: 'Parent Folder ID', description: 'Leave empty to create a top-level folder.', required: false }),+ },+ outputSchema: pandadocSchemas['folder'],+ async run({ auth, propsValue }) {+ return pandadocApi.createFolder({+ apiKey: auth.secret_text,+ name: pandadocInputs.requiredString({ value: propsValue.name, label: 'Folder Name' }),+ parentId: pandadocInputs.optionalString(propsValue.parent_folder_id),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-file.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-file.tsnew file mode 100644index 00000000000..ee8f2f08cdf--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-file.ts@@ -0,0 +1,68 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocFiles } from '../common/files';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const createDocumentFromFile = createAction({+ auth: pandadocAuth,+ name: 'create_document_from_file',+ classification: 'WRITE',+ displayName: 'Create Document from File',+ description: 'Creates a document from a PDF (or DOCX) file or a public file URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a PandaDoc document from a PDF/DOCX file or public URL, with recipients. If the PDF has PandaDoc field tags, every tag must get a value in Field Values (keyed by tag name) and recipient roles must match the tag roles; set Parse Form Fields for PDFs with fillable form fields instead. By default waits until the document is ready to send. Not idempotent: each call creates a new document.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({ displayName: 'Document Name', required: true }),+ file: Property.File({ displayName: 'File', description: 'A PDF or DOCX file. Used instead of File URL when both are set.', required: false }),+ url: Property.ShortText({ displayName: 'File URL', description: 'Public URL of a PDF or DOCX file.', required: false }),+ recipients: pandadocAiProps.recipients({ required: true }),+ fields: pandadocAiProps.fieldValues(),+ parse_form_fields: Property.Checkbox({+ displayName: 'Parse Form Fields',+ description: 'Turn on for PDFs with fillable form fields; leave off for PDFs with PandaDoc field tags.',+ required: false,+ defaultValue: false,+ }),+ folder_id: Property.ShortText({ displayName: 'Folder ID', required: false }),+ tags: Property.Array({ displayName: 'Tags', required: false }),+ metadata: Property.Object({ displayName: 'Metadata', required: false }),+ wait_until_ready: pandadocAiProps.waitUntilReady(),+ },+ outputSchema: pandadocSchemas['createdDocument'],+ async run({ auth, propsValue }) {+ const fields = pandadocInputs.fieldValues(propsValue.fields);+ const tags = pandadocInputs.stringList(propsValue.tags);+ const metadata = pandadocInputs.stringRecord(propsValue.metadata);+ const folderId = pandadocInputs.optionalString(propsValue.folder_id);+ const recipients = pandadocInputs.recipients(propsValue.recipients);+ if (recipients.length === 0) {+ throw new Error('Add at least one recipient.');+ }+ const data = {+ name: pandadocInputs.requiredString({ value: propsValue.name, label: 'Document Name' }),+ recipients,+ parse_form_fields: propsValue.parse_form_fields === true,+ ...(Object.keys(fields).length > 0 ? { fields } : {}),+ ...(folderId === undefined ? {} : { folder_uuid: folderId }),+ ...(tags.length > 0 ? { tags } : {}),+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),+ };+ const waitForDraft = propsValue.wait_until_ready !== false;+ const file = pandadocFiles.readUploadFile({ value: propsValue.file, label: 'File' });+ if (file !== undefined) {+ return pandadocApi.createDocumentFromUpload({ apiKey: auth.secret_text, file, data, waitForDraft });+ }+ const url = pandadocInputs.optionalString(propsValue.url);+ if (url === undefined) {+ throw new Error('Provide a File or a File URL.');+ }+ return pandadocApi.createDocument({ apiKey: auth.secret_text, body: { ...data, url }, waitForDraft });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-template.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-template.tsindex c9eed4256b9..fa05d7dd92b 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-template.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-document-from-template.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import {templateDropdown,folderDropdown,@@ -12,16 +14,17 @@ import {} from '../common/dynamic-dropdowns';export const createDocumentFromTemplate = createAction({+ auth: pandadocAuth,name: 'createDocumentFromTemplate',classification: 'WRITE',displayName: 'Create Document from Template',description: 'Creates a document from a PandaDoc Template.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Create a new PandaDoc document from an existing template, supplying recipients, prefilled field/token values, folder, tags, and metadata. Use to generate a contract or agreement that can then be sent for signature. Requires a valid template UUID; not idempotent — each call creates a separate document.',+ description:+ 'Create a new PandaDoc document from a template, with recipients, merge-field values, variables, folder, tags and metadata. Not idempotent: each call creates another document.',idempotent: false,},- auth: pandadocAuth,props: {template_uuid: templateDropdown,name: Property.ShortText({@@ -31,34 +34,16 @@ export const createDocumentFromTemplate = createAction({}),recipients: Property.Array({displayName: 'Recipients',- description: 'List of recipients to whom the document will be sent',+ description: 'People who will receive the document. Use the role names defined in the template so they get the right fields.',required: true,properties: {- email: Property.ShortText({- displayName: 'Email',- description: 'Recipient email address',- required: false,- }),- phone: Property.ShortText({- displayName: 'Phone',- description: 'Recipient phone number',- required: false,- }),- first_name: Property.ShortText({- displayName: 'First Name',- required: false,- }),- last_name: Property.ShortText({- displayName: 'Last Name',- required: false,- }),+ email: Property.ShortText({ displayName: 'Email', description: 'Recipient email address', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', description: 'Recipient phone number', required: false }),+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),role: recipientRoleDropdown,custom_role: customRecipientRoleInput,- signing_order: Property.Number({- displayName: 'Signing Order',- description: 'Set a signing order for recipient',- required: false,- }),+ signing_order: Property.Number({ displayName: 'Signing Order', description: 'Set a signing order for recipient', required: false }),},}),fields: templateFields,@@ -67,14 +52,8 @@ export const createDocumentFromTemplate = createAction({description: 'Pass values for the variables in the template',required: false,properties: {- name: Property.ShortText({- displayName: 'Variable Name',- required: true,- }),- value: Property.ShortText({- displayName: 'Variable Value',- required: true,- }),+ name: Property.ShortText({ displayName: 'Variable Name', required: true }),+ value: Property.ShortText({ displayName: 'Variable Value', required: true }),},}),folder_uuid: folderDropdown,@@ -89,76 +68,40 @@ export const createDocumentFromTemplate = createAction({}),metadata: Property.Object({displayName: 'Metadata',+ description: 'Additional data in key-value format to associate with document',+ required: false,+ }),+ wait_until_ready: Property.Checkbox({+ displayName: 'Wait Until Ready to Send',description:- 'Additional data in key-value format to associate with document',+ 'PandaDoc prepares new documents in the background. Turn this on to wait (up to 90 seconds) until the document is in draft, so a following Send Document step does not fail.',required: false,+ defaultValue: false,}),},+ outputSchema: pandadocSchemas['rawCreatedDocument'],async run({ auth, propsValue }) {- const body: any = {- template_uuid: propsValue.template_uuid,- name: propsValue.name,- recipients: propsValue.recipients?.map((recipient: any) => {- const processedRecipient: any = {- email: recipient.email,- phone: recipient.phone,- first_name: recipient.first_name,- last_name: recipient.last_name,- signing_order: recipient.signing_order,- };-- // Handle role with custom support- if (recipient.role) {- if (recipient.role === 'custom' && recipient.custom_role) {- processedRecipient.role = recipient.custom_role;- } else if (recipient.role !== 'custom') {- processedRecipient.role = recipient.role;- }- }-- return processedRecipient;- }),+ const fields = pandadocInputs.fieldValues(propsValue.fields);+ const tokens = pandadocInputs.tokenList(propsValue.tokens);+ const tags = (propsValue.tags ?? []).flatMap((item) => {+ const tag = pandadocInputs.pickCustom({ value: readKey({ item, key: 'tag' }), custom: readKey({ item, key: 'custom_tag' }) });+ return tag === undefined ? [] : [tag];+ });+ const metadata = pandadocInputs.stringRecord(propsValue.metadata);+ const body = {+ template_uuid: pandadocInputs.requiredString({ value: propsValue.template_uuid, label: 'Template' }),+ name: pandadocInputs.requiredString({ value: propsValue.name, label: 'Document Name' }),+ recipients: pandadocInputs.recipients(propsValue.recipients),+ ...(Object.keys(fields).length > 0 ? { fields } : {}),+ ...(tokens.length > 0 ? { tokens } : {}),+ ...(propsValue.folder_uuid ? { folder_uuid: propsValue.folder_uuid } : {}),+ ...(tags.length > 0 ? { tags } : {}),+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),};-- if (propsValue.fields) {- body.fields = Object.fromEntries(- Object.entries(propsValue.fields)- .filter(([_, value]) => value !== undefined && value !== '')- .map(([key, value]) => [key, { value }])- );- }-- if (propsValue.tokens) {- body.tokens = propsValue.tokens;- }-- if (propsValue.folder_uuid) {- body.folder_uuid = propsValue.folder_uuid;- }-- if (propsValue.tags) {- body.tags = propsValue.tags- .map((tagItem: any) => {- // Handle tag with custom support- if (tagItem.tag === 'custom' && tagItem.custom_tag) {- return tagItem.custom_tag;- } else if (tagItem.tag !== 'custom') {- return tagItem.tag;- }- return null;- })- .filter(Boolean);- }-- if (propsValue.metadata) {- body.metadata = propsValue.metadata;- }-- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.POST,- '/documents',- body- );+ return pandadocApi.createDocumentRaw({ apiKey: auth.secret_text, body, waitForDraft: propsValue.wait_until_ready === true });},});++function readKey({ item, key }: { item: unknown; key: string }): unknown {+ return item !== null && typeof item === 'object' ? Reflect.get(item, key) : undefined;+}diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-or-update-contact.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-or-update-contact.tsindex c79ea3536ad..b05072fb952 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/create-or-update-contact.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-or-update-contact.ts@@ -1,7 +1,10 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import {+ contactUpdateDropdown,countryDropdown,customCountryInput,stateDropdown,@@ -9,181 +12,64 @@ import {jobTitleDropdown,customJobTitleInput,industryDropdown,- customIndustryInput+ customIndustryInput,} from '../common/dynamic-dropdowns';export const createOrUpdateContact = createAction({+ auth: pandadocAuth,name: 'createOrUpdateContact',classification: 'WRITE',displayName: 'Create or Update Contact',description: 'Creates a new or update an existing contact.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Create a new PandaDoc contact or update an existing one, depending on whether a contact ID is supplied: with an ID it patches that contact, without one it creates a new contact. Use to maintain recipient/contact records. Not idempotent in create mode — omitting the contact ID creates a duplicate on each call.',+ description: 'Create a PandaDoc contact, or update the selected one. Not idempotent in create mode: each call without a contact creates another one.',idempotent: false,},- auth: pandadocAuth,props: {- contact_id: Property.Dropdown({- auth: pandadocAuth,- displayName: 'Contact ID (for Update)',- description: 'Select a contact to update. Leave empty to create a new contact.',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- first_name: string | null;- last_name: string | null;- email: string | null;- }>;- }>(auth.secret_text, HttpMethod.GET, '/contacts?count=100');-- const options = response.results.map((contact) => {- const name = [contact.first_name, contact.last_name].filter(Boolean).join(' ') || 'Unnamed';- const email = contact.email ? ` <${contact.email}>` : '';- return {- label: `${name}${email}`,- value: contact.id,- };- });-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load contacts',- options: [],- };- }- },- }),- email: Property.ShortText({- displayName: 'Email',- description: 'An email address of the contact',- required: false,- }),- first_name: Property.ShortText({- displayName: 'First Name',- description: 'Contact\'s first name',- required: false,- }),- last_name: Property.ShortText({- displayName: 'Last Name',- description: 'Contact\'s last name',- required: false,- }),- company: Property.ShortText({- displayName: 'Company',- description: 'Contact\'s company name',- required: false,- }),+ contact_id: contactUpdateDropdown,+ email: Property.ShortText({ displayName: 'Email', description: 'An email address of the contact', required: false }),+ first_name: Property.ShortText({ displayName: 'First Name', description: "Contact's first name", required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', description: "Contact's last name", required: false }),+ company: Property.ShortText({ displayName: 'Company', description: "Contact's company name", required: false }),job_title: jobTitleDropdown,custom_job_title: customJobTitleInput,industry: industryDropdown,custom_industry: customIndustryInput,- phone: Property.ShortText({- displayName: 'Phone',- description: 'A phone number',- required: false,- }),+ phone: Property.ShortText({ displayName: 'Phone', description: 'A phone number', required: false }),country: countryDropdown,custom_country: customCountryInput,state: stateDropdown,custom_state: customStateInput,- street_address: Property.ShortText({- displayName: 'Street Address',- description: 'A street address',- required: false,- }),- city: Property.ShortText({- displayName: 'City',- description: 'A city name',- required: false,- }),- postal_code: Property.ShortText({- displayName: 'Postal Code',- description: 'A postal code',- required: false,- }),+ street_address: Property.ShortText({ displayName: 'Street Address', description: 'A street address', required: false }),+ city: Property.ShortText({ displayName: 'City', description: 'A city name', required: false }),+ postal_code: Property.ShortText({ displayName: 'Postal Code', description: 'A postal code', required: false }),},+ outputSchema: pandadocSchemas['rawContact'],async run({ auth, propsValue }) {- const body: any = {};-- if (propsValue.email !== undefined) body.email = propsValue.email;- if (propsValue.first_name !== undefined) body.first_name = propsValue.first_name;- if (propsValue.last_name !== undefined) body.last_name = propsValue.last_name;- if (propsValue.company !== undefined) body.company = propsValue.company;-- // Handle job title with custom support- if (propsValue.job_title !== undefined) {- if (propsValue.job_title === 'custom' && propsValue.custom_job_title) {- body.job_title = propsValue.custom_job_title;- } else if (propsValue.job_title !== 'custom') {- body.job_title = propsValue.job_title;- }- }-- // Handle industry with custom support- if (propsValue.industry !== undefined) {- if (propsValue.industry === 'custom' && propsValue.custom_industry) {- body.industry = propsValue.custom_industry;- } else if (propsValue.industry !== 'custom') {- body.industry = propsValue.industry;- }- }-- if (propsValue.phone !== undefined) body.phone = propsValue.phone;-- // Handle country with custom support- if (propsValue.country !== undefined) {- if (propsValue.country === 'custom' && propsValue.custom_country) {- body.country = propsValue.custom_country;- } else if (propsValue.country !== 'custom') {- body.country = propsValue.country;- }- }-- // Handle state with custom support- if (propsValue.state !== undefined) {- if (propsValue.state === 'custom' && propsValue.custom_state) {- body.state = propsValue.custom_state;- } else if (propsValue.state !== 'custom') {- body.state = propsValue.state;- }- }-- if (propsValue.street_address !== undefined) body.street_address = propsValue.street_address;- if (propsValue.city !== undefined) body.city = propsValue.city;- if (propsValue.postal_code !== undefined) body.postal_code = propsValue.postal_code;-- if (propsValue.contact_id) {- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.PATCH,- `/contacts/${propsValue.contact_id}`,- body- );- } else {- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.POST,- '/contacts',- body- );+ const values: Record<string, string | undefined> = {+ email: clearableText(propsValue.email),+ first_name: clearableText(propsValue.first_name),+ last_name: clearableText(propsValue.last_name),+ company: clearableText(propsValue.company),+ job_title: pandadocInputs.pickCustom({ value: propsValue.job_title, custom: propsValue.custom_job_title }),+ industry: pandadocInputs.pickCustom({ value: propsValue.industry, custom: propsValue.custom_industry }),+ phone: clearableText(propsValue.phone),+ country: pandadocInputs.pickCustom({ value: propsValue.country, custom: propsValue.custom_country }),+ state: pandadocInputs.pickCustom({ value: propsValue.state, custom: propsValue.custom_state }),+ street_address: clearableText(propsValue.street_address),+ city: clearableText(propsValue.city),+ postal_code: clearableText(propsValue.postal_code),+ };+ const body = Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));+ const contactId = pandadocInputs.optionalString(propsValue.contact_id);+ if (contactId !== undefined) {+ return pandadocApi.updateContactRaw({ apiKey: auth.secret_text, contactId, body });}+ return pandadocApi.createContactRaw({ apiKey: auth.secret_text, body });},});++function clearableText(value: unknown): string | undefined {+ return typeof value === 'string' ? value.trim() : pandadocInputs.optionalString(value);+}diff --git a/packages/pieces/community/pandadoc/src/lib/actions/create-signing-link.ts b/packages/pieces/community/pandadoc/src/lib/actions/create-signing-link.tsnew file mode 100644index 00000000000..cad38fff324--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/create-signing-link.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const createSigningLink = createAction({+ auth: pandadocAuth,+ name: 'create_signing_link',+ classification: 'WRITE',+ displayName: 'Create Signing Link',+ description: 'Creates a temporary link a recipient can open to view and sign a sent document.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a temporary signing session link for one recipient (by email) of a PandaDoc document that has already been sent (silent send is fine). Share the URL with that recipient only; it expires after Lifetime seconds (default 3600). Each call creates a new session.',+ idempotent: false,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ recipient_email: Property.ShortText({ displayName: 'Recipient Email', description: 'Must be a recipient of the document.', required: true }),+ lifetime: Property.Number({ displayName: 'Lifetime (Seconds)', description: 'How long the link stays valid. Default 3600 (1 hour).', required: false }),+ },+ outputSchema: pandadocSchemas['signingLink'],+ async run({ auth, propsValue }) {+ const lifetime = pandadocInputs.optionalNumber(propsValue.lifetime);+ if (lifetime !== undefined && (!Number.isInteger(lifetime) || lifetime < 1)) {+ throw new Error('Lifetime must be a whole number of seconds greater than 0.');+ }+ return pandadocApi.createSigningLink({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ recipient: pandadocInputs.requiredString({ value: propsValue.recipient_email, label: 'Recipient Email' }),+ lifetime,+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/delete-contact.ts b/packages/pieces/community/pandadoc/src/lib/actions/delete-contact.tsnew file mode 100644index 00000000000..8f55e8dce8e--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/delete-contact.ts@@ -0,0 +1,28 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const deleteContact = createAction({+ auth: pandadocAuth,+ name: 'delete_contact',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Contact',+ description: 'Deletes a contact.',+ audience: 'both',+ aiMetadata: {+ description: 'Permanently delete a PandaDoc contact by contact ID. Documents already sent to the contact are not affected. Safe to retry: an already deleted contact is reported as such.',+ idempotent: true,+ },+ props: {+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),+ },+ outputSchema: pandadocSchemas['deleted'],+ async run({ auth, propsValue }) {+ return pandadocApi.deleteContact({+ apiKey: auth.secret_text,+ contactId: pandadocInputs.requiredString({ value: propsValue.contact_id, label: 'Contact ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/delete-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/delete-document.tsnew file mode 100644index 00000000000..89ea91cdc59--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/delete-document.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const deleteDocument = createAction({+ auth: pandadocAuth,+ name: 'delete_document',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Document',+ description: 'Deletes a document.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Delete a PandaDoc document by ID. It moves to the PandaDoc trash and disappears from searches and signing. A document that no longer exists (404) is reported as already deleted; PandaDoc answers 403 for a document already in its trash, which is reported as an error that says so.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ },+ outputSchema: pandadocSchemas['deleted'],+ async run({ auth, propsValue }) {+ return pandadocApi.deleteDocument({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/download-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/download-document.tsindex ce218fcaa44..dd7a0aac213 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/download-document.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/download-document.ts@@ -1,21 +1,29 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod, httpClient } from '@activepieces/pieces-common';-import { pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import { documentDropdown, watermarkTextDropdown, customWatermarkTextInput } from '../common/dynamic-dropdowns';export const downloadDocument = createAction({+ auth: pandadocAuth,name: 'downloadDocument',classification: 'READ',displayName: 'Download Document',- description: 'Downloads a document as PDF.',- audience: 'both',+ description: 'Downloads a document as PDF (or a zip of PDFs, one per section).',+ audience: 'human',aiMetadata: {- description: 'Download a PandaDoc document by ID as a PDF file, optionally as a zip of separate per-section PDFs and with configurable watermark text, color, font size, and opacity. Use to fetch the rendered document for storage or forwarding. Read-only and idempotent.',+ description: 'Download a PandaDoc document as a PDF file, optionally watermarked, as separate files, or as the protected (certified) copy of a completed document. Read-only.',idempotent: true,},- auth: pandadocAuth,props: {document_id: documentDropdown,+ protected_copy: Property.Checkbox({+ displayName: 'Download Protected (Completed) Copy',+ description: 'Download the certified, tamper-protected PDF of a completed document. Only works for completed documents; watermark options are ignored.',+ required: false,+ defaultValue: false,+ }),separate_files: Property.Checkbox({displayName: 'Download as Separate Files',description: 'Download document bundle as a zip archive of separate PDFs (1 file per section)',@@ -46,70 +54,36 @@ export const downloadDocument = createAction({description: 'Enter a custom HEX color code (e.g., #FF5733). Only used if "Custom HEX Code" is selected above.',required: false,}),- watermark_font_size: Property.Number({- displayName: 'Watermark Font Size',- description: 'Font size of the watermark text',- required: false,- }),- watermark_opacity: Property.Number({- displayName: 'Watermark Opacity',- description: 'Opacity of the watermark (0.0 to 1.0)',- required: false,- }),+ watermark_font_size: Property.Number({ displayName: 'Watermark Font Size', description: 'Font size of the watermark text', required: false }),+ watermark_opacity: Property.Number({ displayName: 'Watermark Opacity', description: 'Opacity of the watermark (0.0 to 1.0)', required: false }),},- async run({ auth, propsValue,files }) {- const queryParams: any = {};-- if (propsValue.separate_files) {- queryParams.separate_files = propsValue.separate_files;+ outputSchema: pandadocSchemas['downloadedFile'],+ async run({ auth, propsValue, files }) {+ const protectedCopy = propsValue.protected_copy === true;+ const separateFiles = propsValue.separate_files === true;+ const opacity = pandadocInputs.optionalNumber(propsValue.watermark_opacity);+ if (opacity !== undefined && (opacity < 0 || opacity > 1)) {+ throw new Error('Watermark Opacity must be between 0.0 and 1.0.');}-- // Handle watermark text with custom support- if (propsValue.watermark_text) {- let watermarkText;- if (propsValue.watermark_text === 'custom' && propsValue.custom_watermark_text) {- watermarkText = propsValue.custom_watermark_text;- } else if (propsValue.watermark_text !== 'custom') {- watermarkText = propsValue.watermark_text;- }- if (watermarkText) {- queryParams.watermark_text = watermarkText;- }- }-- if (propsValue.watermark_color) {- // Use custom color if specified, otherwise use selected preset- const colorValue = propsValue.watermark_color === 'custom'- ? propsValue.custom_watermark_color- : propsValue.watermark_color;- if (colorValue) {- queryParams.watermark_color = colorValue;- }- }- if (propsValue.watermark_font_size) {- queryParams.watermark_font_size = propsValue.watermark_font_size;- }- if (propsValue.watermark_opacity !== undefined) {- queryParams.watermark_opacity = propsValue.watermark_opacity;- }-- const queryString = new URLSearchParams(queryParams).toString();- const endpoint = `https://api.pandadoc.com/public/v1/documents/${propsValue.document_id}/download${queryString ? `?${queryString}` : ''}`;-- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: endpoint,- headers: {- Authorization: `API-Key ${(auth.secret_text)}`,- },- responseType:'arraybuffer'+ const query = protectedCopy+ ? { separate_files: separateFiles ? true : undefined }+ : {+ separate_files: separateFiles ? true : undefined,+ watermark_text: pandadocInputs.pickCustom({ value: propsValue.watermark_text, custom: propsValue.custom_watermark_text }),+ watermark_color: pandadocInputs.pickCustom({ value: propsValue.watermark_color, custom: propsValue.custom_watermark_color }),+ watermark_font_size: pandadocInputs.optionalNumber(propsValue.watermark_font_size),+ watermark_opacity: opacity,+ };+ const result = await pandadocApi.downloadDocument({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document' }),+ protectedCopy,+ query,});-- return {- file: await files.write({- fileName: 'file.pdf',- data: Buffer.from(response.body)- })- }+ return {+ file: await files.write({ fileName: result.fileName, data: result.data }),+ file_name: result.fileName,+ protected: protectedCopy,+ };},});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/find-contacts.ts b/packages/pieces/community/pandadoc/src/lib/actions/find-contacts.tsnew file mode 100644index 00000000000..55a5dcc3d93--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/find-contacts.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const findContacts = createAction({+ auth: pandadocAuth,+ name: 'find_contacts',+ classification: 'SEARCH',+ displayName: 'Find Contacts',+ description: 'Finds contacts by exact email, or lists all contacts.',+ audience: 'both',+ aiMetadata: {+ description: 'Find PandaDoc contacts by exact email address, or list all contacts when Email is empty. Use it before Create Contact to avoid duplicates and to get contact IDs. Read-only.',+ idempotent: true,+ },+ props: {+ email: Property.ShortText({ displayName: 'Email', description: 'Exact email to match. Leave empty to list all contacts.', required: false }),+ },+ outputSchema: pandadocSchemas['contactList'],+ async run({ auth, propsValue }) {+ return pandadocApi.listContacts({ apiKey: auth.secret_text, email: pandadocInputs.optionalString(propsValue.email) });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/find-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/find-document.tsindex 61dff21e6d0..75dd0e6f4d9 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/find-document.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/find-document.ts@@ -1,176 +1,66 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { PandaDocQuery } from '../common/client';+import { metadataQuery, pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';+import { DOCUMENT_STATUS_OPTIONS } from '../common/statuses';import {formDropdown,folderDropdown,contactDropdown,memberDropdown,tagDropdown,- customTagInput+ customTagInput,+ templateFilterSingleDropdown,} from '../common/dynamic-dropdowns';export const findDocument = createAction({+ auth: pandadocAuth,name: 'findDocument',classification: 'SEARCH',displayName: 'Find Document(s)',- description: 'Finds documents based various filter.',- audience: 'both',+ description: 'Finds documents using filters such as name, status, template, folder, contact and dates.',+ audience: 'human',aiMetadata: {- description: 'Search and list PandaDoc documents, optionally narrowed by query text, status, template, form, folder, contact, tags, date ranges, or metadata; with no filters it returns all documents (paginated). Use to locate documents or enumerate them before acting on a specific one. Read-only and idempotent.',+ description: 'Search PandaDoc documents with filters (text, status, template, folder, contact, tag, dates, metadata). Read-only.',idempotent: true,},- auth: pandadocAuth,props: {- q: Property.ShortText({- displayName: 'Search Query',- description: 'Search documents by name or reference number',- required: false,- }),- id: Property.ShortText({- displayName: 'Document ID',- description: 'Search for document by its specific ID',- required: false,- }),+ q: Property.ShortText({ displayName: 'Search Query', description: 'Search documents by name or reference number', required: false }),+ id: Property.ShortText({ displayName: 'Document ID', description: 'Search for document by its specific ID', required: false }),status: Property.StaticDropdown({displayName: 'Status',description: 'Filter documents by status',required: false,- options: {- options: [- { label: 'Draft', value: 0 },- { label: 'Sent', value: 1 },- { label: 'Completed', value: 2 },- { label: 'Uploaded', value: 3 },- { label: 'Error', value: 4 },- { label: 'Viewed', value: 5 },- { label: 'Waiting Approval', value: 6 },- { label: 'Approved', value: 7 },- { label: 'Rejected', value: 8 },- { label: 'Waiting Pay', value: 9 },- { label: 'Paid', value: 10 },- { label: 'Voided', value: 11 },- { label: 'Declined', value: 12 },- { label: 'External Review', value: 13 },- ],- },+ options: { options: DOCUMENT_STATUS_OPTIONS },}),status__ne: Property.StaticDropdown({displayName: 'Exclude Status',description: 'Exclude documents with this status',required: false,- options: {- options: [- { label: 'Draft', value: 0 },- { label: 'Sent', value: 1 },- { label: 'Completed', value: 2 },- { label: 'Uploaded', value: 3 },- { label: 'Error', value: 4 },- { label: 'Viewed', value: 5 },- { label: 'Waiting Approval', value: 6 },- { label: 'Approved', value: 7 },- { label: 'Rejected', value: 8 },- { label: 'Waiting Pay', value: 9 },- { label: 'Paid', value: 10 },- { label: 'Voided', value: 11 },- { label: 'Declined', value: 12 },- { label: 'External Review', value: 13 },- ],- },- }),- template_id: Property.Dropdown({- auth: pandadocAuth,- displayName: 'Template',- description: 'Filter by parent template (cannot be used with Form)',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/templates?count=100');-- const options = response.results.map((template) => ({- label: `${template.name} - ${template.id.substring(0, 8)}...`,- value: template.id,- }));-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load templates',- options: [],- };- }- },+ options: { options: DOCUMENT_STATUS_OPTIONS },}),+ template_id: templateFilterSingleDropdown,form_id: formDropdown,folder_uuid: folderDropdown,contact_id: contactDropdown,membership_id: memberDropdown,tag: tagDropdown,custom_tag: customTagInput,- created_from: Property.DateTime({- displayName: 'Created From',- description: 'Include only documents created on or after this date',- required: false,- }),- created_to: Property.DateTime({- displayName: 'Created To',- description: 'Include only documents created before this date',- required: false,- }),- completed_from: Property.DateTime({- displayName: 'Completed From',- description: 'Include only documents completed on or after this date',- required: false,- }),- completed_to: Property.DateTime({- displayName: 'Completed To',- description: 'Include only documents completed before this date',- required: false,- }),- modified_from: Property.DateTime({- displayName: 'Modified From',- description: 'Include only documents modified on or after this date',- required: false,- }),- modified_to: Property.DateTime({- displayName: 'Modified To',- description: 'Include only documents modified before this date',- required: false,- }),+ created_from: Property.DateTime({ displayName: 'Created From', description: 'Include only documents created on or after this date', required: false }),+ created_to: Property.DateTime({ displayName: 'Created To', description: 'Include only documents created before this date', required: false }),+ completed_from: Property.DateTime({ displayName: 'Completed From', description: 'Include only documents completed on or after this date', required: false }),+ completed_to: Property.DateTime({ displayName: 'Completed To', description: 'Include only documents completed before this date', required: false }),+ modified_from: Property.DateTime({ displayName: 'Modified From', description: 'Include only documents modified on or after this date', required: false }),+ modified_to: Property.DateTime({ displayName: 'Modified To', description: 'Include only documents modified before this date', required: false }),deleted: Property.Checkbox({- displayName: 'Show Deleted Documents',- description: 'Return only deleted documents',- required: false,- }),- count: Property.Number({- displayName: 'Results Count',- description: 'Number of documents to return (default: 50, max: 100)',- required: false,- }),- page: Property.Number({- displayName: 'Page Number',- description: 'Page number for pagination (starts with 1)',+ displayName: 'Only Deleted Documents',+ description: 'When on, returns only deleted documents instead of active ones.',required: false,}),+ count: Property.Number({ displayName: 'Results Count', description: 'Number of documents to return (default: 50, max: 100)', required: false }),+ page: Property.Number({ displayName: 'Page Number', description: 'Page number for pagination (starts with 1)', required: false }),order_by: Property.StaticDropdown({displayName: 'Order By',description: 'Sort results by field',@@ -193,57 +83,31 @@ export const findDocument = createAction({required: false,}),},+ outputSchema: pandadocSchemas['rawFindDocuments'],async run({ auth, propsValue }) {- const queryParams: any = {};-- // Build query parameters with only provided values- if (propsValue.q) queryParams.q = propsValue.q;- if (propsValue.id) queryParams.id = propsValue.id;- if (propsValue.status !== undefined) queryParams.status = propsValue.status;- if (propsValue.status__ne !== undefined) queryParams.status__ne = propsValue.status__ne;- if (propsValue.template_id) queryParams.template_id = propsValue.template_id;- if (propsValue.form_id) queryParams.form_id = propsValue.form_id;- if (propsValue.folder_uuid) queryParams.folder_uuid = propsValue.folder_uuid;- if (propsValue.contact_id) queryParams.contact_id = propsValue.contact_id;- if (propsValue.membership_id) queryParams.membership_id = propsValue.membership_id;-- // Handle tag with custom support- if (propsValue.tag) {- let tagValue;- if (propsValue.tag === 'custom' && propsValue.custom_tag) {- tagValue = propsValue.custom_tag;- } else if (propsValue.tag !== 'custom') {- tagValue = propsValue.tag;- }- if (tagValue) {- queryParams.tag = tagValue;- }- }-- if (propsValue.created_from) queryParams.created_from = propsValue.created_from;- if (propsValue.created_to) queryParams.created_to = propsValue.created_to;- if (propsValue.completed_from) queryParams.completed_from = propsValue.completed_from;- if (propsValue.completed_to) queryParams.completed_to = propsValue.completed_to;- if (propsValue.modified_from) queryParams.modified_from = propsValue.modified_from;- if (propsValue.modified_to) queryParams.modified_to = propsValue.modified_to;- if (propsValue.deleted) queryParams.deleted = propsValue.deleted;- if (propsValue.count) queryParams.count = propsValue.count;- if (propsValue.page) queryParams.page = propsValue.page;- if (propsValue.order_by) queryParams.order_by = propsValue.order_by;-- if (propsValue.metadata) {- for (const [key, value] of Object.entries(propsValue.metadata)) {- queryParams[`metadata_${key}`] = value;- }- }-- const queryString = new URLSearchParams(queryParams).toString();- const endpoint = queryString ? `/documents?${queryString}` : '/documents';-- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.GET,- endpoint- );+ const query: PandaDocQuery = {+ q: pandadocInputs.optionalString(propsValue.q),+ id: pandadocInputs.optionalString(propsValue.id),+ status: pandadocInputs.optionalNumber(propsValue.status),+ status__ne: pandadocInputs.optionalNumber(propsValue.status__ne),+ template_id: pandadocInputs.optionalString(propsValue.template_id),+ form_id: pandadocInputs.optionalString(propsValue.form_id),+ folder_uuid: pandadocInputs.optionalString(propsValue.folder_uuid),+ contact_id: pandadocInputs.optionalString(propsValue.contact_id),+ membership_id: pandadocInputs.optionalString(propsValue.membership_id),+ tag: pandadocInputs.pickCustom({ value: propsValue.tag, custom: propsValue.custom_tag }),+ created_from: pandadocInputs.optionalString(propsValue.created_from),+ created_to: pandadocInputs.optionalString(propsValue.created_to),+ completed_from: pandadocInputs.optionalString(propsValue.completed_from),+ completed_to: pandadocInputs.optionalString(propsValue.completed_to),+ modified_from: pandadocInputs.optionalString(propsValue.modified_from),+ modified_to: pandadocInputs.optionalString(propsValue.modified_to),+ deleted: propsValue.deleted === true ? true : undefined,+ count: pandadocInputs.boundedCount({ value: propsValue.count, label: 'Results Count' }),+ page: pandadocInputs.positivePage(propsValue.page),+ order_by: pandadocInputs.optionalString(propsValue.order_by),+ ...metadataQuery(propsValue.metadata),+ };+ return pandadocApi.listDocumentsRaw({ apiKey: auth.secret_text, query });},});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/get-document-attachments.ts b/packages/pieces/community/pandadoc/src/lib/actions/get-document-attachments.tsindex 57fb9ab83ad..9bb1ece0415 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/get-document-attachments.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/get-document-attachments.ts@@ -1,28 +1,31 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { createAction } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import { documentDropdown, documentAttachmentDropdown } from '../common/dynamic-dropdowns';export const getDocumentAttachments = createAction({+ auth: pandadocAuth,name: 'getDocumentAttachments',classification: 'READ',displayName: 'Get Document Attachment',description: 'Retrieves details of a specific attachment from a document.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Retrieve details of a single attachment on a PandaDoc document, identified by document ID and attachment ID. Use to inspect a known attachment. Read-only and idempotent.',+ description: 'Get the details of one attachment on a PandaDoc document. Read-only.',idempotent: true,},- auth: pandadocAuth,props: {document_id: documentDropdown,attachment_id: documentAttachmentDropdown,},+ outputSchema: pandadocSchemas['rawAttachment'],async run({ auth, propsValue }) {- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.GET,- `/documents/${propsValue.document_id}/attachments/${propsValue.attachment_id}`- );+ return pandadocApi.getAttachmentRaw({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document' }),+ attachmentId: pandadocInputs.requiredString({ value: propsValue.attachment_id, label: 'Attachment' }),+ });},});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/get-document-details.ts b/packages/pieces/community/pandadoc/src/lib/actions/get-document-details.tsindex b067ee412dd..e15474c5b3d 100644--- a/packages/pieces/community/pandadoc/src/lib/actions/get-document-details.ts+++ b/packages/pieces/community/pandadoc/src/lib/actions/get-document-details.ts@@ -1,27 +1,29 @@import { createAction } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocClient, pandadocAuth } from '../common';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';import { documentDropdown } from '../common/dynamic-dropdowns';export const getDocumentDetails = createAction({+ auth: pandadocAuth,name: 'getDocumentDetails',classification: 'READ',displayName: 'Get Document',description: 'Retrieves comprehensive document data.',- audience: 'both',+ audience: 'human',aiMetadata: {- description: 'Retrieve the full detail record for a single PandaDoc document by its ID, including status, recipients, fields, and metadata. Use when you already know the document ID and need its complete data. Read-only and idempotent.',+ description: 'Get the full details of one PandaDoc document: status, recipients, fields, tokens and metadata. Read-only.',idempotent: true,},- auth: pandadocAuth,props: {document_id: documentDropdown,},+ outputSchema: pandadocSchemas['rawDocumentDetails'],async run({ auth, propsValue }) {- return await pandadocClient.makeRequest(- auth.secret_text,- HttpMethod.GET,- `/documents/${propsValue.document_id}/details`- );+ return pandadocApi.getDocumentDetailsRaw({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document' }),+ });},});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/get-template-details.ts b/packages/pieces/community/pandadoc/src/lib/actions/get-template-details.tsnew file mode 100644index 00000000000..46bda3a8649--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/get-template-details.ts@@ -0,0 +1,29 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const getTemplateDetails = createAction({+ auth: pandadocAuth,+ name: 'get_template_details',+ classification: 'READ',+ displayName: 'Get Template Details',+ description: 'Gets a template with its roles, fields and variables.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Get one PandaDoc template by ID with its recipient roles, fields (with merge field names) and variables/tokens. Call it before Create Document from Template to learn which roles and field names to pass. Read-only.',+ idempotent: true,+ },+ props: {+ template_id: Property.ShortText({ displayName: 'Template ID', required: true }),+ },+ outputSchema: pandadocSchemas['templateDetails'],+ async run({ auth, propsValue }) {+ return pandadocApi.getTemplateDetails({+ apiKey: auth.secret_text,+ templateId: pandadocInputs.requiredString({ value: propsValue.template_id, label: 'Template ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/list-document-fields.ts b/packages/pieces/community/pandadoc/src/lib/actions/list-document-fields.tsnew file mode 100644index 00000000000..4a8ef07a919--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/list-document-fields.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const listDocumentFields = createAction({+ auth: pandadocAuth,+ name: 'list_document_fields',+ classification: 'READ',+ displayName: 'List Document Fields',+ description: 'Lists the fields of a document with their current values.',+ audience: 'both',+ aiMetadata: {+ description: 'List every field on a PandaDoc document (text, date, checkbox, signature...) with its merge field name, value, whether it is filled, and which recipient it is assigned to. Read-only.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ },+ outputSchema: pandadocSchemas['fieldList'],+ async run({ auth, propsValue }) {+ return pandadocApi.listDocumentFields({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/list-document-folders.ts b/packages/pieces/community/pandadoc/src/lib/actions/list-document-folders.tsnew file mode 100644index 00000000000..4e646aa785e--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/list-document-folders.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const listDocumentFolders = createAction({+ auth: pandadocAuth,+ name: 'list_document_folders',+ classification: 'SEARCH',+ displayName: 'List Document Folders',+ description: 'Lists document folders, optionally inside a parent folder.',+ audience: 'both',+ aiMetadata: {+ description: 'List PandaDoc document folders at the top level or inside a parent folder ID. Returns folder IDs for Move Document to Folder and search filters. Up to 100 per page. Read-only.',+ idempotent: true,+ },+ props: {+ parent_folder_id: Property.ShortText({ displayName: 'Parent Folder ID', description: 'Leave empty for top-level folders.', required: false }),+ count: Property.Number({ displayName: 'Results per Page', description: '1 to 100, default 50.', required: false }),+ page: Property.Number({ displayName: 'Page', description: 'Starts at 1.', required: false }),+ },+ outputSchema: pandadocSchemas['folderList'],+ async run({ auth, propsValue }) {+ return pandadocApi.listFolders({+ apiKey: auth.secret_text,+ query: {+ parent_uuid: pandadocInputs.optionalString(propsValue.parent_folder_id),+ count: pandadocInputs.boundedCount({ value: propsValue.count, label: 'Results per Page' }),+ page: pandadocInputs.positivePage(propsValue.page),+ },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/list-templates.ts b/packages/pieces/community/pandadoc/src/lib/actions/list-templates.tsnew file mode 100644index 00000000000..e953456d135--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/list-templates.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const listTemplates = createAction({+ auth: pandadocAuth,+ name: 'list_templates',+ classification: 'SEARCH',+ displayName: 'List Templates',+ description: 'Lists or searches templates.',+ audience: 'both',+ aiMetadata: {+ description: 'List PandaDoc templates, optionally filtered by name text, tag or folder ID. Returns template IDs to use with Create Document from Template and Get Template Details. Up to 100 per page. Read-only.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({ displayName: 'Search Text', description: 'Matches template name.', required: false }),+ tag: Property.ShortText({ displayName: 'Tag', required: false }),+ folder_id: Property.ShortText({ displayName: 'Folder ID', required: false }),+ count: Property.Number({ displayName: 'Results per Page', description: '1 to 100, default 50.', required: false }),+ page: Property.Number({ displayName: 'Page', description: 'Starts at 1.', required: false }),+ },+ outputSchema: pandadocSchemas['templateList'],+ async run({ auth, propsValue }) {+ const tag = pandadocInputs.optionalString(propsValue.tag);+ return pandadocApi.listTemplates({+ apiKey: auth.secret_text,+ query: {+ q: pandadocInputs.optionalString(propsValue.query),+ tag: tag === undefined ? undefined : [tag],+ folder_uuid: pandadocInputs.optionalString(propsValue.folder_id),+ count: pandadocInputs.boundedCount({ value: propsValue.count, label: 'Results per Page' }),+ page: pandadocInputs.positivePage(propsValue.page),+ },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/move-document-to-folder.ts b/packages/pieces/community/pandadoc/src/lib/actions/move-document-to-folder.tsnew file mode 100644index 00000000000..6fbd7b53676--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/move-document-to-folder.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const moveDocumentToFolder = createAction({+ auth: pandadocAuth,+ name: 'move_document_to_folder',+ classification: 'WRITE',+ displayName: 'Move Document to Folder',+ description: 'Moves a document into a folder.',+ audience: 'both',+ aiMetadata: {+ description: 'Move a PandaDoc document into a documents folder by folder ID (from List Document Folders or Create Document Folder). Idempotent: moving again to the same folder changes nothing.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ folder_id: Property.ShortText({ displayName: 'Folder ID', required: true }),+ },+ outputSchema: pandadocSchemas['moved'],+ async run({ auth, propsValue }) {+ return pandadocApi.moveDocumentToFolder({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ folderId: pandadocInputs.requiredString({ value: propsValue.folder_id, label: 'Folder ID' }),+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/send-document-reminder.ts b/packages/pieces/community/pandadoc/src/lib/actions/send-document-reminder.tsnew file mode 100644index 00000000000..1b2af860426--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/send-document-reminder.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const sendDocumentReminder = createAction({+ auth: pandadocAuth,+ name: 'send_document_reminder',+ classification: 'WRITE',+ displayName: 'Send Document Reminder',+ description: 'Emails a reminder to recipients who have not yet completed a sent document.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Send a manual reminder email for a sent PandaDoc document. With no recipient IDs it reminds every recipient who has not finished; otherwise only the listed recipient IDs (from Get Document). Per-recipient results tell you who was reminded. Not idempotent: each call emails again.',+ idempotent: false,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ recipient_ids: Property.Array({ displayName: 'Recipient IDs', description: 'Leave empty to remind all pending recipients.', required: false }),+ subject: Property.ShortText({ displayName: 'Email Subject', required: false }),+ message: Property.LongText({ displayName: 'Email Message', required: false }),+ },+ outputSchema: pandadocSchemas['reminder'],+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const documentId = pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' });+ const subject = pandadocInputs.optionalString(propsValue.subject);+ const message = pandadocInputs.optionalString(propsValue.message);+ const explicit = pandadocInputs.stringList(propsValue.recipient_ids);+ const recipientIds =+ explicit.length > 0+ ? explicit+ : (await pandadocApi.getDocumentDetails({ apiKey, documentId })).recipients.flatMap((recipient) =>+ recipient.id !== null && recipient.has_completed !== true && recipient.recipient_type !== 'CC' ? [recipient.id] : [],+ );+ if (recipientIds.length === 0) {+ throw new Error('No pending recipients to remind on this document.');+ }+ const customization = subject === undefined && message === undefined ? {} : { email_customization: { ...(subject === undefined ? {} : { subject }), ...(message === undefined ? {} : { message }) } };+ return pandadocApi.sendReminder({+ apiKey,+ documentId,+ body: { reminders: recipientIds.map((recipientId) => ({ recipient_id: recipientId, delivery_methods: { email: true, sms: false }, ...customization })) },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/send-document.ts b/packages/pieces/community/pandadoc/src/lib/actions/send-document.tsnew file mode 100644index 00000000000..5ee312b2c22--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/send-document.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const sendDocument = createAction({+ auth: pandadocAuth,+ name: 'send_document',+ classification: 'WRITE',+ displayName: 'Send Document',+ description: 'Sends a draft document to its recipients for viewing or signing.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Send a PandaDoc document that is in draft status to its recipients by email, with an optional subject and message. Silent sends without emailing (useful with signing links). Fails with a conflict if the document is still uploading or already sent. Not idempotent: each call sends again.',+ idempotent: false,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ subject: Property.ShortText({ displayName: 'Email Subject', required: false }),+ message: Property.LongText({ displayName: 'Email Message', required: false }),+ silent: Property.Checkbox({+ displayName: 'Silent (No Email)',+ description: 'Send without emailing recipients, for example when you share a signing link yourself.',+ required: false,+ defaultValue: false,+ }),+ sender_email: Property.ShortText({+ displayName: 'Sender Email',+ description: 'Email of a workspace member to send as. Leave empty to send as the API key owner.',+ required: false,+ }),+ },+ outputSchema: pandadocSchemas['sentDocument'],+ async run({ auth, propsValue }) {+ const subject = pandadocInputs.optionalString(propsValue.subject);+ const message = pandadocInputs.optionalString(propsValue.message);+ const senderEmail = pandadocInputs.optionalString(propsValue.sender_email);+ return pandadocApi.sendDocument({+ apiKey: auth.secret_text,+ documentId: pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' }),+ body: {+ silent: propsValue.silent === true,+ ...(subject === undefined ? {} : { subject }),+ ...(message === undefined ? {} : { message }),+ ...(senderEmail === undefined ? {} : { sender: { email: senderEmail } }),+ },+ });+ },+});diff --git a/packages/pieces/community/pandadoc/src/lib/actions/update-document-status.ts b/packages/pieces/community/pandadoc/src/lib/actions/update-document-status.tsnew file mode 100644index 00000000000..47b09de47d6--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/actions/update-document-status.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocApi } from '../common/api';+import { pandadocAiProps } from '../common/ai-props';+import { pandadocInputs } from '../common/inputs';+import { pandadocSchemas } from '../common/schemas';++export const updateDocumentStatus = createAction({+ auth: pandadocAuth,+ name: 'update_document_status',+ classification: 'WRITE',+ displayName: 'Update Document Status',+ description: 'Manually marks a document as completed, paid, voided or declined.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Manually change a PandaDoc document status to completed, paid, voided or declined (for example void a sent contract), with an optional private note and optional email to recipients. Only these four targets are allowed by PandaDoc. Idempotent for the same target status.',+ idempotent: true,+ },+ props: {+ document_id: pandadocAiProps.documentId(),+ status: Property.StaticDropdown({+ displayName: 'New Status',+ required: true,+ options: {+ options: [+ { label: 'Completed', value: 2 },+ { label: 'Paid', value: 10 },+ { label: 'Voided', value: 11 },+ { label: 'Declined', value: 12 },+ ],+ },+ }),+ note: Property.LongText({ displayName: 'Private Note', required: false }),+ notify_recipients: Property.Checkbox({ displayName: 'Notify Recipients', required: false, defaultValue: false }),+ },+ outputSchema: pandadocSchemas['statusChange'],+ async run({ auth, propsValue }) {+ const apiKey = auth.secret_text;+ const documentId = pandadocInputs.requiredString({ value: propsValue.document_id, label: 'Document ID' });+ const status = pandadocInputs.optionalNumber(propsValue.status);+ if (status === undefined || !STATUS_NAMES[status]) {+ throw new Error('New Status must be completed, paid, voided or declined.');+ }+ const note = pandadocInputs.optionalString(propsValue.note);+ const before = await pandadocApi.getDocumentStatus({ apiKey, documentId });+ await pandadocApi.changeDocumentStatus({+ apiKey,+ documentId,+ body: { status, notify_recipients: propsValue.notify_recipients === true, ...(note === undefined ? {} : { note }) },+ });+ return { id: documentId, status: STATUS_NAMES[status], previous_status: before.status };+ },+});++const STATUS_NAMES: Record<number, string> = { 2: 'document.completed', 10: 'document.paid', 11: 'document.voided', 12: 'document.declined' };diff --git a/packages/pieces/community/pandadoc/src/lib/common/ai-props.ts b/packages/pieces/community/pandadoc/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..10c50136772--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/ai-props.ts@@ -0,0 +1,44 @@+import { Property } from '@activepieces/pieces-framework';++function documentId() {+ return Property.ShortText({+ displayName: 'Document ID',+ description: 'The PandaDoc document ID, for example from Search Documents or a create step.',+ required: true,+ });+}++function recipients({ required }: { required: boolean }) {+ return Property.Array({+ displayName: 'Recipients',+ description: 'People who will receive the document. Each needs an email (or phone). Role must match a role name in the template or file.',+ required,+ properties: {+ email: Property.ShortText({ displayName: 'Email', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),+ role: Property.ShortText({ displayName: 'Role', required: false }),+ signing_order: Property.Number({ displayName: 'Signing Order', required: false }),+ },+ });+}++function fieldValues() {+ return Property.Object({+ displayName: 'Field Values',+ description: 'Values for fields, keyed by merge field name, for example {"client_name": "Jane Doe", "agree": true}. Get merge field names from Get Template Details.',+ required: false,+ });+}++function waitUntilReady() {+ return Property.Checkbox({+ displayName: 'Wait Until Ready to Send',+ description: 'Wait (up to 90 seconds) until PandaDoc finishes preparing the document, so it can be sent right away.',+ required: false,+ defaultValue: true,+ });+}++export const pandadocAiProps = { documentId, recipients, fieldValues, waitUntilReady };diff --git a/packages/pieces/community/pandadoc/src/lib/common/api.ts b/packages/pieces/community/pandadoc/src/lib/common/api.tsnew file mode 100644index 00000000000..1a96362ebd5--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/api.ts@@ -0,0 +1,353 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { encodeId, isPandaDocStatus, pandadocDownload, pandadocRequest, PandaDocQuery, sanitizeFileName } from './client';+import { pandadocNormalize } from './normalize';++async function getJson({ apiKey, path, query }: { apiKey: string; path: string; query?: PandaDocQuery }): Promise<unknown> {+ const response = await pandadocRequest<unknown>({ apiKey, method: HttpMethod.GET, path, query });+ return response.body;+}++async function send({ apiKey, method, path, body, query, flag }: { apiKey: string; method: HttpMethod; path: string; body?: unknown; query?: PandaDocQuery; flag?: string }): Promise<unknown> {+ const response = await pandadocRequest<unknown>({ apiKey, method, path, body, query, flag });+ return response.body;+}++async function getDocumentStatus({ apiKey, documentId }: { apiKey: string; documentId: string }) {+ const body = await getJson({ apiKey, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}` });+ return pandadocNormalize.documentSummary(body);+}++async function waitUntilReady({ apiKey, documentId, timeoutMs = WAIT_TIMEOUT_MS }: { apiKey: string; documentId: string; timeoutMs?: number }) {+ const deadline = Date.now() + timeoutMs;+ let delay = FIRST_POLL_DELAY_MS;+ for (;;) {+ await sleep(delay);+ const status = await getDocumentStatus({ apiKey, documentId });+ if (status.status !== 'document.uploaded') {+ if (status.status === 'document.error') {+ throw new Error(`PandaDoc could not process document ${documentId} (status document.error). Check the file or template and the field values.`);+ }+ return status;+ }+ if (Date.now() + delay > deadline) {+ throw new Error(+ `Document ${documentId} is still being processed by PandaDoc after ${Math.round(timeoutMs / 1000)} seconds. It was created; check its status later with Get Document.`,+ );+ }+ delay = Math.min(delay * 2, MAX_POLL_DELAY_MS);+ }+}++async function createDocumentRaw({ apiKey, body, waitForDraft }: { apiKey: string; body: unknown; waitForDraft: boolean }): Promise<Record<string, unknown>> {+ const created = pandadocNormalize.rec(await send({ apiKey, method: HttpMethod.POST, path: '/documents', body }));+ const id = pandadocNormalize.str(created['id']);+ if (!waitForDraft || id === null) {+ return created;+ }+ const ready = await waitUntilReady({ apiKey, documentId: id });+ return { ...created, status: ready.status, date_modified: ready.date_modified, version: ready.version };+}++async function createDocument({ apiKey, body, waitForDraft }: { apiKey: string; body: unknown; waitForDraft: boolean }) {+ const created = pandadocNormalize.documentSummary(await send({ apiKey, method: HttpMethod.POST, path: '/documents', body }));+ if (!waitForDraft || created.id === null) {+ return created;+ }+ const ready = await waitUntilReady({ apiKey, documentId: created.id });+ return { ...created, ...ready };+}++async function createDocumentFromUpload({+ apiKey,+ file,+ data,+ waitForDraft,+}: {+ apiKey: string;+ file: UploadFile;+ data: Record<string, unknown>;+ waitForDraft: boolean;+}) {+ const form = new FormData();+ form.append('file', new Blob([new Uint8Array(file.data)], { type: file.contentType }), file.fileName);+ form.append('data', JSON.stringify(data));+ const created = pandadocNormalize.documentSummary(await send({ apiKey, method: HttpMethod.POST, path: '/documents', flag: 'upload', body: form }));+ if (!waitForDraft || created.id === null) {+ return created;+ }+ const ready = await waitUntilReady({ apiKey, documentId: created.id });+ return { ...created, ...ready };+}++async function getDocumentDetailsRaw({ apiKey, documentId }: { apiKey: string; documentId: string }): Promise<unknown> {+ return getJson({ apiKey, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/details` });+}++async function getDocumentDetails({ apiKey, documentId }: { apiKey: string; documentId: string }) {+ return pandadocNormalize.documentDetails(await getDocumentDetailsRaw({ apiKey, documentId }));+}++async function listDocumentsRaw({ apiKey, query }: { apiKey: string; query: PandaDocQuery }): Promise<unknown> {+ return getJson({ apiKey, path: '/documents', query });+}++async function listDocuments({ apiKey, query }: { apiKey: string; query: PandaDocQuery }) {+ const body = pandadocNormalize.rec(await listDocumentsRaw({ apiKey, query }));+ const documents = pandadocNormalize.list(body['results']).map(pandadocNormalize.documentSummary);+ return { documents, count: documents.length };+}++async function sendDocument({ apiKey, documentId, body }: { apiKey: string; documentId: string; body: Record<string, unknown> }) {+ const response = await send({ apiKey, method: HttpMethod.POST, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/send`, body });+ const doc = pandadocNormalize.rec(response);+ return {+ ...pandadocNormalize.documentSummary(doc),+ recipients: pandadocNormalize.list(doc['recipients']).map(pandadocNormalize.recipient),+ };+}++async function createSigningLink({ apiKey, documentId, recipient, lifetime }: { apiKey: string; documentId: string; recipient: string; lifetime: number | undefined }) {+ const response = pandadocNormalize.rec(+ await send({+ apiKey,+ method: HttpMethod.POST,+ path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/session`,+ body: lifetime === undefined ? { recipient } : { recipient, lifetime },+ }),+ );+ const sessionId = pandadocNormalize.str(response['id']);+ return {+ session_id: sessionId,+ url: sessionId === null ? null : `https://app.pandadoc.com/s/${encodeURIComponent(sessionId)}`,+ expires_at: pandadocNormalize.str(response['expires_at']),+ document_id: documentId,+ recipient_email: recipient,+ };+}++async function sendReminder({ apiKey, documentId, body }: { apiKey: string; documentId: string; body: Record<string, unknown> }) {+ const response = pandadocNormalize.rec(+ await send({ apiKey, method: HttpMethod.POST, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/send-reminder`, body }),+ );+ const results = pandadocNormalize.list(response['result']).map((item) => {+ const r = pandadocNormalize.rec(item);+ const email = pandadocNormalize.rec(r['email']);+ const sms = pandadocNormalize.rec(r['sms']);+ return {+ recipient_id: pandadocNormalize.str(r['recipient_id']),+ email_status: pandadocNormalize.str(email['status']),+ email_detail: pandadocNormalize.str(email['detail']),+ sms_status: pandadocNormalize.str(sms['status']),+ sms_detail: pandadocNormalize.str(sms['detail']),+ };+ });+ return { document_id: documentId, results };+}++async function changeDocumentStatus({ apiKey, documentId, body }: { apiKey: string; documentId: string; body: Record<string, unknown> }) {+ await send({ apiKey, method: HttpMethod.PATCH, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/status`, body });+}++async function deleteDocument({ apiKey, documentId }: { apiKey: string; documentId: string }) {+ try {+ await send({ apiKey, method: HttpMethod.DELETE, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}` });+ return { deleted: true, already_deleted: false, id: documentId };+ } catch (error) {+ if (isPandaDocStatus({ error, statuses: [404] })) {+ return { deleted: true, already_deleted: true, id: documentId };+ }+ if (isPandaDocStatus({ error, statuses: [403] })) {+ throw new Error(+ `PandaDoc refused to delete document ${documentId} (HTTP 403). It is either already deleted (PandaDoc answers 403 for documents in the trash) or the API key's user cannot access it.`,+ );+ }+ throw error;+ }+}++async function moveDocumentToFolder({ apiKey, documentId, folderId }: { apiKey: string; documentId: string; folderId: string }) {+ await send({+ apiKey,+ method: HttpMethod.POST,+ path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/move-to-folder/${encodeId({ id: folderId, label: 'Folder ID' })}`,+ });+ return { id: documentId, folder_id: folderId, moved: true };+}++async function addRecipient({ apiKey, documentId, contactId }: { apiKey: string; documentId: string; contactId: string }) {+ const response = pandadocNormalize.rec(+ await send({+ apiKey,+ method: HttpMethod.POST,+ path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/recipients`,+ body: { id: contactId, kind: 'contact' },+ }),+ );+ return { document_id: documentId, contact_id: contactId, recipient_id: pandadocNormalize.str(response['recipient_id']) };+}++async function listDocumentFields({ apiKey, documentId }: { apiKey: string; documentId: string }) {+ const response = pandadocNormalize.rec(await getJson({ apiKey, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/fields` }));+ const fields = pandadocNormalize.list(response['fields']).map(pandadocNormalize.field);+ return { document_id: documentId, fields, count: fields.length };+}++async function listTemplates({ apiKey, query }: { apiKey: string; query: PandaDocQuery }) {+ const body = pandadocNormalize.rec(await getJson({ apiKey, path: '/templates', query }));+ const templates = pandadocNormalize.list(body['results']).map(pandadocNormalize.templateSummary);+ return { templates, count: templates.length };+}++async function getTemplateDetailsRaw({ apiKey, templateId }: { apiKey: string; templateId: string }): Promise<unknown> {+ return getJson({ apiKey, path: `/templates/${encodeId({ id: templateId, label: 'Template ID' })}/details` });+}++async function getTemplateDetails({ apiKey, templateId }: { apiKey: string; templateId: string }) {+ return pandadocNormalize.templateDetails(await getTemplateDetailsRaw({ apiKey, templateId }));+}++async function listFolders({ apiKey, query }: { apiKey: string; query: PandaDocQuery }) {+ const body = pandadocNormalize.rec(await getJson({ apiKey, path: '/documents/folders', query }));+ const folders = pandadocNormalize.list(body['results']).map(pandadocNormalize.folder);+ return { folders, count: folders.length };+}++async function createFolder({ apiKey, name, parentId }: { apiKey: string; name: string; parentId: string | undefined }) {+ const body = await send({ apiKey, method: HttpMethod.POST, path: '/documents/folders', body: parentId ? { name, parent_uuid: parentId } : { name } });+ return { ...pandadocNormalize.folder(body), parent_uuid: parentId ?? null };+}++async function listContacts({ apiKey, email }: { apiKey: string; email: string | undefined }) {+ const body = pandadocNormalize.rec(await getJson({ apiKey, path: '/contacts', query: { email } }));+ const contacts = pandadocNormalize.list(body['results']).map(pandadocNormalize.contact);+ return { contacts, count: contacts.length };+}++async function createContactRaw({ apiKey, body }: { apiKey: string; body: Record<string, unknown> }): Promise<unknown> {+ return send({ apiKey, method: HttpMethod.POST, path: '/contacts', body });+}++async function updateContactRaw({ apiKey, contactId, body }: { apiKey: string; contactId: string; body: Record<string, unknown> }): Promise<unknown> {+ return send({ apiKey, method: HttpMethod.PATCH, path: `/contacts/${encodeId({ id: contactId, label: 'Contact ID' })}`, body });+}++async function deleteContact({ apiKey, contactId }: { apiKey: string; contactId: string }) {+ try {+ await send({ apiKey, method: HttpMethod.DELETE, path: `/contacts/${encodeId({ id: contactId, label: 'Contact ID' })}` });+ return { deleted: true, already_deleted: false, id: contactId };+ } catch (error) {+ if (isPandaDocStatus({ error, statuses: [404] })) {+ return { deleted: true, already_deleted: true, id: contactId };+ }+ throw error;+ }+}++async function listAttachmentsRaw({ apiKey, documentId }: { apiKey: string; documentId: string }): Promise<unknown> {+ return getJson({ apiKey, path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/attachments` });+}++async function listAttachments({ apiKey, documentId }: { apiKey: string; documentId: string }) {+ const attachments = pandadocNormalize.list(await listAttachmentsRaw({ apiKey, documentId })).map(pandadocNormalize.attachment);+ return { document_id: documentId, attachments, count: attachments.length };+}++async function getAttachmentRaw({ apiKey, documentId, attachmentId }: { apiKey: string; documentId: string; attachmentId: string }): Promise<unknown> {+ return getJson({+ apiKey,+ path: `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/attachments/${encodeId({ id: attachmentId, label: 'Attachment ID' })}`,+ });+}++async function createAttachmentRaw({+ apiKey,+ documentId,+ url,+ file,+ name,+}: {+ apiKey: string;+ documentId: string;+ url: string | undefined;+ file: UploadFile | undefined;+ name: string | undefined;+}): Promise<unknown> {+ const path = `/documents/${encodeId({ id: documentId, label: 'Document ID' })}/attachments`;+ if (file !== undefined) {+ const form = new FormData();+ form.append('file', new Blob([new Uint8Array(file.data)], { type: file.contentType }), file.fileName);+ if (name) {+ form.append('name', name);+ }+ return send({ apiKey, method: HttpMethod.POST, path, flag: 'upload', body: form });+ }+ if (!url) {+ throw new Error('Provide either a File URL or a File to attach.');+ }+ return send({ apiKey, method: HttpMethod.POST, path, body: name ? { source: url, name } : { source: url } });+}++async function downloadDocument({+ apiKey,+ documentId,+ protectedCopy,+ query,+}: {+ apiKey: string;+ documentId: string;+ protectedCopy: boolean;+ query: PandaDocQuery;+}) {+ const id = encodeId({ id: documentId, label: 'Document ID' });+ const result = await pandadocDownload({ apiKey, path: `/documents/${id}/${protectedCopy ? 'download-protected' : 'download'}`, query });+ const isZip = result.contentType?.includes('zip') === true || query['separate_files'] === true;+ const extension = isZip ? 'zip' : 'pdf';+ const fallback = `${documentId}.${extension}`;+ const fromHeader = result.fileName;+ const fileName = fromHeader === null ? fallback : fromHeader.toLowerCase().endsWith(`.${extension}`) ? fromHeader : `${fromHeader}.${extension}`;+ return { data: result.data, fileName: sanitizeFileName(fileName) ?? fallback, contentType: result.contentType };+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++export const pandadocApi = {+ getDocumentStatus,+ waitUntilReady,+ createDocumentRaw,+ createDocument,+ createDocumentFromUpload,+ getDocumentDetailsRaw,+ getDocumentDetails,+ listDocumentsRaw,+ listDocuments,+ sendDocument,+ createSigningLink,+ sendReminder,+ changeDocumentStatus,+ deleteDocument,+ moveDocumentToFolder,+ addRecipient,+ listDocumentFields,+ listTemplates,+ getTemplateDetailsRaw,+ getTemplateDetails,+ listFolders,+ createFolder,+ listContacts,+ createContactRaw,+ updateContactRaw,+ deleteContact,+ listAttachmentsRaw,+ listAttachments,+ getAttachmentRaw,+ createAttachmentRaw,+ downloadDocument,+};++export type UploadFile = { data: Buffer; fileName: string; contentType: string };++const WAIT_TIMEOUT_MS = 90000;+const FIRST_POLL_DELAY_MS = 3000;+const MAX_POLL_DELAY_MS = 20000;diff --git a/packages/pieces/community/pandadoc/src/lib/common/auth.ts b/packages/pieces/community/pandadoc/src/lib/common/auth.tsindex d138ec14180..1f1350e497f 100644--- a/packages/pieces/community/pandadoc/src/lib/common/auth.ts+++ b/packages/pieces/community/pandadoc/src/lib/common/auth.ts@@ -1,31 +1,25 @@import { PieceAuth } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';+import { pandadocRequest } from './client';export const pandadocAuth = PieceAuth.SecretText({displayName: 'API Key',- description:- 'Your PandaDoc API key. Get it from the Developer Dashboard in your PandaDoc account.',- required: true,+ description: `Your PandaDoc API key.++1. In PandaDoc, open **Settings > Integrations > API** (the Developer Dashboard).+2. Copy the **Sandbox** key for testing or the **Production** key for live documents.+3. Paste it here.+Sandbox keys are limited to 10 requests per minute and can only send documents to email addresses in your own domain.`,+ required: true,validate: async ({ auth }) => {try {- await httpClient.sendRequest({- method: HttpMethod.GET,- url: 'https://api.pandadoc.com/public/v1/documents',- headers: {- Authorization: `API-Key ${auth}`,- },- });-- return {- valid: true,- };- } catch (error: any) {+ await pandadocRequest({ apiKey: auth, method: HttpMethod.GET, path: '/members/current' });+ return { valid: true };+ } catch (error) {return {valid: false,- error: `Authentication failed: ${- error?.response?.data?.detail || error.message- }`,+ error: error instanceof Error ? error.message : 'Could not validate the PandaDoc API key.',};}},diff --git a/packages/pieces/community/pandadoc/src/lib/common/client.ts b/packages/pieces/community/pandadoc/src/lib/common/client.tsnew file mode 100644index 00000000000..e7e05109b09--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/client.ts@@ -0,0 +1,276 @@+import { Readable } from 'stream';+import { httpClient, HttpMessageBody, HttpMethod, HttpRequest } from '@activepieces/pieces-common';++export const PANDADOC_API_BASE = 'https://api.pandadoc.com/public/v1';++export type PandaDocQuery = Record<string, string | number | boolean | string[] | undefined | null>;++export class PandaDocApiError extends Error {+ readonly status: number;+ readonly responseBody: unknown;++ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: unknown }) {+ super(message);+ this.name = 'PandaDocApiError';+ this.status = status;+ this.responseBody = responseBody;+ }+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export function encodeId({ id, label }: { id: unknown; label: string }): string {+ const trimmed = typeof id === 'string' ? id.trim() : typeof id === 'number' ? String(id) : '';+ if (trimmed.length === 0) {+ throw new Error(`${label} is required.`);+ }+ return encodeURIComponent(trimmed);+}++export function buildPandaDocUrl({ path, query, flag }: { path: string; query?: PandaDocQuery; flag?: string }): string {+ if (+ !path.startsWith('/') ||+ path.startsWith('//') ||+ path.includes('?') ||+ path.includes('#') ||+ path.split('/').some((segment) => segment === '..' || segment === '.')+ ) {+ throw new Error(`Refusing to call PandaDoc with an unexpected path: ${path}`);+ }+ const url = new URL(PANDADOC_API_BASE + path);+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ if (item.length > 0) {+ url.searchParams.append(key, item);+ }+ }+ continue;+ }+ url.searchParams.set(key, String(value));+ }+ }+ const built = url.toString();+ if (flag === undefined) {+ return built;+ }+ return `${built}${url.search.length > 0 ? '&' : '?'}${encodeURIComponent(flag)}`;+}++let verifiedTlsAgent: Promise<unknown> | undefined;++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++export async function pandadocRequest<T extends HttpMessageBody = HttpMessageBody>({+ apiKey,+ method,+ path,+ query,+ body,+ flag,+ timeoutMs = DEFAULT_TIMEOUT_MS,+}: {+ apiKey: string;+ method: HttpMethod;+ path: string;+ query?: PandaDocQuery;+ flag?: string;+ body?: unknown;+ timeoutMs?: number;+}): Promise<{ status: number; body: T }> {+ const isForm = body instanceof FormData;+ const headers: Record<string, string> = {+ Authorization: `API-Key ${apiKey.trim()}`,+ Accept: 'application/json',+ };+ if (body !== undefined && !isForm) {+ headers['Content-Type'] = 'application/json';+ }+ const request: HttpRequest = {+ method,+ url: buildPandaDocUrl({ path, query, flag }),+ headers,+ body: body === undefined ? undefined : isForm ? body : JSON.stringify(body),+ redactBodyInErrors: true,+ timeout: timeoutMs,+ };+ try {+ const response = await httpClient.sendRequest<T>(request, { dispatcher: await verifiedTls() });+ return { status: response.status, body: response.body };+ } catch (error) {+ throw mapPandaDocError(error);+ }+}++export async function pandadocDownload({+ apiKey,+ path,+ query,+ timeoutMs = DOWNLOAD_TIMEOUT_MS,+ maxBytes = MAX_DOWNLOAD_BYTES,+}: {+ apiKey: string;+ path: string;+ query?: PandaDocQuery;+ timeoutMs?: number;+ maxBytes?: number;+}): Promise<{ data: Buffer; fileName: string | null; contentType: string | null }> {+ const request: HttpRequest = {+ method: HttpMethod.GET,+ url: buildPandaDocUrl({ path, query }),+ headers: {+ Authorization: `API-Key ${apiKey.trim()}`,+ Accept: 'application/pdf, application/zip, application/octet-stream, */*',+ },+ responseType: 'stream',+ timeout: timeoutMs,+ };+ let response;+ try {+ response = await httpClient.sendRequest<Readable>(request, { dispatcher: await verifiedTls() });+ } catch (error) {+ throw mapPandaDocError(error);+ }+ const data = await readStream({ stream: response.body, timeoutMs, maxBytes });+ return {+ data,+ fileName: fileNameFromDisposition(headerString(response.headers?.['content-disposition'])),+ contentType: headerString(response.headers?.['content-type']),+ };+}++function headerString(value: string | string[] | undefined): string | null {+ if (Array.isArray(value)) {+ return value[0] ?? null;+ }+ return typeof value === 'string' && value.length > 0 ? value : null;+}++export function fileNameFromDisposition(disposition: string | null): string | null {+ if (disposition === null) {+ return null;+ }+ const encoded = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(disposition);+ if (encoded) {+ try {+ return sanitizeFileName(decodeURIComponent(encoded[1].trim()));+ } catch {+ return sanitizeFileName(encoded[1].trim());+ }+ }+ const plain = /filename\s*=\s*"?([^";]+)"?/.exec(disposition);+ return plain ? sanitizeFileName(plain[1].trim()) : null;+}++export function sanitizeFileName(name: string): string | null {+ const cleaned = name.replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').trim();+ return cleaned.length > 0 ? cleaned.slice(0, 200) : null;+}++function readStream({ stream, timeoutMs, maxBytes }: { stream: Readable; timeoutMs: number; maxBytes: number }): Promise<Buffer> {+ return new Promise((resolve, reject) => {+ const chunks: Buffer[] = [];+ let total = 0;+ const timer = setTimeout(() => {+ stream.destroy(new Error(`PandaDoc download did not finish within ${Math.round(timeoutMs / 1000)} seconds.`));+ }, timeoutMs);+ stream.on('data', (chunk: Buffer | string) => {+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;+ total += buffer.length;+ if (total > maxBytes) {+ stream.destroy(new Error(`PandaDoc file is larger than ${Math.round(maxBytes / (1024 * 1024))} MB.`));+ return;+ }+ chunks.push(buffer);+ });+ stream.on('end', () => {+ clearTimeout(timer);+ resolve(Buffer.concat(chunks));+ });+ stream.on('error', (error) => {+ clearTimeout(timer);+ reject(error);+ });+ });+}++export function mapPandaDocError(error: unknown): unknown {+ if (error instanceof PandaDocApiError) {+ return error;+ }+ if (!isRecord(error) && !(error instanceof Error)) {+ return error;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (!isRecord(response) || typeof response['status'] !== 'number') {+ return error;+ }+ return buildPandaDocError({ status: response['status'], responseBody: response['body'] });+}++export function isPandaDocStatus({ error, statuses }: { error: unknown; statuses: number[] }): boolean {+ const mapped = mapPandaDocError(error);+ return mapped instanceof PandaDocApiError && statuses.includes(mapped.status);+}++export function vendorDetail(responseBody: unknown): string | undefined {+ let parsed = responseBody;+ if (Buffer.isBuffer(parsed)) {+ parsed = parsed.toString('utf8');+ }+ if (typeof parsed === 'string') {+ const trimmed = parsed.trim();+ if (trimmed.length === 0) {+ return undefined;+ }+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ return trimmed.startsWith('<') ? undefined : trimmed.slice(0, MAX_DETAIL);+ }+ }+ if (!isRecord(parsed)) {+ return undefined;+ }+ const detail = parsed['detail'] ?? parsed['info_message'] ?? parsed['message'] ?? parsed['error'];+ if (typeof detail === 'string') {+ return detail.slice(0, MAX_DETAIL);+ }+ if (detail === undefined || detail === null) {+ return undefined;+ }+ return JSON.stringify(detail).slice(0, MAX_DETAIL);+}++export function buildPandaDocError({ status, responseBody }: { status: number; responseBody: unknown }): PandaDocApiError {+ const detailText = vendorDetail(responseBody);+ const base = detailText !== undefined && /key type is not permitted/i.test(detailText)+ ? 'PandaDoc does not allow this type of API key (for example a sandbox key) to use this feature. Use a production API key'+ : STATUS_MESSAGES[status] ?? (status >= 500 ? 'PandaDoc returned a server error. Retry later' : 'PandaDoc request failed');+ const message = detailText === undefined ? `${base} (HTTP ${status}).` : `${base} (HTTP ${status}): ${detailText}`;+ return new PandaDocApiError({ message, status, responseBody });+}++const STATUS_MESSAGES: Record<number, string> = {+ 400: 'PandaDoc rejected the request as invalid',+ 401: 'PandaDoc rejected the API key. Check the API key in the PandaDoc connection',+ 403: 'PandaDoc denied access. Check that the API key belongs to a workspace with access to this item, or that your plan includes this feature',+ 404: 'PandaDoc could not find the item. Check the ID',+ 409: 'PandaDoc reported a conflict. The document is probably not in the right status yet (for example still uploading, or already sent)',+ 423: 'PandaDoc locked the document. Try again later',+ 429: 'PandaDoc rate limit reached (sandbox keys allow 10 requests per minute per endpoint). Retry in a minute',+};++const DEFAULT_TIMEOUT_MS = 30000;+const DOWNLOAD_TIMEOUT_MS = 120000;+const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;+const MAX_DETAIL = 500;diff --git a/packages/pieces/community/pandadoc/src/lib/common/dynamic-dropdowns.ts b/packages/pieces/community/pandadoc/src/lib/common/dynamic-dropdowns.tsindex f6be5954abf..916bf4e9cf5 100644--- a/packages/pieces/community/pandadoc/src/lib/common/dynamic-dropdowns.ts+++ b/packages/pieces/community/pandadoc/src/lib/common/dynamic-dropdowns.ts@@ -1,136 +1,208 @@import { Property, DynamicPropsValue } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';-import { pandadocAuth, pandadocClient } from './index';+import { pandadocAuth } from './auth';+import { pandadocRequest, PandaDocQuery } from './client';+import { pandadocNormalize } from './normalize';++async function fetchList({ apiKey, path, query }: { apiKey: string; path: string; query?: PandaDocQuery }): Promise<Record<string, unknown>[]> {+ const response = await pandadocRequest<unknown>({ apiKey, method: HttpMethod.GET, path, query });+ const body = response.body;+ const items = Array.isArray(body) ? body : pandadocNormalize.list(pandadocNormalize.rec(body)['results']);+ return items.map(pandadocNormalize.rec);+}++function shortId(id: string): string {+ return id.length > 8 ? `${id.substring(0, 8)}...` : id;+}++function label({ name, fallback }: { name: unknown; fallback: string }): string {+ const text = pandadocNormalize.str(name);+ return text !== null && text.trim().length > 0 ? text : fallback;+}++async function documentOptions({ apiKey, searchValue }: { apiKey: string; searchValue: string | undefined }) {+ const docs = await fetchList({+ apiKey,+ path: '/documents',+ query: { count: 100, order_by: '-date_modified', q: searchValue && searchValue.trim().length > 0 ? searchValue.trim() : undefined },+ });+ return docs.flatMap((doc) => {+ const id = pandadocNormalize.str(doc['id']);+ if (id === null) {+ return [];+ }+ const status = pandadocNormalize.str(doc['status'])?.replace('document.', '') ?? 'unknown';+ return [{ label: `${label({ name: doc['name'], fallback: id })} (${status})`, value: id }];+ });+}++async function templateOptions({ apiKey, searchValue }: { apiKey: string; searchValue: string | undefined }) {+ const templates = await fetchList({+ apiKey,+ path: '/templates',+ query: { count: 100, q: searchValue && searchValue.trim().length > 0 ? searchValue.trim() : undefined },+ });+ return templates.flatMap((template) => {+ const id = pandadocNormalize.str(template['id']);+ return id === null ? [] : [{ label: `${label({ name: template['name'], fallback: id })} - ${shortId(id)}`, value: id }];+ });+}++async function folderOptions({ apiKey }: { apiKey: string }) {+ const folders = await fetchList({ apiKey, path: '/documents/folders', query: { count: 100 } });+ return folders.flatMap((folder) => {+ const id = pandadocNormalize.str(folder['uuid']);+ return id === null ? [] : [{ label: `${label({ name: folder['name'], fallback: id })} - ${shortId(id)}`, value: id }];+ });+}++async function contactOptions({ apiKey }: { apiKey: string }) {+ const contacts = await fetchList({ apiKey, path: '/contacts' });+ return contacts.flatMap((contact) => {+ const id = pandadocNormalize.str(contact['id']);+ if (id === null) {+ return [];+ }+ const name = [pandadocNormalize.str(contact['first_name']), pandadocNormalize.str(contact['last_name'])].filter((part) => part !== null && part.length > 0).join(' ') || 'Unnamed';+ const email = pandadocNormalize.str(contact['email']);+ return [{ label: `${name}${email ? ` <${email}>` : ''}`, value: id }];+ });+}++function unauthenticated() {+ return { disabled: true, placeholder: 'Please connect your PandaDoc account first', options: [] };+}++function failed(error: unknown) {+ return { disabled: true, placeholder: error instanceof Error ? error.message.slice(0, 200) : 'Failed to load options', options: [] };+}-// Documents dropdownexport const documentDropdown = Property.Dropdown({auth: pandadocAuth,-displayName: 'Document',- description: 'Select a document from your PandaDoc workspace',+ description: 'Select a document. The newest documents are listed first; type to search by name.',required: true,refreshers: [],- options: async ({ auth }) => {+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();}-try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- status: string;- date_created: string;- }>;- }>(- auth.secret_text,- HttpMethod.GET,- '/documents?count=100&order_by=date_created'- );-- const options = response.results.map((doc) => ({- label: doc.name,- value: doc.id,- }));-- return {- disabled: false,- options,- };+ return { disabled: false, options: await documentOptions({ apiKey: auth.secret_text, searchValue }) };} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load documents',- options: [],- };+ return failed(error);}},});-// Templates dropdownexport const templateDropdown = Property.Dropdown({auth: pandadocAuth,-displayName: 'Template',- description: 'Select a template from your PandaDoc workspace',+ description: 'Select a template from your PandaDoc workspace. Type to search by name.',required: true,refreshers: [],- options: async ({ auth }) => {+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();+ }+ try {+ return { disabled: false, options: await templateOptions({ apiKey: auth.secret_text, searchValue }) };+ } catch (error) {+ return failed(error);}+ },+});+export const templateFilterDropdown = Property.MultiSelectDropdown({+ auth: pandadocAuth,+ displayName: 'Filter by Templates',+ description: 'Only trigger for documents created from these templates (leave empty for all).',+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return unauthenticated();+ }try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/templates?count=100');-- const options = response.results.map((template) => ({- label: template.name,- value: template.id,- }));+ return { disabled: false, options: await templateOptions({ apiKey: auth.secret_text, searchValue: undefined }) };+ } catch (error) {+ return failed(error);+ }+ },+});- return {- disabled: false,- options,- };+export const folderFilterDropdown = Property.MultiSelectDropdown({+ auth: pandadocAuth,+ displayName: 'Filter by Folders',+ description: 'Only trigger for documents stored in these folders (leave empty for all).',+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return unauthenticated();+ }+ try {+ return { disabled: false, options: await folderOptions({ apiKey: auth.secret_text }) };} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load templates',- options: [],- };+ return failed(error);}},});export const templateFields = Property.DynamicProperties({displayName: 'Template Fields',+ description: 'Values for the template fields that have a merge field name. Leave a field empty to keep its default.',refreshers: ['template_uuid'],required: false,auth: pandadocAuth,props: async ({ auth, template_uuid }) => {- if (!auth || !template_uuid) return {};-+ const templateId = pandadocNormalize.str(template_uuid);+ if (!auth || templateId === null || templateId.length === 0) {+ return {};+ }const fields: DynamicPropsValue = {};-- const response = await pandadocClient.makeRequest<{- fields: Array<{- field_id: string;- type: string;- name: string;- }>;- }>(- auth as unknown as string,- HttpMethod.GET,- `/templates/${template_uuid}/details`- );-- for (const prop of response.fields) {- fields[prop.field_id] = Property.ShortText({- displayName: prop.name,- required: false,+ try {+ const response = await pandadocRequest<unknown>({+ apiKey: auth.secret_text,+ method: HttpMethod.GET,+ path: `/templates/${encodeURIComponent(templateId)}/details`,+ });+ const details = pandadocNormalize.templateDetails(response.body);+ for (const field of details.fields) {+ if (field.merge_field === null || field.merge_field.length === 0 || field.merge_field in fields) {+ continue;+ }+ const displayName = field.name && field.name !== field.merge_field ? `${field.name} (${field.merge_field})` : field.merge_field;+ fields[field.merge_field] =+ field.type === 'checkbox'+ ? Property.StaticDropdown({+ displayName,+ description: 'Leave empty to keep the template default.',+ required: false,+ options: {+ options: [+ { label: 'Checked', value: true },+ { label: 'Unchecked', value: false },+ ],+ },+ })+ : Property.ShortText({+ displayName,+ description: field.type === 'date' ? 'Date in ISO 8601 format, for example 2026-12-31T00:00:00.000Z.' : undefined,+ required: false,+ });+ }+ } catch (error) {+ fields['template_fields_error'] = Property.MarkDown({+ value: `Could not load the template fields: ${error instanceof Error ? error.message : 'unknown error'}`,});}-return fields;},});-// Folders dropdownexport const folderDropdown = Property.Dropdown({auth: pandadocAuth,displayName: 'Folder',@@ -139,42 +211,16 @@ export const folderDropdown = Property.Dropdown({refreshers: [],options: async ({ auth }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();}-try {- const response = await pandadocClient.makeRequest<{- results: Array<{- uuid: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/documents/folders?count=100');-- const options = response.results.map((folder) => ({- label: `${folder.name} - ${folder.uuid.substring(0, 8)}...`,- value: folder.uuid,- }));-- return {- disabled: false,- options,- };+ return { disabled: false, options: await folderOptions({ apiKey: auth.secret_text }) };} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load folders',- options: [],- };+ return failed(error);}},});-// Contacts dropdownexport const contactDropdown = Property.Dropdown({auth: pandadocAuth,displayName: 'Contact',@@ -183,49 +229,53 @@ export const contactDropdown = Property.Dropdown({refreshers: [],options: async ({ auth }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();+ }+ try {+ return { disabled: false, options: await contactOptions({ apiKey: auth.secret_text }) };+ } catch (error) {+ return failed(error);}+ },+});+export const contactUpdateDropdown = Property.Dropdown({+ auth: pandadocAuth,+ displayName: 'Contact ID (for Update)',+ description: 'Select a contact to update. Leave empty to create a new contact.',+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return unauthenticated();+ }try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- first_name: string | null;- last_name: string | null;- email: string | null;- }>;- }>(auth.secret_text, HttpMethod.GET, '/contacts?count=100');-- const options = response.results.map((contact) => {- const name =- [contact.first_name, contact.last_name].filter(Boolean).join(' ') ||- 'Unnamed';- const email = contact.email ? ` <${contact.email}>` : '';- return {- label: `${name}${email} - ${contact.id.substring(0, 8)}...`,- value: contact.id,- };- });+ return { disabled: false, options: await contactOptions({ apiKey: auth.secret_text }) };+ } catch (error) {+ return failed(error);+ }+ },+});- return {- disabled: false,- options,- };+export const templateFilterSingleDropdown = Property.Dropdown({+ auth: pandadocAuth,+ displayName: 'Template',+ description: 'Filter by parent template (cannot be used with Form)',+ required: false,+ refreshers: [],+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {+ if (!auth) {+ return unauthenticated();+ }+ try {+ return { disabled: false, options: await templateOptions({ apiKey: auth.secret_text, searchValue }) };} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load contacts',- options: [],- };+ return failed(error);}},});-// Forms dropdownexport const formDropdown = Property.Dropdown({auth: pandadocAuth,displayName: 'Form',@@ -234,42 +284,23 @@ export const formDropdown = Property.Dropdown({refreshers: [],options: async ({ auth }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();}-try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- status: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/forms?count=100');-- const options = response.results.map((form) => ({- label: `${form.name} (${form.status}) - ${form.id.substring(0, 8)}...`,- value: form.id,- }));-+ const forms = await fetchList({ apiKey: auth.secret_text, path: '/forms', query: { count: 100 } });return {disabled: false,- options,+ options: forms.flatMap((form) => {+ const id = pandadocNormalize.str(form['id']);+ return id === null ? [] : [{ label: `${label({ name: form['name'], fallback: id })} (${pandadocNormalize.str(form['status']) ?? 'unknown'})`, value: id }];+ }),};} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load forms',- options: [],- };+ return failed(error);}},});-// Members dropdownexport const memberDropdown = Property.Dropdown({auth: pandadocAuth,displayName: 'Member',@@ -278,52 +309,29 @@ export const memberDropdown = Property.Dropdown({refreshers: [],options: async ({ auth }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();}-try {- const response = await pandadocClient.makeRequest<{- results: Array<{- membership_id: string;- first_name: string;- last_name: string;- email: string;- role: string;- is_active: boolean;- }>;- }>(auth.secret_text, HttpMethod.GET, '/members');-- const options = response.results- .filter((member) => member.is_active)- .map((member) => {- const name =- [member.first_name, member.last_name].filter(Boolean).join(' ') ||- 'Unnamed';- return {- label: `${name} (${member.role}) - ${member.email}`,- value: member.membership_id,- };- });-+ const members = await fetchList({ apiKey: auth.secret_text, path: '/members' });return {disabled: false,- options,+ options: members+ .filter((member) => member['is_active'] === true)+ .flatMap((member) => {+ const id = pandadocNormalize.str(member['membership_id']);+ if (id === null) {+ return [];+ }+ const name = [pandadocNormalize.str(member['first_name']), pandadocNormalize.str(member['last_name'])].filter((part) => part !== null && part.length > 0).join(' ') || 'Unnamed';+ return [{ label: `${name} (${pandadocNormalize.str(member['role']) ?? 'member'}) - ${pandadocNormalize.str(member['email']) ?? ''}`, value: id }];+ }),};} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load members',- options: [],- };+ return failed(error);}},});-// Document attachments dropdown (dependent on document selection)export const documentAttachmentDropdown = Property.Dropdown({auth: pandadocAuth,displayName: 'Attachment',@@ -332,54 +340,27 @@ export const documentAttachmentDropdown = Property.Dropdown({refreshers: ['document_id'],options: async ({ auth, document_id }) => {if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };+ return unauthenticated();}-- if (!document_id) {- return {- disabled: true,- placeholder: 'Please select a document first',- options: [],- };+ const documentId = pandadocNormalize.str(document_id);+ if (documentId === null || documentId.length === 0) {+ return { disabled: true, placeholder: 'Please select a document first', options: [] };}-try {- const response = await pandadocClient.makeRequest<- Array<{- uuid: string;- name: string | null;- date_created: string;- }>- >(- auth.secret_text,- HttpMethod.GET,- `/documents/${document_id}/attachments`- );-- const options = response.map((attachment) => ({- label: `${attachment.name || 'Unnamed Attachment'}`,- value: attachment.uuid,- }));-+ const attachments = await fetchList({ apiKey: auth.secret_text, path: `/documents/${encodeURIComponent(documentId)}/attachments` });return {disabled: false,- options,+ options: attachments.flatMap((attachment) => {+ const id = pandadocNormalize.str(attachment['uuid']);+ return id === null ? [] : [{ label: label({ name: attachment['name'], fallback: 'Unnamed Attachment' }), value: id }];+ }),};} catch (error) {- return {- disabled: true,- placeholder: 'Failed to load attachments',- options: [],- };+ return failed(error);}},});-// Country dropdown with custom input supportexport const countryDropdown = Property.StaticDropdown({displayName: 'Country',description: 'Select a country or choose "Other" to enter a custom country',@@ -420,7 +401,6 @@ export const countryDropdown = Property.StaticDropdown({},});-// Custom country input fieldexport const customCountryInput = Property.ShortText({displayName: 'Custom Country',description:@@ -428,7 +408,6 @@ export const customCountryInput = Property.ShortText({required: false,});-// US/Canada States dropdown with custom input supportexport const stateDropdown = Property.StaticDropdown({displayName: 'State/Province',description:@@ -436,7 +415,7 @@ export const stateDropdown = Property.StaticDropdown({required: false,options: {options: [- // US States+{ label: 'Alabama (US)', value: 'Alabama' },{ label: 'Alaska (US)', value: 'Alaska' },{ label: 'Arizona (US)', value: 'Arizona' },@@ -487,7 +466,7 @@ export const stateDropdown = Property.StaticDropdown({{ label: 'West Virginia (US)', value: 'West Virginia' },{ label: 'Wisconsin (US)', value: 'Wisconsin' },{ label: 'Wyoming (US)', value: 'Wyoming' },- // Canadian Provinces+{ label: 'Alberta (CA)', value: 'Alberta' },{ label: 'British Columbia (CA)', value: 'British Columbia' },{ label: 'Manitoba (CA)', value: 'Manitoba' },@@ -504,7 +483,7 @@ export const stateDropdown = Property.StaticDropdown({{ label: 'Quebec (CA)', value: 'Quebec' },{ label: 'Saskatchewan (CA)', value: 'Saskatchewan' },{ label: 'Yukon (CA)', value: 'Yukon' },- // Other common ones+{ label: 'England (UK)', value: 'England' },{ label: 'Scotland (UK)', value: 'Scotland' },{ label: 'Wales (UK)', value: 'Wales' },@@ -520,7 +499,6 @@ export const stateDropdown = Property.StaticDropdown({},});-// Custom state input fieldexport const customStateInput = Property.ShortText({displayName: 'Custom State/Province',description:@@ -528,7 +506,6 @@ export const customStateInput = Property.ShortText({required: false,});-// Job title dropdown with custom input supportexport const jobTitleDropdown = Property.StaticDropdown({displayName: 'Job Title',description:@@ -536,7 +513,7 @@ export const jobTitleDropdown = Property.StaticDropdown({required: false,options: {options: [- // Executive Level+{ label: 'CEO / Chief Executive Officer', value: 'CEO' },{ label: 'CTO / Chief Technology Officer', value: 'CTO' },{ label: 'CFO / Chief Financial Officer', value: 'CFO' },@@ -545,7 +522,7 @@ export const jobTitleDropdown = Property.StaticDropdown({{ label: 'Vice President', value: 'Vice President' },{ label: 'Director', value: 'Director' },{ label: 'Manager', value: 'Manager' },- // Sales & Marketing+{ label: 'Sales Manager', value: 'Sales Manager' },{ label: 'Sales Representative', value: 'Sales Representative' },{ label: 'Account Manager', value: 'Account Manager' },@@ -555,7 +532,7 @@ export const jobTitleDropdown = Property.StaticDropdown({},{ label: 'Marketing Manager', value: 'Marketing Manager' },{ label: 'Marketing Coordinator', value: 'Marketing Coordinator' },- // Technical+{ label: 'Software Engineer', value: 'Software Engineer' },{ label: 'Senior Software Engineer', value: 'Senior Software Engineer' },{ label: 'Lead Developer', value: 'Lead Developer' },@@ -563,18 +540,18 @@ export const jobTitleDropdown = Property.StaticDropdown({{ label: 'Data Scientist', value: 'Data Scientist' },{ label: 'Product Manager', value: 'Product Manager' },{ label: 'IT Manager', value: 'IT Manager' },- // Operations+{ label: 'Operations Manager', value: 'Operations Manager' },{ label: 'Project Manager', value: 'Project Manager' },{ label: 'Program Manager', value: 'Program Manager' },{ label: 'Business Analyst', value: 'Business Analyst' },{ label: 'Consultant', value: 'Consultant' },- // Finance & Legal+{ label: 'Accountant', value: 'Accountant' },{ label: 'Financial Analyst', value: 'Financial Analyst' },{ label: 'Legal Counsel', value: 'Legal Counsel' },{ label: 'Compliance Officer', value: 'Compliance Officer' },- // HR & Admin+{ label: 'HR Manager', value: 'HR Manager' },{ label: 'HR Coordinator', value: 'HR Coordinator' },{ label: 'Office Manager', value: 'Office Manager' },@@ -585,7 +562,6 @@ export const jobTitleDropdown = Property.StaticDropdown({},});-// Custom job title input fieldexport const customJobTitleInput = Property.ShortText({displayName: 'Custom Job Title',description:@@ -593,7 +569,6 @@ export const customJobTitleInput = Property.ShortText({required: false,});-// Industry dropdown with custom input supportexport const industryDropdown = Property.StaticDropdown({displayName: 'Industry',description:@@ -639,7 +614,6 @@ export const industryDropdown = Property.StaticDropdown({},});-// Custom industry input fieldexport const customIndustryInput = Property.ShortText({displayName: 'Custom Industry',description:@@ -647,7 +621,6 @@ export const customIndustryInput = Property.ShortText({required: false,});-// Recipient role dropdown with custom input supportexport const recipientRoleDropdown = Property.StaticDropdown({displayName: 'Recipient Role',description:@@ -680,7 +653,6 @@ export const recipientRoleDropdown = Property.StaticDropdown({},});-// Custom recipient role input fieldexport const customRecipientRoleInput = Property.ShortText({displayName: 'Custom Recipient Role',description:@@ -688,7 +660,6 @@ export const customRecipientRoleInput = Property.ShortText({required: false,});-// Watermark text dropdown with custom input supportexport const watermarkTextDropdown = Property.StaticDropdown({displayName: 'Watermark Text',description:@@ -715,7 +686,6 @@ export const watermarkTextDropdown = Property.StaticDropdown({},});-// Custom watermark text input fieldexport const customWatermarkTextInput = Property.ShortText({displayName: 'Custom Watermark Text',description:@@ -723,7 +693,6 @@ export const customWatermarkTextInput = Property.ShortText({required: false,});-// Tag suggestions dropdown with custom input supportexport const tagDropdown = Property.StaticDropdown({displayName: 'Tag',description: 'Select a common tag or choose "Custom" to enter your own',@@ -756,7 +725,6 @@ export const tagDropdown = Property.StaticDropdown({},});-// Custom tag input fieldexport const customTagInput = Property.ShortText({displayName: 'Custom Tag',description: 'Enter a custom tag (only used if "Custom" is selected above)',diff --git a/packages/pieces/community/pandadoc/src/lib/common/files.ts b/packages/pieces/community/pandadoc/src/lib/common/files.tsnew file mode 100644index 00000000000..8e51257f92a--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/files.ts@@ -0,0 +1,42 @@+import { isRecord } from './client';+import { UploadFile } from './api';++function readUploadFile({ value, label }: { value: unknown; label: string }): UploadFile | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (!isRecord(value)) {+ throw new Error(`${label} is not a valid file.`);+ }+ const data = value['data'];+ const filename = value['filename'];+ const base64 = value['base64'];+ const buffer = Buffer.isBuffer(data) ? data : typeof base64 === 'string' ? Buffer.from(base64, 'base64') : undefined;+ if (buffer === undefined || buffer.length === 0) {+ throw new Error(`${label} is empty.`);+ }+ if (buffer.length > MAX_UPLOAD_BYTES) {+ throw new Error(`${label} is larger than PandaDoc's 50 MB upload limit.`);+ }+ const fileName = typeof filename === 'string' && filename.length > 0 ? filename : 'file';+ const extension = typeof value['extension'] === 'string' ? value['extension'] : fileName.split('.').pop() ?? '';+ return { data: buffer, fileName, contentType: CONTENT_TYPES[extension.toLowerCase()] ?? 'application/octet-stream' };+}++export const pandadocFiles = { readUploadFile };++const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;+const CONTENT_TYPES: Record<string, string> = {+ pdf: 'application/pdf',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ doc: 'application/msword',+ rtf: 'application/rtf',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ txt: 'text/plain',+ csv: 'text/csv',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ zip: 'application/zip',+};diff --git a/packages/pieces/community/pandadoc/src/lib/common/index.ts b/packages/pieces/community/pandadoc/src/lib/common/index.tsindex 8a9de8a731b..e8b49f4c64d 100644--- a/packages/pieces/community/pandadoc/src/lib/common/index.ts+++ b/packages/pieces/community/pandadoc/src/lib/common/index.ts@@ -1,49 +1,2 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';--const BASE_URL = 'https://api.pandadoc.com/public/v1';--export const pandadocClient = {- async makeRequest<T = any>(- auth: string,- method: HttpMethod,- endpoint: string,- body?: any- ): Promise<T> {- const response = await httpClient.sendRequest<T>({- method,- url: `${BASE_URL}${endpoint}`,- headers: {- Authorization: `API-Key ${auth}`,- 'Content-Type': 'application/json',- },- body: body ? JSON.stringify(body) : undefined,- });-- return response.body;- },-- async makeFileRequest(- auth: string,- method: HttpMethod,- endpoint: string,- file?: any- ): Promise<any> {- const formData = new FormData();- if (file) {- formData.append('file', file);- }-- const response = await httpClient.sendRequest({- method,- url: `${BASE_URL}${endpoint}`,- headers: {- Authorization: `API-Key ${auth}`,- },- body: formData,- });-- return response.body;- },-};-export * from './auth';+export * from './client';diff --git a/packages/pieces/community/pandadoc/src/lib/common/inputs.ts b/packages/pieces/community/pandadoc/src/lib/common/inputs.tsnew file mode 100644index 00000000000..cfb40375559--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/inputs.ts@@ -0,0 +1,172 @@+import { isRecord } from './client';++function pickCustom({ value, custom }: { value: unknown; custom: unknown }): string | undefined {+ if (typeof value !== 'string' || value.length === 0) {+ return undefined;+ }+ if (value === 'custom') {+ return typeof custom === 'string' && custom.trim().length > 0 ? custom.trim() : undefined;+ }+ return value;+}++function optionalString(value: unknown): string | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return String(value);+ }+ if (typeof value !== 'string') {+ return undefined;+ }+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}++function requiredString({ value, label }: { value: unknown; label: string }): string {+ const result = optionalString(value);+ if (result === undefined) {+ throw new Error(`${label} is required.`);+ }+ return result;+}++function optionalNumber(value: unknown): number | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ if (typeof value === 'string' && value.trim().length > 0 && Number.isFinite(Number(value))) {+ return Number(value);+ }+ return undefined;+}++function boundedCount({ value, label }: { value: unknown; label: string }): number | undefined {+ const count = optionalNumber(value);+ if (count === undefined) {+ return undefined;+ }+ if (!Number.isInteger(count) || count < 1 || count > 100) {+ throw new Error(`${label} must be a whole number between 1 and 100.`);+ }+ return count;+}++function positivePage(value: unknown): number | undefined {+ const page = optionalNumber(value);+ if (page === undefined) {+ return undefined;+ }+ if (!Number.isInteger(page) || page < 1) {+ throw new Error('Page must be a whole number starting at 1.');+ }+ return page;+}++function stringRecord(value: unknown): Record<string, string> {+ if (!isRecord(value)) {+ return {};+ }+ return Object.fromEntries(+ Object.entries(value).flatMap(([key, item]) => {+ if (item === undefined || item === null) {+ return [];+ }+ return [[key, typeof item === 'string' ? item : JSON.stringify(item)]];+ }),+ );+}++function fieldValues(value: unknown): Record<string, { value: string | number | boolean }> {+ if (!isRecord(value)) {+ return {};+ }+ return Object.fromEntries(+ Object.entries(value).flatMap(([key, item]) => {+ if (typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) {+ return [[key, { value: item }]];+ }+ if (typeof item === 'string' && item.length > 0) {+ return [[key, { value: item }]];+ }+ if (isRecord(item) && ['string', 'number', 'boolean'].includes(typeof item['value'])) {+ const inner = item['value'];+ return typeof inner === 'string' || typeof inner === 'number' || typeof inner === 'boolean' ? [[key, { value: inner }]] : [];+ }+ return [];+ }),+ );+}++function tokenList(value: unknown): { name: string; value: string }[] {+ if (Array.isArray(value)) {+ return value.flatMap((item) => {+ if (!isRecord(item)) {+ return [];+ }+ const name = optionalString(item['name']);+ const tokenValue = item['value'];+ return name === undefined || tokenValue === undefined || tokenValue === null ? [] : [{ name, value: String(tokenValue) }];+ });+ }+ return Object.entries(stringRecord(value)).map(([name, tokenValue]) => ({ name, value: tokenValue }));+}++function stringList(value: unknown): string[] {+ if (typeof value === 'string') {+ return value.split(',').map((item) => item.trim()).filter((item) => item.length > 0);+ }+ if (!Array.isArray(value)) {+ return [];+ }+ return value.flatMap((item) => {+ const text = optionalString(item);+ return text === undefined ? [] : [text];+ });+}++function recipients(value: unknown): Record<string, unknown>[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.flatMap((item) => {+ if (!isRecord(item)) {+ return [];+ }+ const email = optionalString(item['email']);+ const phone = optionalString(item['phone']);+ if (email === undefined && phone === undefined) {+ throw new Error('Each recipient needs an email or a phone number.');+ }+ const role = pickCustom({ value: item['role'], custom: item['custom_role'] });+ const signingOrder = optionalNumber(item['signing_order']);+ return [+ {+ ...(email === undefined ? {} : { email }),+ ...(phone === undefined ? {} : { phone }),+ ...(optionalString(item['first_name']) === undefined ? {} : { first_name: optionalString(item['first_name']) }),+ ...(optionalString(item['last_name']) === undefined ? {} : { last_name: optionalString(item['last_name']) }),+ ...(role === undefined ? {} : { role }),+ ...(signingOrder === undefined ? {} : { signing_order: signingOrder }),+ },+ ];+ });+}++export function metadataQuery(value: unknown): Record<string, string> {+ return Object.fromEntries(+ Object.entries(stringRecord(value)).map(([key, item]) => [`metadata_${key}`, item]),+ );+}++export const pandadocInputs = {+ pickCustom,+ optionalString,+ requiredString,+ optionalNumber,+ boundedCount,+ positivePage,+ stringRecord,+ fieldValues,+ tokenList,+ stringList,+ recipients,+};diff --git a/packages/pieces/community/pandadoc/src/lib/common/normalize.ts b/packages/pieces/community/pandadoc/src/lib/common/normalize.tsnew file mode 100644index 00000000000..33527a9479f--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/normalize.ts@@ -0,0 +1,329 @@+import { isRecord } from './client';++function str(value: unknown): string | null {+ if (typeof value === 'string') {+ return value;+ }+ if (typeof value === 'number' || typeof value === 'boolean') {+ return String(value);+ }+ return null;+}++function num(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ if (typeof value === 'string' && value.trim().length > 0 && Number.isFinite(Number(value))) {+ return Number(value);+ }+ return null;+}++function bool(value: unknown): boolean | null {+ return typeof value === 'boolean' ? value : null;+}++function rec(value: unknown): Record<string, unknown> {+ return isRecord(value) ? value : {};+}++function list(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function stringList(value: unknown): string[] {+ return list(value).flatMap((item) => (typeof item === 'string' ? [item] : []));+}++function documentSummary(raw: unknown): DocumentSummary {+ const doc = rec(raw);+ return {+ id: str(doc['id']),+ name: str(doc['name']),+ status: str(doc['status']),+ date_created: str(doc['date_created']),+ date_modified: str(doc['date_modified']),+ date_sent: str(doc['date_sent']),+ date_completed: str(doc['date_completed']),+ expiration_date: str(doc['expiration_date']),+ version: str(doc['version']),+ };+}++function recipient(raw: unknown): DocumentRecipient {+ const r = rec(raw);+ return {+ id: str(r['id']),+ email: str(r['email']),+ first_name: str(r['first_name']),+ last_name: str(r['last_name']),+ phone: str(r['phone']),+ role: str(r['role']),+ recipient_type: str(r['recipient_type']),+ has_completed: bool(r['has_completed']),+ signing_order: num(r['signing_order']),+ contact_id: str(r['contact_id']),+ shared_link: str(r['shared_link']),+ };+}++function field(raw: unknown): DocumentField {+ const f = rec(raw);+ const assigned = rec(f['assigned_to']);+ const assignee = rec(f['assignee_details']);+ return {+ uuid: str(f['uuid']),+ name: str(f['name']),+ merge_field: str(f['merge_field']),+ field_id: str(f['field_id']),+ type: str(f['type']),+ value: f['value'] === undefined ? null : f['value'],+ is_filled: bool(f['is_filled']),+ assigned_to_email: str(assigned['email']) ?? str(assignee['email']) ?? str(f['assignee']),+ assigned_to_role: str(assigned['role']),+ };+}++function tokens(raw: unknown): { name: string | null; value: string | null }[] {+ return list(raw).map((item) => {+ const t = rec(item);+ return { name: str(t['name']), value: str(t['value']) };+ });+}++function documentDetails(raw: unknown): DocumentDetails {+ const doc = rec(raw);+ const template = rec(doc['template']);+ const createdBy = rec(doc['created_by']);+ const sentBy = rec(doc['sent_by']);+ const grandTotal = rec(doc['grand_total']);+ return {+ ...documentSummary(doc),+ ref_number: str(doc['ref_number']),+ folder_uuid: str(doc['folder_uuid']),+ template_id: str(template['id']),+ template_name: str(template['name']),+ created_by_email: str(createdBy['email']),+ sent_by_email: str(sentBy['email']),+ grand_total_amount: str(grandTotal['amount']),+ grand_total_currency: str(grandTotal['currency']),+ tags: stringList(doc['tags']),+ metadata: rec(doc['metadata']),+ tokens: tokens(doc['tokens']),+ fields: list(doc['fields']).map(field),+ recipients: list(doc['recipients']).map(recipient),+ };+}++function webhookEvent({ event, data }: { event: string; data: unknown }): WebhookDocumentEvent {+ const raw = rec(data);+ const actionBy = rec(raw['action_by']);+ const error = rec(raw['error']);+ return {+ event,+ ...documentDetails(raw),+ action_by_email: str(actionBy['email']),+ action_by_first_name: str(actionBy['first_name']),+ action_by_last_name: str(actionBy['last_name']),+ action_date: str(raw['action_date']),+ error_type: str(error['type']),+ error_detail: str(error['detail']) ?? (error['detail'] === undefined || error['detail'] === null ? null : JSON.stringify(error['detail'])),+ };+}++function attachment(raw: unknown): DocumentAttachment {+ const a = rec(raw);+ const createdBy = rec(a['created_by']);+ return {+ uuid: str(a['uuid']),+ name: str(a['name']),+ date_created: str(a['date_created']),+ type: str(a['type']),+ created_by_email: str(createdBy['email']),+ };+}++function contact(raw: unknown): Contact {+ const c = rec(raw);+ return {+ id: str(c['id']),+ email: str(c['email']),+ first_name: str(c['first_name']),+ last_name: str(c['last_name']),+ company: str(c['company']),+ job_title: str(c['job_title']),+ phone: str(c['phone']),+ country: str(c['country']),+ state: str(c['state']),+ street_address: str(c['street_address']),+ city: str(c['city']),+ postal_code: str(c['postal_code']),+ };+}++function templateSummary(raw: unknown): TemplateSummary {+ const t = rec(raw);+ return {+ id: str(t['id']),+ name: str(t['name']),+ date_created: str(t['date_created']),+ date_modified: str(t['date_modified']),+ version: str(t['version']),+ };+}++function templateDetails(raw: unknown): TemplateDetails {+ const t = rec(raw);+ const roles = list(t['roles']).map((item) => {+ const r = rec(item);+ return { id: str(r['id']), name: str(r['name']), signing_order: num(r['signing_order']) };+ });+ return {+ ...templateSummary(t),+ folder_uuid: str(t['folder_uuid']),+ tags: stringList(t['tags']),+ roles,+ fields: list(t['fields']).map(field),+ tokens: tokens(t['tokens']),+ };+}++function folder(raw: unknown): Folder {+ const f = rec(raw);+ return {+ uuid: str(f['uuid']),+ name: str(f['name']),+ date_created: str(f['date_created']),+ has_folders: bool(f['has_folders']),+ has_items: bool(f['has_items']),+ };+}++export const pandadocNormalize = {+ str,+ num,+ rec,+ list,+ documentSummary,+ documentDetails,+ webhookEvent,+ attachment,+ contact,+ templateSummary,+ templateDetails,+ folder,+ field,+ recipient,+};++export type DocumentSummary = {+ id: string | null;+ name: string | null;+ status: string | null;+ date_created: string | null;+ date_modified: string | null;+ date_sent: string | null;+ date_completed: string | null;+ expiration_date: string | null;+ version: string | null;+};++export type DocumentRecipient = {+ id: string | null;+ email: string | null;+ first_name: string | null;+ last_name: string | null;+ phone: string | null;+ role: string | null;+ recipient_type: string | null;+ has_completed: boolean | null;+ signing_order: number | null;+ contact_id: string | null;+ shared_link: string | null;+};++export type DocumentField = {+ uuid: string | null;+ name: string | null;+ merge_field: string | null;+ field_id: string | null;+ type: string | null;+ value: unknown;+ is_filled: boolean | null;+ assigned_to_email: string | null;+ assigned_to_role: string | null;+};++export type DocumentDetails = DocumentSummary & {+ ref_number: string | null;+ folder_uuid: string | null;+ template_id: string | null;+ template_name: string | null;+ created_by_email: string | null;+ sent_by_email: string | null;+ grand_total_amount: string | null;+ grand_total_currency: string | null;+ tags: string[];+ metadata: Record<string, unknown>;+ tokens: { name: string | null; value: string | null }[];+ fields: DocumentField[];+ recipients: DocumentRecipient[];+};++export type WebhookDocumentEvent = DocumentDetails & {+ event: string;+ action_by_email: string | null;+ action_by_first_name: string | null;+ action_by_last_name: string | null;+ action_date: string | null;+ error_type: string | null;+ error_detail: string | null;+};++export type DocumentAttachment = {+ uuid: string | null;+ name: string | null;+ date_created: string | null;+ type: string | null;+ created_by_email: string | null;+};++export type Contact = {+ id: string | null;+ email: string | null;+ first_name: string | null;+ last_name: string | null;+ company: string | null;+ job_title: string | null;+ phone: string | null;+ country: string | null;+ state: string | null;+ street_address: string | null;+ city: string | null;+ postal_code: string | null;+};++export type TemplateSummary = {+ id: string | null;+ name: string | null;+ date_created: string | null;+ date_modified: string | null;+ version: string | null;+};++export type TemplateDetails = TemplateSummary & {+ folder_uuid: string | null;+ tags: string[];+ roles: { id: string | null; name: string | null; signing_order: number | null }[];+ fields: DocumentField[];+ tokens: { name: string | null; value: string | null }[];+};++export type Folder = {+ uuid: string | null;+ name: string | null;+ date_created: string | null;+ has_folders: boolean | null;+ has_items: boolean | null;+};diff --git a/packages/pieces/community/pandadoc/src/lib/common/schemas.ts b/packages/pieces/community/pandadoc/src/lib/common/schemas.tsnew file mode 100644index 00000000000..946c33cadd7--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/schemas.ts@@ -0,0 +1,329 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const statusDescription = 'PandaDoc status, for example document.draft, document.sent, document.completed or document.voided.';++const documentSummaryFields: OutputSchemaField[] = [+ { key: 'id', label: 'Document ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status', description: statusDescription },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_modified', label: 'Modified At', format: 'datetime' },+ { key: 'date_sent', label: 'Sent At', format: 'datetime' },+ { key: 'date_completed', label: 'Completed At', format: 'datetime' },+ { key: 'expiration_date', label: 'Expires At', format: 'datetime' },+ { key: 'version', label: 'Version' },+];++const recipientFields: OutputSchemaField[] = [+ { key: 'id', label: 'Recipient ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'role', label: 'Role' },+ { key: 'recipient_type', label: 'Recipient Type', description: 'signer, approver or CC.' },+ { key: 'has_completed', label: 'Has Completed', format: 'boolean' },+ { key: 'signing_order', label: 'Signing Order', format: 'number' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'shared_link', label: 'Signing Link', format: 'url' },+];++const fieldFields: OutputSchemaField[] = [+ { key: 'uuid', label: 'Field UUID' },+ { key: 'name', label: 'Name' },+ { key: 'merge_field', label: 'Merge Field', description: 'The key to use when prefilling this field.' },+ { key: 'type', label: 'Type' },+ { key: 'value', label: 'Value' },+ { key: 'is_filled', label: 'Is Filled', format: 'boolean' },+ { key: 'assigned_to_email', label: 'Assigned To (Email)', format: 'email' },+ { key: 'assigned_to_role', label: 'Assigned To (Role)' },+];++const tokenFields: OutputSchemaField[] = [+ { key: 'name', label: 'Name' },+ { key: 'value', label: 'Value' },+];++const documentDetailsFields: OutputSchemaField[] = [+ ...documentSummaryFields,+ { key: 'ref_number', label: 'Reference Number' },+ { key: 'folder_uuid', label: 'Folder ID' },+ { key: 'template_id', label: 'Template ID' },+ { key: 'template_name', label: 'Template Name' },+ { key: 'created_by_email', label: 'Created By (Email)', format: 'email' },+ { key: 'sent_by_email', label: 'Sent By (Email)', format: 'email' },+ { key: 'grand_total_amount', label: 'Grand Total' },+ { key: 'grand_total_currency', label: 'Currency' },+ { key: 'tags', label: 'Tags' },+ { key: 'metadata', label: 'Metadata', dynamicKey: true },+ { key: 'tokens', label: 'Tokens', labelKey: 'name', listItems: tokenFields },+ { key: 'recipients', label: 'Recipients', labelKey: 'email', listItems: recipientFields },+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: fieldFields },+];++const rawDocumentDetailsFields: OutputSchemaField[] = [+ { key: 'id', label: 'Document ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status', description: statusDescription },+ { key: 'ref_number', label: 'Reference Number' },+ { key: 'folder_uuid', label: 'Folder ID' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_modified', label: 'Modified At', format: 'datetime' },+ { key: 'date_sent', label: 'Sent At', format: 'datetime' },+ { key: 'date_completed', label: 'Completed At', format: 'datetime' },+ { key: 'expiration_date', label: 'Expires At', format: 'datetime' },+ { key: 'version', label: 'Version' },+ { key: 'template', label: 'Template', children: [+ { key: 'id', label: 'Template ID' },+ { key: 'name', label: 'Template Name' },+ ] },+ { key: 'created_by', label: 'Created By', children: [+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ ] },+ { key: 'grand_total', label: 'Grand Total', children: [+ { key: 'amount', label: 'Amount' },+ { key: 'currency', label: 'Currency' },+ ] },+ { key: 'tags', label: 'Tags' },+ { key: 'metadata', label: 'Metadata', dynamicKey: true },+ { key: 'tokens', label: 'Tokens', labelKey: 'name', listItems: tokenFields },+ { key: 'recipients', label: 'Recipients', labelKey: 'email', listItems: [+ { key: 'id', label: 'Recipient ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'role', label: 'Role' },+ { key: 'recipient_type', label: 'Recipient Type' },+ { key: 'has_completed', label: 'Has Completed', format: 'boolean' },+ { key: 'signing_order', label: 'Signing Order', format: 'number' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'shared_link', label: 'Signing Link', format: 'url' },+ ] },+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: [+ { key: 'uuid', label: 'Field UUID' },+ { key: 'name', label: 'Name' },+ { key: 'merge_field', label: 'Merge Field' },+ { key: 'type', label: 'Type' },+ { key: 'value', label: 'Value' },+ { key: 'is_filled', label: 'Is Filled', format: 'boolean' },+ ] },+];++const rawCreatedDocumentFields: OutputSchemaField[] = [+ { key: 'id', label: 'Document ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status', description: 'document.uploaded right after creation; document.draft once PandaDoc has processed it.' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_modified', label: 'Modified At', format: 'datetime' },+ { key: 'expiration_date', label: 'Expires At', format: 'datetime' },+ { key: 'version', label: 'Version' },+];++const attachmentFields: OutputSchemaField[] = [+ { key: 'uuid', label: 'Attachment ID' },+ { key: 'name', label: 'Name' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'type', label: 'Type' },+];++const contactFields: OutputSchemaField[] = [+ { key: 'id', label: 'Contact ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'company', label: 'Company' },+ { key: 'job_title', label: 'Job Title' },+ { key: 'phone', label: 'Phone' },+ { key: 'street_address', label: 'Street Address' },+ { key: 'city', label: 'City' },+ { key: 'state', label: 'State' },+ { key: 'postal_code', label: 'Postal Code' },+ { key: 'country', label: 'Country' },+];++const templateSummaryFields: OutputSchemaField[] = [+ { key: 'id', label: 'Template ID' },+ { key: 'name', label: 'Name' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_modified', label: 'Modified At', format: 'datetime' },+ { key: 'version', label: 'Version' },+];++const folderFields: OutputSchemaField[] = [+ { key: 'uuid', label: 'Folder ID' },+ { key: 'name', label: 'Name' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+];++const webhookEventFields: OutputSchemaField[] = [+ { key: 'event', label: 'Event', description: 'PandaDoc webhook event, for example document_state_changed.' },+ ...documentDetailsFields,+ { key: 'action_by_email', label: 'Action By (Email)', format: 'email' },+ { key: 'action_by_first_name', label: 'Action By (First Name)' },+ { key: 'action_by_last_name', label: 'Action By (Last Name)' },+ { key: 'action_date', label: 'Action Date', format: 'datetime' },+];++export const pandadocSchemas: Record<string, OutputSchema> = {+ rawCreatedDocument: { fields: rawCreatedDocumentFields },+ rawDocumentDetails: { fields: rawDocumentDetailsFields },+ rawFindDocuments: {+ fields: [+ { key: 'results', label: 'Documents', labelKey: 'name', listItems: documentSummaryFields },+ ],+ },+ rawAttachment: {+ fields: [+ ...attachmentFields,+ { key: 'created_by', label: 'Created By', children: [+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ ] },+ ],+ },+ rawContact: { fields: contactFields },+ downloadedFile: {+ fields: [+ { key: 'file', label: 'File', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ { key: 'protected', label: 'Protected Copy', format: 'boolean' },+ ],+ },+ createdDocument: { fields: [...documentSummaryFields] },+ documentDetails: { fields: documentDetailsFields },+ documentList: {+ fields: [+ { key: 'documents', label: 'Documents', labelKey: 'name', listItems: documentSummaryFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ sentDocument: {+ fields: [+ ...documentSummaryFields,+ { key: 'recipients', label: 'Recipients', labelKey: 'email', listItems: recipientFields },+ ],+ },+ signingLink: {+ fields: [+ { key: 'url', label: 'Signing Link', format: 'url' },+ { key: 'session_id', label: 'Session ID' },+ { key: 'expires_at', label: 'Expires At', format: 'datetime' },+ { key: 'document_id', label: 'Document ID' },+ { key: 'recipient_email', label: 'Recipient Email', format: 'email' },+ ],+ },+ reminder: {+ fields: [+ { key: 'document_id', label: 'Document ID' },+ { key: 'results', label: 'Results', labelKey: 'recipient_id', listItems: [+ { key: 'recipient_id', label: 'Recipient ID' },+ { key: 'email_status', label: 'Email Status' },+ { key: 'email_detail', label: 'Email Detail' },+ { key: 'sms_status', label: 'SMS Status' },+ { key: 'sms_detail', label: 'SMS Detail' },+ ] },+ ],+ },+ statusChange: {+ fields: [+ { key: 'id', label: 'Document ID' },+ { key: 'status', label: 'New Status', description: statusDescription },+ { key: 'previous_status', label: 'Previous Status' },+ ],+ },+ deleted: {+ fields: [+ { key: 'id', label: 'ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'already_deleted', label: 'Was Already Deleted', format: 'boolean' },+ ],+ },+ moved: {+ fields: [+ { key: 'id', label: 'Document ID' },+ { key: 'folder_id', label: 'Folder ID' },+ { key: 'moved', label: 'Moved', format: 'boolean' },+ ],+ },+ recipientAdded: {+ fields: [+ { key: 'document_id', label: 'Document ID' },+ { key: 'contact_id', label: 'Contact ID' },+ { key: 'recipient_id', label: 'Recipient ID' },+ ],+ },+ fieldList: {+ fields: [+ { key: 'document_id', label: 'Document ID' },+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: fieldFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ templateList: {+ fields: [+ { key: 'templates', label: 'Templates', labelKey: 'name', listItems: templateSummaryFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ templateDetails: {+ fields: [+ ...templateSummaryFields,+ { key: 'folder_uuid', label: 'Folder ID' },+ { key: 'tags', label: 'Tags' },+ { key: 'roles', label: 'Roles', labelKey: 'name', listItems: [+ { key: 'id', label: 'Role ID' },+ { key: 'name', label: 'Role Name', description: 'Use this as the recipient role when creating a document.' },+ { key: 'signing_order', label: 'Signing Order', format: 'number' },+ ] },+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: fieldFields },+ { key: 'tokens', label: 'Tokens', labelKey: 'name', listItems: tokenFields },+ ],+ },+ folderList: {+ fields: [+ { key: 'folders', label: 'Folders', labelKey: 'name', listItems: [+ ...folderFields,+ { key: 'has_folders', label: 'Has Subfolders', format: 'boolean' },+ { key: 'has_items', label: 'Has Documents', format: 'boolean' },+ ] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ folder: {+ fields: [...folderFields, { key: 'parent_uuid', label: 'Parent Folder ID' }],+ },+ contact: { fields: contactFields },+ contactList: {+ fields: [+ { key: 'contacts', label: 'Contacts', labelKey: 'email', listItems: contactFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ attachment: { fields: [...attachmentFields, { key: 'created_by_email', label: 'Created By (Email)', format: 'email' }] },+ attachmentList: {+ fields: [+ { key: 'document_id', label: 'Document ID' },+ { key: 'attachments', label: 'Attachments', labelKey: 'name', listItems: [...attachmentFields, { key: 'created_by_email', label: 'Created By (Email)', format: 'email' }] },+ { key: 'count', label: 'Count', format: 'number' },+ ],+ },+ aiDownloadedFile: {+ fields: [+ { key: 'file', label: 'File', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ { key: 'protected', label: 'Protected Copy', format: 'boolean' },+ { key: 'document_id', label: 'Document ID' },+ ],+ },+ webhookEvent: { fields: webhookEventFields },+ creationFailedEvent: {+ fields: [+ { key: 'event', label: 'Event' },+ { key: 'id', label: 'Document ID' },+ { key: 'error_type', label: 'Error Type', description: 'For example validation_error.' },+ { key: 'error_detail', label: 'Error Detail', description: 'Why PandaDoc could not create the document.' },+ ],+ },+};diff --git a/packages/pieces/community/pandadoc/src/lib/common/statuses.ts b/packages/pieces/community/pandadoc/src/lib/common/statuses.tsnew file mode 100644index 00000000000..7386358eb2b--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/statuses.ts@@ -0,0 +1,35 @@+export const DOCUMENT_STATUS_OPTIONS = [+ { label: 'Draft', value: 0 },+ { label: 'Sent', value: 1 },+ { label: 'Completed', value: 2 },+ { label: 'Uploaded', value: 3 },+ { label: 'Error', value: 4 },+ { label: 'Viewed', value: 5 },+ { label: 'Waiting Approval', value: 6 },+ { label: 'Approved', value: 7 },+ { label: 'Rejected', value: 8 },+ { label: 'Waiting Pay', value: 9 },+ { label: 'Paid', value: 10 },+ { label: 'Voided', value: 11 },+ { label: 'Declined', value: 12 },+ { label: 'External Review', value: 13 },+ { label: 'Signed (Notarization Pending)', value: 14 },+];++export const DOCUMENT_STATUS_CODES: Record<string, number> = {+ draft: 0,+ sent: 1,+ completed: 2,+ uploaded: 3,+ error: 4,+ viewed: 5,+ waiting_approval: 6,+ approved: 7,+ rejected: 8,+ waiting_pay: 9,+ paid: 10,+ voided: 11,+ declined: 12,+ external_review: 13,+ signed: 14,+};diff --git a/packages/pieces/community/pandadoc/src/lib/common/webhook.ts b/packages/pieces/community/pandadoc/src/lib/common/webhook.tsnew file mode 100644index 00000000000..c31d1ad3963--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/common/webhook.ts@@ -0,0 +1,211 @@+import { createHmac, timingSafeEqual } from 'crypto';+import { HttpMethod } from '@activepieces/pieces-common';+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';+import { encodeId, isPandaDocStatus, isRecord, pandadocRequest } from './client';+import { pandadocApi } from './api';+import { pandadocNormalize, WebhookDocumentEvent } from './normalize';++function verifySignature({ sharedKey, rawBody, signature }: { sharedKey: string; rawBody: unknown; signature: string | undefined }): boolean {+ const raw = typeof rawBody === 'string' ? Buffer.from(rawBody, 'utf8') : Buffer.isBuffer(rawBody) ? rawBody : undefined;+ if (raw === undefined || signature === undefined || !/^[0-9a-fA-F]{64}$/.test(signature)) {+ return false;+ }+ const expected = Buffer.from(createHmac('sha256', sharedKey).update(raw).digest('hex'), 'utf8');+ const received = Buffer.from(signature.toLowerCase(), 'utf8');+ return received.length === expected.length && timingSafeEqual(received, expected);+}++async function subscribe({+ apiKey,+ webhookUrl,+ name,+ events,+ store,+ storeKey,+}: {+ apiKey: string;+ webhookUrl: string;+ name: string;+ events: string[];+ store: WebhookStore;+ storeKey: string;+}): Promise<void> {+ const response = await pandadocRequest<unknown>({+ apiKey,+ method: HttpMethod.POST,+ path: '/webhook-subscriptions',+ body: {+ name: `Activepieces: ${name}`,+ url: webhookUrl,+ active: true,+ triggers: events,+ payload: ['metadata', 'fields', 'tokens'],+ },+ });+ const body = pandadocNormalize.rec(response.body);+ const webhookId = pandadocNormalize.str(body['uuid']);+ if (webhookId === null) {+ throw new Error('PandaDoc did not return the new webhook subscription ID.');+ }+ const sharedKey = pandadocNormalize.str(body['shared_key']);+ await store.put<StoredWebhook>(storeKey, { webhookId, sharedKey });+}++async function unsubscribe({ apiKey, store, storeKey }: { apiKey: string; store: WebhookStore; storeKey: string }): Promise<void> {+ const stored = await readStored({ store, storeKey });+ if (stored.webhookId === null) {+ return;+ }+ try {+ await pandadocRequest({ apiKey, method: HttpMethod.DELETE, path: `/webhook-subscriptions/${encodeId({ id: stored.webhookId, label: 'Webhook ID' })}` });+ } catch (error) {+ if (!isPandaDocStatus({ error, statuses: [404] })) {+ throw error;+ }+ }+ await store.delete(storeKey);+ await store.delete(LEGACY_STORE_KEY);+}++async function readStored({ store, storeKey }: { store: WebhookStore; storeKey: string }): Promise<{ webhookId: string | null; sharedKey: string | null }> {+ const current = await store.get<unknown>(storeKey);+ if (isRecord(current) && typeof current['webhookId'] === 'string') {+ const sharedKey = current['sharedKey'];+ return { webhookId: current['webhookId'], sharedKey: typeof sharedKey === 'string' && sharedKey.length > 0 ? sharedKey : null };+ }+ const legacy = await store.get<unknown>(LEGACY_STORE_KEY);+ return { webhookId: typeof legacy === 'string' && legacy.length > 0 ? legacy : null, sharedKey: null };+}++async function receive({+ payload,+ store,+ storeKey,+ events,+ select,+}: {+ payload: { body: unknown; rawBody?: unknown; headers: Record<string, string | undefined>; queryParams?: Record<string, string | undefined> };+ store: WebhookStore;+ storeKey: string;+ events: string[];+ select?: (items: WebhookDocumentEvent[]) => Promise<WebhookDocumentEvent[]> | WebhookDocumentEvent[];+}): Promise<WebhookDocumentEvent[]> {+ const stored = await readStored({ store, storeKey });+ if (stored.sharedKey !== null && !verifySignature({ sharedKey: stored.sharedKey, rawBody: payload.rawBody, signature: payload.queryParams?.['signature'] })) {+ return [];+ }+ const items = parseItems(payload.body)+ .filter((item) => events.includes(item.event))+ .map((item) => pandadocNormalize.webhookEvent(item));+ if (items.length === 0) {+ return [];+ }+ const deliveryId = headerValue({ headers: payload.headers, name: EVENT_ID_HEADER });+ if (deliveryId === undefined) {+ return select === undefined ? items : select(items);+ }+ const dedupeKey = `${storeKey}_deliveries`;+ const seen = (await store.get<string[]>(dedupeKey)) ?? [];+ if (seen.includes(deliveryId)) {+ return [];+ }+ const keyed = items.map((item, index) => ({ ...item, [DEDUPE_KEY_PROPERTY]: `${deliveryId}:${index}` }));+ const selected = select === undefined ? keyed : await select(keyed);+ await store.put(dedupeKey, [...seen, deliveryId].slice(-MAX_REMEMBERED_DELIVERIES));+ return selected;+}++function parseItems(body: unknown): { event: string; data: unknown }[] {+ const parsed = typeof body === 'string' || Buffer.isBuffer(body) ? safeJson(body.toString()) : body;+ const list = Array.isArray(parsed) ? parsed : isRecord(parsed) ? [parsed] : [];+ return list.flatMap((item) => {+ if (!isRecord(item) || typeof item['event'] !== 'string' || !isRecord(item['data'])) {+ return [];+ }+ return [{ event: item['event'], data: item['data'] }];+ });+}++function safeJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return undefined;+ }+}++function headerValue({ headers, name }: { headers: Record<string, string | undefined> | undefined; name: string }): string | undefined {+ if (headers === undefined) {+ return undefined;+ }+ const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name);+ const value = match?.[1];+ return typeof value === 'string' && value.length > 0 ? value : undefined;+}++async function matchesFilters({+ apiKey,+ item,+ templateIds,+ folderIds,+}: {+ apiKey: string;+ item: WebhookDocumentEvent;+ templateIds: string[] | undefined;+ folderIds: string[] | undefined;+}): Promise<boolean> {+ const wantsTemplate = templateIds !== undefined && templateIds.length > 0;+ const wantsFolder = folderIds !== undefined && folderIds.length > 0;+ if (!wantsTemplate && !wantsFolder) {+ return true;+ }+ const needsLookup = (wantsTemplate && item.template_id === null) || (wantsFolder && item.folder_uuid === null);+ const details = needsLookup && item.id !== null ? await pandadocApi.getDocumentDetails({ apiKey, documentId: item.id }) : undefined;+ const templateId = item.template_id ?? details?.template_id ?? null;+ const folderId = item.folder_uuid ?? details?.folder_uuid ?? null;+ if (wantsTemplate && (templateId === null || !templateIds.includes(templateId))) {+ return false;+ }+ if (wantsFolder && (folderId === null || !folderIds.includes(folderId))) {+ return false;+ }+ return true;+}++async function filterItems({+ apiKey,+ items,+ templateIds,+ folderIds,+}: {+ apiKey: string;+ items: WebhookDocumentEvent[];+ templateIds: string[] | undefined;+ folderIds: string[] | undefined;+}): Promise<WebhookDocumentEvent[]> {+ const checks = await Promise.all(items.map((item) => matchesFilters({ apiKey, item, templateIds, folderIds })));+ return items.filter((_, index) => checks[index]);+}++export const pandadocWebhook = {+ verifySignature,+ subscribe,+ unsubscribe,+ readStored,+ receive,+ matchesFilters,+ filterItems,+ parseItems,+};++export type WebhookStore = {+ get<T>(key: string): Promise<T | null>;+ put<T>(key: string, value: T): Promise<T>;+ delete(key: string): Promise<void>;+};++type StoredWebhook = { webhookId: string; sharedKey: string | null };++const LEGACY_STORE_KEY = 'webhook_id';+const EVENT_ID_HEADER = 'x-pandadoc-webhook-event-id';+const MAX_REMEMBERED_DELIVERIES = 200;diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/document-completed.ts b/packages/pieces/community/pandadoc/src/lib/triggers/document-completed.tsindex 00a0ae896b0..e2ab3049199 100644--- a/packages/pieces/community/pandadoc/src/lib/triggers/document-completed.ts+++ b/packages/pieces/community/pandadoc/src/lib/triggers/document-completed.ts@@ -1,246 +1,56 @@-import {- createTrigger,- TriggerStrategy,- Property,-} from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { WebhookHandshakeStrategy } from '@activepieces/pieces-framework';-import { pandadocAuth, pandadocClient } from '../common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { folderFilterDropdown, templateFilterDropdown } from '../common/dynamic-dropdowns';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocSampleEvent } from './sample-data';export const documentCompleted = createTrigger({+ auth: pandadocAuth,name: 'documentCompleted',classification: 'READ',displayName: 'Document Completed',- description:- 'Triggers when a document is completed.',+ description: 'Triggers when a document is completed (all recipients have signed or approved).',aiMetadata: {- description: 'Fires when a PandaDoc document is completed — i.e. it reaches the completed state or all recipients finish signing. Optionally scoped to specific templates and/or folders. Represents a fully executed/signed document.',+ description:+ 'Fires once when a PandaDoc document reaches the completed status, meaning every recipient has finished. Optionally limited to documents from specific templates or in specific folders. Delivers the full document with recipients, fields and metadata.',},- auth: pandadocAuth,props: {- template_filter: Property.MultiSelectDropdown({- auth: pandadocAuth,- displayName: 'Filter by Templates',- description:- 'Only trigger for documents created from specific templates (leave empty for all)',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/templates?count=100');-- const options = response.results.map((template) => ({- label: `${template.name} - ${template.id.substring(0, 8)}...`,- value: template.id,- }));-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load templates',- options: [],- };- }- },- }),- folder_filter: Property.MultiSelectDropdown({- auth: pandadocAuth,- displayName: 'Filter by Folders',- description:- 'Only trigger for documents in specific folders (leave empty for all)',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- uuid: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/documents/folders?count=100');-- const options = response.results.map((folder) => ({- label: `${folder.name} - ${folder.uuid.substring(0, 8)}...`,- value: folder.uuid,- }));-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load folders',- options: [],- };- }- },- }),- },- sampleData: {- event_type: 'document_state_changed',- data: {- id: 'sample_document_id',- name: 'Sample Contract',- status: 'document.completed',- date_completed: '2024-01-15T10:30:00Z',- template: {- id: 'template_id',- name: 'Contract Template',- },- folder_uuid: 'folder_uuid',- recipients: [- {- id: 'recipient_id',- email: '[email protected]',- has_completed: true,- signature_date: '2024-01-15T10:30:00Z',- },- ],- },+ template_filter: templateFilterDropdown,+ folder_filter: folderFilterDropdown,},+ sampleData: { ...pandadocSampleEvent, status: 'document.completed' },+ outputSchema: pandadocSchemas['webhookEvent'],type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const webhookSubscription = await httpClient.sendRequest({- method: HttpMethod.POST,- url: 'https://api.pandadoc.com/public/v1/webhook-subscriptions',- headers: {- Authorization: `API-Key ${context.auth.secret_text}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- name: `Activepieces Document Completed`,- url: context.webhookUrl,- active: true,- triggers: ['document_state_changed', 'recipient_completed'],- payload: ['fields', 'products', 'tokens', 'metadata', 'pricing'],- }),+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Document Completed',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,});-- await context.store?.put('webhook_id', webhookSubscription.body.uuid);},async onDisable(context) {- const webhookId = await context.store?.get('webhook_id');- if (webhookId) {- try {- await httpClient.sendRequest({- method: HttpMethod.DELETE,- url: `https://api.pandadoc.com/public/v1/webhook-subscriptions/${webhookId}`,- headers: {- Authorization: `API-Key ${context.auth.secret_text}`,- },- });- } catch (error) {- console.log('Error cleaning up webhook:', error);- }- }+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });},async run(context) {- const payload = context.payload.body as any;-- if (- payload.event_type === 'document_state_changed' &&- payload.data?.status === 'document.completed'- ) {- const documentData = payload.data;-- if (- context.propsValue.template_filter &&- context.propsValue.template_filter.length > 0- ) {- const templateId = documentData?.template?.id;- if (- !templateId ||- !context.propsValue.template_filter.includes(templateId)- ) {- return [];- }- }-- if (- context.propsValue.folder_filter &&- context.propsValue.folder_filter.length > 0- ) {- const folderUuid = documentData?.folder_uuid;- if (- !folderUuid ||- !context.propsValue.folder_filter.includes(folderUuid)- ) {- return [];- }- }-- return [documentData];- }-- if (payload.event_type === 'recipient_completed') {- const allCompleted = payload.data?.recipients?.every(- (recipient: any) => recipient.has_completed- );- if (allCompleted) {- const documentData = payload.data;-- if (- context.propsValue.template_filter &&- context.propsValue.template_filter.length > 0- ) {- const templateId = documentData?.template?.id;- if (- !templateId ||- !context.propsValue.template_filter.includes(templateId)- ) {- return [];- }- }-- if (- context.propsValue.folder_filter &&- context.propsValue.folder_filter.length > 0- ) {- const folderUuid = documentData?.folder_uuid;- if (- !folderUuid ||- !context.propsValue.folder_filter.includes(folderUuid)- ) {- return [];- }- }-- return [documentData];- }- }-- return [];- },- handshakeConfiguration: {- strategy: WebhookHandshakeStrategy.NONE,+ return pandadocWebhook.receive({+ payload: context.payload,+ store: context.store,+ storeKey: STORE_KEY,+ events: EVENTS,+ select: (items) =>+ pandadocWebhook.filterItems({+ apiKey: context.auth.secret_text,+ items: items.filter((item) => item.status === 'document.completed'),+ templateIds: context.propsValue.template_filter,+ folderIds: context.propsValue.folder_filter,+ }),+ });},});++const EVENTS = ['document_state_changed'];+const STORE_KEY = 'pandadoc_document_completed_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/document-creation-failed.ts b/packages/pieces/community/pandadoc/src/lib/triggers/document-creation-failed.tsnew file mode 100644index 00000000000..70ef186991c--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/triggers/document-creation-failed.ts@@ -0,0 +1,46 @@+import { createTrigger, DEDUPE_KEY_PROPERTY, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocCreationFailedSample } from './sample-data';++export const documentCreationFailed = createTrigger({+ auth: pandadocAuth,+ name: 'document_creation_failed',+ classification: 'READ',+ displayName: 'Document Creation Failed',+ description: 'Triggers when PandaDoc fails to create a document requested through the API (for example a bad file or missing field values).',+ aiMetadata: {+ description:+ 'Fires when PandaDoc could not finish creating a document that was requested asynchronously, so the document never reaches draft. Use it to alert someone or retry with corrected input.',+ },+ props: {},+ sampleData: pandadocCreationFailedSample,+ outputSchema: pandadocSchemas['creationFailedEvent'],+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Document Creation Failed',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,+ });+ },+ async onDisable(context) {+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ const items = await pandadocWebhook.receive({ payload: context.payload, store: context.store, storeKey: STORE_KEY, events: EVENTS });+ return items.map((item) => ({ event: item.event, id: item.id, error_type: item.error_type, error_detail: item.error_detail, ...dedupeKey(item) }));+ },+});++function dedupeKey(item: object): Record<string, unknown> {+ const key: unknown = Reflect.get(item, DEDUPE_KEY_PROPERTY);+ return key === undefined ? {} : { [DEDUPE_KEY_PROPERTY]: key };+}++const EVENTS = ['document_creation_failed'];+const STORE_KEY = 'pandadoc_document_creation_failed_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/document-deleted.ts b/packages/pieces/community/pandadoc/src/lib/triggers/document-deleted.tsnew file mode 100644index 00000000000..e39d8cbc3a4--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/triggers/document-deleted.ts@@ -0,0 +1,39 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocSampleEvent } from './sample-data';++export const documentDeleted = createTrigger({+ auth: pandadocAuth,+ name: 'document_deleted',+ classification: 'READ',+ displayName: 'Document Deleted',+ description: 'Triggers when a document is deleted.',+ aiMetadata: {+ description: 'Fires when a PandaDoc document is deleted. Delivers the ID, name and last known status of the deleted document.',+ },+ props: {},+ sampleData: { ...pandadocSampleEvent, event: 'document_deleted' },+ outputSchema: pandadocSchemas['webhookEvent'],+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Document Deleted',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,+ });+ },+ async onDisable(context) {+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return pandadocWebhook.receive({ payload: context.payload, store: context.store, storeKey: STORE_KEY, events: EVENTS });+ },+});++const EVENTS = ['document_deleted'];+const STORE_KEY = 'pandadoc_document_deleted_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/document-state-changed.ts b/packages/pieces/community/pandadoc/src/lib/triggers/document-state-changed.tsindex 25644fad12c..e4f0c21035c 100644--- a/packages/pieces/community/pandadoc/src/lib/triggers/document-state-changed.ts+++ b/packages/pieces/community/pandadoc/src/lib/triggers/document-state-changed.ts@@ -1,21 +1,23 @@-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { WebhookHandshakeStrategy } from '@activepieces/pieces-framework';-import { pandadocAuth } from '../common';+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocSampleEvent } from './sample-data';export const documentStateChanged = createTrigger({+ auth: pandadocAuth,name: 'documentStateChanged',classification: 'READ',displayName: 'Document State Changed',description: 'Triggers when a document status changes.',aiMetadata: {- description: 'Fires whenever a PandaDoc document changes status (e.g. draft, sent, viewed, completed, paid, voided, declined), optionally filtered to specific target statuses. Represents a transition in a document lifecycle.',+ description:+ 'Fires whenever a PandaDoc document changes status (for example draft, sent, viewed, completed, paid, voided or declined), optionally only for selected target statuses. Delivers the document with its new status, recipients, fields and metadata.',},- auth: pandadocAuth,props: {filter_status: Property.StaticMultiSelectDropdown({displayName: 'Filter by Status',- description: 'Only trigger for specific status changes (leave empty for all)',+ description: 'Only trigger when the document moves into one of these statuses (leave empty for all).',required: false,options: {options: [@@ -37,80 +39,33 @@ export const documentStateChanged = createTrigger({},}),},- sampleData: {- event_type: 'document_state_changed',- data: {- id: 'sample_document_id',- name: 'Sample Contract',- status: 'document.sent',- previous_status: 'document.draft',- date_modified: '2024-01-15T10:30:00Z',- date_sent: '2024-01-15T10:30:00Z',- recipients: [- {- id: 'recipient_id',- email: '[email protected]',- has_completed: false,- role: 'Client'- }- ]- }- },+ sampleData: { ...pandadocSampleEvent, status: 'document.sent', date_completed: null },+ outputSchema: pandadocSchemas['webhookEvent'],type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const webhookSubscription = await httpClient.sendRequest({- method: HttpMethod.POST,- url: 'https://api.pandadoc.com/public/v1/webhook-subscriptions',- headers: {- Authorization: `API-Key ${(context.auth.secret_text)}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- name: `Activepieces Document State Changed`,- url: context.webhookUrl,- active: true,- triggers: ['document_state_changed'],- payload: ['fields', 'products', 'tokens', 'metadata', 'pricing'],- }),+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Document State Changed',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,});-- await context.store?.put('webhook_id', webhookSubscription.body.uuid);},async onDisable(context) {- const webhookId = await context.store?.get('webhook_id');- if (webhookId) {- try {- await httpClient.sendRequest({- method: HttpMethod.DELETE,- url: `https://api.pandadoc.com/public/v1/webhook-subscriptions/${webhookId}`,- headers: {- Authorization: `API-Key ${(context.auth.secret_text)}`,- },- });- } catch (error) {- console.log('Error cleaning up webhook:', error);- }- }+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });},async run(context) {- const payload = context.payload.body as any;-- if (payload.event_type === 'document_state_changed') {- const documentData = payload.data;- const currentStatus = documentData?.status;-- if (context.propsValue.filter_status && context.propsValue.filter_status.length > 0) {- if (!context.propsValue.filter_status.includes(currentStatus)) {- return [];- }- }-- return [documentData];- }-- return [];- },- handshakeConfiguration: {- strategy: WebhookHandshakeStrategy.NONE,+ const statuses = context.propsValue.filter_status ?? [];+ return pandadocWebhook.receive({+ payload: context.payload,+ store: context.store,+ storeKey: STORE_KEY,+ events: EVENTS,+ select: (items) => items.filter((item) => statuses.length === 0 || (item.status !== null && statuses.includes(item.status))),+ });},});++const EVENTS = ['document_state_changed'];+const STORE_KEY = 'pandadoc_document_state_changed_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/document-updated.ts b/packages/pieces/community/pandadoc/src/lib/triggers/document-updated.tsindex e202aea52d6..5cd68be0f66 100644--- a/packages/pieces/community/pandadoc/src/lib/triggers/document-updated.ts+++ b/packages/pieces/community/pandadoc/src/lib/triggers/document-updated.ts@@ -1,105 +1,26 @@-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { WebhookHandshakeStrategy } from '@activepieces/pieces-framework';-import { pandadocAuth, pandadocClient } from '../common';+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { folderFilterDropdown, templateFilterDropdown } from '../common/dynamic-dropdowns';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocSampleEvent } from './sample-data';export const documentUpdated = createTrigger({+ auth: pandadocAuth,name: 'documentUpdated',classification: 'READ',displayName: 'Document Updated',- description: 'Triggers when a document is updated.',+ description: 'Triggers when a sent document is moved back to draft so it can be edited.',aiMetadata: {- description: 'Fires when a PandaDoc document is updated, optionally scoped to specific templates, folders, and/or update types (content, recipients, settings, status, fields, name, or metadata changes). Represents an edit to an existing document.',+ description:+ 'Fires when PandaDoc reports a document_updated event, which happens when a sent document is returned to draft for editing. Optionally limited to documents from specific templates or in specific folders. Delivers the document with recipients, fields and metadata.',},- auth: pandadocAuth,props: {- template_filter: Property.MultiSelectDropdown({- auth: pandadocAuth,- displayName: 'Filter by Templates',- description: 'Only trigger for documents created from specific templates (leave empty for all)',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- id: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/templates?count=100');-- const options = response.results.map((template) => ({- label: `${template.name} - ${template.id.substring(0, 8)}...`,- value: template.id,- }));-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load templates',- options: [],- };- }- },- }),- folder_filter: Property.MultiSelectDropdown({- auth: pandadocAuth,- displayName: 'Filter by Folders',- description: 'Only trigger for documents in specific folders (leave empty for all)',- required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Please authenticate first',- options: [],- };- }-- try {- const response = await pandadocClient.makeRequest<{- results: Array<{- uuid: string;- name: string;- date_created: string;- }>;- }>(auth.secret_text, HttpMethod.GET, '/documents/folders?count=100');-- const options = response.results.map((folder) => ({- label: `${folder.name} - ${folder.uuid.substring(0, 8)}...`,- value: folder.uuid,- }));-- return {- disabled: false,- options,- };- } catch (error) {- return {- disabled: true,- placeholder: 'Failed to load folders',- options: [],- };- }- },- }),+ template_filter: templateFilterDropdown,+ folder_filter: folderFilterDropdown,update_type_filter: Property.StaticMultiSelectDropdown({- displayName: 'Filter by Update Type',- description: 'Only trigger for specific types of updates (leave empty for all)',+ displayName: 'Filter by Update Type (no longer used)',+ description: 'PandaDoc does not report which part of a document changed, so this filter is ignored. Leave it empty.',required: false,options: {options: [@@ -114,120 +35,38 @@ export const documentUpdated = createTrigger({},}),},- sampleData: {- event_type: 'document_updated',- data: {- id: 'sample_document_id',- name: 'Sample Contract',- status: 'document.draft',- date_modified: '2024-01-15T10:30:00Z',- content_date_modified: '2024-01-15T10:30:00Z',- updated_fields: ['name', 'recipients'],- template: {- id: 'template_id',- name: 'Contract Template'- },- folder_uuid: 'folder_uuid',- recipients: [- {- id: 'recipient_id',- email: '[email protected]',- has_completed: false,- role: 'Client'- }- ]- }- },+ sampleData: { ...pandadocSampleEvent, event: 'document_updated', status: 'document.draft', date_completed: null },+ outputSchema: pandadocSchemas['webhookEvent'],type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const webhookSubscription = await httpClient.sendRequest({- method: HttpMethod.POST,- url: 'https://api.pandadoc.com/public/v1/webhook-subscriptions',- headers: {- Authorization: `API-Key ${(context.auth.secret_text)}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- name: `Activepieces Document Updated`,- url: context.webhookUrl,- active: true,- triggers: ['document_updated'],- payload: ['fields', 'products', 'tokens', 'metadata', 'pricing'],- }),+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Document Updated',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,});-- await context.store?.put('webhook_id', webhookSubscription.body.uuid);},async onDisable(context) {- const webhookId = await context.store?.get('webhook_id');- if (webhookId) {- try {- await httpClient.sendRequest({- method: HttpMethod.DELETE,- url: `https://api.pandadoc.com/public/v1/webhook-subscriptions/${webhookId}`,- headers: {- Authorization: `API-Key ${(context.auth.secret_text)}`,- },- });- } catch (error) {- console.log('Error cleaning up webhook:', error);- }- }+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });},async run(context) {- const payload = context.payload.body as any;-- if (payload.event_type === 'document_updated') {- const documentData = payload.data;-- if (context.propsValue.template_filter && context.propsValue.template_filter.length > 0) {- const templateId = documentData?.template?.id;- if (!templateId || !context.propsValue.template_filter.includes(templateId)) {- return [];- }- }-- if (context.propsValue.folder_filter && context.propsValue.folder_filter.length > 0) {- const folderUuid = documentData?.folder_uuid;- if (!folderUuid || !context.propsValue.folder_filter.includes(folderUuid)) {- return [];- }- }-- if (context.propsValue.update_type_filter && context.propsValue.update_type_filter.length > 0) {- const updatedFields = documentData?.updated_fields || [];- const hasMatchingUpdate = context.propsValue.update_type_filter.some((filterType: string) => {- switch (filterType) {- case 'content':- return updatedFields.includes('content') || documentData?.content_date_modified;- case 'recipients':- return updatedFields.includes('recipients');- case 'settings':- return updatedFields.includes('settings');- case 'status':- return updatedFields.includes('status');- case 'fields':- return updatedFields.includes('fields');- case 'name':- return updatedFields.includes('name');- case 'metadata':- return updatedFields.includes('metadata');- default:- return false;- }- });-- if (!hasMatchingUpdate) {- return [];- }- }-- return [documentData];- }-- return [];- },- handshakeConfiguration: {- strategy: WebhookHandshakeStrategy.NONE,+ return pandadocWebhook.receive({+ payload: context.payload,+ store: context.store,+ storeKey: STORE_KEY,+ events: EVENTS,+ select: (items) =>+ pandadocWebhook.filterItems({+ apiKey: context.auth.secret_text,+ items,+ templateIds: context.propsValue.template_filter,+ folderIds: context.propsValue.folder_filter,+ }),+ });},});++const EVENTS = ['document_updated'];+const STORE_KEY = 'pandadoc_document_updated_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/recipient-completed.ts b/packages/pieces/community/pandadoc/src/lib/triggers/recipient-completed.tsnew file mode 100644index 00000000000..fdd21b426ad--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/triggers/recipient-completed.ts@@ -0,0 +1,65 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { pandadocAuth } from '../common/auth';+import { folderFilterDropdown, templateFilterDropdown } from '../common/dynamic-dropdowns';+import { pandadocSchemas } from '../common/schemas';+import { pandadocWebhook } from '../common/webhook';+import { pandadocSampleEvent } from './sample-data';++export const recipientCompleted = createTrigger({+ auth: pandadocAuth,+ name: 'recipient_completed',+ classification: 'READ',+ displayName: 'Recipient Completed',+ description: 'Triggers when one recipient finishes their part of a document (signs or approves).',+ aiMetadata: {+ description:+ 'Fires each time a single PandaDoc recipient completes their part of a document, before the whole document is necessarily complete. The action_by fields identify who finished. Optionally limited to specific templates or folders.',+ },+ props: {+ template_filter: templateFilterDropdown,+ folder_filter: folderFilterDropdown,+ },+ sampleData: {+ ...pandadocSampleEvent,+ event: 'recipient_completed',+ template_id: '5Hzwf88ZsNoiMesAMugaPR',+ template_name: 'Invoice',+ action_by_email: '[email protected]',+ action_by_first_name: 'Jane',+ action_by_last_name: 'Doe',+ action_date: '2026-10-20T20:36:10.247Z',+ },+ outputSchema: pandadocSchemas['webhookEvent'],+ type: TriggerStrategy.WEBHOOK,+ async onEnable(context) {+ await pandadocWebhook.subscribe({+ apiKey: context.auth.secret_text,+ webhookUrl: context.webhookUrl,+ name: 'Recipient Completed',+ events: EVENTS,+ store: context.store,+ storeKey: STORE_KEY,+ });+ },+ async onDisable(context) {+ await pandadocWebhook.unsubscribe({ apiKey: context.auth.secret_text, store: context.store, storeKey: STORE_KEY });+ },+ async run(context) {+ return pandadocWebhook.receive({+ payload: context.payload,+ store: context.store,+ storeKey: STORE_KEY,+ events: EVENTS,+ select: (items) =>+ pandadocWebhook.filterItems({+ apiKey: context.auth.secret_text,+ items,+ templateIds: context.propsValue.template_filter,+ folderIds: context.propsValue.folder_filter,+ }),+ });+ },+});++const EVENTS = ['recipient_completed'];+const STORE_KEY = 'pandadoc_recipient_completed_webhook';diff --git a/packages/pieces/community/pandadoc/src/lib/triggers/sample-data.ts b/packages/pieces/community/pandadoc/src/lib/triggers/sample-data.tsnew file mode 100644index 00000000000..83fa073d92b--- /dev/null+++ b/packages/pieces/community/pandadoc/src/lib/triggers/sample-data.ts@@ -0,0 +1,125 @@+export const pandadocSampleEvent = {+ "event": "document_state_changed",+ "id": "75LGDfaNYjJtT3SvaeZ9Li",+ "name": "Sales agreement",+ "status": "document.completed",+ "date_created": "2026-10-20T20:01:41.809699Z",+ "date_modified": "2026-10-20T20:06:46.215915Z",+ "date_sent": null,+ "date_completed": null,+ "expiration_date": "2026-12-19T20:06:21.221924Z",+ "version": "2",+ "ref_number": null,+ "folder_uuid": null,+ "template_id": null,+ "template_name": null,+ "created_by_email": "[email protected]",+ "sent_by_email": "[email protected]",+ "grand_total_amount": "0.00",+ "grand_total_currency": "JOD",+ "tags": [+ "sales"+ ],+ "metadata": {+ "source": "crm",+ "document__created_via_public_api": "true",+ "document__creation_source": "public api"+ },+ "tokens": [],+ "fields": [+ {+ "uuid": "04c0e5f5-c734-4904-a828-6a11ef76c999",+ "name": "like",+ "merge_field": "like",+ "field_id": "checkbox04c0e5f5-c734-4904-a828-6a11ef76c999",+ "type": "checkbox",+ "value": true,+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ },+ {+ "uuid": "28430672-2f72-4a9c-9565-e10efc0dae0f",+ "name": "Text",+ "merge_field": null,+ "field_id": "text28430672-2f72-4a9c-9565-e10efc0dae0f",+ "type": "text",+ "value": "",+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ },+ {+ "uuid": "7f459202-1aba-4105-8b8f-da3e3a855824",+ "name": "name",+ "merge_field": "name",+ "field_id": "text7f459202-1aba-4105-8b8f-da3e3a855824",+ "type": "text",+ "value": "AP Test",+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ },+ {+ "uuid": "e824141d-be7a-4728-8ae9-fb0e97e075cf",+ "name": "Date",+ "merge_field": null,+ "field_id": "datee824141d-be7a-4728-8ae9-fb0e97e075cf",+ "type": "date",+ "value": null,+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ },+ {+ "uuid": "e833ce51-8380-4f0c-9c93-e709b949afd7",+ "name": "Initials",+ "merge_field": null,+ "field_id": "initialse833ce51-8380-4f0c-9c93-e709b949afd7",+ "type": "initials",+ "value": {},+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ },+ {+ "uuid": "eeb86fe0-2414-4f6c-8405-5ded05d47b17",+ "name": "Signature",+ "merge_field": null,+ "field_id": "signatureeeb86fe0-2414-4f6c-8405-5ded05d47b17",+ "type": "signature",+ "value": {},+ "is_filled": null,+ "assigned_to_email": "[email protected]",+ "assigned_to_role": null+ }+ ],+ "recipients": [+ {+ "id": "PoPafStm8fNFL9DdhjATLb",+ "email": "[email protected]",+ "first_name": "Jane",+ "last_name": "Doe",+ "phone": "",+ "role": "",+ "recipient_type": "signer",+ "has_completed": false,+ "signing_order": null,+ "contact_id": "s3ozKL7VJRL3hGdxXcqoJG",+ "shared_link": "https://app.pandadoc.com/document/v2?token=0123456789abcdef0123456789abcdef01234567"+ }+ ],+ "action_by_email": null,+ "action_by_first_name": null,+ "action_by_last_name": null,+ "action_date": null,+ "error_type": null,+ "error_detail": null+};++export const pandadocCreationFailedSample = {+ "event": "document_creation_failed",+ "id": "Hb64Mn5FytFXm5vW9VXvPj",+ "error_type": "validation_error",+ "error_detail": "All field tags within PDF must be declared within 'fields' object of the JSON Payload. No field with optId='like' found in 'fields' object, fields passed were ['name']"+};diff --git a/packages/pieces/community/pandadoc/test/pandadoc.test.ts b/packages/pieces/community/pandadoc/test/pandadoc.test.tsnew file mode 100644index 00000000000..adcdb9109c7--- /dev/null+++ b/packages/pieces/community/pandadoc/test/pandadoc.test.ts@@ -0,0 +1,239 @@+import { createHmac } from 'crypto';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createOrUpdateContact } from '../src/lib/actions/create-or-update-contact';+import { buildPandaDocError, buildPandaDocUrl, fileNameFromDisposition, PandaDocApiError } from '../src/lib/common/client';+import { pandadocInputs, metadataQuery } from '../src/lib/common/inputs';+import { pandadocNormalize } from '../src/lib/common/normalize';+import { pandadocWebhook, WebhookStore } from '../src/lib/common/webhook';++const CAPTURED_BODY =+ '[{"event":"document_creation_failed","data":{"id":"Hb64Mn5FytFXm5vW9VXvPj","error":{"type":"validation_error","detail":"All field tags within PDF must be declared within \'fields\' object of the JSON Payload. No field with optId=\'like\' found in \'fields\' object, fields passed were [\'name\']"}}}]';+const CAPTURED_KEY = '9msLz7xi8zHXke6usg2uNm';+const CAPTURED_SIGNATURE = '1515a53b5f84d2ef17fb04799987c93bb546d2a3f53ea6700fc3aece76864cbf';++function memoryStore(initial: Record<string, unknown> = {}): WebhookStore & { data: Record<string, unknown> } {+ const data: Record<string, unknown> = { ...initial };+ return {+ data,+ async get<T>(key: string): Promise<T | null> {+ return key in data ? Reflect.get(data, key) : null;+ },+ async put<T>(key: string, value: T): Promise<T> {+ data[key] = value;+ return value;+ },+ async delete(key: string): Promise<void> {+ delete data[key];+ },+ };+}++function stateChangedBody(status: string): string {+ return JSON.stringify([{ event: 'document_state_changed', data: { id: 'doc1', name: 'Doc', status, template: { id: 'tpl1', name: 'T' } } }]);+}++function sign({ body, key }: { body: string; key: string }): string {+ return createHmac('sha256', key).update(body).digest('hex');+}++describe('signature verification', () => {+ it('accepts the signature PandaDoc sent for a real delivery', () => {+ expect(pandadocWebhook.verifySignature({ sharedKey: CAPTURED_KEY, rawBody: CAPTURED_BODY, signature: CAPTURED_SIGNATURE })).toBe(true);+ expect(pandadocWebhook.verifySignature({ sharedKey: CAPTURED_KEY, rawBody: Buffer.from(CAPTURED_BODY), signature: CAPTURED_SIGNATURE.toUpperCase() })).toBe(true);+ });++ it('rejects a wrong key, a tampered body, a short signature or a missing raw body', () => {+ expect(pandadocWebhook.verifySignature({ sharedKey: 'other', rawBody: CAPTURED_BODY, signature: CAPTURED_SIGNATURE })).toBe(false);+ expect(pandadocWebhook.verifySignature({ sharedKey: CAPTURED_KEY, rawBody: CAPTURED_BODY + ' ', signature: CAPTURED_SIGNATURE })).toBe(false);+ expect(pandadocWebhook.verifySignature({ sharedKey: CAPTURED_KEY, rawBody: CAPTURED_BODY, signature: 'abc' })).toBe(false);+ expect(pandadocWebhook.verifySignature({ sharedKey: CAPTURED_KEY, rawBody: undefined, signature: CAPTURED_SIGNATURE })).toBe(false);+ });+});++describe('receive', () => {+ const storeKey = 'pandadoc_test_webhook';++ it('rejects unsigned deliveries once a shared key is stored', async () => {+ const store = memoryStore({ [storeKey]: { webhookId: 'w1', sharedKey: 'k1' } });+ const body = stateChangedBody('document.completed');+ const result = await pandadocWebhook.receive({+ payload: { body: JSON.parse(body), rawBody: body, headers: {}, queryParams: {} },+ store,+ storeKey,+ events: ['document_state_changed'],+ });+ expect(result).toEqual([]);+ });++ it('accepts signed deliveries and dedupes by X-PandaDoc-Webhook-Event-Id', async () => {+ const store = memoryStore({ [storeKey]: { webhookId: 'w1', sharedKey: 'k1' } });+ const body = stateChangedBody('document.completed');+ const payload = {+ body: JSON.parse(body),+ rawBody: body,+ headers: { 'X-PandaDoc-Webhook-Event-Id': 'evt-1' },+ queryParams: { signature: sign({ body, key: 'k1' }) },+ };+ const first = await pandadocWebhook.receive({ payload, store, storeKey, events: ['document_state_changed'] });+ expect(first).toHaveLength(1);+ expect(first[0].status).toBe('document.completed');+ expect(first[0].template_id).toBe('tpl1');+ expect(Reflect.get(first[0], '_dedupe_key')).toBe('evt-1:0');+ const second = await pandadocWebhook.receive({ payload, store, storeKey, events: ['document_state_changed'] });+ expect(second).toEqual([]);+ });++ it('leaves no dedupe marker when filtering fails, so a PandaDoc resend is processed', async () => {+ const store = memoryStore({ [storeKey]: { webhookId: 'w1', sharedKey: 'k1' } });+ const body = stateChangedBody('document.completed');+ const payload = {+ body: JSON.parse(body),+ rawBody: body,+ headers: { 'X-PandaDoc-Webhook-Event-Id': 'evt-2' },+ queryParams: { signature: sign({ body, key: 'k1' }) },+ };+ await expect(+ pandadocWebhook.receive({+ payload,+ store,+ storeKey,+ events: ['document_state_changed'],+ select: async () => {+ throw new Error('document lookup failed');+ },+ }),+ ).rejects.toThrow('document lookup failed');+ expect(store.data[`${storeKey}_deliveries`]).toBeUndefined();+ const resend = await pandadocWebhook.receive({ payload, store, storeKey, events: ['document_state_changed'], select: async (items) => items });+ expect(resend).toHaveLength(1);+ expect(Reflect.get(resend[0], '_dedupe_key')).toBe('evt-2:0');+ expect(store.data[`${storeKey}_deliveries`]).toEqual(['evt-2']);+ const duplicate = await pandadocWebhook.receive({ payload, store, storeKey, events: ['document_state_changed'], select: async (items) => items });+ expect(duplicate).toEqual([]);+ });++ it('keeps accepting unsigned deliveries for legacy subscriptions that only stored webhook_id', async () => {+ const store = memoryStore({ webhook_id: 'legacy-uuid' });+ const body = stateChangedBody('document.sent');+ const result = await pandadocWebhook.receive({+ payload: { body, headers: {}, queryParams: {} },+ store,+ storeKey,+ events: ['document_state_changed'],+ });+ expect(result).toHaveLength(1);+ expect(await pandadocWebhook.readStored({ store, storeKey })).toEqual({ webhookId: 'legacy-uuid', sharedKey: null });+ });++ it('ignores events the trigger did not subscribe to', async () => {+ const store = memoryStore();+ const result = await pandadocWebhook.receive({+ payload: { body: CAPTURED_BODY, headers: {}, queryParams: {} },+ store,+ storeKey,+ events: ['document_state_changed'],+ });+ expect(result).toEqual([]);+ });++ it('normalizes a creation failed delivery with its error', async () => {+ const store = memoryStore({ [storeKey]: { webhookId: 'w1', sharedKey: CAPTURED_KEY } });+ const result = await pandadocWebhook.receive({+ payload: { body: JSON.parse(CAPTURED_BODY), rawBody: CAPTURED_BODY, headers: {}, queryParams: { signature: CAPTURED_SIGNATURE } },+ store,+ storeKey,+ events: ['document_creation_failed'],+ });+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('Hb64Mn5FytFXm5vW9VXvPj');+ expect(result[0].error_type).toBe('validation_error');+ expect(result[0].error_detail).toContain("optId='like'");+ });+});++describe('client helpers', () => {+ it('builds URLs with array params and bare flags', () => {+ expect(buildPandaDocUrl({ path: '/documents', flag: 'upload' })).toBe('https://api.pandadoc.com/public/v1/documents?upload');+ expect(buildPandaDocUrl({ path: '/templates', query: { tag: ['a', 'b'], q: undefined, count: 10 } })).toBe(+ 'https://api.pandadoc.com/public/v1/templates?tag=a&tag=b&count=10',+ );+ expect(() => buildPandaDocUrl({ path: '/documents/../members' })).toThrow();+ });++ it('builds readable errors without a body field', () => {+ const error = buildPandaDocError({ status: 429, responseBody: { type: 'request_error', detail: 'Too many requests' } });+ expect(error).toBeInstanceOf(PandaDocApiError);+ expect(error.message).toContain('rate limit');+ expect(error.message).toContain('Too many requests');+ expect('body' in error).toBe(false);+ expect(error.responseBody).toEqual({ type: 'request_error', detail: 'Too many requests' });+ expect(buildPandaDocError({ status: 401, responseBody: { detail: 'Key type is not permitted.' } }).message).toContain('production API key');+ });++ it('reads file names from content-disposition', () => {+ expect(fileNameFromDisposition('attachment; filename="Deal.pdf"')).toBe('Deal.pdf');+ expect(fileNameFromDisposition("attachment; filename*=UTF-8''Sales%20deal.pdf")).toBe('Sales deal.pdf');+ expect(fileNameFromDisposition('attachment; filename="../../etc/passwd"')).toBe('.._.._etc_passwd');+ expect(fileNameFromDisposition(null)).toBeNull();+ });+});++describe('inputs', () => {+ it('wraps field values by merge field name and skips empty ones', () => {+ expect(pandadocInputs.fieldValues({ name: 'Jane', agree: true, empty: '', amount: 5, nested: { value: 'x' } })).toEqual({+ name: { value: 'Jane' },+ agree: { value: true },+ amount: { value: 5 },+ nested: { value: 'x' },+ });+ });++ it('sends a checkbox field only when it was set to Checked or Unchecked', () => {+ expect(pandadocInputs.fieldValues({ agree: undefined, optIn: false, terms: true })).toEqual({+ optIn: { value: false },+ terms: { value: true },+ });+ });++ it('prefixes every metadata filter key, including ones that start with metadata_', () => {+ expect(metadataQuery({ source: 'crm', metadata_id: '7' })).toEqual({ metadata_source: 'crm', metadata_metadata_id: '7' });+ });++ it('maps recipients and requires an email or phone', () => {+ expect(pandadocInputs.recipients([{ email: '[email protected]', role: 'custom', custom_role: 'Client', signing_order: 1 }])).toEqual([+ { email: '[email protected]', role: 'Client', signing_order: 1 },+ ]);+ expect(() => pandadocInputs.recipients([{ first_name: 'x' }])).toThrow();+ });++ it('turns token objects and arrays into PandaDoc tokens', () => {+ expect(pandadocInputs.tokenList({ 'Client.Company': 'Acme' })).toEqual([{ name: 'Client.Company', value: 'Acme' }]);+ expect(pandadocInputs.tokenList([{ name: 'A', value: 1 }])).toEqual([{ name: 'A', value: '1' }]);+ });+});++describe('normalize', () => {+ it('reads field assignees from webhook payloads', () => {+ const field = pandadocNormalize.field({ name: 'like', merge_field: 'like', assignee: '[email protected]', assignee_details: { email: '[email protected]' } });+ expect(field.assigned_to_email).toBe('[email protected]');+ });+});++describe('create or update contact', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('sends cleared text fields as empty strings so PandaDoc clears them', async () => {+ const bodies: unknown[] = [];+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: { body?: string }) => {+ bodies.push(JSON.parse(init.body ?? '{}'));+ return new Response(JSON.stringify({ id: 'c1', email: '[email protected]' }), { status: 200, headers: { 'content-type': 'application/json' } });+ }));+ await Reflect.apply(createOrUpdateContact.run, undefined, [{+ auth: { secret_text: 'key' },+ propsValue: { contact_id: 'c1', company: '', phone: ' ', city: 'Amman' },+ }]);+ expect(bodies[0]).toEqual({ company: '', phone: '', city: 'Amman' });+ });+});diff --git a/packages/pieces/community/pandadoc/vitest.config.ts b/packages/pieces/community/pandadoc/vitest.config.tsnew file mode 100644index 00000000000..ba8ade4a178--- /dev/null+++ b/packages/pieces/community/pandadoc/vitest.config.ts@@ -0,0 +1,17 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})