Skip to content

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

feat(zoho-crm): work with records in any module, watch new and updated records, and add agent actions (#15982)

Odai Ahmad15547e957fb5
diff --git a/bun.lock b/bun.lock
index 75f893bb814..01f160364f7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10227,16 +10227,16 @@
},
"packages/pieces/community/zoho-crm": {
"name": "@activepieces/piece-zoho-crm",
- "version": "0.3.1",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
- "dayjs": "1.11.9",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/zoho-desk": {
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index c700014f177..4f9687a9cd0 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -8,6 +8,16 @@ icon: "hammer"
### What has changed?
+#### Zoho CRM Read File and Custom API Call only send the token to the connection's Zoho CRM hosts
+
+Read File used to send the connection's Zoho access token to whatever URL it was given, including hosts outside Zoho. From Zoho CRM 0.4.0 it only fetches `https` URLs on the connection's own Zoho API host under `/crm/` (for example `https://www.zohoapis.com/crm/bulk/v8/read/<job>/result`), or on that data centre's download hosts (for example `https://download-accl.zoho.com/v2/crm/...` for a data backup). Custom Zoho function URLs (`/crm/.../functions/...`) and URLs in another data centre are refused. Any other URL fails before a request is made. Redirects are followed only to those same hosts; a redirect anywhere else stops the download before that host is requested. The file is streamed, so the deployment's file size limit (`AP_MAX_FILE_SIZE_MB`) applies.
+
+Custom API Call keeps working with paths such as `/Leads` and with full URLs on the connection's own API host (for example `https://www.zohoapis.com/crm/v8/...`). A full URL on any other host, including other Zoho hosts, now fails before a request is made instead of receiving the token.
+
+#### What you need to do
+
+Nothing if your Read File steps point at Zoho CRM backup, bulk-read or API file URLs of the connected account, and your Custom API Call steps use a path or a URL on the connection's API host. If a step calls any other URL, replace it with the HTTP piece's Send HTTP Request action. Steps keep running on the version they were built with until you upgrade them.
+
#### Instagram for Business no longer reports success when a reel fails to publish
Publishing a reel uploads the video to Instagram and then waits for Instagram to finish processing it before the post goes live. The piece used to give up after about a hundred seconds and return the boolean `false`, which the flow recorded as a **successful** step. Anything downstream carried on with `false` where a media id was expected, and nothing in the run said the post had not been published.
diff --git a/packages/pieces/community/zoho-crm/package.json b/packages/pieces/community/zoho-crm/package.json
index a5e2aa42e14..43cc333b9c0 100644
--- a/packages/pieces/community/zoho-crm/package.json
+++ b/packages/pieces/community/zoho-crm/package.json
@@ -1,21 +1,22 @@
{
"name": "@activepieces/piece-zoho-crm",
- "version": "0.3.1",
+ "version": "0.4.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:*",
- "dayjs": "1.11.9",
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/zoho-crm/src/i18n/translation.json b/packages/pieces/community/zoho-crm/src/i18n/translation.json
index 4c1a59e5002..e2be28028ef 100644
--- a/packages/pieces/community/zoho-crm/src/i18n/translation.json
+++ b/packages/pieces/community/zoho-crm/src/i18n/translation.json
@@ -10,32 +10,330 @@
"zohocloud.ca (Canada)": "zohocloud.ca (Canada)",
"Authentication for Zoho CRM": "Authentication for Zoho CRM",
"Read file": "Read file",
+ "Create Record": "Create Record",
+ "Update Record": "Update Record",
+ "Get Record": "Get Record",
+ "Create or Update Record": "Create or Update Record",
+ "Delete Record": "Delete Record",
+ "Convert Lead": "Convert Lead",
+ "Add Note": "Add Note",
+ "Add Tags to Record": "Add Tags to Record",
+ "Upload Attachment": "Upload Attachment",
+ "List Modules": "List Modules",
+ "Get Module Fields": "Get Module Fields",
+ "Get Related Lists": "Get Related Lists",
+ "List Users": "List Users",
+ "Get User": "Get User",
+ "Get Current User": "Get Current User",
+ "List Records": "List Records",
+ "Upsert Record": "Upsert Record",
+ "Create Lead": "Create Lead",
+ "Create Contact": "Create Contact",
+ "Create Deal": "Create Deal",
+ "Create Event": "Create Event",
+ "List Notes": "List Notes",
+ "Get Note": "Get Note",
+ "Create Note": "Create Note",
+ "Update Note": "Update Note",
+ "Delete Note": "Delete Note",
+ "List Tags": "List Tags",
+ "Create Tag": "Create Tag",
+ "Add Tags": "Add Tags",
+ "Remove Tags": "Remove Tags",
+ "List Related Records": "List Related Records",
+ "Link Related Record": "Link Related Record",
+ "List Attachments": "List Attachments",
+ "Attach Link": "Attach Link",
+ "Download Attachment": "Download Attachment",
+ "Create Email Draft": "Create Email Draft",
+ "List Email Drafts": "List Email Drafts",
+ "Update Email Draft": "Update Email Draft",
"Custom API Call": "Custom API Call",
"Download a file content from Zoho CRM. e.g.: a Backup File": "Download a file content from Zoho CRM. e.g.: a Backup File",
+ "Creates a record in any module, including custom fields.": "Creates a record in any module, including custom fields.",
+ "Updates fields of a record in any module. Fields left empty are not changed.": "Updates fields of a record in any module. Fields left empty are not changed.",
+ "Gets a record by id from any module, with all its fields.": "Gets a record by id from any module, with all its fields.",
+ "Updates the record that matches on the duplicate-check fields, or creates it if none matches.": "Updates the record that matches on the duplicate-check fields, or creates it if none matches.",
+ "Deletes a record (it moves to the Zoho CRM Recycle Bin).": "Deletes a record (it moves to the Zoho CRM Recycle Bin).",
+ "Converts a lead into a contact and account, and optionally a deal.": "Converts a lead into a contact and account, and optionally a deal.",
+ "Adds a note to a record.": "Adds a note to a record.",
+ "Adds existing or new tags to a record. New tag names are created first.": "Adds existing or new tags to a record. New tag names are created first.",
+ "Attaches a file to a record.": "Attaches a file to a record.",
+ "Lists the modules available through the API.": "Lists the modules available through the API.",
+ "Lists the fields of a module, custom fields included.": "Lists the fields of a module, custom fields included.",
+ "Lists the related lists of a module.": "Lists the related lists of a module.",
+ "Lists CRM users.": "Lists CRM users.",
+ "Gets a CRM user by id.": "Gets a CRM user by id.",
+ "Gets the connected CRM user.": "Gets the connected CRM user.",
+ "Lists records of a module, one page at a time.": "Lists records of a module, one page at a time.",
+ "Gets one record by id.": "Gets one record by id.",
+ "Creates a record in any module from a JSON object of fields.": "Creates a record in any module from a JSON object of fields.",
+ "Updates the given fields of a record; other fields are unchanged.": "Updates the given fields of a record; other fields are unchanged.",
+ "Deletes a record (moves it to the Recycle Bin).": "Deletes a record (moves it to the Recycle Bin).",
+ "Updates the matching record or creates it.": "Updates the matching record or creates it.",
+ "Creates a lead.": "Creates a lead.",
+ "Creates a contact.": "Creates a contact.",
+ "Creates a deal.": "Creates a deal.",
+ "Creates a calendar event (meeting).": "Creates a calendar event (meeting).",
+ "Converts a lead to a contact, account and optional deal.": "Converts a lead to a contact, account and optional deal.",
+ "Lists notes of a record, or all notes.": "Lists notes of a record, or all notes.",
+ "Gets a note by id.": "Gets a note by id.",
+ "Changes the title or content of a note.": "Changes the title or content of a note.",
+ "Deletes a note.": "Deletes a note.",
+ "Lists the tags of a module.": "Lists the tags of a module.",
+ "Creates a tag in a module, or returns it if it exists.": "Creates a tag in a module, or returns it if it exists.",
+ "Adds tags to one or more records.": "Adds tags to one or more records.",
+ "Removes tags from one or more records.": "Removes tags from one or more records.",
+ "Lists records in a related list of a record.": "Lists records in a related list of a record.",
+ "Associates a record with another record through a related list.": "Associates a record with another record through a related list.",
+ "Lists the attachments of a record.": "Lists the attachments of a record.",
+ "Attaches a URL to a record as a link attachment.": "Attaches a URL to a record as a link attachment.",
+ "Downloads a file attachment of a record.": "Downloads a file attachment of a record.",
+ "Saves an email draft on a record without sending it.": "Saves an email draft on a record without sending it.",
+ "Lists the email drafts saved on a record.": "Lists the email drafts saved on a record.",
+ "Changes an email draft; fields you leave empty keep their value.": "Changes an email draft; fields you leave empty keep their value.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"URL": "URL",
+ "Module": "Module",
+ "Fields": "Fields",
+ "Additional Fields (JSON)": "Additional Fields (JSON)",
+ "Automation to Run": "Automation to Run",
+ "Skip All Automation": "Skip All Automation",
+ "Record": "Record",
+ "Clear Fields": "Clear Fields",
+ "Duplicate Check Fields": "Duplicate Check Fields",
+ "Run Workflows": "Run Workflows",
+ "Lead": "Lead",
+ "Existing Account": "Existing Account",
+ "Existing Contact": "Existing Contact",
+ "Overwrite Contact's Account": "Overwrite Contact's Account",
+ "Owner": "Owner",
+ "Notify Lead Owner": "Notify Lead Owner",
+ "Notify New Owner": "Notify New Owner",
+ "Create a Deal": "Create a Deal",
+ "Deal Name": "Deal Name",
+ "Deal Stage": "Deal Stage",
+ "Deal Closing Date": "Deal Closing Date",
+ "Deal Amount": "Deal Amount",
+ "Deal Pipeline": "Deal Pipeline",
+ "Other Deal Fields (JSON)": "Other Deal Fields (JSON)",
+ "Title": "Title",
+ "Content": "Content",
+ "Existing Tags": "Existing Tags",
+ "New Tag Names": "New Tag Names",
+ "File": "File",
+ "File Name": "File Name",
+ "Module API Name": "Module API Name",
+ "Include Read-Only Fields": "Include Read-Only Fields",
+ "User Type": "User Type",
+ "Page": "Page",
+ "Per Page": "Per Page",
+ "User ID": "User ID",
+ "Page Token": "Page Token",
+ "Sort By": "Sort By",
+ "Sort Order": "Sort Order",
+ "Custom View ID": "Custom View ID",
+ "Record ID": "Record ID",
+ "Data": "Data",
+ "Skip Automation": "Skip Automation",
+ "Append Multi-Select Fields": "Append Multi-Select Fields",
+ "Last Name": "Last Name",
+ "First Name": "First Name",
+ "Company": "Company",
+ "Email": "Email",
+ "Phone": "Phone",
+ "Mobile": "Mobile",
+ "Website": "Website",
+ "Lead Source": "Lead Source",
+ "Lead Status": "Lead Status",
+ "Description": "Description",
+ "Owner User ID": "Owner User ID",
+ "Additional Fields": "Additional Fields",
+ "Account ID": "Account ID",
+ "Mailing Street": "Mailing Street",
+ "Mailing City": "Mailing City",
+ "Mailing State": "Mailing State",
+ "Mailing Zip": "Mailing Zip",
+ "Mailing Country": "Mailing Country",
+ "Stage": "Stage",
+ "Closing Date": "Closing Date",
+ "Amount": "Amount",
+ "Pipeline": "Pipeline",
+ "Contact ID": "Contact ID",
+ "Start": "Start",
+ "End": "End",
+ "All Day": "All Day",
+ "Venue": "Venue",
+ "Related Module": "Related Module",
+ "Related Record ID": "Related Record ID",
+ "Lead ID": "Lead ID",
+ "Existing Account ID": "Existing Account ID",
+ "Existing Contact ID": "Existing Contact ID",
+ "Overwrite Contact Account": "Overwrite Contact Account",
+ "Parent Module": "Parent Module",
+ "Parent Record ID": "Parent Record ID",
+ "Note ID": "Note ID",
+ "Tag Name": "Tag Name",
+ "Color": "Color",
+ "Record IDs": "Record IDs",
+ "Tag Names": "Tag Names",
+ "Related List API Name": "Related List API Name",
+ "Relation Fields": "Relation Fields",
+ "Attachment URL": "Attachment URL",
+ "Attachment ID": "Attachment ID",
+ "From": "From",
+ "To": "To",
+ "Cc": "Cc",
+ "Bcc": "Bcc",
+ "Subject": "Subject",
+ "Body": "Body",
+ "Content Format": "Content Format",
+ "Reply To": "Reply To",
+ "Draft ID": "Draft ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
- "Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "The full URL to use, including the base URL": "The full URL to use, including the base URL",
+ "Full https URL on your Zoho API host (/crm/...) or download host.": "Full https URL on your Zoho API host (/crm/...) or download host.",
+ "The Zoho CRM module (for example Leads, Contacts, Deals or a custom module).": "The Zoho CRM module (for example Leads, Contacts, Deals or a custom module).",
+ "Standard and custom fields of the module. Read-only, formula, subform and file fields are not listed.": "Standard and custom fields of the module. Read-only, formula, subform and file fields are not listed.",
+ "Optional raw fields by API name, for fields the form does not list (e.g. subform rows). Values set in the form above win over the same key here.": "Optional raw fields by API name, for fields the form does not list (e.g. subform rows). Values set in the form above win over the same key here.",
+ "Empty runs Zoho's default workflows; pick some to run only those.": "Empty runs Zoho's default workflows; pick some to run only those.",
+ "Run no workflow, approval or blueprint for this record.": "Run no workflow, approval or blueprint for this record.",
+ "Pick one of the 200 most recently modified records, or map a record id from an earlier step.": "Pick one of the 200 most recently modified records, or map a record id from an earlier step.",
+ "Only the fields you fill in are changed. Use \"Clear Fields\" to blank a field.": "Only the fields you fill in are changed. Use \"Clear Fields\" to blank a field.",
+ "Field API names to set to empty (e.g. \"Phone\", \"Custom_Field__c\").": "Field API names to set to empty (e.g. \"Phone\", \"Custom_Field__c\").",
+ "Run no workflow, approval or blueprint for this update.": "Run no workflow, approval or blueprint for this update.",
+ "Fields used to find an existing record. Leave empty to use Zoho's default (Email for Leads/Contacts, Account_Name for Accounts, Deal_Name for Deals, Name for custom modules).": "Fields used to find an existing record. Leave empty to use Zoho's default (Email for Leads/Contacts, Account_Name for Accounts, Deal_Name for Deals, Name for custom modules).",
+ "Run delete workflows configured in Zoho (Zoho default: on).": "Run delete workflows configured in Zoho (Zoho default: on).",
+ "Link to this account; the lead's Company must match its name.": "Link to this account; the lead's Company must match its name.",
+ "Merge into this contact; the lead's name and email must match.": "Merge into this contact; the lead's name and email must match.",
+ "Move the existing contact to the given account.": "Move the existing contact to the given account.",
+ "Active user who owns the new records; empty keeps the lead owner.": "Active user who owns the new records; empty keeps the lead owner.",
+ "A Stage picklist value of your org, e.g. \"Qualification\".": "A Stage picklist value of your org, e.g. \"Qualification\".",
+ "Date as yyyy-MM-dd, e.g. 2026-12-31.": "Date as yyyy-MM-dd, e.g. 2026-12-31.",
+ "Required when your org uses pipelines, e.g. \"Standard (Standard)\".": "Required when your org uses pipelines, e.g. \"Standard (Standard)\".",
+ "Tags already defined for the module.": "Tags already defined for the module.",
+ "Tag names to create (if missing) and add.": "Tag names to create (if missing) and add.",
+ "Optional. Overrides the file name.": "Optional. Overrides the file name.",
+ "Module API name from List Modules, e.g. \"Leads\", \"Contacts\", \"Deals\", \"Accounts\" or \"CustomModule1\". Not the display label.": "Module API name from List Modules, e.g. \"Leads\", \"Contacts\", \"Deals\", \"Accounts\" or \"CustomModule1\". Not the display label.",
+ "Also list fields that cannot be written (formula, system, auto-number).": "Also list fields that cannot be written (formula, system, auto-number).",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "1 to 200 (default 200).": "1 to 200 (default 200).",
+ "Numeric user id, e.g. \"5725767000000411001\".": "Numeric user id, e.g. \"5725767000000411001\".",
+ "Module API name from List Modules, e.g. \"Leads\", \"Contacts\", \"Deals\" or \"CustomModule1\".": "Module API name from List Modules, e.g. \"Leads\", \"Contacts\", \"Deals\" or \"CustomModule1\".",
+ "Field API names to return (max 50). Leave empty for id, then the custom fields of the module, then its standard fields (50 in total).": "Field API names to return (max 50). Leave empty for id, then the custom fields of the module, then its standard fields (50 in total).",
+ "1 to 200. Default 50.": "1 to 200. Default 50.",
+ "Page number for the first 2,000 records. Do not combine with page_token.": "Page number for the first 2,000 records. Do not combine with page_token.",
+ "next_page_token from a previous call, needed beyond 2,000 records.": "next_page_token from a previous call, needed beyond 2,000 records.",
+ "Optional id of a custom view (cvid) to list only its records.": "Optional id of a custom view (cvid) to list only its records.",
+ "Numeric Zoho record id, e.g. \"5725767000000524157\" (from List Records or a create result).": "Numeric Zoho record id, e.g. \"5725767000000524157\" (from List Records or a create result).",
+ "Optional field API names to return; empty returns all fields.": "Optional field API names to return; empty returns all fields.",
+ "JSON object of field API names to values, e.g. {\"Last_Name\": \"Doe\", \"Email\": \"[email protected]\", \"Owner\": {\"id\": \"5725767000000411001\"}}. Get API names and picklist values from Get Module Fields. Dates as \"2026-10-01\", date-times as \"2026-10-01T09:00:00+02:00\", lookups as {\"id\": \"...\"}.": "JSON object of field API names to values, e.g. {\"Last_Name\": \"Doe\", \"Email\": \"[email protected]\", \"Owner\": {\"id\": \"5725767000000411001\"}}. Get API names and picklist values from Get Module Fields. Dates as \"2026-10-01\", date-times as \"2026-10-01T09:00:00+02:00\", lookups as {\"id\": \"...\"}.",
+ "When true, no workflow, approval or blueprint runs for this change. Default false (Zoho runs its automation).": "When true, no workflow, approval or blueprint runs for this change. Default false (Zoho runs its automation).",
+ "Multi-select picklist API names whose new values should be added to the current ones instead of replacing them.": "Multi-select picklist API names whose new values should be added to the current ones instead of replacing them.",
+ "Default true.": "Default true.",
+ "Field API names to match on, e.g. [\"Email\"]. Empty uses the module default.": "Field API names to match on, e.g. [\"Email\"]. Empty uses the module default.",
+ "Required in many orgs' layouts.": "Required in many orgs' layouts.",
+ "Job title (Designation).": "Job title (Designation).",
+ "A Lead_Source picklist value of your org, e.g. \"Web Download\".": "A Lead_Source picklist value of your org, e.g. \"Web Download\".",
+ "A Lead_Status picklist value of your org, e.g. \"Not Contacted\".": "A Lead_Status picklist value of your org, e.g. \"Not Contacted\".",
+ "Optional user id (from List Users or Get Current User). Default: the connected user.": "Optional user id (from List Users or Get Current User). Default: the connected user.",
+ "Optional JSON of other field API names, including custom fields, e.g. {\"Custom_Field__c\": \"x\"}. The named props above win over the same key here.": "Optional JSON of other field API names, including custom fields, e.g. {\"Custom_Field__c\": \"x\"}. The named props above win over the same key here.",
+ "Id of an existing Accounts record.": "Id of an existing Accounts record.",
+ "yyyy-MM-dd, e.g. \"2026-12-31\". Required in many layouts.": "yyyy-MM-dd, e.g. \"2026-12-31\". Required in many layouts.",
+ "Pipeline name when the org uses pipelines, e.g. \"Standard (Standard)\".": "Pipeline name when the org uses pipelines, e.g. \"Standard (Standard)\".",
+ "ISO 8601 with offset, e.g. \"2026-10-01T09:00:00+02:00\".": "ISO 8601 with offset, e.g. \"2026-10-01T09:00:00+02:00\".",
+ "ISO 8601 with offset, after Start.": "ISO 8601 with offset, after Start.",
+ "Module API name of the record to link (What_Id), e.g. \"Deals\" or \"Accounts\". Give with related_record_id.": "Module API name of the record to link (What_Id), e.g. \"Deals\" or \"Accounts\". Give with related_record_id.",
+ "Set to also create a deal.": "Set to also create a deal.",
+ "yyyy-MM-dd.": "yyyy-MM-dd.",
+ "Module API name of the record, e.g. \"Leads\". Give with parent_id.": "Module API name of the record, e.g. \"Leads\". Give with parent_id.",
+ "1 to 200 (default 50).": "1 to 200 (default 50).",
+ "Numeric note id from List Notes.": "Numeric note id from List Notes.",
+ "Module API name from List Modules, e.g. \"Leads\" or \"Deals\".": "Module API name from List Modules, e.g. \"Leads\" or \"Deals\".",
+ "Numeric record ids (max 500).": "Numeric record ids (max 500).",
+ "Tag names, e.g. [\"VIP\", \"Webinar 2026\"].": "Tag names, e.g. [\"VIP\", \"Webinar 2026\"].",
+ "Module API name of the parent record, e.g. \"Accounts\" or \"Leads\".": "Module API name of the parent record, e.g. \"Accounts\" or \"Leads\".",
+ "Numeric id of the parent record.": "Numeric id of the parent record.",
+ "api_name from Get Related Lists, e.g. \"Contacts\", \"Deals\", \"Campaigns\", \"Products\".": "api_name from Get Related Lists, e.g. \"Contacts\", \"Deals\", \"Campaigns\", \"Products\".",
+ "Field API names to return (max 50).": "Field API names to return (max 50).",
+ "next_page_token from a previous call (beyond 2,000 records).": "next_page_token from a previous call (beyond 2,000 records).",
+ "Id of the record to link.": "Id of the record to link.",
+ "Optional fields of the relation, e.g. {\"Member_Status\": \"Invited\"}.": "Optional fields of the relation, e.g. {\"Member_Status\": \"Invited\"}.",
+ "Full URL, e.g. \"https://example.com/proposal.pdf\".": "Full URL, e.g. \"https://example.com/proposal.pdf\".",
+ "Module of the record, e.g. \"Leads\", \"Contacts\", \"Deals\" or \"Accounts\".": "Module of the record, e.g. \"Leads\", \"Contacts\", \"Deals\" or \"Accounts\".",
+ "Numeric id of the record the draft belongs to.": "Numeric id of the record the draft belongs to.",
+ "Sender email, e.g. the connected user's email.": "Sender email, e.g. the connected user's email.",
+ "Recipient emails.": "Recipient emails.",
+ "HTML (rich text) or plain text. Default HTML.": "HTML (rich text) or plain text. Default HTML.",
+ "Optional: return only this draft.": "Optional: return only this draft.",
+ "1 to 10 (Zoho maximum 10).": "1 to 10 (Zoho maximum 10).",
+ "Draft id from List Email Drafts (a long hex string).": "Draft id from List Email Drafts (a long hex string).",
+ "Replaces the To list; omit it to keep the current list.": "Replaces the To list; omit it to keep the current list.",
+ "Replaces the Cc list; omit it to keep the current list.": "Replaces the Cc list; omit it to keep the current list.",
+ "Replaces the Bcc list; omit it to keep the current list.": "Replaces the Bcc list; omit it to keep the current list.",
+ "Leave empty to keep the current format.": "Leave empty to keep the current format.",
"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.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "workflow": "workflow",
+ "approval": "approval",
+ "blueprint": "blueprint",
+ "pathfinder": "pathfinder",
+ "orchestration": "orchestration",
+ "AllUsers": "AllUsers",
+ "ActiveUsers": "ActiveUsers",
+ "DeactiveUsers": "DeactiveUsers",
+ "ConfirmedUsers": "ConfirmedUsers",
+ "NotConfirmedUsers": "NotConfirmedUsers",
+ "DeletedUsers": "DeletedUsers",
+ "ActiveConfirmedUsers": "ActiveConfirmedUsers",
+ "AdminUsers": "AdminUsers",
+ "ActiveConfirmedAdmins": "ActiveConfirmedAdmins",
+ "id": "id",
+ "Created_Time": "Created_Time",
+ "Modified_Time": "Modified_Time",
+ "Descending": "Descending",
+ "Ascending": "Ascending",
+ "#F17574": "#F17574",
+ "#F48435": "#F48435",
+ "#E7A826": "#E7A826",
+ "#A8C026": "#A8C026",
+ "#63C57E": "#63C57E",
+ "#1DB9B4": "#1DB9B4",
+ "#57B1FD": "#57B1FD",
+ "#879BFC": "#879BFC",
+ "#D297EE": "#D297EE",
+ "#FD87BD": "#FD87BD",
+ "#969696": "#969696",
+ "#658BA8": "#658BA8",
+ "#B88562": "#B88562",
+ "HTML": "HTML",
+ "Plain text": "Plain text",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Contact": "New Contact",
- "Triggers when a new contact is created": "Triggers when a new contact is created"
+ "New Record": "New Record",
+ "Updated Record": "Updated Record",
+ "Triggers when a new contact is created": "Triggers when a new contact is created",
+ "Triggers when a record is created in any module (custom fields included).": "Triggers when a record is created in any module (custom fields included).",
+ "Triggers when a record is modified in any module.": "Triggers when a record is modified in any module.",
+ "Fields to Include": "Fields to Include",
+ "Include Newly Created Records": "Include Newly Created Records",
+ "Optional. Up to 4 extra Contacts fields (for example custom fields) to include. Zoho returns at most 50 fields per record and this trigger already requests 46 standard ones.": "Optional. Up to 4 extra Contacts fields (for example custom fields) to include. Zoho returns at most 50 fields per record and this trigger already requests 46 standard ones.",
+ "The module to watch (standard or custom).": "The module to watch (standard or custom).",
+ "Optional, up to 47. Leave empty for id, then custom, then standard fields (50 in total).": "Optional, up to 47. Leave empty for id, then custom, then standard fields (50 in total).",
+ "Also fire for records created but not edited since the last check.": "Also fire for records created but not edited since the last check."
}
\ No newline at end of file
diff --git a/packages/pieces/community/zoho-crm/src/index.ts b/packages/pieces/community/zoho-crm/src/index.ts
index d6bcc9dfe9c..3500cd919da 100644
--- a/packages/pieces/community/zoho-crm/src/index.ts
+++ b/packages/pieces/community/zoho-crm/src/index.ts
@@ -1,13 +1,21 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- OAuth2PropertyValue,
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { newContact } from './lib/triggers/new-contact';
+import { newRecordTrigger } from './lib/triggers/new-record';
+import { updatedRecordTrigger } from './lib/triggers/updated-record';
import { readFile } from './lib/actions/read-file';
+import { createRecordAction } from './lib/actions/create-record';
+import { updateRecordAction } from './lib/actions/update-record';
+import { getRecordAction } from './lib/actions/get-record';
+import { upsertRecordAction } from './lib/actions/upsert-record';
+import { deleteRecordAction } from './lib/actions/delete-record';
+import { convertLeadAction } from './lib/actions/convert-lead';
+import { addNoteAction } from './lib/actions/add-note';
+import { addTagsToRecordAction } from './lib/actions/add-tags-to-record';
+import { uploadAttachmentAction } from './lib/actions/upload-attachment';
+import { zohoAiActions } from './lib/actions/ai';
+import { customApiAuthHeaders, getApiDomain, readField } from './lib/common/client';
import { zohoCrmAuth } from './lib/auth';
export const zohoCrm = createPiece({
@@ -15,24 +23,37 @@ export const zohoCrm = createPiece({
description: 'Customer relationship management software',
logoUrl: 'https://cdn.activepieces.com/pieces/zoho-crm.png',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
categories: [PieceCategory.SALES_AND_CRM],
authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud","ikus060"],
auth: zohoCrmAuth,
actions: [
readFile,
+ createRecordAction,
+ updateRecordAction,
+ getRecordAction,
+ upsertRecordAction,
+ deleteRecordAction,
+ convertLeadAction,
+ addNoteAction,
+ addTagsToRecordAction,
+ uploadAttachmentAction,
+ ...zohoAiActions,
createCustomApiCallAction({
- baseUrl: (auth) =>
- {
- const data = (auth as OAuth2PropertyValue).data;
- return data && data['api_domain']? `${data['api_domain']}/crm/v3` : ''
- },
-
+ baseUrl: (auth) => {
+ if (!auth) {
+ return '';
+ }
+ try {
+ return `${getApiDomain(auth)}/crm/v3`;
+ } catch {
+ return '';
+ }
+ },
+
auth: zohoCrmAuth,
- authMapping: async (auth) => ({
- Authorization: `Zoho-oauthtoken ${(auth as OAuth2PropertyValue).access_token}`,
- }),
+ authMapping: async (auth, propsValue) => customApiAuthHeaders({ auth, url: readField({ value: propsValue['url'], key: 'url' }) }),
}),
],
- triggers: [newContact],
+ triggers: [newContact, newRecordTrigger, updatedRecordTrigger],
});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/add-note.ts b/packages/pieces/community/zoho-crm/src/lib/actions/add-note.ts
new file mode 100644
index 00000000000..32733a59bdd
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/add-note.ts
@@ -0,0 +1,36 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName, requireId } from '../common/client';
+import { moduleDropdown, recordDropdown } from '../common/props';
+import { createNote } from '../common/records';
+import { childWriteOutputSchema } from '../output-schemas';
+
+export const addNoteAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'add_note',
+ classification: 'WRITE',
+ displayName: 'Add Note',
+ description: 'Adds a note to a record.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds a note (optional title plus content) to one Zoho CRM record in any module. Use to log a call summary or context on a lead, contact, deal or account. Not idempotent: each call adds another note.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown(),
+ record_id: recordDropdown(),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ },
+ outputSchema: childWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ return createNote({
+ auth,
+ module: requireApiName({ value: propsValue.module, name: 'Module' }),
+ recordId: requireId({ value: propsValue.record_id, name: 'Record' }),
+ title: propsValue.title,
+ content: propsValue.content,
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/add-tags-to-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/add-tags-to-record.ts
new file mode 100644
index 00000000000..710b07084e8
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/add-tags-to-record.ts
@@ -0,0 +1,48 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { ZohoCrmError, requireApiName, requireId, stringList } from '../common/client';
+import { moduleDropdown, recordDropdown, tagsDropdown } from '../common/props';
+import { changeTags, ensureTag } from '../common/records';
+import { tagChangeOutputSchema } from '../output-schemas';
+
+export const addTagsToRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'add_tags_to_record',
+ classification: 'WRITE',
+ displayName: 'Add Tags to Record',
+ description: 'Adds existing or new tags to a record. New tag names are created first.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds tags to one Zoho CRM record, creating any tag name that does not exist yet in the module. Existing tags on the record are kept. Idempotent: adding a tag the record already has changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ module: moduleDropdown(),
+ record_id: recordDropdown(),
+ tags: tagsDropdown(),
+ new_tags: Property.Array({
+ displayName: 'New Tag Names',
+ description: 'Tag names to create (if missing) and add.',
+ required: false,
+ }),
+ },
+ outputSchema: tagChangeOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module, name: 'Module' });
+ const recordId = requireId({ value: propsValue.record_id, name: 'Record' });
+ const existing = stringList(propsValue.tags);
+ const created = stringList(propsValue.new_tags);
+ const names = [...new Set([...existing, ...created])];
+ if (names.length === 0) {
+ throw new ZohoCrmError('Choose at least one tag or enter a new tag name.');
+ }
+ if (names.length > 10) {
+ throw new ZohoCrmError('Zoho allows at most 10 tags per record.');
+ }
+ for (const name of created) {
+ await ensureTag({ auth, module, name });
+ }
+ return changeTags({ auth, module, recordIds: [recordId], tags: names.map((name) => ({ name })), mode: 'add' });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/drafts.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/drafts.ts
new file mode 100644
index 00000000000..ff880926d46
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/drafts.ts
@@ -0,0 +1,271 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import {
+ ZohoAuth,
+ ZohoCrmError,
+ optionalInt,
+ readField,
+ readString,
+ requireApiName,
+ requireId,
+ requireKey,
+ stringList,
+ unwrapWriteItem,
+ zohoRequest,
+ validatePaging,
+} from '../../common/client';
+import { flattenDraft } from '../../common/flatten';
+import { draftWriteOutputSchema, listDraftsOutputSchema } from '../../output-schemas-ai';
+
+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+const moduleApiName = Property.ShortText({
+ displayName: 'Module API Name',
+ description: 'Module of the record, e.g. "Leads", "Contacts", "Deals" or "Accounts".',
+ required: true,
+});
+const recordId = Property.ShortText({ displayName: 'Record ID', description: 'Numeric id of the record the draft belongs to.', required: true });
+const draftId = Property.ShortText({ displayName: 'Draft ID', description: 'Draft id from List Email Drafts (a long hex string).', required: true });
+
+function email({ value, name }: { value: unknown; name: string }): string {
+ const s = typeof value === 'string' ? value.trim() : '';
+ if (!EMAIL_RE.test(s)) throw new ZohoCrmError(`${name} must be an email address.`);
+ return s;
+}
+
+function recipients({ value, name }: { value: unknown; name: string }): { email: string }[] | undefined {
+ if (value === undefined || value === null) return undefined;
+ return stringList(value).map((v) => ({ email: email({ value: v, name }) }));
+}
+
+function replacementRecipients({ value, name }: { value: unknown; name: string }): { email: string }[] | undefined {
+ const list = recipients({ value, name });
+ if (list !== undefined && list.length === 0) {
+ throw new ZohoCrmError(`${name} is empty. Zoho keeps a draft's ${name} recipients when asked to remove them all, so pass the new addresses, or leave ${name} out to keep the current list.`);
+ }
+ return list;
+}
+
+function draftPath({ module, id }: { module: string; id: string }): string {
+ return `/${encodeURIComponent(module)}/${id}/__email_drafts`;
+}
+
+async function fetchDraft({ auth, module, id, draft }: { auth: ZohoAuth; module: string; id: string; draft: string }): Promise<Record<string, unknown>> {
+ const body = await zohoRequest<{ __email_drafts?: Record<string, unknown>[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: `${draftPath({ module, id })}/${draft}`,
+ });
+ const found = body?.__email_drafts?.[0];
+ if (!found) throw new ZohoCrmError(`No draft ${draft} on ${module} ${id}.`, 404, 'NOT_FOUND');
+ return found;
+}
+
+function toRecipientObjects(value: unknown): { email: string; user_name?: string }[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ return value.flatMap((v) => {
+ if (typeof v === 'string') return [{ email: v }];
+ const address = readString(readField({ value: v, key: 'email' }));
+ if (address === undefined) return [];
+ const userName = readString(readField({ value: v, key: 'user_name' }));
+ return [{ email: address, ...(userName !== undefined ? { user_name: userName } : {}) }];
+ });
+}
+
+function emailFrom(value: unknown): string | undefined {
+ if (typeof value === 'string') return value;
+ return readString(readField({ value, key: 'email' }));
+}
+
+export function mergeDraft({
+ current,
+ changes,
+ draft,
+}: {
+ current: Record<string, unknown>;
+ changes: DraftChanges;
+ draft: string;
+}): Record<string, unknown> {
+ const merged: Record<string, unknown> = {
+ id: draft,
+ from: changes.from ?? emailFrom(current['from']),
+ rich_text: changes.rich_text ?? (typeof current['rich_text'] === 'boolean' ? current['rich_text'] : true),
+ };
+ const to = changes.to ?? toRecipientObjects(current['to']);
+ const cc = changes.cc ?? toRecipientObjects(current['cc']);
+ const bcc = changes.bcc ?? toRecipientObjects(current['bcc']);
+ if (to) merged['to'] = to;
+ if (cc) merged['cc'] = cc;
+ if (bcc) merged['bcc'] = bcc;
+ const subject = changes.subject ?? current['subject'];
+ const content = changes.content ?? current['content'];
+ const replyTo = changes.reply_to ?? emailFrom(current['reply_to']);
+ if (typeof subject === 'string') merged['subject'] = subject;
+ if (typeof content === 'string') merged['content'] = content;
+ if (replyTo) merged['reply_to'] = replyTo;
+ if (current['schedule_details']) merged['schedule_details'] = current['schedule_details'];
+ if (Array.isArray(current['attachments']) && current['attachments'].length > 0) {
+ merged['attachments'] = current['attachments'];
+ }
+ if (!merged['from']) throw new ZohoCrmError('The draft has no from address; pass from.');
+ return merged;
+}
+
+const richTextProp = (forUpdate: boolean) =>
+ Property.StaticDropdown({
+ displayName: 'Content Format',
+ description: forUpdate ? 'Leave empty to keep the current format.' : 'HTML (rich text) or plain text. Default HTML.',
+ required: false,
+ options: { options: [{ label: 'HTML', value: 'true' }, { label: 'Plain text', value: 'false' }] },
+ });
+
+function richText(value: unknown): boolean | undefined {
+ if (value === 'true' || value === true) return true;
+ if (value === 'false' || value === false) return false;
+ return undefined;
+}
+
+export const createEmailDraftAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_email_draft',
+ classification: 'WRITE',
+ displayName: 'Create Email Draft',
+ description: 'Saves an email draft on a record without sending it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Saves an email draft (from, to, cc, bcc, subject, body) in the Emails related list of one Zoho CRM record, without sending it; a person can review and send it from the CRM. The from address must be one the connected user may send from (their own email, see Get Current User). Not idempotent: each call saves another draft.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ from: Property.ShortText({ displayName: 'From', description: 'Sender email, e.g. the connected user\'s email.', required: true }),
+ to: Property.Array({ displayName: 'To', description: 'Recipient emails.', required: false }),
+ cc: Property.Array({ displayName: 'Cc', required: false }),
+ bcc: Property.Array({ displayName: 'Bcc', required: false }),
+ subject: Property.ShortText({ displayName: 'Subject', required: false }),
+ content: Property.LongText({ displayName: 'Body', required: false }),
+ rich_text: richTextProp(false),
+ reply_to: Property.ShortText({ displayName: 'Reply To', required: false }),
+ },
+ outputSchema: draftWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const to = recipients({ value: p.to, name: 'to' });
+ const cc = recipients({ value: p.cc, name: 'cc' });
+ const bcc = recipients({ value: p.bcc, name: 'bcc' });
+ const draft: Record<string, unknown> = {
+ from: email({ value: p.from, name: 'from' }),
+ rich_text: richText(p.rich_text) ?? true,
+ ...(to && to.length > 0 ? { to } : {}),
+ ...(cc && cc.length > 0 ? { cc } : {}),
+ ...(bcc && bcc.length > 0 ? { bcc } : {}),
+ ...(p.subject ? { subject: p.subject } : {}),
+ ...(p.content ? { content: p.content } : {}),
+ ...(p.reply_to ? { reply_to: email({ value: p.reply_to, name: 'reply_to' }) } : {}),
+ };
+ const body = await zohoRequest<unknown>({ auth, method: HttpMethod.POST, path: draftPath({ module, id }), body: { __email_drafts: [draft] } });
+ const item = unwrapWriteItem({ body, key: '__email_drafts' });
+ return { id: readString(item.details?.['id']) ?? null, module, record_id: id, status: item.status ?? null, message: item.message ?? null };
+ },
+});
+
+export const listEmailDraftsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_email_drafts',
+ classification: 'SEARCH',
+ displayName: 'List Email Drafts',
+ description: 'Lists the email drafts saved on a record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists email drafts saved on one Zoho CRM record (at most 10 per page), or returns one draft when draft_id is given. Use to find a draft id before Update Email Draft. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ draft_id: Property.ShortText({ displayName: 'Draft ID', description: 'Optional: return only this draft.', required: false }),
+ page: Property.Number({ displayName: 'Page', required: false }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 10 (Zoho maximum 10).', required: false }),
+ },
+ outputSchema: listDraftsOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const draft = p.draft_id ? requireKey({ value: p.draft_id, name: 'draft_id' }) : undefined;
+ const page = optionalInt({ value: p.page, name: 'page', min: 1, max: 2000 });
+ const perPage = optionalInt({ value: p.per_page, name: 'per_page', min: 1, max: 10 });
+ validatePaging({ page, perPage: perPage ?? 10, tokenSupported: false });
+ const body = await zohoRequest<{ __email_drafts?: Record<string, unknown>[]; info?: { more_records?: boolean } }>({
+ auth,
+ method: HttpMethod.GET,
+ path: draft ? `${draftPath({ module, id })}/${draft}` : draftPath({ module, id }),
+ query: draft ? undefined : { ...(page ? { page: String(page) } : {}), ...(perPage ? { per_page: String(perPage) } : {}) },
+ });
+ const drafts = (body?.__email_drafts ?? []).map(flattenDraft);
+ return { drafts, count: drafts.length, more_records: body?.info?.more_records === true };
+ },
+});
+
+export const updateEmailDraftAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_update_email_draft',
+ classification: 'WRITE',
+ displayName: 'Update Email Draft',
+ description: 'Changes an email draft; fields you leave empty keep their value.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes an existing email draft on a Zoho CRM record without sending it; it reads the draft first and keeps every field you do not pass (recipients, subject, body, attachments, schedule). A recipient list you pass replaces that list; Zoho cannot empty a list, so an empty list is refused. Idempotent: the same changes give the same draft.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ draft_id: draftId,
+ from: Property.ShortText({ displayName: 'From', required: false }),
+ to: Property.Array({ displayName: 'To', description: 'Replaces the To list; omit it to keep the current list.', required: false }),
+ cc: Property.Array({ displayName: 'Cc', description: 'Replaces the Cc list; omit it to keep the current list.', required: false }),
+ bcc: Property.Array({ displayName: 'Bcc', description: 'Replaces the Bcc list; omit it to keep the current list.', required: false }),
+ subject: Property.ShortText({ displayName: 'Subject', required: false }),
+ content: Property.LongText({ displayName: 'Body', required: false }),
+ rich_text: richTextProp(true),
+ reply_to: Property.ShortText({ displayName: 'Reply To', required: false }),
+ },
+ outputSchema: draftWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const draft = requireKey({ value: p.draft_id, name: 'draft_id' });
+ const changes: DraftChanges = {
+ from: p.from ? email({ value: p.from, name: 'from' }) : undefined,
+ to: replacementRecipients({ value: p.to, name: 'to' }),
+ cc: replacementRecipients({ value: p.cc, name: 'cc' }),
+ bcc: replacementRecipients({ value: p.bcc, name: 'bcc' }),
+ subject: p.subject || undefined,
+ content: p.content || undefined,
+ rich_text: richText(p.rich_text),
+ reply_to: p.reply_to ? email({ value: p.reply_to, name: 'reply_to' }) : undefined,
+ };
+ const current = await fetchDraft({ auth, module, id, draft });
+ const merged = mergeDraft({ current, changes, draft });
+ const body = await zohoRequest<unknown>({ auth, method: HttpMethod.PUT, path: draftPath({ module, id }), body: { __email_drafts: [merged] } });
+ const item = unwrapWriteItem({ body, key: '__email_drafts' });
+ return { id: readString(item.details?.['id']) ?? draft, module, record_id: id, status: item.status ?? null, message: item.message ?? null };
+ },
+});
+
+type DraftChanges = {
+ from?: string;
+ to?: { email: string }[];
+ cc?: { email: string }[];
+ bcc?: { email: string }[];
+ subject?: string;
+ content?: string;
+ rich_text?: boolean;
+ reply_to?: string;
+};
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/index.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/index.ts
new file mode 100644
index 00000000000..3005db3267e
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/index.ts
@@ -0,0 +1,73 @@
+import {
+ getCurrentUserAtomic,
+ getModuleFieldsAtomic,
+ getRelatedListsAtomic,
+ getUserAtomic,
+ listModulesAtomic,
+ listUsersAtomic,
+} from './metadata';
+import {
+ createRecordAtomic,
+ deleteRecordAtomic,
+ getRecordAtomic,
+ listRecordsAtomic,
+ updateRecordAtomic,
+ upsertRecordAtomic,
+} from './records';
+import { convertLeadAtomic, createContactAtomic, createDealAtomic, createEventAtomic, createLeadAtomic } from './typed';
+import {
+ addTagsAtomic,
+ createNoteAtomic,
+ createTagAtomic,
+ deleteNoteAtomic,
+ getNoteAtomic,
+ listNotesAtomic,
+ listTagsAtomic,
+ removeTagsAtomic,
+ updateNoteAtomic,
+} from './notes-tags';
+import {
+ downloadAttachmentAtomic,
+ listRelatedRecordsAtomic,
+ linkRelatedRecordAtomic,
+ listAttachmentsAtomic,
+ uploadAttachmentAtomic,
+} from './related-attachments';
+import { createEmailDraftAtomic, listEmailDraftsAtomic, updateEmailDraftAtomic } from './drafts';
+
+export const zohoAiActions = [
+ listModulesAtomic,
+ getModuleFieldsAtomic,
+ getRelatedListsAtomic,
+ listUsersAtomic,
+ getUserAtomic,
+ getCurrentUserAtomic,
+ listRecordsAtomic,
+ getRecordAtomic,
+ createRecordAtomic,
+ updateRecordAtomic,
+ deleteRecordAtomic,
+ upsertRecordAtomic,
+ createLeadAtomic,
+ createContactAtomic,
+ createDealAtomic,
+ createEventAtomic,
+ convertLeadAtomic,
+ listNotesAtomic,
+ getNoteAtomic,
+ createNoteAtomic,
+ updateNoteAtomic,
+ deleteNoteAtomic,
+ listTagsAtomic,
+ createTagAtomic,
+ addTagsAtomic,
+ removeTagsAtomic,
+ listRelatedRecordsAtomic,
+ linkRelatedRecordAtomic,
+ listAttachmentsAtomic,
+ uploadAttachmentAtomic,
+ downloadAttachmentAtomic,
+ createEmailDraftAtomic,
+ listEmailDraftsAtomic,
+ updateEmailDraftAtomic,
+];
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/metadata.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/metadata.ts
new file mode 100644
index 00000000000..aaf02be5f4e
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/metadata.ts
@@ -0,0 +1,237 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import { ZohoCrmError, optionalInt, requireApiName, requireId, validatePaging, zohoRequest } from '../../common/client';
+import { flattenRelatedList, flattenUser } from '../../common/flatten';
+import { isApiReadOnly } from '../../common/fields';
+import { listFields, listModules } from '../../common/metadata';
+import {
+ listModulesOutputSchema,
+ listUsersOutputSchema,
+ moduleFieldsOutputSchema,
+ relatedListsOutputSchema,
+ userOutputSchema,
+} from '../../output-schemas-ai';
+
+const moduleApiName = Property.ShortText({
+ displayName: 'Module API Name',
+ description: 'Module API name from List Modules, e.g. "Leads", "Contacts", "Deals", "Accounts" or "CustomModule1". Not the display label.',
+ required: true,
+});
+
+export const listModulesAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_modules',
+ classification: 'SEARCH',
+ displayName: 'List Modules',
+ description: 'Lists the modules available through the API.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Zoho CRM modules the API can use, with each module\'s API name, labels and whether records can be created, edited or deleted. Call this first to get the module_api_name every record, note, tag and attachment action needs; the API name can differ from the label (e.g. "Deals" labelled "Opportunities", custom modules named "CustomModule1"). Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: listModulesOutputSchema,
+ async run({ auth }) {
+ const modules = (await listModules(auth))
+ .filter((m) => m.api_supported !== false)
+ .map((m) => ({
+ api_name: m.api_name,
+ module_name: m.module_name ?? null,
+ plural_label: m.plural_label ?? null,
+ singular_label: m.singular_label ?? null,
+ generated_type: m.generated_type ?? null,
+ creatable: m.creatable ?? null,
+ editable: m.editable ?? null,
+ deletable: m.deletable ?? null,
+ }));
+ return { modules, count: modules.length };
+ },
+});
+
+export const getModuleFieldsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_module_fields',
+ classification: 'SEARCH',
+ displayName: 'Get Module Fields',
+ description: 'Lists the fields of a module, custom fields included.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every field of one Zoho CRM module with its API name, label, data type, whether it is required on create, read-only status, picklist values and lookup target. Call before creating or updating records to learn field API names, allowed picklist values (e.g. Deal Stage) and custom fields. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ include_read_only: Property.Checkbox({
+ displayName: 'Include Read-Only Fields',
+ description: 'Also list fields that cannot be written (formula, system, auto-number).',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ outputSchema: moduleFieldsOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' });
+ const all = await listFields({ auth, module: module });
+ const fields = all
+ .filter((f) => f.visible !== false)
+ .filter((f) => propsValue.include_read_only !== false || !isApiReadOnly(f))
+ .map((f) => ({
+ api_name: f.api_name,
+ field_label: f.display_label ?? f.field_label ?? f.api_name,
+ data_type: f.data_type ?? null,
+ required: f.system_mandatory === true,
+ read_only: isApiReadOnly(f),
+ custom_field: f.custom_field === true,
+ lookup_module: f.lookup?.module?.api_name ?? null,
+ max_length: f.length ?? null,
+ picklist_values: (f.pick_list_values ?? [])
+ .map((p) => p.actual_value)
+ .filter((v): v is string => typeof v === 'string' && v !== '-None-'),
+ }));
+ return { module, fields, count: fields.length };
+ },
+});
+
+export const getRelatedListsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_related_lists',
+ classification: 'SEARCH',
+ displayName: 'Get Related Lists',
+ description: 'Lists the related lists of a module.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the related lists of one Zoho CRM module (e.g. Contacts, Deals or Campaigns under Accounts) with the related_list API name and the related module. Call before List Related Records or Link Related Record to get the related_list_api_name. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: { module_api_name: moduleApiName },
+ outputSchema: relatedListsOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' });
+ const body = await zohoRequest<{ related_lists?: Record<string, unknown>[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/related_lists',
+ query: { module },
+ });
+ const related_lists = (body?.related_lists ?? []).map(flattenRelatedList);
+ return { module, related_lists, count: related_lists.length };
+ },
+});
+
+const USER_TYPES = [
+ 'AllUsers',
+ 'ActiveUsers',
+ 'DeactiveUsers',
+ 'ConfirmedUsers',
+ 'NotConfirmedUsers',
+ 'DeletedUsers',
+ 'ActiveConfirmedUsers',
+ 'AdminUsers',
+ 'ActiveConfirmedAdmins',
+];
+
+export const listUsersAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_users',
+ classification: 'SEARCH',
+ displayName: 'List Users',
+ description: 'Lists CRM users.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists users of the Zoho CRM org, filtered by type (active users by default), one page of up to 200 (page numbers reach the first 2,000 users). Use to find a user id for a record Owner or a lead conversion assignee; use Get Current User for the connected user. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ type: Property.StaticDropdown({
+ displayName: 'User Type',
+ required: false,
+ defaultValue: 'ActiveUsers',
+ options: { options: USER_TYPES.map((t) => ({ label: t, value: t })) },
+ }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 200 (default 200).', required: false }),
+ },
+ outputSchema: listUsersOutputSchema,
+ async run({ auth, propsValue }) {
+ const type = propsValue.type ?? 'ActiveUsers';
+ if (!USER_TYPES.includes(type)) {
+ throw new ZohoCrmError(`type must be one of ${USER_TYPES.join(', ')}.`);
+ }
+ const page = optionalInt({ value: propsValue.page, name: 'page', min: 1, max: 2000 });
+ const perPage = optionalInt({ value: propsValue.per_page, name: 'per_page', min: 1, max: 200 });
+ validatePaging({ page, perPage: perPage ?? 200, tokenSupported: false });
+ const body = await zohoRequest<{ users?: Record<string, unknown>[]; info?: { more_records?: boolean } }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/users',
+ query: {
+ type,
+ ...(page ? { page: String(page) } : {}),
+ ...(perPage ? { per_page: String(perPage) } : {}),
+ },
+ });
+ const users = (body?.users ?? []).map(flattenUser);
+ return { users, count: users.length, more_records: body?.info?.more_records === true };
+ },
+});
+
+export const getUserAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_user',
+ classification: 'READ',
+ displayName: 'Get User',
+ description: 'Gets a CRM user by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Fetches one Zoho CRM user by id with name, email, role, profile and status. Use to resolve an Owner id seen on a record; to find users by listing use List Users. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user id, e.g. "5725767000000411001".', required: true }),
+ },
+ outputSchema: userOutputSchema,
+ async run({ auth, propsValue }) {
+ const id = requireId({ value: propsValue.user_id, name: 'user_id' });
+ const body = await zohoRequest<{ users?: Record<string, unknown>[] }>({ auth, method: HttpMethod.GET, path: `/users/${id}` });
+ const user = body?.users?.[0];
+ if (!user) {
+ throw new ZohoCrmError(`No user with id ${id} was found.`, 404, 'NOT_FOUND');
+ }
+ return flattenUser(user);
+ },
+});
+
+export const getCurrentUserAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User',
+ description: 'Gets the connected CRM user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the Zoho CRM user this connection acts as (id, name, email, role, profile). Use to get the default Owner id or the "from" address for an email draft. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: userOutputSchema,
+ async run({ auth }) {
+ const body = await zohoRequest<{ users?: Record<string, unknown>[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/users',
+ query: { type: 'CurrentUser' },
+ });
+ const user = body?.users?.[0];
+ if (!user) {
+ throw new ZohoCrmError('Zoho did not return the current user.');
+ }
+ return flattenUser(user);
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/notes-tags.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/notes-tags.ts
new file mode 100644
index 00000000000..4e7bf25ecee
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/notes-tags.ts
@@ -0,0 +1,299 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import {
+ ZohoCrmError,
+ ZohoListResponse,
+ flattenWriteResult,
+ optionalInt,
+ requireApiName,
+ requireId,
+ stringList,
+ unwrapWriteItem,
+ zohoRequest,
+ validatePaging,
+} from '../../common/client';
+import { flattenNote } from '../../common/flatten';
+import { TAG_COLORS, changeTags, createNote, ensureTag, listTags, notDeletedError } from '../../common/records';
+import {
+ createTagOutputSchema,
+ listNotesOutputSchema,
+ listTagsOutputSchema,
+ noteChangeOutputSchema,
+ noteOutputSchema,
+ noteWriteOutputSchema,
+} from '../../output-schemas-ai';
+import { tagChangeOutputSchema } from '../../output-schemas';
+
+const NOTE_FIELDS = 'Note_Title,Note_Content,Parent_Id,Owner,Created_Time,Modified_Time';
+
+const moduleApiName = Property.ShortText({
+ displayName: 'Module API Name',
+ description: 'Module API name from List Modules, e.g. "Leads" or "Deals".',
+ required: true,
+});
+
+const noteId = Property.ShortText({ displayName: 'Note ID', description: 'Numeric note id from List Notes.', required: true });
+
+export const listNotesAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_notes',
+ classification: 'SEARCH',
+ displayName: 'List Notes',
+ description: 'Lists notes of a record, or all notes.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists notes attached to one Zoho CRM record (give parent_module and parent_id), or all notes in the org when both are empty (admin users only), one page of up to 200; page numbers reach the first 2,000 notes. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ parent_module: Property.ShortText({ displayName: 'Parent Module', description: 'Module API name of the record, e.g. "Leads". Give with parent_id.', required: false }),
+ parent_id: Property.ShortText({ displayName: 'Parent Record ID', required: false }),
+ page: Property.Number({ displayName: 'Page', required: false }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 200 (default 50).', required: false }),
+ },
+ outputSchema: listNotesOutputSchema,
+ async run({ auth, propsValue: p }) {
+ if (!p.parent_module !== !p.parent_id) {
+ throw new ZohoCrmError('Give parent_module and parent_id together, or neither.');
+ }
+ const path = p.parent_module
+ ? `/${encodeURIComponent(requireApiName({ value: p.parent_module, name: 'parent_module' }))}/${requireId({ value: p.parent_id, name: 'parent_id' })}/Notes`
+ : '/Notes';
+ const page = optionalInt({ value: p.page, name: 'page', min: 1, max: 2000 });
+ const perPage = optionalInt({ value: p.per_page, name: 'per_page', min: 1, max: 200 }) ?? 50;
+ validatePaging({ page, perPage, tokenSupported: false });
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path,
+ query: {
+ fields: NOTE_FIELDS,
+ per_page: String(perPage),
+ ...(page ? { page: String(page) } : {}),
+ },
+ });
+ const notes = (body?.data ?? []).map(flattenNote);
+ return { notes, count: notes.length, more_records: body?.info?.more_records === true };
+ },
+});
+
+export const getNoteAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_note',
+ classification: 'READ',
+ displayName: 'Get Note',
+ description: 'Gets a note by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Fetches one Zoho CRM note by id with its title, content, parent record and owner. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: { note_id: noteId },
+ outputSchema: noteOutputSchema,
+ async run({ auth, propsValue }) {
+ const id = requireId({ value: propsValue.note_id, name: 'note_id' });
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/Notes/${id}`,
+ query: { fields: NOTE_FIELDS },
+ });
+ const note = body?.data?.[0];
+ if (!note) throw new ZohoCrmError(`No note with id ${id} was found.`, 404, 'NOT_FOUND');
+ return flattenNote(note);
+ },
+});
+
+export const createNoteAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_note',
+ classification: 'WRITE',
+ displayName: 'Create Note',
+ description: 'Adds a note to a record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a note (content required, title optional) to one Zoho CRM record identified by module API name and record id. Use to log context such as a call summary. Not idempotent: each call adds another note.',
+ idempotent: false,
+ },
+ props: {
+ parent_module: moduleApiName,
+ parent_id: Property.ShortText({ displayName: 'Parent Record ID', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ },
+ outputSchema: noteWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ return createNote({
+ auth,
+ module: requireApiName({ value: p.parent_module, name: 'parent_module' }),
+ recordId: requireId({ value: p.parent_id, name: 'parent_id' }),
+ title: p.title,
+ content: p.content,
+ });
+ },
+});
+
+export const updateNoteAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_update_note',
+ classification: 'WRITE',
+ displayName: 'Update Note',
+ description: 'Changes the title or content of a note.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes the title and/or content of one Zoho CRM note; a field you leave out keeps its value (only title and content can change). Idempotent: re-sending the same text converges on the same note.',
+ idempotent: true,
+ },
+ props: {
+ note_id: noteId,
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ content: Property.LongText({ displayName: 'Content', required: false }),
+ },
+ outputSchema: noteChangeOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const id = requireId({ value: p.note_id, name: 'note_id' });
+ const data: Record<string, unknown> = {};
+ if (p.title !== undefined && p.title !== null && p.title !== '') data['Note_Title'] = p.title;
+ if (p.content !== undefined && p.content !== null && p.content !== '') data['Note_Content'] = p.content;
+ if (Object.keys(data).length === 0) {
+ throw new ZohoCrmError('Give a new title or content.');
+ }
+ const body = await zohoRequest<unknown>({ auth, method: HttpMethod.PUT, path: `/Notes/${id}`, body: { data: [data] } });
+ return { ...flattenWriteResult(unwrapWriteItem({ body })), id };
+ },
+});
+
+export const deleteNoteAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_delete_note',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Note',
+ description: 'Deletes a note.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Deletes one Zoho CRM note by id. Only use when asked to remove the note. Not idempotent: deleting it again returns an error.',
+ idempotent: false,
+ },
+ props: { note_id: noteId },
+ outputSchema: noteChangeOutputSchema,
+ async run({ auth, propsValue }) {
+ const id = requireId({ value: propsValue.note_id, name: 'note_id' });
+ let body: unknown;
+ try {
+ body = await zohoRequest<unknown>({ auth, method: HttpMethod.DELETE, path: `/Notes/${id}` });
+ } catch (error) {
+ throw notDeletedError({ error, what: `note ${id}` });
+ }
+ return { ...flattenWriteResult(unwrapWriteItem({ body })), id };
+ },
+});
+
+export const listTagsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_tags',
+ classification: 'SEARCH',
+ displayName: 'List Tags',
+ description: 'Lists the tags of a module.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists the tags defined for one Zoho CRM module (name, id, color). Use to check tag names before Add Tags or Remove Tags. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: { module_api_name: moduleApiName },
+ outputSchema: listTagsOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' });
+ const tags = (await listTags({ auth, module: module })).map((t) => ({
+ id: t.id,
+ name: t.name,
+ color_code: t.color_code ?? null,
+ created_time: t.created_time ?? null,
+ modified_time: t.modified_time ?? null,
+ }));
+ return { module, tags, count: tags.length };
+ },
+});
+
+export const createTagAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_tag',
+ classification: 'WRITE',
+ displayName: 'Create Tag',
+ description: 'Creates a tag in a module, or returns it if it exists.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets or creates a tag by name (case-insensitive) in one Zoho CRM module, returning created false when it already existed. Use before Add Tags when the tag may be new; a module holds at most 100 tags. Idempotent: repeating returns the same tag.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ name: Property.ShortText({ displayName: 'Tag Name', required: true }),
+ color_code: Property.StaticDropdown({
+ displayName: 'Color',
+ required: false,
+ options: { options: TAG_COLORS.map((c) => ({ label: c, value: c })) },
+ }),
+ },
+ outputSchema: createTagOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const { tag, created } = await ensureTag({ auth, module, name: p.name, colorCode: p.color_code });
+ return { id: tag.id, name: tag.name, color_code: tag.color_code ?? null, module, created };
+ },
+});
+
+const tagNames = Property.Array({ displayName: 'Tag Names', description: 'Tag names, e.g. ["VIP", "Webinar 2026"].', required: true });
+const recordIds = Property.Array({ displayName: 'Record IDs', description: 'Numeric record ids (max 500).', required: true });
+
+function tagInputs(p: { module_api_name: unknown; record_ids: unknown; tags: unknown }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const ids = stringList(p.record_ids).map((id) => requireId({ value: id, name: 'record_ids' }));
+ const names = stringList(p.tags);
+ if (names.length > 10) throw new ZohoCrmError('Zoho allows at most 10 tags per record.');
+ return { module, ids, tags: names.map((name) => ({ name })) };
+}
+
+export const addTagsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_add_tags',
+ classification: 'WRITE',
+ displayName: 'Add Tags',
+ description: 'Adds tags to one or more records.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds tags by name to up to 500 records of one Zoho CRM module, keeping tags the records already have (max 10 per record). A tag name the module does not have yet is created by Zoho on the fly; use Create Tag first only to pick its color. Idempotent: re-adding an existing tag changes nothing.',
+ idempotent: true,
+ },
+ props: { module_api_name: moduleApiName, record_ids: recordIds, tags: tagNames },
+ outputSchema: tagChangeOutputSchema,
+ async run({ auth, propsValue }) {
+ const { module, ids, tags } = tagInputs(propsValue);
+ return changeTags({ auth, module, recordIds: ids, tags, mode: 'add' });
+ },
+});
+
+export const removeTagsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_remove_tags',
+ classification: 'WRITE',
+ displayName: 'Remove Tags',
+ description: 'Removes tags from one or more records.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes tags by name from up to 500 records of one Zoho CRM module; the tags themselves stay defined in the module. Idempotent: removing a tag that is not on a record changes nothing.',
+ idempotent: true,
+ },
+ props: { module_api_name: moduleApiName, record_ids: recordIds, tags: tagNames },
+ outputSchema: tagChangeOutputSchema,
+ async run({ auth, propsValue }) {
+ const { module, ids, tags } = tagInputs(propsValue);
+ return changeTags({ auth, module, recordIds: ids, tags, mode: 'remove' });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/records.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/records.ts
new file mode 100644
index 00000000000..c661d5c1ba2
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/records.ts
@@ -0,0 +1,287 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import {
+ ZohoCrmError,
+ ZohoListResponse,
+ optionalId,
+ optionalInt,
+ parseJsonObject,
+ parseTriggers,
+ requireApiName,
+ requireId,
+ stringList,
+ validatePaging,
+ zohoRequest,
+} from '../../common/client';
+import { defaultFieldSelection, listFields } from '../../common/metadata';
+import { createRecord, deleteRecord, getRecord, updateRecord, upsertRecord } from '../../common/records';
+import {
+ aiUpsertOutputSchema,
+ aiWriteOutputSchema,
+ listRecordsOutputSchema,
+} from '../../output-schemas-ai';
+import { deleteOutputSchema, recordOutputSchema } from '../../output-schemas';
+
+const moduleApiName = Property.ShortText({
+ displayName: 'Module API Name',
+ description: 'Module API name from List Modules, e.g. "Leads", "Contacts", "Deals" or "CustomModule1".',
+ required: true,
+});
+
+const recordId = Property.ShortText({
+ displayName: 'Record ID',
+ description: 'Numeric Zoho record id, e.g. "5725767000000524157" (from List Records or a create result).',
+ required: true,
+});
+
+const dataProp = (required: boolean) =>
+ Property.Json({
+ displayName: 'Data',
+ description:
+ 'JSON object of field API names to values, e.g. {"Last_Name": "Doe", "Email": "[email protected]", "Owner": {"id": "5725767000000411001"}}. Get API names and picklist values from Get Module Fields. Dates as "2026-10-01", date-times as "2026-10-01T09:00:00+02:00", lookups as {"id": "..."}.',
+ required,
+ });
+
+const skipAutomation = Property.Checkbox({
+ displayName: 'Skip Automation',
+ description: 'When true, no workflow, approval or blueprint runs for this change. Default false (Zoho runs its automation).',
+ required: false,
+ defaultValue: false,
+});
+
+export const listRecordsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_records',
+ classification: 'SEARCH',
+ displayName: 'List Records',
+ description: 'Lists records of a module, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists records of one Zoho CRM module one page at a time (up to 200), sorted by id, Created_Time or Modified_Time, optionally within a custom view. Use to browse or page through a module; it does not filter by field value, so use Get Record when you know the id. Returns at most 50 fields per record (default: id, then custom fields, then standard fields, up to 50). Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ fields: Property.Array({
+ displayName: 'Fields',
+ description: 'Field API names to return (max 50). Leave empty for id, then the custom fields of the module, then its standard fields (50 in total).',
+ required: false,
+ }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 200. Default 50.', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number for the first 2,000 records. Do not combine with page_token.', required: false }),
+ page_token: Property.ShortText({ displayName: 'Page Token', description: 'next_page_token from a previous call, needed beyond 2,000 records.', required: false }),
+ sort_by: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ options: { options: ['id', 'Created_Time', 'Modified_Time'].map((v) => ({ label: v, value: v })) },
+ }),
+ sort_order: Property.StaticDropdown({
+ displayName: 'Sort Order',
+ required: false,
+ options: { options: [{ label: 'Descending', value: 'desc' }, { label: 'Ascending', value: 'asc' }] },
+ }),
+ custom_view_id: Property.ShortText({ displayName: 'Custom View ID', description: 'Optional id of a custom view (cvid) to list only its records.', required: false }),
+ },
+ outputSchema: listRecordsOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' });
+ const perPage = optionalInt({ value: propsValue.per_page, name: 'per_page', min: 1, max: 200 }) ?? 50;
+ const page = optionalInt({ value: propsValue.page, name: 'page', min: 1, max: 2000 });
+ const pageToken = propsValue.page_token?.trim() || undefined;
+ validatePaging({ page, perPage, pageToken, tokenSupported: true });
+ const cvid = optionalId({ value: propsValue.custom_view_id, name: 'custom_view_id' });
+ let fields = stringList(propsValue.fields).map((f) => requireApiName({ value: f, name: 'fields' }));
+ if (fields.length > 50) {
+ throw new ZohoCrmError('Zoho returns at most 50 fields per call.');
+ }
+ if (fields.length === 0) {
+ fields = defaultFieldSelection({ fields: await listFields({ auth, module: module }) });
+ }
+ const sortBy = propsValue.sort_by;
+ const sortOrder = propsValue.sort_order;
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}`,
+ query: {
+ fields: fields.join(','),
+ per_page: String(perPage),
+ ...(page ? { page: String(page) } : {}),
+ ...(pageToken ? { page_token: pageToken } : {}),
+ ...(sortBy ? { sort_by: sortBy } : {}),
+ ...(sortOrder ? { sort_order: sortOrder } : {}),
+ ...(cvid ? { cvid } : {}),
+ },
+ });
+ const records = body?.data ?? [];
+ return {
+ module,
+ records,
+ count: records.length,
+ more_records: body?.info?.more_records === true,
+ page: body?.info?.page ?? page ?? null,
+ next_page_token: body?.info?.next_page_token ?? null,
+ fields_requested: fields.join(','),
+ };
+ },
+});
+
+export const getRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_get_record',
+ classification: 'READ',
+ displayName: 'Get Record',
+ description: 'Gets one record by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Fetches one Zoho CRM record by module API name and record id, with all fields (keys are field API names, custom fields included) unless a field list is given. Use when you hold a record id; use List Records to browse. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ fields: Property.Array({ displayName: 'Fields', description: 'Optional field API names to return; empty returns all fields.', required: false }),
+ },
+ outputSchema: recordOutputSchema,
+ async run({ auth, propsValue }) {
+ return getRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' }),
+ id: requireId({ value: propsValue.record_id, name: 'record_id' }),
+ fields: stringList(propsValue.fields).map((f) => requireApiName({ value: f, name: 'fields' })),
+ });
+ },
+});
+
+export const createRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_record',
+ classification: 'WRITE',
+ displayName: 'Create Record',
+ description: 'Creates a record in any module from a JSON object of fields.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one record in any Zoho CRM module (standard or custom) from a JSON object of field API names; prefer Create Lead, Create Contact, Create Deal or Create Event for those modules, and Upsert Record when the record may already exist. Resolve field API names and required fields with Get Module Fields first. Not idempotent: each call creates a new record.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ data: dataProp(true),
+ skip_automation: skipAutomation,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ return createRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' }),
+ record: parseJsonObject({ value: propsValue.data, name: 'data' }),
+ trigger: parseTriggers({ value: undefined, skipAll: propsValue.skip_automation }),
+ });
+ },
+});
+
+export const updateRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_update_record',
+ classification: 'WRITE',
+ displayName: 'Update Record',
+ description: 'Updates the given fields of a record; other fields are unchanged.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates only the fields present in data on one Zoho CRM record; fields you omit keep their values and a field set to null is cleared. Multi-select picklists are replaced unless listed in append_multiselect_fields. Not idempotent: every call counts as an edit and runs the module\'s on-edit workflows unless automation is skipped.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ data: dataProp(true),
+ append_multiselect_fields: Property.Array({
+ displayName: 'Append Multi-Select Fields',
+ description: 'Multi-select picklist API names whose new values should be added to the current ones instead of replacing them.',
+ required: false,
+ }),
+ skip_automation: skipAutomation,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ const record = parseJsonObject({ value: propsValue.data, name: 'data' });
+ if ('id' in record) {
+ throw new ZohoCrmError('Do not put "id" in data; pass it as record_id.');
+ }
+ return updateRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' }),
+ id: requireId({ value: propsValue.record_id, name: 'record_id' }),
+ record,
+ appendMultiSelect: stringList(propsValue.append_multiselect_fields).map((f) => requireApiName({ value: f, name: 'append_multiselect_fields' })),
+ trigger: parseTriggers({ value: undefined, skipAll: propsValue.skip_automation }),
+ });
+ },
+});
+
+export const deleteRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_delete_record',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Record',
+ description: 'Deletes a record (moves it to the Recycle Bin).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes one Zoho CRM record by module and id; it moves to the Recycle Bin, restorable only from the Zoho UI. Only use when the user asked to delete; to change data use Update Record. Not idempotent: a second call on the same id fails.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ run_workflows: Property.Checkbox({ displayName: 'Run Workflows', description: 'Default true.', required: false, defaultValue: true }),
+ },
+ outputSchema: deleteOutputSchema,
+ async run({ auth, propsValue }) {
+ return deleteRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' }),
+ id: requireId({ value: propsValue.record_id, name: 'record_id' }),
+ runWorkflows: propsValue.run_workflows !== false,
+ });
+ },
+});
+
+export const upsertRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_upsert_record',
+ classification: 'WRITE',
+ displayName: 'Upsert Record',
+ description: 'Updates the matching record or creates it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Inserts or updates one Zoho CRM record, matching on duplicate_check_fields (Zoho default: Email for Leads/Contacts, Account_Name for Accounts, Deal_Name for Deals, Name for custom modules); the result says action insert or update. Use as find-or-create. Not idempotent: when the data has no value for a duplicate-check field, every call inserts a new record.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ data: dataProp(true),
+ duplicate_check_fields: Property.Array({
+ displayName: 'Duplicate Check Fields',
+ description: 'Field API names to match on, e.g. ["Email"]. Empty uses the module default.',
+ required: false,
+ }),
+ skip_automation: skipAutomation,
+ },
+ outputSchema: aiUpsertOutputSchema,
+ async run({ auth, propsValue }) {
+ return upsertRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module_api_name, name: 'module_api_name' }),
+ record: parseJsonObject({ value: propsValue.data, name: 'data' }),
+ duplicateCheckFields: stringList(propsValue.duplicate_check_fields).map((f) => requireApiName({ value: f, name: 'duplicate_check_fields' })),
+ trigger: parseTriggers({ value: undefined, skipAll: propsValue.skip_automation }),
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/related-attachments.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/related-attachments.ts
new file mode 100644
index 00000000000..7204969618d
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/related-attachments.ts
@@ -0,0 +1,259 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import {
+ ZohoAuth,
+ ZohoCrmError,
+ ZohoListResponse,
+ optionalInt,
+ parseJsonObject,
+ requireApiName,
+ requireId,
+ stringList,
+ unwrapWriteItem,
+ zohoRequest,
+ zohoApiUrl,
+ validatePaging,
+} from '../../common/client';
+import { downloadToFile } from '../../common/download';
+import { flattenAttachment } from '../../common/flatten';
+import { defaultFieldSelection } from '../../common/metadata';
+import { tryListFields, uploadAttachment } from '../../common/records';
+import {
+ downloadAttachmentOutputSchema,
+ linkRelatedOutputSchema,
+ listAttachmentsOutputSchema,
+ relatedRecordsOutputSchema,
+} from '../../output-schemas-ai';
+import { childWriteOutputSchema } from '../../output-schemas';
+
+const ATTACHMENT_FIELDS = 'id,File_Name,Size,Created_Time,Modified_Time,Owner,Created_By,$file_id,$se_module,$type,$link_url';
+
+const moduleApiName = Property.ShortText({
+ displayName: 'Module API Name',
+ description: 'Module API name of the parent record, e.g. "Accounts" or "Leads".',
+ required: true,
+});
+const recordId = Property.ShortText({ displayName: 'Record ID', description: 'Numeric id of the parent record.', required: true });
+const relatedList = Property.ShortText({
+ displayName: 'Related List API Name',
+ description: 'api_name from Get Related Lists, e.g. "Contacts", "Deals", "Campaigns", "Products".',
+ required: true,
+});
+
+async function relatedModuleFields({ auth, module, related }: { auth: ZohoAuth; module: string; related: string }): Promise<string[]> {
+ const body = await zohoRequest<{ related_lists?: { api_name?: string; module?: { api_name?: string } }[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/related_lists',
+ query: { module },
+ });
+ const target = body?.related_lists?.find((r) => r.api_name === related)?.module?.api_name;
+ if (!target) return ['id'];
+ const fields = await tryListFields({ auth, module: target });
+ return fields ? defaultFieldSelection({ fields }) : ['id'];
+}
+
+export const listRelatedRecordsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_related_records',
+ classification: 'SEARCH',
+ displayName: 'List Related Records',
+ description: 'Lists records in a related list of a record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the records in one related list of a Zoho CRM record, e.g. the Contacts or Deals of an Account, one page of up to 200 (at most 50 fields per record; default id, then custom fields, then standard fields of the related module). Get related_list_api_name from Get Related Lists. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ related_list_api_name: relatedList,
+ fields: Property.Array({ displayName: 'Fields', description: 'Field API names to return (max 50).', required: false }),
+ page: Property.Number({ displayName: 'Page', required: false }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 200 (default 50).', required: false }),
+ page_token: Property.ShortText({ displayName: 'Page Token', description: 'next_page_token from a previous call (beyond 2,000 records).', required: false }),
+ },
+ outputSchema: relatedRecordsOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const related = requireApiName({ value: p.related_list_api_name, name: 'related_list_api_name' });
+ const page = optionalInt({ value: p.page, name: 'page', min: 1, max: 2000 });
+ const perPage = optionalInt({ value: p.per_page, name: 'per_page', min: 1, max: 200 }) ?? 50;
+ const pageToken = p.page_token?.trim() || undefined;
+ validatePaging({ page, perPage, pageToken, tokenSupported: true });
+ let fields = stringList(p.fields).map((f) => requireApiName({ value: f, name: 'fields' }));
+ if (fields.length > 50) throw new ZohoCrmError('Zoho returns at most 50 fields per call.');
+ if (fields.length === 0) fields = await relatedModuleFields({ auth, module, related });
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}/${id}/${encodeURIComponent(related)}`,
+ query: {
+ fields: fields.join(','),
+ per_page: String(perPage),
+ ...(page ? { page: String(page) } : {}),
+ ...(pageToken ? { page_token: pageToken } : {}),
+ },
+ });
+ const records = body?.data ?? [];
+ return {
+ module,
+ record_id: id,
+ related_list: related,
+ records,
+ count: records.length,
+ more_records: body?.info?.more_records === true,
+ next_page_token: body?.info?.next_page_token ?? null,
+ };
+ },
+});
+
+export const linkRelatedRecordAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_link_related_record',
+ classification: 'WRITE',
+ displayName: 'Link Related Record',
+ description: 'Associates a record with another record through a related list.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Associates an existing record with a Zoho CRM record through a related list, or updates the relation\'s own fields (e.g. add a Contact to a Campaign with a Member_Status, or a Product to a Deal). Supported relations include Campaigns with Leads/Contacts and Products with Leads/Accounts/Contacts/Deals/Price Books. Idempotent: linking the same pair again leaves one link.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ related_list_api_name: relatedList,
+ related_record_id: Property.ShortText({ displayName: 'Related Record ID', description: 'Id of the record to link.', required: true }),
+ relation_fields: Property.Json({ displayName: 'Relation Fields', description: 'Optional fields of the relation, e.g. {"Member_Status": "Invited"}.', required: false }),
+ },
+ outputSchema: linkRelatedOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const related = requireApiName({ value: p.related_list_api_name, name: 'related_list_api_name' });
+ const relatedId = requireId({ value: p.related_record_id, name: 'related_record_id' });
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/${encodeURIComponent(module)}/${id}/${encodeURIComponent(related)}`,
+ body: { data: [{ ...parseJsonObject({ value: p.relation_fields, name: 'relation_fields' }), id: relatedId }] },
+ });
+ const item = unwrapWriteItem({ body });
+ return {
+ module,
+ record_id: id,
+ related_list: related,
+ related_record_id: relatedId,
+ status: item.status ?? null,
+ code: item.code ?? null,
+ message: item.message ?? null,
+ };
+ },
+});
+
+export const listAttachmentsAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_list_attachments',
+ classification: 'SEARCH',
+ displayName: 'List Attachments',
+ description: 'Lists the attachments of a record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the attachments of one Zoho CRM record (file name, size, type, link URL, owner, attachment id), one page of up to 200 (page numbers reach the first 2,000). Use to find the attachment_id for Download Attachment; a "Link URL" attachment cannot be downloaded and carries its link_url instead. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ page: Property.Number({ displayName: 'Page', required: false }),
+ per_page: Property.Number({ displayName: 'Per Page', description: '1 to 200 (default 50).', required: false }),
+ },
+ outputSchema: listAttachmentsOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const page = optionalInt({ value: p.page, name: 'page', min: 1, max: 2000 });
+ const perPage = optionalInt({ value: p.per_page, name: 'per_page', min: 1, max: 200 }) ?? 50;
+ validatePaging({ page, perPage, tokenSupported: false });
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}/${id}/Attachments`,
+ query: { fields: ATTACHMENT_FIELDS, per_page: String(perPage), ...(page ? { page: String(page) } : {}) },
+ });
+ const attachments = (body?.data ?? []).map(flattenAttachment);
+ return { attachments, count: attachments.length, more_records: body?.info?.more_records === true };
+ },
+});
+
+export const uploadAttachmentAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_upload_attachment',
+ classification: 'WRITE',
+ displayName: 'Attach Link',
+ description: 'Attaches a URL to a record as a link attachment.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a link attachment (a public http(s) URL plus an optional title) to one Zoho CRM record. Use to attach a document that lives online; Zoho stores the link, not a copy of the file. Not idempotent: each call adds another attachment.',
+ idempotent: false,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ attachment_url: Property.ShortText({ displayName: 'Attachment URL', description: 'Full URL, e.g. "https://example.com/proposal.pdf".', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ },
+ outputSchema: childWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ return uploadAttachment({
+ auth,
+ module: requireApiName({ value: p.module_api_name, name: 'module_api_name' }),
+ recordId: requireId({ value: p.record_id, name: 'record_id' }),
+ attachmentUrl: p.attachment_url,
+ title: p.title,
+ });
+ },
+});
+
+export const downloadAttachmentAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_download_attachment',
+ classification: 'READ',
+ displayName: 'Download Attachment',
+ description: 'Downloads a file attachment of a record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Downloads one file attachment of a Zoho CRM record by attachment id (from List Attachments) and returns it as a stored file. Link attachments cannot be downloaded. The file size limit of this Activepieces deployment applies. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module_api_name: moduleApiName,
+ record_id: recordId,
+ attachment_id: Property.ShortText({ displayName: 'Attachment ID', required: true }),
+ },
+ outputSchema: downloadAttachmentOutputSchema,
+ async run({ auth, propsValue: p, files }) {
+ const module = requireApiName({ value: p.module_api_name, name: 'module_api_name' });
+ const id = requireId({ value: p.record_id, name: 'record_id' });
+ const attachmentId = requireId({ value: p.attachment_id, name: 'attachment_id' });
+ const downloaded = await downloadToFile({
+ auth,
+ url: zohoApiUrl({ auth, path: `/${encodeURIComponent(module)}/${id}/Attachments/${attachmentId}` }),
+ files,
+ fallbackName: `attachment-${attachmentId}`,
+ });
+ return {
+ file: downloaded.file,
+ file_name: downloaded.fileName,
+ size: downloaded.size,
+ content_type: downloaded.contentType,
+ };
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/ai/typed.ts b/packages/pieces/community/zoho-crm/src/lib/actions/ai/typed.ts
new file mode 100644
index 00000000000..a0f8f668908
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/ai/typed.ts
@@ -0,0 +1,286 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../../auth';
+import { ZohoCrmError, optionalId, parseJsonObject, requireApiName, requireId } from '../../common/client';
+import { convertFieldValue } from '../../common/fields';
+import { convertLead, createRecord } from '../../common/records';
+import { aiWriteOutputSchema } from '../../output-schemas-ai';
+import { convertLeadOutputSchema } from '../../output-schemas';
+
+const additionalFields = Property.Json({
+ displayName: 'Additional Fields',
+ description: 'Optional JSON of other field API names, including custom fields, e.g. {"Custom_Field__c": "x"}. The named props above win over the same key here.',
+ required: false,
+});
+
+const ownerId = Property.ShortText({
+ displayName: 'Owner User ID',
+ description: 'Optional user id (from List Users or Get Current User). Default: the connected user.',
+ required: false,
+});
+
+function compact(values: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined && value !== null && value !== ''));
+}
+
+function withCommon({ record, extra, owner }: { record: Record<string, unknown>; extra: unknown; owner: unknown }): Record<string, unknown> {
+ const id = optionalId({ value: owner, name: 'owner_id' });
+ return { ...parseJsonObject({ value: extra, name: 'additional_fields' }), ...record, ...(id ? { Owner: { id } } : {}) };
+}
+
+function lookup({ value, name }: { value: unknown; name: string }): { id: string } | undefined {
+ const id = optionalId({ value, name });
+ return id ? { id } : undefined;
+}
+
+function dateOnly({ value, name }: { value: unknown; name: string }): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ return String(convertFieldValue({ field: { api_name: name, data_type: 'date' }, value }));
+}
+
+function dateTime({ value, name }: { value: unknown; name: string }): string {
+ return String(convertFieldValue({ field: { api_name: name, data_type: 'datetime' }, value }));
+}
+
+function num({ value, name }: { value: unknown; name: string }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ return Number(convertFieldValue({ field: { api_name: name, data_type: 'double' }, value }));
+}
+
+export const createLeadAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_lead',
+ classification: 'WRITE',
+ displayName: 'Create Lead',
+ description: 'Creates a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one Zoho CRM lead with typed fields (Last Name required; company, email, phone, source, status) plus optional custom fields. Use for new prospects; use Upsert Record on Leads with Email to avoid duplicates, or Create Contact for an existing customer. Not idempotent: each call creates another lead.',
+ idempotent: false,
+ },
+ props: {
+ last_name: Property.ShortText({ displayName: 'Last Name', required: true }),
+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),
+ company: Property.ShortText({ displayName: 'Company', description: 'Required in many orgs\' layouts.', required: false }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ mobile: Property.ShortText({ displayName: 'Mobile', required: false }),
+ title: Property.ShortText({ displayName: 'Title', description: 'Job title (Designation).', required: false }),
+ website: Property.ShortText({ displayName: 'Website', required: false }),
+ lead_source: Property.ShortText({ displayName: 'Lead Source', description: 'A Lead_Source picklist value of your org, e.g. "Web Download".', required: false }),
+ lead_status: Property.ShortText({ displayName: 'Lead Status', description: 'A Lead_Status picklist value of your org, e.g. "Not Contacted".', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ owner_id: ownerId,
+ additional_fields: additionalFields,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const record = compact({
+ Last_Name: p.last_name,
+ First_Name: p.first_name,
+ Company: p.company,
+ Email: p.email,
+ Phone: p.phone,
+ Mobile: p.mobile,
+ Designation: p.title,
+ Website: p.website,
+ Lead_Source: p.lead_source,
+ Lead_Status: p.lead_status,
+ Description: p.description,
+ });
+ return createRecord({ auth, module: 'Leads', record: withCommon({ record, extra: p.additional_fields, owner: p.owner_id }) });
+ },
+});
+
+export const createContactAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_contact',
+ classification: 'WRITE',
+ displayName: 'Create Contact',
+ description: 'Creates a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one Zoho CRM contact with typed fields (Last Name required; email, phone, account, mailing address) plus optional custom fields. Use for a person tied to a customer account; use Upsert Record on Contacts with Email to avoid duplicates. Not idempotent: each call creates another contact.',
+ idempotent: false,
+ },
+ props: {
+ last_name: Property.ShortText({ displayName: 'Last Name', required: true }),
+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ mobile: Property.ShortText({ displayName: 'Mobile', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ account_id: Property.ShortText({ displayName: 'Account ID', description: 'Id of an existing Accounts record.', required: false }),
+ mailing_street: Property.ShortText({ displayName: 'Mailing Street', required: false }),
+ mailing_city: Property.ShortText({ displayName: 'Mailing City', required: false }),
+ mailing_state: Property.ShortText({ displayName: 'Mailing State', required: false }),
+ mailing_zip: Property.ShortText({ displayName: 'Mailing Zip', required: false }),
+ mailing_country: Property.ShortText({ displayName: 'Mailing Country', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ owner_id: ownerId,
+ additional_fields: additionalFields,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const record = compact({
+ Last_Name: p.last_name,
+ First_Name: p.first_name,
+ Email: p.email,
+ Phone: p.phone,
+ Mobile: p.mobile,
+ Title: p.title,
+ Account_Name: lookup({ value: p.account_id, name: 'account_id' }),
+ Mailing_Street: p.mailing_street,
+ Mailing_City: p.mailing_city,
+ Mailing_State: p.mailing_state,
+ Mailing_Zip: p.mailing_zip,
+ Mailing_Country: p.mailing_country,
+ Description: p.description,
+ });
+ return createRecord({ auth, module: 'Contacts', record: withCommon({ record, extra: p.additional_fields, owner: p.owner_id }) });
+ },
+});
+
+export const createDealAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_deal',
+ classification: 'WRITE',
+ displayName: 'Create Deal',
+ description: 'Creates a deal.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one Zoho CRM deal (Deal Name and Stage required; amount, closing date, pipeline, account and contact optional). Stage and Pipeline values are org-specific, so read them from Get Module Fields on Deals first. Not idempotent: each call creates another deal.',
+ idempotent: false,
+ },
+ props: {
+ deal_name: Property.ShortText({ displayName: 'Deal Name', required: true }),
+ stage: Property.ShortText({ displayName: 'Stage', description: 'A Stage picklist value of your org, e.g. "Qualification".', required: true }),
+ closing_date: Property.ShortText({ displayName: 'Closing Date', description: 'yyyy-MM-dd, e.g. "2026-12-31". Required in many layouts.', required: false }),
+ amount: Property.Number({ displayName: 'Amount', required: false }),
+ pipeline: Property.ShortText({ displayName: 'Pipeline', description: 'Pipeline name when the org uses pipelines, e.g. "Standard (Standard)".', required: false }),
+ account_id: Property.ShortText({ displayName: 'Account ID', required: false }),
+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ owner_id: ownerId,
+ additional_fields: additionalFields,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const record = compact({
+ Deal_Name: p.deal_name,
+ Stage: p.stage,
+ Closing_Date: dateOnly({ value: p.closing_date, name: 'closing_date' }),
+ Amount: num({ value: p.amount, name: 'amount' }),
+ Pipeline: p.pipeline,
+ Account_Name: lookup({ value: p.account_id, name: 'account_id' }),
+ Contact_Name: lookup({ value: p.contact_id, name: 'contact_id' }),
+ Description: p.description,
+ });
+ return createRecord({ auth, module: 'Deals', record: withCommon({ record, extra: p.additional_fields, owner: p.owner_id }) });
+ },
+});
+
+export const createEventAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_create_event',
+ classification: 'WRITE',
+ displayName: 'Create Event',
+ description: 'Creates a calendar event (meeting).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one Zoho CRM event (meeting) with a title, start and end date-time, optional venue and an optional link to a record (What_Id plus its module, e.g. a Deal or Account). Use to log or schedule a meeting against a CRM record. Not idempotent: each call creates another event.',
+ idempotent: false,
+ },
+ props: {
+ event_title: Property.ShortText({ displayName: 'Title', required: true }),
+ start_datetime: Property.ShortText({ displayName: 'Start', description: 'ISO 8601 with offset, e.g. "2026-10-01T09:00:00+02:00".', required: true }),
+ end_datetime: Property.ShortText({ displayName: 'End', description: 'ISO 8601 with offset, after Start.', required: true }),
+ all_day: Property.Checkbox({ displayName: 'All Day', required: false, defaultValue: false }),
+ venue: Property.ShortText({ displayName: 'Venue', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ related_module: Property.ShortText({ displayName: 'Related Module', description: 'Module API name of the record to link (What_Id), e.g. "Deals" or "Accounts". Give with related_record_id.', required: false }),
+ related_record_id: Property.ShortText({ displayName: 'Related Record ID', required: false }),
+ owner_id: ownerId,
+ additional_fields: additionalFields,
+ },
+ outputSchema: aiWriteOutputSchema,
+ async run({ auth, propsValue: p }) {
+ const start = dateTime({ value: p.start_datetime, name: 'start_datetime' });
+ const end = dateTime({ value: p.end_datetime, name: 'end_datetime' });
+ if (Date.parse(end) < Date.parse(start)) {
+ throw new ZohoCrmError('end_datetime must not be before start_datetime.');
+ }
+ const relatedId = optionalId({ value: p.related_record_id, name: 'related_record_id' });
+ if ((relatedId === undefined) !== (!p.related_module)) {
+ throw new ZohoCrmError('Give related_module and related_record_id together.');
+ }
+ const record = compact({
+ Event_Title: p.event_title,
+ Start_DateTime: start,
+ End_DateTime: end,
+ All_day: p.all_day === true ? true : undefined,
+ Venue: p.venue,
+ Description: p.description,
+ What_Id: relatedId ? { id: relatedId } : undefined,
+ $se_module: relatedId && p.related_module ? requireApiName({ value: p.related_module, name: 'related_module' }) : undefined,
+ });
+ return createRecord({ auth, module: 'Events', record: withCommon({ record, extra: p.additional_fields, owner: p.owner_id }) });
+ },
+});
+
+export const convertLeadAtomic = createAction({
+ auth: zohoCrmAuth,
+ name: 'zoho_crm_convert_lead',
+ classification: 'WRITE',
+ displayName: 'Convert Lead',
+ description: 'Converts a lead to a contact, account and optional deal.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Converts one Zoho CRM lead into a contact and account (new, or existing ones by id) and optionally creates a deal when deal_name is given (deal_stage and deal_closing_date then required). Use once a lead is qualified. Not idempotent: a converted lead cannot be converted again (ID_ALREADY_CONVERTED).',
+ idempotent: false,
+ },
+ props: {
+ lead_id: Property.ShortText({ displayName: 'Lead ID', required: true }),
+ account_id: Property.ShortText({ displayName: 'Existing Account ID', required: false }),
+ contact_id: Property.ShortText({ displayName: 'Existing Contact ID', required: false }),
+ assign_to: Property.ShortText({ displayName: 'Owner User ID', required: false }),
+ overwrite: Property.Checkbox({ displayName: 'Overwrite Contact Account', required: false, defaultValue: false }),
+ notify_lead_owner: Property.Checkbox({ displayName: 'Notify Lead Owner', required: false, defaultValue: false }),
+ notify_new_entity_owner: Property.Checkbox({ displayName: 'Notify New Owner', required: false, defaultValue: false }),
+ deal_name: Property.ShortText({ displayName: 'Deal Name', description: 'Set to also create a deal.', required: false }),
+ deal_stage: Property.ShortText({ displayName: 'Deal Stage', required: false }),
+ deal_closing_date: Property.ShortText({ displayName: 'Deal Closing Date', description: 'yyyy-MM-dd.', required: false }),
+ deal_amount: Property.Number({ displayName: 'Deal Amount', required: false }),
+ deal_pipeline: Property.ShortText({ displayName: 'Deal Pipeline', required: false }),
+ },
+ outputSchema: convertLeadOutputSchema,
+ async run({ auth, propsValue: p }) {
+ if (p.deal_name && (!p.deal_stage || !p.deal_closing_date)) {
+ throw new ZohoCrmError('deal_stage and deal_closing_date are required when deal_name is set.');
+ }
+ const deal = p.deal_name
+ ? compact({
+ Deal_Name: p.deal_name,
+ Stage: p.deal_stage,
+ Closing_Date: dateOnly({ value: p.deal_closing_date, name: 'deal_closing_date' }),
+ Amount: num({ value: p.deal_amount, name: 'deal_amount' }),
+ Pipeline: p.deal_pipeline,
+ })
+ : {};
+ return convertLead({
+ auth,
+ leadId: requireId({ value: p.lead_id, name: 'lead_id' }),
+ accountId: optionalId({ value: p.account_id, name: 'account_id' }),
+ contactId: optionalId({ value: p.contact_id, name: 'contact_id' }),
+ assignTo: optionalId({ value: p.assign_to, name: 'assign_to' }),
+ overwrite: p.overwrite === true ? true : undefined,
+ notifyLeadOwner: p.notify_lead_owner === true ? true : undefined,
+ notifyNewEntityOwner: p.notify_new_entity_owner === true ? true : undefined,
+ deal,
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/convert-lead.ts b/packages/pieces/community/zoho-crm/src/lib/actions/convert-lead.ts
new file mode 100644
index 00000000000..3d56c38f46b
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/convert-lead.ts
@@ -0,0 +1,76 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { ZohoCrmError, optionalId, parseJsonObject, requireId } from '../common/client';
+import { convertFieldValue } from '../common/fields';
+import { recordDropdown, userDropdown } from '../common/props';
+import { convertLead } from '../common/records';
+import { convertLeadOutputSchema } from '../output-schemas';
+
+export const convertLeadAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'convert_lead',
+ classification: 'WRITE',
+ displayName: 'Convert Lead',
+ description: 'Converts a lead into a contact and account, and optionally a deal.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Converts one Zoho CRM lead into a contact plus an account (or links it to existing ones) and can create a deal in the same call. Use when a qualified lead should become a customer record. Not idempotent: a lead can be converted only once and a second call fails with ID_ALREADY_CONVERTED.',
+ idempotent: false,
+ },
+ props: {
+ lead_id: recordDropdown({ displayName: 'Lead', fixedModule: 'Leads' }),
+ account_id: recordDropdown({
+ displayName: 'Existing Account',
+ description: 'Link to this account; the lead\'s Company must match its name.',
+ fixedModule: 'Accounts',
+ required: false,
+ }),
+ contact_id: recordDropdown({
+ displayName: 'Existing Contact',
+ description: 'Merge into this contact; the lead\'s name and email must match.',
+ fixedModule: 'Contacts',
+ required: false,
+ }),
+ overwrite: Property.Checkbox({ displayName: 'Overwrite Contact\'s Account', description: 'Move the existing contact to the given account.', required: false, defaultValue: false }),
+ assign_to: userDropdown({
+ displayName: 'Owner',
+ description: 'Active user who owns the new records; empty keeps the lead owner.',
+ }),
+ notify_lead_owner: Property.Checkbox({ displayName: 'Notify Lead Owner', required: false, defaultValue: false }),
+ notify_new_entity_owner: Property.Checkbox({ displayName: 'Notify New Owner', required: false, defaultValue: false }),
+ create_deal: Property.Checkbox({ displayName: 'Create a Deal', required: false, defaultValue: false }),
+ deal_name: Property.ShortText({ displayName: 'Deal Name', required: false }),
+ deal_stage: Property.ShortText({ displayName: 'Deal Stage', description: 'A Stage picklist value of your org, e.g. "Qualification".', required: false }),
+ deal_closing_date: Property.ShortText({ displayName: 'Deal Closing Date', description: 'Date as yyyy-MM-dd, e.g. 2026-12-31.', required: false }),
+ deal_amount: Property.Number({ displayName: 'Deal Amount', required: false }),
+ deal_pipeline: Property.ShortText({ displayName: 'Deal Pipeline', description: 'Required when your org uses pipelines, e.g. "Standard (Standard)".', required: false }),
+ deal_extra: Property.Json({ displayName: 'Other Deal Fields (JSON)', required: false }),
+ },
+ outputSchema: convertLeadOutputSchema,
+ async run({ auth, propsValue }) {
+ const deal: Record<string, unknown> = {};
+ if (propsValue.create_deal === true) {
+ Object.assign(deal, parseJsonObject({ value: propsValue.deal_extra, name: 'Other Deal Fields' }));
+ if (!propsValue.deal_name || !propsValue.deal_stage || !propsValue.deal_closing_date) {
+ throw new ZohoCrmError('To create a deal, Deal Name, Deal Stage and Deal Closing Date are required.');
+ }
+ deal['Deal_Name'] = propsValue.deal_name;
+ deal['Stage'] = propsValue.deal_stage;
+ deal['Closing_Date'] = convertFieldValue({ field: { api_name: 'Deal Closing Date', data_type: 'date' }, value: propsValue.deal_closing_date });
+ if (propsValue.deal_amount !== undefined && propsValue.deal_amount !== null) deal['Amount'] = Number(propsValue.deal_amount);
+ if (propsValue.deal_pipeline) deal['Pipeline'] = propsValue.deal_pipeline;
+ }
+ return convertLead({
+ auth,
+ leadId: requireId({ value: propsValue.lead_id, name: 'Lead' }),
+ accountId: optionalId({ value: propsValue.account_id, name: 'Existing Account' }),
+ contactId: optionalId({ value: propsValue.contact_id, name: 'Existing Contact' }),
+ assignTo: optionalId({ value: propsValue.assign_to, name: 'Owner' }),
+ overwrite: propsValue.overwrite === true ? true : undefined,
+ notifyLeadOwner: propsValue.notify_lead_owner === true ? true : undefined,
+ notifyNewEntityOwner: propsValue.notify_new_entity_owner === true ? true : undefined,
+ deal,
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/create-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/create-record.ts
new file mode 100644
index 00000000000..8646f2af863
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/create-record.ts
@@ -0,0 +1,54 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { WORKFLOW_TRIGGERS, parseTriggers, requireApiName } from '../common/client';
+import { buildRecordPayload } from '../common/fields';
+import { additionalFieldsProp, moduleDropdown, recordFieldsProp } from '../common/props';
+import { createRecord, tryListFields } from '../common/records';
+import { recordWriteOutputSchema } from '../output-schemas';
+
+export const createRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'create_record',
+ classification: 'WRITE',
+ displayName: 'Create Record',
+ description: 'Creates a record in any module, including custom fields.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates one record in a chosen Zoho CRM module (standard or custom) from a form of that module\'s fields, custom fields included. Use to add a lead, contact, deal or custom-module record; use Create or Update Record instead when the record may already exist. Not idempotent: each call creates a new record.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown({ filter: 'creatable' }),
+ fields: recordFieldsProp({ mode: 'create' }),
+ additional_fields: additionalFieldsProp(),
+ triggers: Property.StaticMultiSelectDropdown({
+ displayName: 'Automation to Run',
+ description: 'Empty runs Zoho\'s default workflows; pick some to run only those.',
+ required: false,
+ options: { options: WORKFLOW_TRIGGERS.map((t) => ({ label: t, value: t })) },
+ }),
+ skip_automation: Property.Checkbox({
+ displayName: 'Skip All Automation',
+ description: 'Run no workflow, approval or blueprint for this record.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: recordWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module, name: 'Module' });
+ const fields = await tryListFields({ auth, module });
+ const record = buildRecordPayload({
+ dynamicValues: propsValue.fields,
+ fields,
+ extraFields: propsValue.additional_fields,
+ });
+ return createRecord({
+ auth,
+ module,
+ record,
+ trigger: parseTriggers({ value: propsValue.triggers, skipAll: propsValue.skip_automation }),
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/delete-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/delete-record.ts
new file mode 100644
index 00000000000..20e1299f377
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/delete-record.ts
@@ -0,0 +1,39 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName, requireId } from '../common/client';
+import { moduleDropdown, recordDropdown } from '../common/props';
+import { deleteRecord } from '../common/records';
+import { deleteOutputSchema } from '../output-schemas';
+
+export const deleteRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'delete_record',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Record',
+ description: 'Deletes a record (it moves to the Zoho CRM Recycle Bin).',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Deletes one Zoho CRM record by module and id; it moves to the Recycle Bin and can be restored from the Zoho UI. Use only when the record must go; to change it use Update Record. Not idempotent: deleting the same id again returns an error.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown({ filter: 'deletable' }),
+ record_id: recordDropdown(),
+ run_workflows: Property.Checkbox({
+ displayName: 'Run Workflows',
+ description: 'Run delete workflows configured in Zoho (Zoho default: on).',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ outputSchema: deleteOutputSchema,
+ async run({ auth, propsValue }) {
+ return deleteRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module, name: 'Module' }),
+ id: requireId({ value: propsValue.record_id, name: 'Record' }),
+ runWorkflows: propsValue.run_workflows !== false,
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/get-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/get-record.ts
new file mode 100644
index 00000000000..cc880607f49
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/get-record.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName, requireId } from '../common/client';
+import { moduleDropdown, recordDropdown } from '../common/props';
+import { getRecord } from '../common/records';
+import { recordOutputSchema } from '../output-schemas';
+
+export const getRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'get_record',
+ classification: 'READ',
+ displayName: 'Get Record',
+ description: 'Gets a record by id from any module, with all its fields.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Fetches one Zoho CRM record by module and id with all its fields (keys are field API names, custom fields included). Use when you know the record id. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ module: moduleDropdown(),
+ record_id: recordDropdown(),
+ },
+ outputSchema: recordOutputSchema,
+ async run({ auth, propsValue }) {
+ return getRecord({
+ auth,
+ module: requireApiName({ value: propsValue.module, name: 'Module' }),
+ id: requireId({ value: propsValue.record_id, name: 'Record' }),
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/read-file.ts b/packages/pieces/community/zoho-crm/src/lib/actions/read-file.ts
index e61509b40fa..93afcc00a45 100644
--- a/packages/pieces/community/zoho-crm/src/lib/actions/read-file.ts
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/read-file.ts
@@ -1,48 +1,39 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
import { zohoCrmAuth } from '../auth';
-import { Property, createAction } from "@activepieces/pieces-framework";
-
+import { downloadToFile, lastPathSegment } from '../common/download';
export const readFile = createAction({
- auth: zohoCrmAuth,
- name: 'read-file',
- classification: 'READ',
- displayName: 'Read file',
- description: 'Download a file content from Zoho CRM. e.g.: a Backup File',
- audience: 'both',
- aiMetadata: { description: 'Downloads the binary content of a file from Zoho CRM (e.g. a backup or attachment) given its full URL, authenticating with the connected account, and returns it as a stored file. Use when you already hold a Zoho CRM file URL and need its bytes for a later step. Requires the complete URL including the base host; read-only, so repeating the call is safe.', idempotent: true },
- props: {
- url: Property.ShortText({
- displayName: 'URL',
- description: 'The full URL to use, including the base URL',
- required: true,
- defaultValue: '',
- })
- },
- run: async ({ auth, propsValue, files }) => {
- const url = propsValue['url'];
-
- const download = await fetch(url, {
- headers: {
- Authorization: `Bearer ${auth.access_token}`,
- },
- })
- .then((response) =>
- response.ok ? response.blob() : Promise.reject(response)
- )
- .catch((error) =>
- Promise.reject(
- new Error(
- `Error when download file:\n\tDownload file response: ${(error as Error).message ?? error
- }`
- )
- )
- );
-
- const fileName = url.split('/').pop() ?? url;
-
- return files.write({
- fileName: fileName,
- data: Buffer.from(await download.arrayBuffer()),
- });
- },
+ auth: zohoCrmAuth,
+ name: 'read-file',
+ classification: 'READ',
+ displayName: 'Read file',
+ description: 'Download a file content from Zoho CRM. e.g.: a Backup File',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Downloads the binary content of a Zoho CRM file (e.g. a data backup or bulk-read result) from its full https URL and returns it as a stored file. Only URLs on the connection\'s own Zoho API host under /crm/ or its data centre\'s download host are accepted, because the token is sent with the request. The file size limit of this Activepieces deployment applies. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'URL',
+ description: 'Full https URL on your Zoho API host (/crm/...) or download host.',
+ required: true,
+ defaultValue: '',
+ }),
+ },
+ run: async ({ auth, propsValue, files }) => {
+ const url = propsValue['url'].trim();
+ const fileName = lastPathSegmentOf(url);
+ const downloaded = await downloadToFile({ auth, url, files, fileName });
+ return downloaded.file;
+ },
});
+
+function lastPathSegmentOf(url: string): string | undefined {
+ try {
+ return lastPathSegment(new URL(url));
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/update-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/update-record.ts
new file mode 100644
index 00000000000..495fd4b9127
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/update-record.ts
@@ -0,0 +1,52 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { parseTriggers, requireApiName, requireId, stringList } from '../common/client';
+import { buildRecordPayload } from '../common/fields';
+import { additionalFieldsProp, moduleDropdown, recordDropdown, recordFieldsProp } from '../common/props';
+import { tryListFields, updateRecord } from '../common/records';
+import { recordWriteOutputSchema } from '../output-schemas';
+
+export const updateRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'update_record',
+ classification: 'WRITE',
+ displayName: 'Update Record',
+ description: 'Updates fields of a record in any module. Fields left empty are not changed.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Updates selected fields of one existing Zoho CRM record by module and id; fields left empty keep their current value, and "Clear Fields" blanks named fields. Multi-select picklists are replaced, not merged. Not idempotent: every call counts as an edit and runs the module\'s on-edit workflows unless automation is skipped.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown({ filter: 'editable' }),
+ record_id: recordDropdown(),
+ fields: recordFieldsProp({ mode: 'update' }),
+ clear_fields: Property.Array({
+ displayName: 'Clear Fields',
+ description: 'Field API names to set to empty (e.g. "Phone", "Custom_Field__c").',
+ required: false,
+ }),
+ additional_fields: additionalFieldsProp(),
+ skip_automation: Property.Checkbox({
+ displayName: 'Skip All Automation',
+ description: 'Run no workflow, approval or blueprint for this update.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: recordWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module, name: 'Module' });
+ const id = requireId({ value: propsValue.record_id, name: 'Record' });
+ const clearFields = stringList(propsValue.clear_fields).map((f) => requireApiName({ value: f, name: 'Clear Fields' }));
+ const fields = await tryListFields({ auth, module });
+ const record = buildRecordPayload({
+ dynamicValues: propsValue.fields,
+ fields,
+ extraFields: propsValue.additional_fields,
+ clearFields,
+ });
+ return updateRecord({ auth, module, id, record, trigger: parseTriggers({ value: undefined, skipAll: propsValue.skip_automation }) });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/upload-attachment.ts b/packages/pieces/community/zoho-crm/src/lib/actions/upload-attachment.ts
new file mode 100644
index 00000000000..92784b96b08
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/upload-attachment.ts
@@ -0,0 +1,36 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName, requireId } from '../common/client';
+import { moduleDropdown, recordDropdown } from '../common/props';
+import { readApFile, uploadAttachment } from '../common/records';
+import { childWriteOutputSchema } from '../output-schemas';
+
+export const uploadAttachmentAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'upload_attachment',
+ classification: 'WRITE',
+ displayName: 'Upload Attachment',
+ description: 'Attaches a file to a record.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Uploads a file from the flow as an attachment on one Zoho CRM record in any module. Use when you hold file bytes from an earlier step. Not idempotent: each call adds another attachment.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown(),
+ record_id: recordDropdown(),
+ file: Property.File({ displayName: 'File', required: true }),
+ file_name: Property.ShortText({ displayName: 'File Name', description: 'Optional. Overrides the file name.', required: false }),
+ },
+ outputSchema: childWriteOutputSchema,
+ async run({ auth, propsValue }) {
+ const file = readApFile(propsValue.file);
+ return uploadAttachment({
+ auth,
+ module: requireApiName({ value: propsValue.module, name: 'Module' }),
+ recordId: requireId({ value: propsValue.record_id, name: 'Record' }),
+ file: { filename: propsValue.file_name || file.filename, data: file.data },
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/actions/upsert-record.ts b/packages/pieces/community/zoho-crm/src/lib/actions/upsert-record.ts
new file mode 100644
index 00000000000..ddf2b43b3a4
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/actions/upsert-record.ts
@@ -0,0 +1,45 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { parseTriggers, requireApiName, stringList } from '../common/client';
+import { buildRecordPayload } from '../common/fields';
+import { additionalFieldsProp, moduleDropdown, recordFieldsProp, uniqueFieldsDropdown } from '../common/props';
+import { tryListFields, upsertRecord } from '../common/records';
+import { upsertOutputSchema } from '../output-schemas';
+
+export const upsertRecordAction = createAction({
+ auth: zohoCrmAuth,
+ name: 'upsert_record',
+ classification: 'WRITE',
+ displayName: 'Create or Update Record',
+ description: 'Updates the record that matches on the duplicate-check fields, or creates it if none matches.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Inserts or updates one Zoho CRM record, matching an existing record on duplicate-check fields (Zoho default: Email for Leads/Contacts, Account_Name for Accounts, Deal_Name for Deals). Use for find-or-create without search. Not idempotent: when the data has no value for a duplicate-check field, every call inserts a new record.',
+ idempotent: false,
+ },
+ props: {
+ module: moduleDropdown({ filter: 'creatable' }),
+ duplicate_check_fields: uniqueFieldsDropdown(),
+ fields: recordFieldsProp({ mode: 'upsert' }),
+ additional_fields: additionalFieldsProp(),
+ skip_automation: Property.Checkbox({
+ displayName: 'Skip All Automation',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: upsertOutputSchema,
+ async run({ auth, propsValue }) {
+ const module = requireApiName({ value: propsValue.module, name: 'Module' });
+ const fields = await tryListFields({ auth, module });
+ const record = buildRecordPayload({ dynamicValues: propsValue.fields, fields, extraFields: propsValue.additional_fields });
+ return upsertRecord({
+ auth,
+ module,
+ record,
+ duplicateCheckFields: stringList(propsValue.duplicate_check_fields).map((f) => requireApiName({ value: f, name: 'Duplicate Check Fields' })),
+ trigger: parseTriggers({ value: undefined, skipAll: propsValue.skip_automation }),
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/client.ts b/packages/pieces/community/zoho-crm/src/lib/common/client.ts
new file mode 100644
index 00000000000..a7e06e4da39
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/client.ts
@@ -0,0 +1,456 @@
+import {
+ HttpMethod,
+ HttpRequest,
+ QueryParams,
+ httpClient,
+} from '@activepieces/pieces-common';
+import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+
+export type ZohoAuth = AppConnectionValueForAuthProperty<typeof zohoCrmAuth>;
+
+const ZOHO_API_VERSION = 'v8';
+
+export class ZohoCrmError extends Error {
+ constructor(
+ message: string,
+ readonly status?: number,
+ readonly code?: string,
+ ) {
+ super(message);
+ this.name = 'ZohoCrmError';
+ }
+}
+
+const FALLBACK_API_DOMAIN_BY_LOCATION: Record<string, string> = {
+ 'zoho.com': 'https://www.zohoapis.com',
+ 'zoho.eu': 'https://www.zohoapis.eu',
+ 'zoho.in': 'https://www.zohoapis.in',
+ 'zoho.com.au': 'https://www.zohoapis.com.au',
+ 'zoho.jp': 'https://www.zohoapis.jp',
+ 'zohocloud.ca': 'https://www.zohoapis.ca',
+};
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function readString(value: unknown): string | undefined {
+ return typeof value === 'string' ? value : undefined;
+}
+
+export function readField({ value, key }: { value: unknown; key: string }): unknown {
+ return isRecord(value) ? value[key] : undefined;
+}
+
+export function errorText(error: unknown): string {
+ return error instanceof Error ? error.message.slice(0, 200) : 'unknown error';
+}
+
+export function getApiDomain(auth: { data?: Record<string, unknown>; props?: Record<string, unknown> }): string {
+ const domain = auth.data?.['api_domain'];
+ if (typeof domain === 'string' && domain.length > 0) {
+ return domain.replace(/\/+$/, '');
+ }
+ const location = auth.props?.['location'];
+ const fallback = typeof location === 'string' ? FALLBACK_API_DOMAIN_BY_LOCATION[location] : undefined;
+ if (fallback) {
+ return fallback;
+ }
+ throw new ZohoCrmError(
+ 'This Zoho CRM connection has no api_domain (it is set by Zoho when you connect). Reconnect the Zoho CRM connection and try again.',
+ );
+}
+
+export function customApiAuthHeaders({
+ auth,
+ url,
+}: {
+ auth: { access_token: string; data?: Record<string, unknown>; props?: Record<string, unknown> };
+ url: unknown;
+}): Record<string, string> {
+ const apiHost = new URL(getApiDomain(auth)).host.toLowerCase();
+ if (typeof url === 'string' && /^https?:\/\//i.test(url.trim())) {
+ if (!isApiHostUrl({ raw: url.trim(), apiHost })) {
+ throw new ZohoCrmError(
+ `Custom API Call sends the Zoho CRM token only to https://${apiHost}. Use a path such as /Leads, or a full https://${apiHost}/crm/... URL.`,
+ );
+ }
+ }
+ return authHeaders(auth);
+}
+
+function isApiHostUrl({ raw, apiHost }: { raw: string; apiHost: string }): boolean {
+ try {
+ const parsed = new URL(raw);
+ return parsed.protocol === 'https:' && parsed.username === '' && parsed.password === '' && parsed.host.toLowerCase() === apiHost;
+ } catch {
+ return false;
+ }
+}
+
+export function authHeaders(auth: { access_token: string }): Record<string, string> {
+ return { Authorization: `Zoho-oauthtoken ${auth.access_token}` };
+}
+
+function readResponse(error: unknown): { status?: number; body?: unknown } | undefined {
+ const response = readField({ value: error, key: 'response' });
+ if (!isRecord(response)) {
+ return undefined;
+ }
+ const status = response['status'];
+ return {
+ status: typeof status === 'number' ? status : undefined,
+ body: response['body'],
+ };
+}
+
+function toErrorBody(record: Record<string, unknown>): ZohoErrorBody {
+ const details = record['details'];
+ return {
+ code: readString(record['code']),
+ message: readString(record['message']),
+ status: readString(record['status']),
+ details: isRecord(details) ? details : undefined,
+ };
+}
+
+function firstErrorBody(body: unknown): ZohoErrorBody | undefined {
+ if (typeof body === 'string') {
+ try {
+ return firstErrorBody(JSON.parse(body));
+ } catch {
+ return { message: body };
+ }
+ }
+ if (!isRecord(body)) {
+ return undefined;
+ }
+ for (const key of ['data', 'tags', '__email_drafts']) {
+ const list = body[key];
+ if (Array.isArray(list) && list.length > 0 && isRecord(list[0])) {
+ return toErrorBody(list[0]);
+ }
+ }
+ return toErrorBody(body);
+}
+
+function describeZohoError({ error, status }: { error: ZohoErrorBody; status?: number }): string {
+ const code = error.code ?? 'ERROR';
+ const field = error.details?.['api_name'];
+ const param = error.details?.['param_name'];
+ const parts = [`Zoho CRM ${code}${status ? ` (HTTP ${status})` : ''}: ${error.message ?? 'request failed'}`];
+ if (typeof field === 'string') {
+ parts.push(`field: ${field}`);
+ }
+ if (typeof param === 'string') {
+ parts.push(`parameter: ${param}`);
+ }
+ const hint = HINTS[code];
+ if (hint) {
+ parts.push(hint);
+ }
+ return parts.join(' — ');
+}
+
+const HINTS: Record<string, string> = {
+ OAUTH_SCOPE_MISMATCH:
+ 'the connection was not granted the OAuth scope this endpoint needs; reconnect it (or this action needs a scope the piece does not request yet)',
+ INVALID_TOKEN: 'the access token is invalid or expired; reconnect the Zoho CRM connection',
+ AUTHENTICATION_FAILURE: 'reconnect the Zoho CRM connection',
+ NO_PERMISSION: 'the connected Zoho user lacks permission for this module or record',
+ INVALID_MODULE: 'use a module API name such as "Leads", "Deals" or "CustomModule1"',
+ INVALID_URL_PATTERN: 'check the module API name and record id',
+ INVALID_DATA: 'check the field API names and value formats',
+ MANDATORY_NOT_FOUND: 'a required field is missing',
+ DUPLICATE_DATA: 'a record with the same unique value already exists (update it, or create-or-update on that field instead)',
+ ID_ALREADY_CONVERTED: 'the lead has already been converted',
+ TOO_MANY_REQUESTS: 'rate limit reached; retry later',
+ INTEGRATION_NOT_ENABLED:
+ 'this org stores file attachments in Zoho WorkDrive and the integration is off; an admin must enable it (Setup, Marketplace, Zoho, WorkDrive), or attach a link instead',
+ DOWNLOAD_NOT_ALLOWED: 'link attachments have no file to download; open their link_url instead',
+};
+
+export function toZohoError(error: unknown): Error {
+ const response = readResponse(error);
+ if (!response) {
+ return error instanceof Error ? error : new Error(String(error));
+ }
+ const parsed = firstErrorBody(response.body);
+ if (response.status === 429) {
+ return new ZohoCrmError(describeZohoError({ error: { ...parsed, code: parsed?.code ?? 'TOO_MANY_REQUESTS' }, status: 429 }), 429, 'TOO_MANY_REQUESTS');
+ }
+ return new ZohoCrmError(describeZohoError({ error: parsed ?? {}, status: response.status }), response.status, parsed?.code);
+}
+
+export function zohoApiUrl({ auth, path, version = ZOHO_API_VERSION }: { auth: ZohoAuth; path: string; version?: string }): string {
+ return `${getApiDomain(auth)}/crm/${version}${path}`;
+}
+
+export async function zohoRequestRaw<T>(req: ZohoRequest): Promise<{ status: number; body: T | undefined; headers: Record<string, unknown> }> {
+ const url = zohoApiUrl({ auth: req.auth, path: req.path, version: req.version });
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method: req.method,
+ url,
+ headers: { ...authHeaders(req.auth), ...(req.headers ?? {}) },
+ queryParams: req.query,
+ body: req.body,
+ responseType: req.responseType,
+ });
+ return { status: response.status, body: response.body, headers: response.headers ?? {} };
+ } catch (error) {
+ throw toZohoError(error);
+ }
+}
+
+export async function zohoRequest<T>(req: ZohoRequest): Promise<T | undefined> {
+ const { status, body } = await zohoRequestRaw<T>(req);
+ if (status === 204) {
+ return undefined;
+ }
+ return body;
+}
+
+function toWriteItem(value: unknown): ZohoWriteItem {
+ if (!isRecord(value)) {
+ return {};
+ }
+ const details = value['details'];
+ const duplicateField = value['duplicate_field'];
+ return {
+ code: readString(value['code']),
+ status: readString(value['status']),
+ message: readString(value['message']),
+ action: readString(value['action']),
+ duplicate_field: typeof duplicateField === 'string' ? duplicateField : null,
+ details: isRecord(details) ? details : undefined,
+ };
+}
+
+function unwrapWriteItems({ body, key = 'data' }: { body: unknown; key?: string }): ZohoWriteItem[] {
+ const list = readField({ value: body, key });
+ if (!Array.isArray(list) || list.length === 0) {
+ throw new ZohoCrmError(`Zoho CRM returned an unexpected response (no "${key}" array).`);
+ }
+ const items = list.map(toWriteItem);
+ const failed = items.find((item) => item.status === 'error');
+ if (failed) {
+ throw new ZohoCrmError(describeZohoError({ error: failed }), undefined, failed.code);
+ }
+ return items;
+}
+
+export function unwrapWriteItem({ body, key = 'data' }: { body: unknown; key?: string }): ZohoWriteItem {
+ return unwrapWriteItems({ body, key })[0];
+}
+
+function userRef(value: unknown): { id: string | null; name: string | null } {
+ return {
+ id: readString(readField({ value, key: 'id' })) ?? null,
+ name: readString(readField({ value, key: 'name' })) ?? null,
+ };
+}
+
+export function flattenWriteResult(item: ZohoWriteItem): Record<string, unknown> {
+ const d = item.details ?? {};
+ const createdBy = userRef(d['Created_By']);
+ const modifiedBy = userRef(d['Modified_By']);
+ return {
+ id: readString(d['id']) ?? null,
+ status: item.status ?? null,
+ code: item.code ?? null,
+ message: item.message ?? null,
+ action: item.action ?? null,
+ duplicate_field: item.duplicate_field ?? null,
+ created_time: readString(d['Created_Time']) ?? null,
+ modified_time: readString(d['Modified_Time']) ?? null,
+ created_by_id: createdBy.id,
+ created_by_name: createdBy.name,
+ modified_by_id: modifiedBy.id,
+ modified_by_name: modifiedBy.name,
+ };
+}
+
+const ID_RE = /^[0-9]{1,25}$/;
+const API_NAME_RE = /^[A-Za-z0-9_$]{1,100}$/;
+const KEY_RE = /^[A-Za-z0-9]{1,200}$/;
+
+export function requireId({ value, name }: { value: unknown; name: string }): string {
+ const s = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!ID_RE.test(s)) {
+ throw new ZohoCrmError(`${name} must be a numeric Zoho id such as "5725767000000524157" (got "${String(value ?? '')}").`);
+ }
+ return s;
+}
+
+export function requireKey({ value, name }: { value: unknown; name: string }): string {
+ const s = typeof value === 'string' ? value.trim() : '';
+ if (!KEY_RE.test(s)) {
+ throw new ZohoCrmError(`${name} must be the id string returned by Zoho (letters and digits only).`);
+ }
+ return s;
+}
+
+export function optionalId({ value, name }: { value: unknown; name: string }): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ return requireId({ value, name });
+}
+
+export function requireApiName({ value, name }: { value: unknown; name: string }): string {
+ const s = typeof value === 'string' ? value.trim() : '';
+ if (!API_NAME_RE.test(s)) {
+ throw new ZohoCrmError(`${name} must be a Zoho API name such as "Leads" or "Custom_Field__c" (got "${String(value ?? '')}").`);
+ }
+ return s;
+}
+
+export function optionalInt({ value, name, min, max }: { value: unknown; name: string; min: number; max: number }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const n = typeof value === 'number' ? value : Number(value);
+ if (!Number.isInteger(n) || n < min || n > max) {
+ throw new ZohoCrmError(`${name} must be a whole number between ${min} and ${max}.`);
+ }
+ return n;
+}
+
+export function validatePaging({
+ page,
+ perPage,
+ pageToken,
+ tokenSupported,
+}: {
+ page?: number;
+ perPage: number;
+ pageToken?: string;
+ tokenSupported: boolean;
+}): void {
+ if (page !== undefined && pageToken) {
+ throw new ZohoCrmError('Use either page or page_token, not both.');
+ }
+ if (page !== undefined && page * perPage > MAX_PAGED_ITEMS) {
+ throw new ZohoCrmError(
+ `Zoho only serves the first ${MAX_PAGED_ITEMS.toLocaleString('en-US')} items by page number (page × per_page).${
+ tokenSupported ? ' Pass next_page_token from the previous result instead.' : ''
+ }`,
+ );
+ }
+}
+
+const MAX_PAGED_ITEMS = 2000;
+
+export function parseJsonObject({ value, name }: { value: unknown; name: string }): Record<string, unknown> {
+ if (value === undefined || value === null || value === '') {
+ return {};
+ }
+ const parsed = typeof value === 'string' ? parseJsonText({ text: value, name }) : value;
+ if (!isRecord(parsed)) {
+ throw new ZohoCrmError(`${name} must be a JSON object, e.g. {"Lead_Source": "Web"}.`);
+ }
+ return parsed;
+}
+
+function parseJsonText({ text, name }: { text: string; name: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new ZohoCrmError(`${name} must be a JSON object, e.g. {"Lead_Source": "Web"}.`);
+ }
+}
+
+function listItems(value: unknown): unknown[] {
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => {
+ if (Array.isArray(item)) {
+ return item;
+ }
+ return typeof item === 'string' ? jsonList(item) ?? [item] : [item];
+ });
+ }
+ const text = String(value);
+ return jsonList(text) ?? text.split(',');
+}
+
+function jsonList(text: string): unknown[] | undefined {
+ const trimmed = text.trim();
+ if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ return Array.isArray(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function stringList(value: unknown): string[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ return listItems(value)
+ .map((v) => (typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : ''))
+ .filter((v) => v.length > 0);
+}
+
+export const WORKFLOW_TRIGGERS = ['workflow', 'approval', 'blueprint', 'pathfinder', 'orchestration'] as const;
+
+const WORKFLOW_TRIGGER_SET = new Set<string>(WORKFLOW_TRIGGERS);
+
+export function parseTriggers({ value, skipAll }: { value: unknown; skipAll?: boolean }): string[] | undefined {
+ if (skipAll === true) {
+ return [];
+ }
+ const list = stringList(value);
+ if (list.length === 0) {
+ return undefined;
+ }
+ const bad = list.filter((t) => !WORKFLOW_TRIGGER_SET.has(t));
+ if (bad.length > 0) {
+ throw new ZohoCrmError(`Unknown automation trigger(s): ${bad.join(', ')}. Allowed: ${WORKFLOW_TRIGGERS.join(', ')}.`);
+ }
+ return list;
+}
+
+type ZohoErrorBody = {
+ code?: string;
+ message?: string;
+ status?: string;
+ details?: Record<string, unknown>;
+};
+
+export type ZohoRequest = {
+ auth: ZohoAuth;
+ method: HttpMethod;
+ path: string;
+ version?: string;
+ query?: QueryParams;
+ body?: unknown;
+ headers?: Record<string, string>;
+ responseType?: HttpRequest['responseType'];
+};
+
+export type ZohoWriteItem = {
+ code?: string;
+ status?: string;
+ message?: string;
+ action?: string;
+ duplicate_field?: string | null;
+ details?: Record<string, unknown>;
+};
+
+export type ZohoListInfo = {
+ per_page?: number;
+ count?: number;
+ page?: number;
+ more_records?: boolean;
+ next_page_token?: string | null;
+ previous_page_token?: string | null;
+ page_token_expiry?: string | null;
+};
+
+export type ZohoListResponse<T> = { data?: T[]; info?: ZohoListInfo };
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/download.ts b/packages/pieces/community/zoho-crm/src/lib/common/download.ts
new file mode 100644
index 00000000000..9f2b774b4bc
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/download.ts
@@ -0,0 +1,175 @@
+import { Readable, Transform, pipeline } from 'node:stream';
+import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { FilesService } from '@activepieces/pieces-framework';
+import { ZohoAuth, ZohoCrmError, authHeaders, getApiDomain, toZohoError } from './client';
+import { TokenHosts, tokenHosts, zohoTokenUrl } from './host-guard';
+
+export async function downloadToFile({
+ auth,
+ url,
+ files,
+ fileName,
+ fallbackName,
+}: {
+ auth: ZohoAuth;
+ url: string;
+ files: FilesService;
+ fileName?: string;
+ fallbackName?: string;
+}): Promise<DownloadedFile> {
+ const hosts = tokenHosts(getApiDomain(auth));
+ const first = zohoTokenUrl({ raw: url, hosts });
+ if (!first) {
+ throw new ZohoCrmError(
+ `Refusing to send the Zoho CRM token to "${url}": the URL must be an https link to this connection's Zoho API (https://${hosts.apiHost}/crm/...)${
+ hosts.downloadHosts.length > 0 ? ` or its download host (https://${hosts.downloadHosts[0]}/...)` : ''
+ }.`,
+ );
+ }
+ const response = await openDownload({ url: first, hosts, accessToken: auth.access_token });
+ const name = fileName ?? fileNameFromDisposition({ header: response.headers['content-disposition'], fallback: fallbackName ?? lastPathSegment(first) });
+ const counted = countBytes(response.body);
+ const file = await files.write({ fileName: name, data: counted.stream }).catch((error: unknown) => {
+ counted.stream.destroy();
+ response.body.destroy();
+ throw error;
+ });
+ const contentType = response.headers['content-type'];
+ return { file, fileName: name, size: counted.total(), contentType: typeof contentType === 'string' ? contentType : null };
+}
+
+export function fileNameFromDisposition({ header, fallback }: { header: unknown; fallback: string }): string {
+ const value = Array.isArray(header) ? header[0] : header;
+ if (typeof value !== 'string') return fallback;
+ const star = /filename\*=(?:[\w!#$%&+^`{}~-]+'[\w-]*')?([^;]+)/i.exec(value);
+ const plain = /filename="?([^";]+)"?/i.exec(value);
+ const raw = star ? safeDecode(star[1].trim().replace(/^"|"$/g, '')) : plain ? plain[1].trim() : undefined;
+ return (raw === undefined ? undefined : safeFileName(raw)) ?? fallback;
+}
+
+export function lastPathSegment(url: URL): string {
+ const last = url.pathname.split('/').filter((part) => part.length > 0).pop();
+ return (last === undefined ? undefined : safeFileName(safeDecode(last))) ?? 'zoho-file';
+}
+
+function safeDecode(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+function safeFileName(raw: string): string | undefined {
+ const base = raw.split(/[\\/]/).pop() ?? '';
+ const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, '').trim();
+ return cleaned.length === 0 || /^\.+$/.test(cleaned) ? undefined : cleaned.slice(0, 200);
+}
+
+async function openDownload({ url, hosts, accessToken }: { url: URL; hosts: TokenHosts; accessToken: string }): Promise<OpenedDownload> {
+ let current = url;
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
+ const withToken = zohoTokenUrl({ raw: current.toString(), hosts }) !== null;
+ let response;
+ try {
+ response = await httpClient.sendRequest<Readable | Buffer | undefined>({
+ method: HttpMethod.GET,
+ url: current.toString(),
+ headers: withToken ? authHeaders({ access_token: accessToken }) : {},
+ responseType: 'stream',
+ followRedirects: false,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+ } catch (error) {
+ throw toZohoError(error);
+ }
+ const body = toReadable(response.body);
+ const headers = response.headers ?? {};
+ if (response.status >= 300 && response.status < 400) {
+ body.destroy();
+ current = redirectTarget({ location: headers['location'], base: current, status: response.status, hosts });
+ continue;
+ }
+ if (response.status === 204) {
+ body.destroy();
+ throw new ZohoCrmError('Zoho returned no file content (a link attachment has no file to download).');
+ }
+ return { body, headers };
+ }
+ throw new ZohoCrmError(`The download was redirected more than ${MAX_REDIRECTS} times, so it was stopped.`);
+}
+
+function redirectTarget({ location, base, status, hosts }: { location: unknown; base: URL; status: number; hosts: TokenHosts }): URL {
+ const value = Array.isArray(location) ? location[0] : location;
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new ZohoCrmError(`Zoho answered HTTP ${status} without a Location header.`);
+ }
+ let target: URL;
+ try {
+ target = new URL(value, base);
+ } catch {
+ throw new ZohoCrmError(`Zoho redirected the download to an address that is not a valid link.`);
+ }
+ if (target.protocol !== 'https:') {
+ throw new ZohoCrmError(`Zoho redirected the download to a non-https address, so it was stopped.`);
+ }
+ if (!isFileHost({ url: target, hosts })) {
+ throw new ZohoCrmError(`Zoho redirected the download to ${target.host}, which is not one of this connection's Zoho CRM file hosts, so it was stopped.`);
+ }
+ return target;
+}
+
+function isFileHost({ url, hosts }: { url: URL; hosts: TokenHosts }): boolean {
+ const host = url.hostname.toLowerCase().replace(/\.$/, '');
+ const standardPort = url.port === '' || url.port === '443';
+ const noUserInfo = url.username === '' && url.password === '';
+ return standardPort && noUserInfo && (host === hosts.apiHost || hosts.downloadHosts.includes(host));
+}
+
+function toReadable(body: Readable | Buffer | undefined): Readable {
+ if (body === undefined) return Readable.from([]);
+ if (Buffer.isBuffer(body)) return Readable.from([body]);
+ return body;
+}
+
+function countBytes(body: Readable): { stream: Readable; total: () => number } {
+ let total = 0;
+ let idleTimer: NodeJS.Timeout | undefined;
+ const clearIdleTimer = (): void => {
+ if (idleTimer !== undefined) {
+ clearTimeout(idleTimer);
+ idleTimer = undefined;
+ }
+ };
+ const counter = new Transform({
+ transform(chunk: unknown, _encoding, callback) {
+ armIdleTimer();
+ const bytes = Buffer.isBuffer(chunk) ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk) : Buffer.from(String(chunk));
+ total += bytes.length;
+ callback(null, bytes);
+ },
+ flush(callback) {
+ clearIdleTimer();
+ callback();
+ },
+ destroy(error, callback) {
+ clearIdleTimer();
+ callback(error);
+ },
+ });
+ const armIdleTimer = (): void => {
+ clearIdleTimer();
+ idleTimer = setTimeout(() => counter.destroy(new ZohoCrmError(`The download stalled for ${IDLE_TIMEOUT_MS / 1000} seconds.`)), IDLE_TIMEOUT_MS);
+ };
+ armIdleTimer();
+ const stream = pipeline(body, counter, () => clearIdleTimer());
+ return { stream, total: () => total };
+}
+
+const MAX_REDIRECTS = 5;
+const REQUEST_TIMEOUT_MS = 60_000;
+const IDLE_TIMEOUT_MS = 60_000;
+
+type OpenedDownload = { body: Readable; headers: Record<string, unknown> };
+
+export type DownloadedFile = { file: string; fileName: string; size: number; contentType: string | null };
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/fields.ts b/packages/pieces/community/zoho-crm/src/lib/common/fields.ts
new file mode 100644
index 00000000000..ac1af66eda9
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/fields.ts
@@ -0,0 +1,241 @@
+import { InputPropertyMap, Property } from '@activepieces/pieces-framework';
+import { ZohoCrmError, parseJsonObject, requireId, stringList } from './client';
+import { ZohoField } from './metadata';
+
+const SKIPPED_TYPES = new Set([
+ 'subform',
+ 'fileupload',
+ 'imageupload',
+ 'profileimage',
+ 'formula',
+ 'autonumber',
+ 'event_reminder',
+ 'RRULE',
+ 'ALARM',
+ 'multiselectlookup',
+ 'multiuserlookup',
+ 'consent_lookup',
+ 'rollup_summary',
+]);
+
+const NUMBER_TYPES = new Set(['integer', 'double', 'decimal', 'currency', 'percent']);
+const BIG_INTEGER_TYPES = new Set(['bigint', 'long']);
+const LOOKUP_TYPES = new Set(['lookup', 'ownerlookup', 'userlookup']);
+const SYSTEM_FIELDS = new Set(['id', 'Created_Time', 'Modified_Time', 'Created_By', 'Modified_By', 'Last_Activity_Time', 'Tag']);
+
+export function isApiReadOnly(field: ZohoField): boolean {
+ if (field.read_only === true) return true;
+ const apiWritableOwner = field.data_type === 'ownerlookup' && field.api_name === 'Owner';
+ return field.field_read_only === true && !apiWritableOwner;
+}
+
+function isWritableField(field: ZohoField): boolean {
+ if (!field.api_name || SYSTEM_FIELDS.has(field.api_name) || field.api_name.startsWith('$')) {
+ return false;
+ }
+ if (isApiReadOnly(field) || field.visible === false) {
+ return false;
+ }
+ return !SKIPPED_TYPES.has(field.data_type ?? '');
+}
+
+function labelOf(field: ZohoField): string {
+ return field.display_label ?? field.field_label ?? field.api_name;
+}
+
+function picklistOptions(field: ZohoField): { label: string; value: string }[] {
+ return (field.pick_list_values ?? []).flatMap((p) => {
+ const value = p.actual_value;
+ if (typeof value !== 'string' || value === '-None-') {
+ return [];
+ }
+ return [{ label: p.display_value ?? value, value }];
+ });
+}
+
+export function buildFieldProps({ fields, mode }: { fields: ZohoField[]; mode: FieldMode }): InputPropertyMap {
+ const props: InputPropertyMap = {};
+ for (const field of fields.filter(isWritableField)) {
+ const required = mode === 'create' && field.system_mandatory === true;
+ const displayName = labelOf(field);
+ const type = field.data_type ?? 'text';
+ const base = `API name: ${field.api_name}.`;
+ if (NUMBER_TYPES.has(type)) {
+ props[field.api_name] = Property.Number({ displayName, description: base, required });
+ } else if (BIG_INTEGER_TYPES.has(type)) {
+ props[field.api_name] = Property.ShortText({ displayName, description: `${base} Whole number, up to 18 digits.`, required });
+ } else if (type === 'boolean') {
+ props[field.api_name] = Property.StaticDropdown({
+ displayName,
+ description: `${base} Leave empty to ${mode === 'update' ? 'keep the current value' : 'use the Zoho default'}.`,
+ required,
+ options: { options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] },
+ });
+ } else if (type === 'date') {
+ props[field.api_name] = Property.ShortText({ displayName, description: `${base} Date as yyyy-MM-dd, e.g. 2026-10-01.`, required });
+ } else if (type === 'datetime') {
+ props[field.api_name] = Property.DateTime({ displayName, description: `${base} Sent as ISO 8601 with offset.`, required });
+ } else if (type === 'picklist') {
+ props[field.api_name] = Property.StaticDropdown({
+ displayName,
+ description: base,
+ required,
+ options: { options: picklistOptions(field) },
+ });
+ } else if (type === 'multiselectpicklist') {
+ props[field.api_name] = Property.StaticMultiSelectDropdown({
+ displayName,
+ description: `${base} Selected values replace the current ones.`,
+ required,
+ options: { options: picklistOptions(field) },
+ });
+ } else if (LOOKUP_TYPES.has(type)) {
+ const target = type === 'lookup' ? field.lookup?.module?.api_name ?? 'the related module' : 'Users';
+ props[field.api_name] = Property.ShortText({
+ displayName,
+ description: `${base} Id of a record in ${target}.`,
+ required,
+ });
+ } else if (type === 'textarea') {
+ props[field.api_name] = Property.LongText({ displayName, description: base, required });
+ } else {
+ props[field.api_name] = Property.ShortText({ displayName, description: base, required });
+ }
+ }
+ return props;
+}
+
+export function fieldsJsonFallbackProp({ reason, mode }: { reason: string; mode: FieldMode }): InputPropertyMap {
+ return {
+ [FIELDS_JSON_KEY]: Property.Json({
+ displayName: 'Fields',
+ description: `The field list could not be loaded (${reason}). Enter a JSON object of field API names and values, e.g. {"Last_Name": "Doe", "Email": "[email protected]"}.`,
+ required: mode === 'create',
+ defaultValue: {},
+ }),
+ };
+}
+
+function isBlank(value: unknown): boolean {
+ return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);
+}
+
+function toDate({ value, api }: { value: unknown; api: string }): string {
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/.exec(String(value).trim());
+ const date = match ? new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))) : undefined;
+ if (!match || !date || date.getUTCMonth() !== Number(match[2]) - 1 || date.getUTCDate() !== Number(match[3])) {
+ throw new ZohoCrmError(`${api} must be a date as yyyy-MM-dd, e.g. 2026-10-01.`);
+ }
+ return `${match[1]}-${match[2]}-${match[3]}`;
+}
+
+function toBigInteger({ value, api }: { value: unknown; api: string }): string {
+ if (typeof value === 'number') {
+ if (!Number.isSafeInteger(value)) {
+ throw new ZohoCrmError(`${api} arrived as a number above 2^53, which is already rounded; pass long integers above 2^53 as text (the exact digits).`);
+ }
+ return String(value);
+ }
+ const digits = String(value).trim();
+ if (!/^-?\d{1,18}$/.test(digits)) {
+ throw new ZohoCrmError(`${api} must be a whole number of at most 18 digits.`);
+ }
+ return digits;
+}
+
+function toDateTime({ value, api }: { value: unknown; api: string }): string {
+ const s = String(value);
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/.test(s)) {
+ return s;
+ }
+ const d = new Date(s);
+ if (Number.isNaN(d.getTime())) {
+ throw new ZohoCrmError(`${api} must be an ISO 8601 date-time such as 2026-10-01T09:00:00+02:00.`);
+ }
+ return d.toISOString().replace(/\.\d{3}Z$/, '+00:00');
+}
+
+function toBoolean({ value, api }: { value: unknown; api: string }): boolean {
+ if (value === true || value === 'true') return true;
+ if (value === false || value === 'false') return false;
+ throw new ZohoCrmError(`${api} must be true or false.`);
+}
+
+function toNumber({ value, api }: { value: unknown; api: string }): number {
+ const n = typeof value === 'number' ? value : Number(value);
+ if (!Number.isFinite(n)) {
+ throw new ZohoCrmError(`${api} must be a number.`);
+ }
+ if (typeof value === 'string' && !isExactDecimal({ text: value.trim(), n })) {
+ throw new ZohoCrmError(`${api} has more digits than can be sent exactly (${value.trim()}); use at most 15 significant digits.`);
+ }
+ return n;
+}
+
+function isExactDecimal({ text, n }: { text: string; n: number }): boolean {
+ const match = /^([+-]?)(\d*)(?:\.(\d*))?$/.exec(text);
+ if (!match) {
+ return true;
+ }
+ const whole = match[2].replace(/^0+/, '');
+ const fraction = (match[3] ?? '').replace(/0+$/, '');
+ if ((whole + fraction).replace(/^0+/, '').length <= MAX_EXACT_DIGITS) {
+ return true;
+ }
+ const canonical = `${match[1] === '-' ? '-' : ''}${whole || '0'}${fraction ? `.${fraction}` : ''}`;
+ return String(n) === canonical;
+}
+
+const MAX_EXACT_DIGITS = 15;
+
+export function convertFieldValue({ field, value }: { field: ZohoField | undefined; value: unknown }): unknown {
+ if (!field) {
+ return value;
+ }
+ const type = field.data_type ?? '';
+ const api = field.api_name;
+ if (NUMBER_TYPES.has(type)) return toNumber({ value, api });
+ if (BIG_INTEGER_TYPES.has(type)) return toBigInteger({ value, api });
+ if (type === 'boolean') return toBoolean({ value, api });
+ if (type === 'date') return toDate({ value, api });
+ if (type === 'datetime') return toDateTime({ value, api });
+ if (type === 'multiselectpicklist') {
+ return stringList(value);
+ }
+ if (LOOKUP_TYPES.has(type)) {
+ if (typeof value === 'object' && value !== null) return value;
+ return { id: requireId({ value, name: api }) };
+ }
+ return value;
+}
+
+export function buildRecordPayload({
+ dynamicValues,
+ fields,
+ extraFields,
+ clearFields,
+}: {
+ dynamicValues: Record<string, unknown> | undefined;
+ fields: ZohoField[] | undefined;
+ extraFields?: unknown;
+ clearFields?: string[];
+}): Record<string, unknown> {
+ const byName = new Map((fields ?? []).map((f) => [f.api_name, f]));
+ const { [FIELDS_JSON_KEY]: fallback, ...values } = dynamicValues ?? {};
+ const formValues = Object.fromEntries(
+ Object.entries(values)
+ .filter(([, value]) => !isBlank(value))
+ .map(([key, value]) => [key, convertFieldValue({ field: byName.get(key), value })]),
+ );
+ const cleared = Object.fromEntries((clearFields ?? []).map((key) => [key, null]));
+ return {
+ ...parseJsonObject({ value: extraFields, name: 'Additional fields' }),
+ ...parseJsonObject({ value: fallback, name: 'Fields' }),
+ ...formValues,
+ ...cleared,
+ };
+}
+
+export const FIELDS_JSON_KEY = '__fields_json';
+
+export type FieldMode = 'create' | 'update' | 'upsert';
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/flatten.ts b/packages/pieces/community/zoho-crm/src/lib/common/flatten.ts
new file mode 100644
index 00000000000..e9af7f59bc7
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/flatten.ts
@@ -0,0 +1,111 @@
+import { isRecord } from './client';
+
+function obj(value: unknown): Record<string, unknown> {
+ return isRecord(value) ? value : {};
+}
+
+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 emailOf(value: unknown): string | null {
+ if (typeof value === 'string') return value;
+ return str(obj(value)['email']);
+}
+
+function emailList(value: unknown): string | null {
+ if (!Array.isArray(value)) return null;
+ const list = value.map(emailOf).filter((v): v is string => v !== null);
+ return list.length > 0 ? list.join(', ') : null;
+}
+
+export function flattenUser(u: Record<string, unknown>): Record<string, unknown> {
+ const role = obj(u['role']);
+ const profile = obj(u['profile']);
+ return {
+ id: str(u['id']),
+ full_name: str(u['full_name']),
+ first_name: str(u['first_name']),
+ last_name: str(u['last_name']),
+ email: str(u['email']),
+ status: str(u['status']),
+ role_id: str(role['id']),
+ role_name: str(role['name']),
+ profile_id: str(profile['id']),
+ profile_name: str(profile['name']),
+ time_zone: str(u['time_zone']),
+ confirm: typeof u['confirm'] === 'boolean' ? u['confirm'] : null,
+ };
+}
+
+export function flattenNote(n: Record<string, unknown>): Record<string, unknown> {
+ const parent = obj(n['Parent_Id']);
+ const parentModule = obj(parent['module']);
+ const owner = obj(n['Owner']);
+ return {
+ id: str(n['id']),
+ title: str(n['Note_Title']),
+ content: str(n['Note_Content']),
+ parent_id: str(parent['id']),
+ parent_name: str(parent['name']),
+ parent_module: str(parentModule['api_name']) ?? str(n['$se_module']),
+ owner_id: str(owner['id']),
+ owner_name: str(owner['name']),
+ created_time: str(n['Created_Time']),
+ modified_time: str(n['Modified_Time']),
+ };
+}
+
+export function flattenAttachment(a: Record<string, unknown>): Record<string, unknown> {
+ const owner = obj(a['Owner']);
+ const createdBy = obj(a['Created_By']);
+ const size = a['Size'];
+ return {
+ id: str(a['id']),
+ file_name: str(a['File_Name']),
+ size: typeof size === 'number' ? size : typeof size === 'string' && size !== '' ? Number(size) : null,
+ file_id: str(a['$file_id']),
+ type: str(a['$type']),
+ link_url: str(a['$link_url']),
+ created_time: str(a['Created_Time']),
+ modified_time: str(a['Modified_Time']),
+ owner_name: str(owner['name']),
+ created_by_name: str(createdBy['name']),
+ parent_module: str(a['$se_module']),
+ };
+}
+
+export function flattenDraft(d: Record<string, unknown>): Record<string, unknown> {
+ const schedule = obj(d['schedule_details']);
+ const attachments = Array.isArray(d['attachments']) ? d['attachments'] : [];
+ return {
+ id: str(d['id']),
+ subject: str(d['subject']),
+ from: emailOf(d['from']),
+ to: emailList(d['to']),
+ cc: emailList(d['cc']),
+ bcc: emailList(d['bcc']),
+ reply_to: emailOf(d['reply_to']),
+ summary: str(d['summary']),
+ content: str(d['content']),
+ rich_text: typeof d['rich_text'] === 'boolean' ? d['rich_text'] : null,
+ scheduled_time: str(schedule['time']),
+ attachment_count: attachments.length,
+ created_time: str(d['created_time']),
+ modified_time: str(d['modified_time']),
+ };
+}
+
+export function flattenRelatedList(r: Record<string, unknown>): Record<string, unknown> {
+ return {
+ api_name: str(r['api_name']),
+ display_label: str(r['display_label']),
+ module_api_name: str(obj(r['module'])['api_name']),
+ type: str(r['type']),
+ href: str(r['href']),
+ status: str(r['status']),
+ id: str(r['id']),
+ };
+}
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/host-guard.ts b/packages/pieces/community/zoho-crm/src/lib/common/host-guard.ts
new file mode 100644
index 00000000000..e9102a1fe23
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/host-guard.ts
@@ -0,0 +1,50 @@
+export function tokenHosts(apiDomain: string): TokenHosts {
+ const apiHost = hostOf(apiDomain);
+ const dataCentre = /^(?:www\.)?zohoapis\.(.+)$/.exec(apiHost)?.[1];
+ const zohoDomains = dataCentre === undefined ? [] : dataCentre === 'ca' ? ['zohocloud.ca'] : [`zoho.${dataCentre}`];
+ return {
+ apiHost,
+ downloadHosts: zohoDomains.flatMap((domain) => [`download-accl.${domain}`, `download.${domain}`]),
+ };
+}
+
+export function zohoTokenUrl({ raw, hosts }: { raw: string; hosts: TokenHosts }): URL | null {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') return null;
+ if (url.port !== '' && url.port !== '443') return null;
+ const host = url.hostname.toLowerCase().replace(/\.$/, '');
+ const path = decodedPath(url.pathname);
+ if (path === null || FUNCTIONS_PATH.test(path)) return null;
+ if (host === hosts.apiHost) {
+ return path.startsWith('/crm/') ? url : null;
+ }
+ if (hosts.downloadHosts.includes(host)) {
+ return path.startsWith('/crm/') || path.startsWith('/v2/crm/') ? url : null;
+ }
+ return null;
+}
+
+function hostOf(apiDomain: string): string {
+ try {
+ return new URL(apiDomain).hostname.toLowerCase();
+ } catch {
+ return '';
+ }
+}
+
+function decodedPath(pathname: string): string | null {
+ try {
+ return decodeURIComponent(pathname).toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+const FUNCTIONS_PATH = /\/functions(\/|$)/;
+
+export type TokenHosts = { apiHost: string; downloadHosts: string[] };
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/metadata.ts b/packages/pieces/community/zoho-crm/src/lib/common/metadata.ts
new file mode 100644
index 00000000000..44ca641afc1
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/metadata.ts
@@ -0,0 +1,89 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ZohoAuth, zohoRequest } from './client';
+
+export async function listModules(auth: ZohoAuth): Promise<ZohoModule[]> {
+ const body = await zohoRequest<{ modules?: ZohoModule[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/modules',
+ });
+ return body?.modules ?? [];
+}
+
+export async function listFields({ auth, module }: { auth: ZohoAuth; module: string }): Promise<ZohoField[]> {
+ const body = await zohoRequest<{ fields?: ZohoField[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/fields',
+ query: { module },
+ });
+ return body?.fields ?? [];
+}
+
+const LOW_VALUE_FIELDS = new Set(['Latitude', 'Longitude', 'Coordinates', 'Record_Image']);
+
+function isLowValue(field: ZohoField): boolean {
+ return LOW_VALUE_FIELDS.has(field.api_name) || field.api_name.endsWith('__s') || field.api_name.startsWith('$');
+}
+
+export function defaultFieldSelection({ fields, max = 50 }: { fields: ZohoField[]; max?: number }): string[] {
+ const readable = fields.filter((f) => f.visible !== false && f.api_name && f.api_name !== 'id');
+ const custom = readable.filter((f) => f.custom_field === true && !isLowValue(f));
+ const standard = readable.filter((f) => f.custom_field !== true && !isLowValue(f));
+ const low = readable.filter((f) => isLowValue(f));
+ return ['id', ...[...custom, ...standard, ...low].map((f) => f.api_name)].slice(0, max);
+}
+
+const NAME_FIELDS = [
+ 'Full_Name',
+ 'Account_Name',
+ 'Deal_Name',
+ 'Subject',
+ 'Event_Title',
+ 'Product_Name',
+ 'Campaign_Name',
+ 'Solution_Title',
+ 'Vendor_Name',
+ 'Price_Book_Name',
+ 'Name',
+ 'Last_Name',
+];
+
+export function nameFieldOf(fields: ZohoField[]): string | undefined {
+ const names = new Set(fields.map((f) => f.api_name));
+ return NAME_FIELDS.find((n) => names.has(n));
+}
+
+export type ZohoModule = {
+ api_name: string;
+ module_name?: string;
+ plural_label?: string;
+ singular_label?: string;
+ api_supported?: boolean;
+ creatable?: boolean;
+ editable?: boolean;
+ deletable?: boolean;
+ viewable?: boolean;
+ generated_type?: string;
+ id?: string;
+};
+
+export type ZohoPicklistValue = { display_value?: string; actual_value?: string };
+
+export type ZohoField = {
+ api_name: string;
+ id?: string;
+ field_label?: string;
+ display_label?: string;
+ data_type?: string;
+ json_type?: string;
+ system_mandatory?: boolean;
+ read_only?: boolean;
+ field_read_only?: boolean;
+ visible?: boolean;
+ custom_field?: boolean;
+ length?: number;
+ pick_list_values?: ZohoPicklistValue[];
+ lookup?: { module?: { api_name?: string } } | null;
+ unique?: unknown;
+};
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/polling.ts b/packages/pieces/community/zoho-crm/src/lib/common/polling.ts
new file mode 100644
index 00000000000..b8c71088854
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/polling.ts
@@ -0,0 +1,220 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Store } from '@activepieces/pieces-framework';
+import { ZohoAuth, ZohoCrmError, ZohoListResponse, zohoRequestRaw } from './client';
+
+export const CURSOR_KEY = 'zoho_poll_cursor';
+
+export async function collectSince({
+ cursor,
+ fetchPage,
+ timeField,
+ maxPages = MAX_POLL_PAGES,
+ maxMarkIds = MAX_MARK_IDS,
+}: {
+ cursor: PollCursor;
+ fetchPage: PageFetcher;
+ timeField: string;
+ maxPages?: number;
+ maxMarkIds?: number;
+}): Promise<{ records: ZohoRecord[]; cursor: PollCursor; truncated: boolean }> {
+ const backlog = cursor.backlog;
+ const seenAtCheckpoint = new Set(cursor.ids);
+ const floorIds = new Set(backlog?.floor.ids ?? []);
+ const fresh = new Map<string, ZohoRecord>();
+ let pageToken = backlog?.pageToken;
+ let reachedCheckpoint = false;
+ let capturedAt: number | undefined;
+ for (let page = 0; page < maxPages && !reachedCheckpoint; page++) {
+ const result = page === 0 ? await fetchFirstPage({ fetchPage, pageToken }) : await fetchPage({ pageToken });
+ capturedAt = capturedAt ?? result.serverTime;
+ for (const record of result.records) {
+ const time = recordTime({ record, timeField });
+ const id = String(record.id ?? '');
+ if (time < cursor.time) {
+ reachedCheckpoint = true;
+ break;
+ }
+ const alreadyEmitted =
+ (time === cursor.time && seenAtCheckpoint.has(id)) ||
+ (backlog !== undefined && (time > backlog.floor.time || (time === backlog.floor.time && floorIds.has(id))));
+ if (!alreadyEmitted && !fresh.has(id)) {
+ fresh.set(id, record);
+ }
+ }
+ if (!result.more) {
+ reachedCheckpoint = true;
+ }
+ if (!reachedCheckpoint) {
+ if (!result.nextPageToken) {
+ throw new ZohoCrmError('Zoho CRM reported more records but sent no next_page_token, so the trigger cannot page back to its last check. It will retry on the next poll.');
+ }
+ pageToken = result.nextPageToken;
+ }
+ }
+ const records = [...fresh.values()].sort((a, b) => recordTime({ record: a, timeField }) - recordTime({ record: b, timeField }));
+ return {
+ records,
+ cursor: nextCursor({ cursor, records, timeField, truncated: !reachedCheckpoint, pageToken, maxMarkIds, capturedAt }),
+ truncated: !reachedCheckpoint,
+ };
+}
+
+export function modulePageFetcher({
+ auth,
+ module,
+ fields,
+ sortBy,
+ apiVersion,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ fields: string[];
+ sortBy: 'Created_Time' | 'Modified_Time';
+ apiVersion?: string;
+}): PageFetcher {
+ return async ({ pageToken }) => {
+ const { status, body, headers } = await zohoRequestRaw<ZohoListResponse<ZohoRecord>>({
+ auth,
+ version: apiVersion,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}`,
+ query: {
+ fields: fields.join(','),
+ sort_by: sortBy,
+ sort_order: 'desc',
+ per_page: '200',
+ ...(pageToken ? { page_token: pageToken } : { page: '1' }),
+ },
+ });
+ const list = status === 204 ? undefined : body;
+ return {
+ records: list?.data ?? [],
+ more: list?.info?.more_records === true,
+ nextPageToken: list?.info?.next_page_token ?? undefined,
+ serverTime: serverTimeOf(headers),
+ };
+ };
+}
+
+export async function zohoNow({ auth, module }: { auth: ZohoAuth; module: string }): Promise<number> {
+ const { headers } = await zohoRequestRaw<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}`,
+ query: { fields: 'id', per_page: '1' },
+ });
+ return serverTimeOf(headers) ?? Date.now();
+}
+
+export async function initCursor({ store, isRepublish, now }: { store: Store; isRepublish?: boolean; now: () => Promise<number> }): Promise<void> {
+ if (isRepublish && (await store.get<PollCursor>(CURSOR_KEY))) {
+ return;
+ }
+ await store.put<PollCursor>(CURSOR_KEY, startCursor(await now()));
+}
+
+export function startCursor(now: number): PollCursor {
+ return { time: Math.floor(now / 1000) * 1000, ids: [] };
+}
+
+const MAX_POLL_PAGES = 25;
+const MAX_MARK_IDS = 5000;
+
+function recordTime({ record, timeField }: { record: ZohoRecord; timeField: string }): number {
+ const raw = record[timeField];
+ const t = typeof raw === 'string' ? Date.parse(raw) : NaN;
+ return Number.isNaN(t) ? 0 : t;
+}
+
+async function fetchFirstPage({ fetchPage, pageToken }: { fetchPage: PageFetcher; pageToken?: string }): Promise<PageResult> {
+ if (pageToken === undefined) {
+ return fetchPage({});
+ }
+ try {
+ return await fetchPage({ pageToken });
+ } catch (error) {
+ if (error instanceof ZohoCrmError && error.status === 400) {
+ return fetchPage({});
+ }
+ throw error;
+ }
+}
+
+function idsAt({ records, time, timeField }: { records: ZohoRecord[]; time: number; timeField: string }): string[] {
+ return records.filter((r) => recordTime({ record: r, timeField }) === time).map((r) => String(r.id ?? ''));
+}
+
+function nextCursor({
+ cursor,
+ records,
+ timeField,
+ truncated,
+ pageToken,
+ maxMarkIds,
+ capturedAt,
+}: {
+ cursor: PollCursor;
+ records: ZohoRecord[];
+ timeField: string;
+ truncated: boolean;
+ pageToken?: string;
+ maxMarkIds: number;
+ capturedAt?: number;
+}): PollCursor {
+ const backlog = cursor.backlog;
+ const newest = records.length > 0 ? recordTime({ record: records[records.length - 1], timeField }) : undefined;
+ const oldest = records.length > 0 ? recordTime({ record: records[0], timeField }) : undefined;
+ const head: PollMark =
+ newest === undefined
+ ? { time: cursor.time, ids: cursor.ids }
+ : {
+ time: newest,
+ ids: newest === cursor.time ? [...cursor.ids, ...idsAt({ records, time: newest, timeField })] : idsAt({ records, time: newest, timeField }),
+ ...(capturedAt !== undefined ? { capturedAt } : {}),
+ };
+ if (truncated && pageToken) {
+ const top = backlog?.top ?? settleMark({ mark: head, maxMarkIds });
+ const floorIds =
+ oldest === undefined
+ ? backlog?.floor.ids ?? top.ids
+ : [...(backlog?.floor.time === oldest ? backlog.floor.ids : []), ...idsAt({ records, time: oldest, timeField })];
+ const floor: PollMark = { time: oldest ?? backlog?.floor.time ?? top.time, ids: floorIds.slice(-maxMarkIds) };
+ return { time: cursor.time, ids: cursor.ids, backlog: { pageToken, top, floor } };
+ }
+ if (backlog) {
+ const atTop = [
+ ...backlog.top.ids,
+ ...(backlog.floor.time === backlog.top.time ? backlog.floor.ids : []),
+ ...idsAt({ records, time: backlog.top.time, timeField }),
+ ];
+ return settleMark({ mark: { ...backlog.top, ids: [...new Set(atTop)] }, maxMarkIds });
+ }
+ return newest === undefined ? cursor : settleMark({ mark: head, maxMarkIds });
+}
+
+function settleMark({ mark, maxMarkIds }: { mark: PollMark; maxMarkIds: number }): PollMark {
+ if (mark.ids.length <= maxMarkIds) {
+ return mark;
+ }
+ if (mark.capturedAt !== undefined && mark.time + 1000 <= mark.capturedAt) {
+ return { time: mark.time + 1000, ids: [] };
+ }
+ return { ...mark, ids: mark.ids.slice(-maxMarkIds) };
+}
+
+function serverTimeOf(headers: Record<string, unknown>): number | undefined {
+ const value = headers['date'];
+ const raw = Array.isArray(value) ? value[0] : value;
+ const time = typeof raw === 'string' ? Date.parse(raw) : NaN;
+ return Number.isNaN(time) ? undefined : time;
+}
+
+type PollMark = { time: number; ids: string[]; capturedAt?: number };
+
+type PageResult = { records: ZohoRecord[]; more: boolean; nextPageToken?: string; serverTime?: number };
+
+export type ZohoRecord = Record<string, unknown> & { id?: string };
+
+export type PollCursor = PollMark & { backlog?: { pageToken: string; top: PollMark; floor: PollMark } };
+
+export type PageFetcher = (request: { pageToken?: string }) => Promise<PageResult>;
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/props.ts b/packages/pieces/community/zoho-crm/src/lib/common/props.ts
new file mode 100644
index 00000000000..86d347ae41a
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/props.ts
@@ -0,0 +1,273 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { InputPropertyMap, Property } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { ZohoAuth, ZohoListResponse, errorText, readField, readString, zohoRequest } from './client';
+import { FieldMode, buildFieldProps, fieldsJsonFallbackProp } from './fields';
+import { listFields, listModules, nameFieldOf } from './metadata';
+
+export function moduleDropdown({
+ displayName = 'Module',
+ description = 'The Zoho CRM module (for example Leads, Contacts, Deals or a custom module).',
+ filter = 'any',
+ required = true,
+}: {
+ displayName?: string;
+ description?: string;
+ filter?: ModuleFilter;
+ required?: boolean;
+} = {}) {
+ return Property.Dropdown({
+ auth: zohoCrmAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Zoho CRM account first' };
+ }
+ try {
+ const modules = await listModules(auth);
+ return {
+ disabled: false,
+ options: modules
+ .filter((m) => m.api_supported !== false)
+ .filter((m) => filter === 'any' || m[filter] !== false)
+ .map((m) => ({ label: m.plural_label ?? m.api_name, value: m.api_name })),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load modules: ${errorText(error)}` };
+ }
+ },
+ });
+}
+
+export function recordDropdown({
+ displayName = 'Record',
+ description = 'Pick one of the 200 most recently modified records, or map a record id from an earlier step.',
+ moduleProp = 'module',
+ fixedModule,
+ required = true,
+}: {
+ displayName?: string;
+ description?: string;
+ moduleProp?: string;
+ fixedModule?: string;
+ required?: boolean;
+} = {}) {
+ return Property.Dropdown({
+ auth: zohoCrmAuth,
+ displayName,
+ description,
+ required,
+ refreshers: fixedModule ? [] : [moduleProp],
+ options: async (props) => {
+ const auth = props.auth;
+ const module = fixedModule ?? props[moduleProp];
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Zoho CRM account first' };
+ }
+ if (typeof module !== 'string' || module.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a module first' };
+ }
+ try {
+ const fields = await listFields({ auth, module });
+ const nameField = nameFieldOf(fields);
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${encodeURIComponent(module)}`,
+ query: {
+ fields: nameField ? `id,${nameField}` : 'id',
+ per_page: '200',
+ sort_by: 'Modified_Time',
+ sort_order: 'desc',
+ },
+ });
+ const records = body?.data ?? [];
+ return {
+ disabled: false,
+ placeholder:
+ records.length === 0
+ ? 'No records in this module'
+ : body?.info?.more_records === true
+ ? `Showing the ${records.length} most recently modified records; map a record id for others.`
+ : undefined,
+ options: records.map((r) => {
+ const id = String(r['id']);
+ const name = nameField ? r[nameField] : undefined;
+ return { label: typeof name === 'string' && name.length > 0 ? `${name} (${id})` : id, value: id };
+ }),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load records: ${errorText(error)}` };
+ }
+ },
+ });
+}
+
+export function recordFieldsProp({ mode, moduleProp = 'module' }: { mode: FieldMode; moduleProp?: string }) {
+ return Property.DynamicProperties({
+ auth: zohoCrmAuth,
+ displayName: 'Fields',
+ description:
+ mode === 'update'
+ ? 'Only the fields you fill in are changed. Use "Clear Fields" to blank a field.'
+ : 'Standard and custom fields of the module. Read-only, formula, subform and file fields are not listed.',
+ required: mode === 'create',
+ refreshers: [moduleProp],
+ props: async (props): Promise<InputPropertyMap> => {
+ const auth = props.auth;
+ const module = props[moduleProp];
+ if (!auth || typeof module !== 'string' || module.length === 0) {
+ return {};
+ }
+ try {
+ const fields = await listFields({ auth, module });
+ return buildFieldProps({ fields, mode });
+ } catch (error) {
+ return fieldsJsonFallbackProp({ reason: errorText(error), mode });
+ }
+ },
+ });
+}
+
+export function uniqueFieldsDropdown(moduleProp = 'module') {
+ return Property.MultiSelectDropdown({
+ auth: zohoCrmAuth,
+ displayName: 'Duplicate Check Fields',
+ description:
+ 'Fields used to find an existing record. Leave empty to use Zoho\'s default (Email for Leads/Contacts, Account_Name for Accounts, Deal_Name for Deals, Name for custom modules).',
+ required: false,
+ refreshers: [moduleProp],
+ options: async (props) => {
+ const auth = props.auth;
+ const module = props[moduleProp];
+ if (!auth || typeof module !== 'string' || module.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a module first' };
+ }
+ try {
+ const fields = await listFields({ auth, module });
+ return {
+ disabled: false,
+ options: fields
+ .filter((f) => f.visible !== false && !f.read_only && ['text', 'email', 'phone', 'website', 'integer', 'bigint', 'autonumber'].includes(f.data_type ?? ''))
+ .map((f) => ({ label: f.display_label ?? f.field_label ?? f.api_name, value: f.api_name })),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load fields: ${errorText(error)}` };
+ }
+ },
+ });
+}
+
+export function tagsDropdown(moduleProp = 'module') {
+ return Property.MultiSelectDropdown({
+ auth: zohoCrmAuth,
+ displayName: 'Existing Tags',
+ description: 'Tags already defined for the module.',
+ required: false,
+ refreshers: [moduleProp],
+ options: async (props) => {
+ const auth = props.auth;
+ const module = props[moduleProp];
+ if (!auth || typeof module !== 'string' || module.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a module first' };
+ }
+ try {
+ const body = await zohoRequest<{ tags?: { name: string }[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/tags',
+ query: { module },
+ });
+ return {
+ disabled: false,
+ options: (body?.tags ?? []).map((t) => ({ label: t.name, value: t.name })),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load tags: ${errorText(error)}` };
+ }
+ },
+ });
+}
+
+export function userDropdown({
+ displayName,
+ description,
+ required = false,
+}: {
+ displayName: string;
+ description: string;
+ required?: boolean;
+}) {
+ return Property.Dropdown({
+ auth: zohoCrmAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Zoho CRM account first' };
+ }
+ const { users, notice } = await listActiveUsers({ auth });
+ if (users.length === 0 && notice) {
+ return { disabled: true, options: [], placeholder: notice };
+ }
+ return {
+ disabled: false,
+ placeholder: notice,
+ options: users.map((u) => ({ label: u.email ? `${u.name} (${u.email})` : u.name, value: u.id })),
+ };
+ },
+ });
+}
+
+async function listActiveUsers({ auth }: { auth: ZohoAuth }): Promise<{ users: UserOption[]; notice?: string }> {
+ const users: UserOption[] = [];
+ for (let page = 1; page <= MAX_USER_PAGES; page++) {
+ let body: { users?: unknown[]; info?: { more_records?: boolean } } | undefined;
+ try {
+ body = await zohoRequest<{ users?: unknown[]; info?: { more_records?: boolean } }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/users',
+ query: { type: 'ActiveUsers', per_page: String(USERS_PER_PAGE), page: String(page) },
+ });
+ } catch (error) {
+ const reason = errorText(error);
+ return { users, notice: users.length === 0 ? `Could not load users: ${reason}` : `Showing the first ${users.length} users; the rest could not be loaded (${reason}).` };
+ }
+ users.push(...(body?.users ?? []).flatMap(toUserOption));
+ if (body?.info?.more_records !== true) {
+ return { users };
+ }
+ }
+ return { users, notice: `Showing the first ${users.length} active users; map a user id for anyone else.` };
+}
+
+function toUserOption(user: unknown): UserOption[] {
+ const id = readString(readField({ value: user, key: 'id' }));
+ if (!id) {
+ return [];
+ }
+ const name = readString(readField({ value: user, key: 'full_name' })) ?? id;
+ return [{ id, name, email: readString(readField({ value: user, key: 'email' })) }];
+}
+
+const USERS_PER_PAGE = 200;
+const MAX_USER_PAGES = 10;
+
+type UserOption = { id: string; name: string; email?: string };
+
+export function additionalFieldsProp() {
+ return Property.Json({
+ displayName: 'Additional Fields (JSON)',
+ description:
+ 'Optional raw fields by API name, for fields the form does not list (e.g. subform rows). Values set in the form above win over the same key here.',
+ required: false,
+ });
+}
+
+type ModuleFilter = 'any' | 'creatable' | 'editable' | 'deletable';
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/record-trigger.ts b/packages/pieces/community/zoho-crm/src/lib/common/record-trigger.ts
new file mode 100644
index 00000000000..9acc9e10e70
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/record-trigger.ts
@@ -0,0 +1,149 @@
+import { Property, Store } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { ZohoAuth, ZohoCrmError, errorText, stringList } from './client';
+import { defaultFieldSelection, listFields } from './metadata';
+import { CURSOR_KEY, PollCursor, ZohoRecord, collectSince, initCursor, modulePageFetcher, startCursor, zohoNow } from './polling';
+import { moduleDropdown } from './props';
+import { tryListFields } from './records';
+
+export const recordTriggerProps = {
+ module: moduleDropdown({ description: 'The module to watch (standard or custom).' }),
+ fields: Property.MultiSelectDropdown({
+ auth: zohoCrmAuth,
+ displayName: 'Fields to Include',
+ description:
+ 'Optional, up to 47. Leave empty for id, then custom, then standard fields (50 in total).',
+ required: false,
+ refreshers: ['module'],
+ options: async ({ auth, module }) => {
+ if (!auth || typeof module !== 'string' || module.length === 0) {
+ return { disabled: true, options: [], placeholder: 'Select a module first' };
+ }
+ try {
+ const fields = await listFields({ auth, module });
+ return {
+ disabled: false,
+ options: fields
+ .filter((f) => f.visible !== false)
+ .map((f) => ({ label: f.display_label ?? f.field_label ?? f.api_name, value: f.api_name })),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load fields: ${errorText(error)}` };
+ }
+ },
+ }),
+};
+
+export async function pollModule({
+ auth,
+ store,
+ module,
+ fields,
+ sortBy,
+ keep,
+ apiVersion,
+}: {
+ auth: ZohoAuth;
+ store: Store;
+ module: string;
+ fields: string[];
+ sortBy: 'Created_Time' | 'Modified_Time';
+ keep?: (record: ZohoRecord) => boolean;
+ apiVersion?: string;
+}): Promise<ZohoRecord[]> {
+ const cursor = (await store.get<PollCursor>(CURSOR_KEY)) ?? startCursor(Date.now());
+ const result = await collectSince({
+ cursor,
+ timeField: sortBy,
+ fetchPage: modulePageFetcher({ auth, module, fields, sortBy, apiVersion }),
+ });
+ await store.put<PollCursor>(CURSOR_KEY, result.cursor);
+ return keep ? result.records.filter(keep) : result.records;
+}
+
+export async function sampleModule({
+ auth,
+ module,
+ fields,
+ sortBy,
+ keep,
+ apiVersion,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ fields: string[];
+ sortBy: 'Created_Time' | 'Modified_Time';
+ keep?: (record: ZohoRecord) => boolean;
+ apiVersion?: string;
+}): Promise<ZohoRecord[]> {
+ const { records } = await modulePageFetcher({ auth, module, fields, sortBy, apiVersion })({});
+ return (keep ? records.filter(keep) : records).slice(0, 5);
+}
+
+export async function triggerFields({
+ auth,
+ store,
+ module,
+ chosen,
+}: {
+ auth: ZohoAuth;
+ store?: Store;
+ module: string;
+ chosen: unknown;
+}): Promise<string[]> {
+ const picked = pickedFields(chosen);
+ if (picked.length > 0) {
+ return [...new Set([...ALWAYS_INCLUDED, ...picked])];
+ }
+ const cached = store ? await store.get<CachedFields>(FIELDS_KEY) : null;
+ if (cached && cached.module === module && Date.now() - cached.at < FIELDS_CACHE_MS) {
+ return cached.fields;
+ }
+ const available = await tryListFields({ auth, module });
+ if (!available) {
+ throw new ZohoCrmError(
+ `Zoho CRM did not let this connection read the ${module} field list, so the default fields cannot be chosen. Pick the fields to include in the trigger settings.`,
+ );
+ }
+ const fields = [...new Set([...ALWAYS_INCLUDED, ...defaultFieldSelection({ fields: available })])].slice(0, MAX_FIELDS);
+ if (store) {
+ await store.put<CachedFields>(FIELDS_KEY, { module, fields, at: Date.now() });
+ }
+ return fields;
+}
+
+export async function startTrigger({
+ auth,
+ module,
+ store,
+ isRepublish,
+ chosen,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ store: Store;
+ isRepublish?: boolean;
+ chosen: unknown;
+}): Promise<void> {
+ pickedFields(chosen);
+ await store.delete(FIELDS_KEY);
+ await initCursor({ store, isRepublish, now: () => zohoNow({ auth, module }) });
+}
+
+function pickedFields(chosen: unknown): string[] {
+ const picked = [...new Set(stringList(chosen).filter((f) => !ALWAYS_INCLUDED.includes(f)))];
+ if (picked.length > MAX_PICKED_FIELDS) {
+ throw new ZohoCrmError(
+ `Fields to Include has ${picked.length} fields. Zoho returns at most ${MAX_FIELDS} fields per record, and id, Created_Time and Modified_Time are always included, so pick at most ${MAX_PICKED_FIELDS}.`,
+ );
+ }
+ return picked;
+}
+
+const ALWAYS_INCLUDED = ['id', 'Created_Time', 'Modified_Time'];
+const MAX_FIELDS = 50;
+const MAX_PICKED_FIELDS = MAX_FIELDS - ALWAYS_INCLUDED.length;
+const FIELDS_KEY = 'zoho_poll_fields';
+const FIELDS_CACHE_MS = 6 * 60 * 60 * 1000;
+
+type CachedFields = { module: string; fields: string[]; at: number };
diff --git a/packages/pieces/community/zoho-crm/src/lib/common/records.ts b/packages/pieces/community/zoho-crm/src/lib/common/records.ts
new file mode 100644
index 00000000000..9198d58e5d7
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/common/records.ts
@@ -0,0 +1,467 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ ZohoAuth,
+ ZohoCrmError,
+ ZohoListResponse,
+ ZohoWriteItem,
+ flattenWriteResult,
+ isRecord,
+ readField,
+ readString,
+ unwrapWriteItem,
+ zohoRequest,
+} from './client';
+import { ZohoField, listFields } from './metadata';
+
+const enc = encodeURIComponent;
+
+export async function tryListFields({ auth, module }: { auth: ZohoAuth; module: string }): Promise<ZohoField[] | undefined> {
+ try {
+ return await listFields({ auth, module });
+ } catch (error) {
+ if (error instanceof ZohoCrmError && (error.status === 403 || METADATA_REFUSED_CODES.has(error.code ?? ''))) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+const METADATA_REFUSED_CODES = new Set(['NO_PERMISSION', 'OAUTH_SCOPE_MISMATCH']);
+
+function ensureExactNumbers({ value, path }: { value: unknown; path: string }): void {
+ if (typeof value === 'number' && Math.abs(value) > Number.MAX_SAFE_INTEGER) {
+ throw new ZohoCrmError(`${path} arrived as a number above 2^53, which is already rounded; pass it as text (the exact digits).`);
+ }
+ if (Array.isArray(value)) {
+ value.forEach((item, index) => ensureExactNumbers({ value: item, path: `${path}[${index}]` }));
+ } else if (isRecord(value)) {
+ Object.entries(value).forEach(([key, item]) => ensureExactNumbers({ value: item, path: `${path}.${key}` }));
+ }
+}
+
+function validateRecord({ record, what }: { record: Record<string, unknown>; what: string }): void {
+ Object.entries(record).forEach(([key, item]) => ensureExactNumbers({ value: item, path: key }));
+ if (Object.keys(record).length === 0) {
+ throw new ZohoCrmError(`${what}: no fields were provided.`);
+ }
+}
+
+export async function createRecord({
+ auth,
+ module,
+ record,
+ trigger,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ record: Record<string, unknown>;
+ trigger?: string[];
+}): Promise<Record<string, unknown>> {
+ validateRecord({ record, what: 'Create record' });
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/${enc(module)}`,
+ body: { data: [record], ...(trigger !== undefined ? { trigger } : {}) },
+ });
+ return { module, ...flattenWriteResult(unwrapWriteItem({ body })) };
+}
+
+export async function updateRecord({
+ auth,
+ module,
+ id,
+ record,
+ trigger,
+ appendMultiSelect,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ id: string;
+ record: Record<string, unknown>;
+ trigger?: string[];
+ appendMultiSelect?: string[];
+}): Promise<Record<string, unknown>> {
+ validateRecord({ record, what: 'Update record' });
+ const data: Record<string, unknown> = { ...record };
+ if (appendMultiSelect && appendMultiSelect.length > 0) {
+ data['$append_values'] = Object.fromEntries(appendMultiSelect.map((f) => [f, true]));
+ }
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/${enc(module)}/${enc(id)}`,
+ body: { data: [data], ...(trigger !== undefined ? { trigger } : {}) },
+ });
+ return { module, ...flattenWriteResult(unwrapWriteItem({ body })) };
+}
+
+export async function upsertRecord({
+ auth,
+ module,
+ record,
+ duplicateCheckFields,
+ trigger,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ record: Record<string, unknown>;
+ duplicateCheckFields?: string[];
+ trigger?: string[];
+}): Promise<Record<string, unknown>> {
+ validateRecord({ record, what: 'Upsert record' });
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/${enc(module)}/upsert`,
+ body: {
+ data: [record],
+ ...(duplicateCheckFields && duplicateCheckFields.length > 0 ? { duplicate_check_fields: duplicateCheckFields } : {}),
+ ...(trigger !== undefined ? { trigger } : {}),
+ },
+ });
+ return { module, ...flattenWriteResult(unwrapWriteItem({ body })) };
+}
+
+export async function getRecord({
+ auth,
+ module,
+ id,
+ fields,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ id: string;
+ fields?: string[];
+}): Promise<Record<string, unknown>> {
+ const body = await zohoRequest<ZohoListResponse<Record<string, unknown>>>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${enc(module)}/${enc(id)}`,
+ query: fields && fields.length > 0 ? { fields: fields.join(',') } : undefined,
+ });
+ const record = body?.data?.[0];
+ if (!record) {
+ throw new ZohoCrmError(`No ${module} record with id ${id} was found.`, 404, 'NOT_FOUND');
+ }
+ return record;
+}
+
+export async function deleteRecord({
+ auth,
+ module,
+ id,
+ runWorkflows,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ id: string;
+ runWorkflows?: boolean;
+}): Promise<Record<string, unknown>> {
+ let body: unknown;
+ try {
+ body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: `/${enc(module)}/${enc(id)}`,
+ query: runWorkflows === false ? { wf_trigger: 'false' } : undefined,
+ });
+ } catch (error) {
+ throw notDeletedError({ error, what: `${module} record ${id}` });
+ }
+ const item = unwrapWriteItem({ body });
+ return { module, deleted: true, ...flattenWriteResult(item), id: readString(item.details?.['id']) ?? id };
+}
+
+export function notDeletedError({ error, what }: { error: unknown; what: string }): unknown {
+ if (error instanceof ZohoCrmError && error.code === 'INVALID_DATA') {
+ return new ZohoCrmError(
+ `Zoho CRM INVALID_DATA: could not delete ${what}; it does not exist or was already deleted.`,
+ error.status,
+ error.code,
+ );
+ }
+ return error;
+}
+
+export type ConvertLeadInput = {
+ auth: ZohoAuth;
+ leadId: string;
+ accountId?: string;
+ contactId?: string;
+ assignTo?: string;
+ overwrite?: boolean;
+ notifyLeadOwner?: boolean;
+ notifyNewEntityOwner?: boolean;
+ deal?: Record<string, unknown>;
+};
+
+export async function convertLead(input: ConvertLeadInput): Promise<Record<string, unknown>> {
+ const entry: Record<string, unknown> = {};
+ if (input.overwrite !== undefined) entry['overwrite'] = input.overwrite;
+ if (input.notifyLeadOwner !== undefined) entry['notify_lead_owner'] = input.notifyLeadOwner;
+ if (input.notifyNewEntityOwner !== undefined) entry['notify_new_entity_owner'] = input.notifyNewEntityOwner;
+ if (input.accountId) entry['Accounts'] = { id: input.accountId };
+ if (input.contactId) entry['Contacts'] = { id: input.contactId };
+ if (input.assignTo) entry['assign_to'] = { id: input.assignTo };
+ if (input.deal && Object.keys(input.deal).length > 0) {
+ Object.entries(input.deal).forEach(([key, item]) => ensureExactNumbers({ value: item, path: `Deal ${key}` }));
+ entry['Deals'] = input.deal;
+ }
+ let item: ZohoWriteItem;
+ try {
+ const body = await zohoRequest<unknown>({
+ auth: input.auth,
+ method: HttpMethod.POST,
+ path: `/Leads/${enc(input.leadId)}/actions/convert`,
+ body: { data: [entry] },
+ });
+ item = unwrapWriteItem({ body });
+ } catch (error) {
+ throw convertMismatchError(error);
+ }
+ const d = item.details ?? {};
+ const refText = ({ entity, key }: { entity: string; key: string }): string | null =>
+ readString(readField({ value: d[entity], key })) ?? null;
+ return {
+ lead_id: input.leadId,
+ status: item.status ?? null,
+ message: item.message ?? null,
+ contact_id: refText({ entity: 'Contacts', key: 'id' }),
+ contact_name: refText({ entity: 'Contacts', key: 'name' }),
+ account_id: refText({ entity: 'Accounts', key: 'id' }),
+ account_name: refText({ entity: 'Accounts', key: 'name' }),
+ deal_id: refText({ entity: 'Deals', key: 'id' }),
+ deal_name: refText({ entity: 'Deals', key: 'name' }),
+ };
+}
+
+function convertMismatchError(error: unknown): unknown {
+ if (!(error instanceof ZohoCrmError) || error.code !== 'INVALID_DATA') {
+ return error;
+ }
+ const match = /(Account|Contact) data doesn't match/i.exec(error.message);
+ if (!match) {
+ return error;
+ }
+ const rule =
+ match[1].toLowerCase() === 'account'
+ ? "Zoho links an existing account only when the lead's Company equals the account name"
+ : "Zoho merges into an existing contact only when the lead's name and email match the contact";
+ return new ZohoCrmError(
+ `Zoho CRM INVALID_DATA: ${match[1]} data doesn't match the lead. ${rule}. Update the lead first, or leave Existing ${match[1]} empty to create a new one.`,
+ error.status,
+ error.code,
+ );
+}
+
+export async function createNote({
+ auth,
+ module,
+ recordId,
+ title,
+ content,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ recordId: string;
+ title?: string;
+ content: string;
+}): Promise<Record<string, unknown>> {
+ if (!content || content.trim().length === 0) {
+ throw new ZohoCrmError('Note content is required.');
+ }
+ const note: Record<string, unknown> = {
+ Parent_Id: { module: { api_name: module }, id: recordId },
+ Note_Content: content,
+ };
+ if (title && title.length > 0) note['Note_Title'] = title;
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/Notes',
+ body: { data: [note] },
+ });
+ return { parent_module: module, parent_id: recordId, ...flattenWriteResult(unwrapWriteItem({ body })) };
+}
+
+export type TagRef = { name?: string; id?: string };
+
+export async function changeTags({
+ auth,
+ module,
+ recordIds,
+ tags,
+ mode,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ recordIds: string[];
+ tags: TagRef[];
+ mode: 'add' | 'remove';
+}): Promise<Record<string, unknown>> {
+ if (recordIds.length === 0) throw new ZohoCrmError('At least one record id is required.');
+ if (recordIds.length > 500) throw new ZohoCrmError('Zoho accepts at most 500 record ids per call.');
+ if (tags.length === 0) throw new ZohoCrmError('At least one tag is required.');
+ const body = await zohoRequest<{ data?: { status?: string; code?: string; message?: string; details?: Record<string, unknown> }[] }>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/${enc(module)}/actions/${mode === 'add' ? 'add_tags' : 'remove_tags'}`,
+ body: { tags, ids: recordIds, ...(mode === 'add' ? { over_write: false } : {}) },
+ });
+ const rows = (body?.data ?? []).map((r) => ({
+ id: readString(r.details?.['id']) ?? null,
+ status: r.status ?? null,
+ code: r.code ?? null,
+ message: r.message ?? null,
+ tags: tagNames(r.details?.['tags']),
+ }));
+ const failed = rows.filter((r) => r.status === 'error');
+ if (rows.length > 0 && failed.length === rows.length) {
+ throw new ZohoCrmError(`Zoho CRM ${failed[0].code}: ${failed[0].message}`);
+ }
+ return { module, results: rows, success_count: rows.length - failed.length, failed_count: failed.length };
+}
+
+export type ZohoTag = { id: string; name: string; color_code?: string | null; created_time?: string; modified_time?: string };
+
+export async function listTags({ auth, module }: { auth: ZohoAuth; module: string }): Promise<ZohoTag[]> {
+ const body = await zohoRequest<{ tags?: ZohoTag[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/settings/tags',
+ query: { module },
+ });
+ return body?.tags ?? [];
+}
+
+export const TAG_COLORS = [
+ '#F17574', '#F48435', '#E7A826', '#A8C026', '#63C57E', '#1DB9B4', '#57B1FD',
+ '#879BFC', '#D297EE', '#FD87BD', '#969696', '#658BA8', '#B88562',
+];
+
+export async function ensureTag({
+ auth,
+ module,
+ name,
+ colorCode,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ name: string;
+ colorCode?: string;
+}): Promise<{ tag: ZohoTag; created: boolean }> {
+ const clean = name.trim();
+ if (clean.length === 0) throw new ZohoCrmError('Tag name is required.');
+ if (colorCode && !TAG_COLORS.includes(colorCode.toUpperCase())) {
+ throw new ZohoCrmError(`color_code must be one of ${TAG_COLORS.join(', ')}.`);
+ }
+ const existing = (await listTags({ auth, module })).find((t) => t.name.toLowerCase() === clean.toLowerCase());
+ if (existing) return { tag: existing, created: false };
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/settings/tags',
+ query: { module },
+ body: { tags: [{ name: clean, ...(colorCode ? { color_code: colorCode.toUpperCase() } : {}) }] },
+ });
+ const item = unwrapWriteItem({ body, key: 'tags' });
+ const d = item.details ?? {};
+ return {
+ tag: { id: String(d['id'] ?? ''), name: clean, color_code: colorCode ?? null, created_time: readString(d['created_time']) },
+ created: true,
+ };
+}
+
+export async function uploadAttachment({
+ auth,
+ module,
+ recordId,
+ file,
+ attachmentUrl,
+ title,
+}: {
+ auth: ZohoAuth;
+ module: string;
+ recordId: string;
+ file?: { filename: string; data: Buffer };
+ attachmentUrl?: string;
+ title?: string;
+}): Promise<Record<string, unknown>> {
+ if ((file ? 1 : 0) + (attachmentUrl ? 1 : 0) !== 1) {
+ throw new ZohoCrmError('Provide exactly one of a file or an attachment URL.');
+ }
+ const parts: MultipartPart[] = [];
+ if (file) {
+ parts.push({ name: 'file', filename: file.filename, data: file.data });
+ } else if (attachmentUrl) {
+ let parsed: URL;
+ try {
+ parsed = new URL(attachmentUrl);
+ } catch {
+ throw new ZohoCrmError('attachment_url must be a full http(s) URL.');
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new ZohoCrmError('attachment_url must be a full http(s) URL.');
+ }
+ parts.push({ name: 'attachmentUrl', data: attachmentUrl });
+ if (title) parts.push({ name: 'title', data: title });
+ }
+ const multipart = buildMultipart({ parts });
+ const body = await zohoRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/${enc(module)}/${enc(recordId)}/Attachments`,
+ headers: { 'Content-Type': multipart.contentType },
+ body: multipart.body,
+ });
+ return { parent_module: module, parent_id: recordId, ...flattenWriteResult(unwrapWriteItem({ body })) };
+}
+
+export function readApFile(value: unknown): { filename: string; data: Buffer } {
+ if (!isRecord(value)) {
+ throw new ZohoCrmError('File is required.');
+ }
+ const data = value['data'];
+ const rawName = value['filename'];
+ const base64 = value['base64'];
+ const filename = typeof rawName === 'string' && rawName.length > 0 ? rawName : 'attachment';
+ if (Buffer.isBuffer(data)) return { filename, data };
+ if (data instanceof Uint8Array) return { filename, data: Buffer.from(data) };
+ if (typeof base64 === 'string') return { filename, data: Buffer.from(base64, 'base64') };
+ throw new ZohoCrmError('File could not be read (no data).');
+}
+
+export function buildMultipart({
+ parts,
+ boundary = `----apZoho${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`,
+}: {
+ parts: MultipartPart[];
+ boundary?: string;
+}): { body: Buffer; contentType: string } {
+ const chunks: Buffer[] = [];
+ for (const part of parts) {
+ const safeName = (part.filename ?? '').replace(/["\r\n]/g, '_');
+ const disposition = part.filename !== undefined
+ ? `form-data; name="${part.name}"; filename="${safeName}"`
+ : `form-data; name="${part.name}"`;
+ const head = `--${boundary}\r\nContent-Disposition: ${disposition}\r\n${part.filename !== undefined ? 'Content-Type: application/octet-stream\r\n' : ''}\r\n`;
+ chunks.push(Buffer.from(head, 'utf8'));
+ chunks.push(typeof part.data === 'string' ? Buffer.from(part.data, 'utf8') : part.data);
+ chunks.push(Buffer.from('\r\n', 'utf8'));
+ }
+ chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'));
+ return { body: Buffer.concat(chunks), contentType: `multipart/form-data; boundary=${boundary}` };
+}
+
+function tagNames(value: unknown): string | null {
+ if (!Array.isArray(value)) {
+ return null;
+ }
+ return value
+ .map((t) => readString(readField({ value: t, key: 'name' })))
+ .filter((name): name is string => typeof name === 'string' && name.length > 0)
+ .join(', ');
+}
+
+type MultipartPart = { name: string; data: string | Buffer; filename?: string };
diff --git a/packages/pieces/community/zoho-crm/src/lib/output-schemas-ai.ts b/packages/pieces/community/zoho-crm/src/lib/output-schemas-ai.ts
new file mode 100644
index 00000000000..a8032a5cbd3
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/output-schemas-ai.ts
@@ -0,0 +1,246 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+import { childChangeOutputSchema, childWriteOutputSchema, recordWriteOutputSchema } from './output-schemas';
+
+const userFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'User ID' },
+ { key: 'full_name', label: 'Full Name' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'status', label: 'Status' },
+ { key: 'role_id', label: 'Role ID' },
+ { key: 'role_name', label: 'Role' },
+ { key: 'profile_id', label: 'Profile ID' },
+ { key: 'profile_name', label: 'Profile' },
+ { key: 'time_zone', label: 'Time Zone' },
+ { key: 'confirm', label: 'Confirmed', format: 'boolean' },
+];
+
+const noteFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Note ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'content', label: 'Content' },
+ { key: 'parent_module', label: 'Parent Module' },
+ { key: 'parent_id', label: 'Parent Record ID' },
+ { key: 'parent_name', label: 'Parent Record' },
+ { key: 'owner_id', label: 'Owner ID' },
+ { key: 'owner_name', label: 'Owner' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+];
+
+const attachmentFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Attachment ID' },
+ { key: 'file_name', label: 'File Name' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'type', label: 'Type' },
+ { key: 'link_url', label: 'Link URL', format: 'url' },
+ { key: 'file_id', label: 'File ID' },
+ { key: 'parent_module', label: 'Parent Module' },
+ { key: 'owner_name', label: 'Owner' },
+ { key: 'created_by_name', label: 'Created By' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+];
+
+const draftFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Draft ID' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'from', label: 'From', format: 'email' },
+ { key: 'to', label: 'To' },
+ { key: 'cc', label: 'Cc' },
+ { key: 'bcc', label: 'Bcc' },
+ { key: 'reply_to', label: 'Reply To', format: 'email' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'content', label: 'Content', format: 'html' },
+ { key: 'rich_text', label: 'Rich Text', format: 'boolean' },
+ { key: 'scheduled_time', label: 'Scheduled Time', format: 'datetime' },
+ { key: 'attachment_count', label: 'Attachments', format: 'number' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+];
+
+const pagingFields: OutputSchema['fields'] = [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'more_records', label: 'More Records', format: 'boolean' },
+];
+
+export const listModulesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'modules',
+ label: 'Modules',
+ labelKey: 'plural_label',
+ listItems: [
+ { key: 'api_name', label: 'API Name' },
+ { key: 'module_name', label: 'Module Name' },
+ { key: 'plural_label', label: 'Plural Label' },
+ { key: 'singular_label', label: 'Singular Label' },
+ { key: 'generated_type', label: 'Type' },
+ { key: 'creatable', label: 'Creatable', format: 'boolean' },
+ { key: 'editable', label: 'Editable', format: 'boolean' },
+ { key: 'deletable', label: 'Deletable', format: 'boolean' },
+ ],
+ },
+ ],
+};
+
+export const moduleFieldsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'field_label',
+ listItems: [
+ { key: 'api_name', label: 'API Name' },
+ { key: 'field_label', label: 'Label' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'required', label: 'Required on Create', format: 'boolean' },
+ { key: 'read_only', label: 'Read Only', format: 'boolean' },
+ { key: 'custom_field', label: 'Custom Field', format: 'boolean' },
+ { key: 'lookup_module', label: 'Lookup Module' },
+ { key: 'max_length', label: 'Max Length', format: 'number' },
+ { key: 'picklist_values', label: 'Picklist Values' },
+ ],
+ },
+ ],
+};
+
+export const relatedListsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'related_lists',
+ label: 'Related Lists',
+ labelKey: 'display_label',
+ listItems: [
+ { key: 'api_name', label: 'API Name' },
+ { key: 'display_label', label: 'Label' },
+ { key: 'module_api_name', label: 'Related Module' },
+ { key: 'type', label: 'Type' },
+ { key: 'href', label: 'Path' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ ],
+};
+
+export const listUsersOutputSchema: OutputSchema = {
+ fields: [...pagingFields, { key: 'users', label: 'Users', labelKey: 'full_name', listItems: userFields }],
+};
+
+export const userOutputSchema: OutputSchema = { fields: userFields };
+
+export const listRecordsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ ...pagingFields,
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'next_page_token', label: 'Next Page Token' },
+ { key: 'fields_requested', label: 'Fields Requested' },
+ { key: 'records', label: 'Records' },
+ ],
+};
+
+export const aiWriteOutputSchema: OutputSchema = recordWriteOutputSchema;
+
+export const aiUpsertOutputSchema: OutputSchema = {
+ fields: [
+ ...recordWriteOutputSchema.fields,
+ { key: 'action', label: 'Action (insert or update)' },
+ { key: 'duplicate_field', label: 'Matched On Field' },
+ ],
+};
+
+export const listNotesOutputSchema: OutputSchema = {
+ fields: [...pagingFields, { key: 'notes', label: 'Notes', labelKey: 'title', listItems: noteFields }],
+};
+
+export const noteOutputSchema: OutputSchema = { fields: noteFields };
+
+export const noteWriteOutputSchema: OutputSchema = childWriteOutputSchema;
+
+export const noteChangeOutputSchema: OutputSchema = childChangeOutputSchema;
+
+export const listTagsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'tags',
+ label: 'Tags',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'color_code', label: 'Color' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+ ],
+ },
+ ],
+};
+
+export const createTagOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'color_code', label: 'Color' },
+ { key: 'module', label: 'Module' },
+ { key: 'created', label: 'Created (false = already existed)', format: 'boolean' },
+ ],
+};
+
+export const relatedRecordsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'record_id', label: 'Record ID' },
+ { key: 'related_list', label: 'Related List' },
+ ...pagingFields,
+ { key: 'next_page_token', label: 'Next Page Token' },
+ { key: 'records', label: 'Related Records' },
+ ],
+};
+
+export const linkRelatedOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'record_id', label: 'Record ID' },
+ { key: 'related_list', label: 'Related List' },
+ { key: 'related_record_id', label: 'Related Record ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'code', label: 'Code' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const listAttachmentsOutputSchema: OutputSchema = {
+ fields: [...pagingFields, { key: 'attachments', label: 'Attachments', labelKey: 'file_name', listItems: attachmentFields }],
+};
+
+export const listDraftsOutputSchema: OutputSchema = {
+ fields: [...pagingFields, { key: 'drafts', label: 'Drafts', labelKey: 'subject', listItems: draftFields }],
+};
+
+export const draftWriteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Draft ID' },
+ { key: 'module', label: 'Module' },
+ { key: 'record_id', label: 'Record ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const downloadAttachmentOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'file', label: 'File' },
+ { key: 'file_name', label: 'File Name' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'content_type', label: 'Content Type' },
+ ],
+};
diff --git a/packages/pieces/community/zoho-crm/src/lib/output-schemas.ts b/packages/pieces/community/zoho-crm/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..886c251e86e
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/output-schemas.ts
@@ -0,0 +1,102 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const writeResultFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Record ID' },
+ { key: 'module', label: 'Module' },
+ { key: 'status', label: 'Status' },
+ { key: 'code', label: 'Code' },
+ { key: 'message', label: 'Message' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+ { key: 'created_by_id', label: 'Created By ID' },
+ { key: 'created_by_name', label: 'Created By' },
+ { key: 'modified_by_id', label: 'Modified By ID' },
+ { key: 'modified_by_name', label: 'Modified By' },
+];
+
+export const recordOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Record ID' },
+ { key: 'Created_Time', label: 'Created Time', format: 'datetime' },
+ { key: 'Modified_Time', label: 'Modified Time', format: 'datetime' },
+ { key: 'record', label: 'All Fields', value: '', dynamicKey: true },
+ ],
+};
+
+export const recordWriteOutputSchema: OutputSchema = { fields: writeResultFields };
+
+export const upsertOutputSchema: OutputSchema = {
+ fields: [
+ ...writeResultFields,
+ { key: 'action', label: 'Action (insert or update)' },
+ { key: 'duplicate_field', label: 'Matched On Field' },
+ ],
+};
+
+export const deleteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Record ID' },
+ { key: 'module', label: 'Module' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const convertLeadOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'lead_id', label: 'Lead ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'contact_name', label: 'Contact Name' },
+ { key: 'account_id', label: 'Account ID' },
+ { key: 'account_name', label: 'Account Name' },
+ { key: 'deal_id', label: 'Deal ID' },
+ { key: 'deal_name', label: 'Deal Name' },
+ ],
+};
+
+export const childWriteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'ID' },
+ { key: 'parent_module', label: 'Parent Module' },
+ { key: 'parent_id', label: 'Parent Record ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+ { key: 'created_by_name', label: 'Created By' },
+ ],
+};
+
+export const childChangeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'code', label: 'Code' },
+ { key: 'message', label: 'Message' },
+ { key: 'created_time', label: 'Created Time', format: 'datetime' },
+ { key: 'modified_time', label: 'Modified Time', format: 'datetime' },
+ { key: 'modified_by_name', label: 'Modified By' },
+ ],
+};
+
+export const tagChangeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'module', label: 'Module' },
+ { key: 'success_count', label: 'Records Updated', format: 'number' },
+ { key: 'failed_count', label: 'Records Failed', format: 'number' },
+ {
+ key: 'results',
+ label: 'Results',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'Record ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ { key: 'tags', label: 'Tags Now On Record' },
+ ],
+ },
+ ],
+};
diff --git a/packages/pieces/community/zoho-crm/src/lib/triggers/new-contact.ts b/packages/pieces/community/zoho-crm/src/lib/triggers/new-contact.ts
index 1cd4dd203ff..dce6bb80789 100644
--- a/packages/pieces/community/zoho-crm/src/lib/triggers/new-contact.ts
+++ b/packages/pieces/community/zoho-crm/src/lib/triggers/new-contact.ts
@@ -1,19 +1,92 @@
-import {
- AuthenticationType,
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
-import {
- AppConnectionValueForAuthProperty,
- createTrigger,
- OAuth2PropertyValue,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
-import dayjs from 'dayjs';
+import { Property, Store, createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { zohoCrmAuth } from '../auth';
+import { errorText } from '../common/client';
+import { listFields } from '../common/metadata';
+import { CURSOR_KEY, PollCursor, initCursor, zohoNow } from '../common/polling';
+import { pollModule, sampleModule } from '../common/record-trigger';
+
+const MAX_EXTRA_FIELDS = 4;
+
+const CONTACT_FIELDS = [
+ 'Owner',
+ 'Email',
+ '$currency_symbol',
+ '$field_states',
+ 'Other_Phone',
+ 'Mailing_State',
+ 'Other_State',
+ '$sharing_permission',
+ 'Other_Country',
+ 'Last_Activity_Time',
+ 'Department',
+ '$state',
+ 'Unsubscribed_Mode',
+ '$process_flow',
+ 'Assistant',
+ 'Mailing_Country',
+ 'id',
+ 'Reporting_To',
+ '$approval',
+ 'Enrich_Status__s',
+ 'Other_City',
+ 'Created_Time',
+ '$wizard_connection_path',
+ '$editable',
+ 'Home_Phone',
+ 'Created_By',
+ '$zia_owner_assignment',
+ 'Secondary_Email',
+ 'Description',
+ 'Vendor_Name',
+ 'Mailing_Zip',
+ '$review_process',
+ 'Twitter',
+ 'Other_Zip',
+ 'Mailing_Street',
+ '$canvas_id',
+ 'Salutation',
+ 'First_Name',
+ 'Full_Name',
+ 'Asst_Phone',
+ 'Record_Image',
+ 'Modified_By',
+ '$review',
+ 'Skype_ID',
+ 'Phone',
+ 'Account_Name',
+];
+
+export function contactFieldsParam(extra: unknown): string {
+ const picked = Array.isArray(extra) ? extra.map(String).filter((f) => f && !CONTACT_FIELDS.includes(f)) : [];
+ const unique = [...new Set(picked)].slice(0, MAX_EXTRA_FIELDS);
+ return [...CONTACT_FIELDS, ...unique].join(',');
+}
+
+const newContactProps = {
+ additional_fields: Property.MultiSelectDropdown({
+ auth: zohoCrmAuth,
+ displayName: 'Additional Fields',
+ description: `Optional. Up to ${MAX_EXTRA_FIELDS} extra Contacts fields (for example custom fields) to include. Zoho returns at most 50 fields per record and this trigger already requests 46 standard ones.`,
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Zoho CRM account first' };
+ }
+ try {
+ const fields = await listFields({ auth, module: 'Contacts' });
+ return {
+ disabled: false,
+ options: fields
+ .filter((f) => f.visible !== false && !CONTACT_FIELDS.includes(f.api_name))
+ .map((f) => ({ label: f.display_label ?? f.field_label ?? f.api_name, value: f.api_name })),
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load fields: ${errorText(error)}` };
+ }
+ },
+ }),
+};
export const newContact = createTrigger({
auth: zohoCrmAuth,
@@ -94,108 +167,48 @@ export const newContact = createTrigger({
Secondary_Email: null,
},
type: TriggerStrategy.POLLING,
- props: {},
+ props: newContactProps,
+ async onEnable(context): Promise<void> {
+ if (context.isRepublish) {
+ await adoptLegacyCursor(context.store);
+ }
+ await initCursor({ store: context.store, isRepublish: context.isRepublish, now: () => zohoNow({ auth: context.auth, module: 'Contacts' }) });
+ },
+ async onDisable(): Promise<void> {
+ return;
+ },
async run(context) {
- return await pollingHelper.poll(polling, {
+ await adoptLegacyCursor(context.store);
+ return pollModule({
auth: context.auth,
store: context.store,
- propsValue: context.propsValue,
- files: context.files,
+ module: 'Contacts',
+ fields: contactFieldsParam(context.propsValue.additional_fields).split(','),
+ sortBy: 'Created_Time',
+ apiVersion: LEGACY_API_VERSION,
});
},
- async test({ auth, propsValue, store, files }): Promise<unknown[]> {
- return await pollingHelper.test(polling, {
- auth,
- store: store,
- propsValue: propsValue,
- files: files,
- });
- },
- async onEnable({ auth, propsValue, store }): Promise<void> {
- await pollingHelper.onEnable(polling, {
- auth,
- store: store,
- propsValue: propsValue,
- });
- },
- async onDisable({ auth, propsValue, store }): Promise<void> {
- await pollingHelper.onDisable(polling, {
- auth,
- store: store,
- propsValue: propsValue,
+ async test(context): Promise<unknown[]> {
+ return sampleModule({
+ auth: context.auth,
+ module: 'Contacts',
+ fields: contactFieldsParam(context.propsValue.additional_fields).split(','),
+ sortBy: 'Created_Time',
+ apiVersion: LEGACY_API_VERSION,
});
},
});
-const polling: Polling<AppConnectionValueForAuthProperty<typeof zohoCrmAuth>, unknown> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth }) => {
- const response = await httpClient.sendRequest<{
- data: { Created_Time: string }[];
- }>({
- url: `${auth.data.api_domain}/crm/v4/Contacts`,
- method: HttpMethod.GET,
- queryParams: {
- perPage: '200',
- sort_order: 'desc',
- sort_by: 'Created_Time',
- fields: [
- 'Owner',
- 'Email',
- '$currency_symbol',
- '$field_states',
- 'Other_Phone',
- 'Mailing_State',
- 'Other_State',
- '$sharing_permission',
- 'Other_Country',
- 'Last_Activity_Time',
- 'Department',
- '$state',
- 'Unsubscribed_Mode',
- '$process_flow',
- 'Assistant',
- 'Mailing_Country',
- 'id',
- 'Reporting_To',
- '$approval',
- 'Enrich_Status__s',
- 'Other_City',
- 'Created_Time',
- '$wizard_connection_path',
- '$editable',
- 'Home_Phone',
- 'Created_By',
- '$zia_owner_assignment',
- 'Secondary_Email',
- 'Description',
- 'Vendor_Name',
- 'Mailing_Zip',
- '$review_process',
- 'Twitter',
- 'Other_Zip',
- 'Mailing_Street',
- '$canvas_id',
- 'Salutation',
- 'First_Name',
- 'Full_Name',
- 'Asst_Phone',
- 'Record_Image',
- 'Modified_By',
- '$review',
- 'Skype_ID',
- 'Phone',
- 'Account_Name',
- ].join(','),
- },
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.access_token,
- },
- });
- return response.body.data.map((record) => ({
- epochMilliSeconds: dayjs(record.Created_Time).valueOf(),
- data: record,
- }));
- },
-};
+async function adoptLegacyCursor(store: Store): Promise<void> {
+ if (await store.get<PollCursor>(CURSOR_KEY)) {
+ return;
+ }
+ const lastPoll = await store.get<unknown>(LEGACY_LAST_POLL_KEY);
+ if (typeof lastPoll === 'number' && Number.isFinite(lastPoll)) {
+ await store.put<PollCursor>(CURSOR_KEY, { time: lastPoll + 1, ids: [] });
+ await store.delete(LEGACY_LAST_POLL_KEY);
+ }
+}
+
+const LEGACY_LAST_POLL_KEY = 'lastPoll';
+const LEGACY_API_VERSION = 'v4';
diff --git a/packages/pieces/community/zoho-crm/src/lib/triggers/new-record.ts b/packages/pieces/community/zoho-crm/src/lib/triggers/new-record.ts
new file mode 100644
index 00000000000..8f9a90bd3c0
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/triggers/new-record.ts
@@ -0,0 +1,57 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName } from '../common/client';
+import { recordOutputSchema } from '../output-schemas';
+import { pollModule, recordTriggerProps, sampleModule, startTrigger, triggerFields } from '../common/record-trigger';
+
+export const newRecordTrigger = createTrigger({
+ auth: zohoCrmAuth,
+ name: 'new_record',
+ classification: 'READ',
+ displayName: 'New Record',
+ description: 'Triggers when a record is created in any module (custom fields included).',
+ aiMetadata: {
+ description:
+ 'Fires once per record newly created in the chosen Zoho CRM module (standard or custom), emitting the record with its field API names as keys, custom fields included (up to 50 fields). Polls by Created_Time.',
+ },
+ props: recordTriggerProps,
+ sampleData: {
+ id: '5725767000000524157',
+ Last_Name: 'Doe',
+ First_Name: 'Jane',
+ Email: '[email protected]',
+ Company: 'Acme Inc',
+ Lead_Source: 'Web Download',
+ Custom_Field__c: 'value',
+ Owner: { name: 'Jane Admin', id: '5725767000000411001', email: '[email protected]' },
+ Created_Time: '2026-09-29T10:15:00+02:00',
+ Modified_Time: '2026-09-29T10:15:00+02:00',
+ },
+ type: TriggerStrategy.POLLING,
+ outputSchema: recordOutputSchema,
+ async onEnable(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ await startTrigger({ auth: context.auth, module, store: context.store, isRepublish: context.isRepublish, chosen: context.propsValue.fields });
+ },
+ async onDisable() {
+ },
+ async run(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ return pollModule({
+ auth: context.auth,
+ store: context.store,
+ module,
+ fields: await triggerFields({ auth: context.auth, store: context.store, module, chosen: context.propsValue.fields }),
+ sortBy: 'Created_Time',
+ });
+ },
+ async test(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ return sampleModule({
+ auth: context.auth,
+ module,
+ fields: await triggerFields({ auth: context.auth, module, chosen: context.propsValue.fields }),
+ sortBy: 'Created_Time',
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/src/lib/triggers/updated-record.ts b/packages/pieces/community/zoho-crm/src/lib/triggers/updated-record.ts
new file mode 100644
index 00000000000..4d1850e611f
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/src/lib/triggers/updated-record.ts
@@ -0,0 +1,69 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { zohoCrmAuth } from '../auth';
+import { requireApiName } from '../common/client';
+import { recordOutputSchema } from '../output-schemas';
+import { ZohoRecord } from '../common/polling';
+import { pollModule, recordTriggerProps, sampleModule, startTrigger, triggerFields } from '../common/record-trigger';
+
+export function isUpdateOnly(record: ZohoRecord): boolean {
+ return record['Modified_Time'] !== record['Created_Time'];
+}
+
+export const updatedRecordTrigger = createTrigger({
+ auth: zohoCrmAuth,
+ name: 'updated_record',
+ classification: 'READ',
+ displayName: 'Updated Record',
+ description: 'Triggers when a record is modified in any module.',
+ aiMetadata: {
+ description:
+ 'Fires once per record modified in the chosen Zoho CRM module since the last poll, emitting the record at its latest state (up to 50 fields, custom fields included). Polls by Modified_Time; by default records that were only created (never edited) are skipped, and several edits between two polls produce one event.',
+ },
+ props: {
+ ...recordTriggerProps,
+ include_new: Property.Checkbox({
+ displayName: 'Include Newly Created Records',
+ description: 'Also fire for records created but not edited since the last check.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ sampleData: {
+ id: '5725767000000524157',
+ Last_Name: 'Doe',
+ Email: '[email protected]',
+ Lead_Status: 'Contacted',
+ Created_Time: '2026-09-28T10:15:00+02:00',
+ Modified_Time: '2026-09-29T11:02:41+02:00',
+ Modified_By: { name: 'Jane Admin', id: '5725767000000411001', email: '[email protected]' },
+ },
+ type: TriggerStrategy.POLLING,
+ outputSchema: recordOutputSchema,
+ async onEnable(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ await startTrigger({ auth: context.auth, module, store: context.store, isRepublish: context.isRepublish, chosen: context.propsValue.fields });
+ },
+ async onDisable() {
+ },
+ async run(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ return pollModule({
+ auth: context.auth,
+ store: context.store,
+ module,
+ fields: await triggerFields({ auth: context.auth, store: context.store, module, chosen: context.propsValue.fields }),
+ sortBy: 'Modified_Time',
+ keep: context.propsValue.include_new === true ? undefined : isUpdateOnly,
+ });
+ },
+ async test(context) {
+ const module = requireApiName({ value: context.propsValue.module, name: 'Module' });
+ return sampleModule({
+ auth: context.auth,
+ module,
+ fields: await triggerFields({ auth: context.auth, module, chosen: context.propsValue.fields }),
+ sortBy: 'Modified_Time',
+ keep: context.propsValue.include_new === true ? undefined : isUpdateOnly,
+ });
+ },
+});
diff --git a/packages/pieces/community/zoho-crm/test/ai-atomics.test.ts b/packages/pieces/community/zoho-crm/test/ai-atomics.test.ts
new file mode 100644
index 00000000000..37577f25f9a
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/ai-atomics.test.ts
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { zohoAiActions } from '../src/lib/actions/ai';
+import { listRecordsAtomic, updateRecordAtomic, upsertRecordAtomic } from '../src/lib/actions/ai/records';
+import { mergeDraft, updateEmailDraftAtomic } from '../src/lib/actions/ai/drafts';
+import { addTagsAtomic, createTagAtomic, updateNoteAtomic } from '../src/lib/actions/ai/notes-tags';
+import { downloadAttachmentAtomic, listRelatedRecordsAtomic, linkRelatedRecordAtomic } from '../src/lib/actions/ai/related-attachments';
+import { fileNameFromDisposition } from '../src/lib/common/download';
+import { getRecordAtomic } from '../src/lib/actions/ai/records';
+import { convertLeadAtomic, createEventAtomic, createLeadAtomic } from '../src/lib/actions/ai/typed';
+import { zohoCrm } from '../src/index';
+import { AUTH_EU, call, httpError, ok, runAction, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const LIST = { fields: undefined, per_page: undefined, page: undefined, page_token: undefined, sort_by: undefined, sort_order: undefined, custom_view_id: undefined };
+const WRITE = { skip_automation: false };
+const LEAD = {
+ first_name: undefined, company: undefined, email: undefined, phone: undefined, mobile: undefined, title: undefined, website: undefined,
+ lead_source: undefined, lead_status: undefined, description: undefined, owner_id: undefined, additional_fields: undefined,
+};
+const EVENT = { all_day: false, venue: undefined, description: undefined, related_module: undefined, related_record_id: undefined, owner_id: undefined, additional_fields: undefined };
+const CONVERT = {
+ account_id: undefined, contact_id: undefined, assign_to: undefined, overwrite: false, notify_lead_owner: false, notify_new_entity_owner: false,
+ deal_name: undefined, deal_stage: undefined, deal_closing_date: undefined, deal_amount: undefined, deal_pipeline: undefined,
+};
+const RELATED = {
+ module_api_name: 'Accounts', record_id: '1', related_list_api_name: 'Contacts', fields: undefined, page: undefined, per_page: undefined, page_token: undefined,
+};
+const DRAFT = { from: undefined, to: undefined, cc: undefined, bcc: undefined, subject: undefined, content: undefined, rich_text: undefined, reply_to: undefined };
+
+beforeEach(() => sendRequest.mockReset());
+
+describe('agent surface metadata', () => {
+ it('ships 34 ai atomics with metadata, and demotes the PR A twins', () => {
+ expect(zohoAiActions).toHaveLength(34);
+ for (const a of zohoAiActions) {
+ expect(a.audience).toBe('ai');
+ expect(a.name.startsWith('zoho_crm_')).toBe(true);
+ expect(a.aiMetadata?.description?.length).toBeGreaterThan(40);
+ expect(typeof a.aiMetadata?.idempotent).toBe('boolean');
+ expect(a.classification).toBeDefined();
+ }
+ const trues = zohoAiActions.filter((a) => a.aiMetadata?.idempotent === true).length;
+ expect(trues).toBe(21);
+ const actions = zohoCrm.actions();
+ expect(Object.keys(actions)).toHaveLength(45);
+ for (const name of ['create_record', 'update_record', 'get_record', 'upsert_record', 'delete_record', 'convert_lead', 'add_note', 'add_tags_to_record', 'upload_attachment']) {
+ expect(actions[name].audience).toBe('human');
+ }
+ expect(actions['read-file'].audience).toBe('both');
+ });
+});
+
+describe('list_records', () => {
+ it('fills fields from metadata when omitted and sends documented params', async () => {
+ ok({ body: { fields: [{ api_name: 'id' }, { api_name: 'Last_Name' }, { api_name: 'Custom__c' }, { api_name: 'Hidden', visible: false }] } });
+ ok({ body: { data: [{ id: '1', Custom__c: 'v' }], info: { more_records: true, next_page_token: 'tkn', page: 1 } } });
+ const out = await runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads', per_page: 2, sort_by: 'Created_Time' } });
+ expect(call(1).url).toBe('https://www.zohoapis.eu/crm/v8/Leads');
+ expect(call(1).queryParams).toEqual({ fields: 'id,Last_Name,Custom__c', per_page: '2', sort_by: 'Created_Time' });
+ expect(out).toMatchObject({ count: 1, more_records: true, next_page_token: 'tkn' });
+ });
+
+ it('handles 204 as an empty page', async () => {
+ ok({ body: undefined, status: 204 });
+ const out = await runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads', fields: ['id'] } });
+ expect(out).toMatchObject({ records: [], count: 0, more_records: false });
+ });
+
+ it('rejects page with page_token, pages past 2,000, and >50 fields before any request', async () => {
+ await expect(runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads', page: 2, page_token: 'x', fields: ['id'] } })).rejects.toThrow(/either page or page_token/);
+ await expect(runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads', page: 11, per_page: 200, fields: ['id'] } })).rejects.toThrow(/2,000/);
+ await expect(runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads', fields: Array.from({ length: 51 }, (_, i) => `F${i}`) } })).rejects.toThrow(/50 fields/);
+ await expect(runAction({ action: listRecordsAtomic, auth: AUTH_EU, propsValue: { ...LIST, module_api_name: 'Leads/../x', fields: ['id'] } })).rejects.toThrow(/API name/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('record writes', () => {
+ it('update sends exactly the given keys and refuses id in data', async () => {
+ ok({ body: { data: [{ status: 'success', code: 'SUCCESS', details: { id: '5725767000000524157' } }] } });
+ await runAction({ action: updateRecordAtomic, auth: AUTH_EU, propsValue: { ...WRITE, module_api_name: 'Deals', record_id: '5725767000000524157', data: { Stage: 'Closed Won' }, append_multiselect_fields: undefined } });
+ expect(call(0)).toMatchObject({ method: 'PUT', url: 'https://www.zohoapis.eu/crm/v8/Deals/5725767000000524157', body: { data: [{ Stage: 'Closed Won' }] } });
+ await expect(runAction({ action: updateRecordAtomic, auth: AUTH_EU, propsValue: { ...WRITE, module_api_name: 'Deals', record_id: '1', data: { id: '2' }, append_multiselect_fields: undefined } })).rejects.toThrow(/record_id/);
+ });
+
+ it('upsert sends duplicate_check_fields and surfaces action', async () => {
+ ok({ body: { data: [{ status: 'success', action: 'update', duplicate_field: 'Email', details: { id: '7' } }] } });
+ const out = await runAction({ action: upsertRecordAtomic, auth: AUTH_EU, propsValue: { ...WRITE, module_api_name: 'Leads', data: { Last_Name: 'D', Email: '[email protected]' }, duplicate_check_fields: ['Email'] } });
+ expect(call(0).url).toBe('https://www.zohoapis.eu/crm/v8/Leads/upsert');
+ expect(call(0).body).toEqual({ data: [{ Last_Name: 'D', Email: '[email protected]' }], duplicate_check_fields: ['Email'] });
+ expect(out).toMatchObject({ id: '7', action: 'update', duplicate_field: 'Email' });
+ });
+
+ it('create_lead: typed props win over additional_fields', async () => {
+ ok({ body: { data: [{ status: 'success', details: { id: '1' } }] }, status: 201 });
+ await runAction({ action: createLeadAtomic, auth: AUTH_EU, propsValue: { ...LEAD, last_name: 'Doe', email: '[email protected]', additional_fields: { Email: '[email protected]', Custom__c: 1 }, owner_id: '42' } });
+ expect(call(0).body.data[0]).toEqual({ Email: '[email protected]', Custom__c: 1, Last_Name: 'Doe', Owner: { id: '42' } });
+ });
+
+ it('create_event validates the related pair and the time order', async () => {
+ await expect(runAction({ action: createEventAtomic, auth: AUTH_EU, propsValue: { ...EVENT, event_title: 'x', start_datetime: '2026-10-01T09:00:00+02:00', end_datetime: '2026-10-01T10:00:00+02:00', related_module: 'Deals' } })).rejects.toThrow(/together/);
+ await expect(runAction({ action: createEventAtomic, auth: AUTH_EU, propsValue: { ...EVENT, event_title: 'x', start_datetime: '2026-10-01T09:00:00+02:00', end_datetime: '2026-10-01T08:00:00+02:00' } })).rejects.toThrow(/not be before/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('convert_lead requires stage + closing date with a deal', async () => {
+ await expect(runAction({ action: convertLeadAtomic, auth: AUTH_EU, propsValue: { ...CONVERT, lead_id: '1', deal_name: 'D' } })).rejects.toThrow(/deal_stage/);
+ ok({ body: { data: [{ status: 'success', details: { Contacts: { id: '2', name: 'C' }, Accounts: { id: '3', name: 'A' }, Deals: { id: '4', name: 'D' } } }] } });
+ const out = await runAction({ action: convertLeadAtomic, auth: AUTH_EU, propsValue: { ...CONVERT, lead_id: '1', deal_name: 'D', deal_stage: 'Qualification', deal_closing_date: '2026-12-31' } });
+ expect(call(0).body).toEqual({ data: [{ Deals: { Deal_Name: 'D', Stage: 'Qualification', Closing_Date: '2026-12-31' } }] });
+ expect(out).toMatchObject({ contact_id: '2', account_id: '3', deal_id: '4' });
+ });
+});
+
+describe('notes, tags, related', () => {
+ it('update_note refuses an empty update and sends only the changed key', async () => {
+ await expect(runAction({ action: updateNoteAtomic, auth: AUTH_EU, propsValue: { note_id: '1', title: undefined, content: undefined } })).rejects.toThrow(/title or content/);
+ ok({ body: { data: [{ status: 'success', details: { id: '1' } }] } });
+ await runAction({ action: updateNoteAtomic, auth: AUTH_EU, propsValue: { note_id: '1', title: undefined, content: 'new' } });
+ expect(call(0).body).toEqual({ data: [{ Note_Content: 'new' }] });
+ });
+
+ it('create_tag returns the existing tag without creating', async () => {
+ ok({ body: { tags: [{ id: '10', name: 'VIP', color_code: '#F17574' }] } });
+ const out = await runAction({ action: createTagAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Leads', name: 'vip', color_code: undefined } });
+ expect(out).toEqual({ id: '10', name: 'VIP', color_code: '#F17574', module: 'Leads', created: false });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('create_tag creates when missing and validates color', async () => {
+ await expect(runAction({ action: createTagAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Leads', name: 'x', color_code: '#000000' } })).rejects.toThrow(/color_code/);
+ ok({ body: { tags: [] } });
+ ok({ body: { tags: [{ code: 'SUCCESS', status: 'success', details: { id: '11' } }] } });
+ const out = await runAction({ action: createTagAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Leads', name: 'New', color_code: undefined } });
+ expect(call(1).body).toEqual({ tags: [{ name: 'New' }] });
+ expect(out).toMatchObject({ id: '11', created: true });
+ });
+
+ it('add_tags keeps existing tags (over_write false) and caps ids', async () => {
+ ok({ body: { data: [{ status: 'success', details: { id: '1', tags: [{ name: 'A' }, { name: 'B' }] } }] } });
+ const out = await runAction({ action: addTagsAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Leads', record_ids: ['1'], tags: ['B'] } });
+ expect(call(0).body).toEqual({ tags: [{ name: 'B' }], ids: ['1'], over_write: false });
+ expect(out).toMatchObject({ success_count: 1, failed_count: 0 });
+ await expect(runAction({ action: addTagsAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Leads', record_ids: Array.from({ length: 501 }, (_, i) => String(i + 1)), tags: ['B'] } })).rejects.toThrow(/500/);
+ });
+
+ it('link_related_record uses the documented batch body', async () => {
+ ok({ body: { data: [{ status: 'success', code: 'SUCCESS', details: { id: '9' } }] } });
+ await runAction({ action: linkRelatedRecordAtomic, auth: AUTH_EU, propsValue: { module_api_name: 'Campaigns', record_id: '1', related_list_api_name: 'Contacts', related_record_id: '9', relation_fields: { Member_Status: 'Invited' } } });
+ expect(call(0)).toMatchObject({ method: 'PUT', url: 'https://www.zohoapis.eu/crm/v8/Campaigns/1/Contacts', body: { data: [{ Member_Status: 'Invited', id: '9' }] } });
+ });
+
+ it('list_related_records fails when Zoho cannot list related lists, instead of returning only ids', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 500, body: { code: 'INTERNAL_ERROR', message: 'boom' } }));
+ await expect(runAction({ action: listRelatedRecordsAtomic, auth: AUTH_EU, propsValue: RELATED })).rejects.toThrow(/INTERNAL_ERROR/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('list_related_records falls back to id only when the user may not read field metadata', async () => {
+ ok({ body: { related_lists: [{ api_name: 'Contacts', module: { api_name: 'Contacts' } }] } });
+ sendRequest.mockRejectedValueOnce(httpError({ status: 403, body: { code: 'NO_PERMISSION', message: 'permission denied' } }));
+ ok({ body: { data: [{ id: '5' }], info: { more_records: false } } });
+ const out = await runAction({ action: listRelatedRecordsAtomic, auth: AUTH_EU, propsValue: RELATED });
+ expect(call(2).queryParams.fields).toBe('id');
+ expect(out).toMatchObject({ count: 1 });
+ });
+
+ it('parses attachment file names', () => {
+ expect(fileNameFromDisposition({ header: 'attachment; filename="report.pdf"', fallback: 'x' })).toBe('report.pdf');
+ expect(fileNameFromDisposition({ header: "attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf", fallback: 'x' })).toBe('résumé.pdf');
+ expect(fileNameFromDisposition({ header: undefined, fallback: 'fallback' })).toBe('fallback');
+ });
+});
+
+describe('output schemas', () => {
+ it('get_record and download_attachment describe what run() returns', () => {
+ expect(getRecordAtomic.outputSchema?.fields.map((f) => f.key)).toEqual(['id', 'Created_Time', 'Modified_Time', 'record']);
+ expect(downloadAttachmentAtomic.outputSchema?.fields.map((f) => f.key)).toEqual(['file', 'file_name', 'size', 'content_type']);
+ });
+});
+
+describe('email draft partial update', () => {
+ const current = {
+ id: 'abc',
+ to: [{ email: '[email protected]', user_name: 'A' }],
+ cc: [{ email: '[email protected]' }],
+ subject: 'Old subject',
+ content: '<p>Old</p>',
+ rich_text: true,
+ schedule_details: { time: '2026-11-30T18:40:00+05:30' },
+ attachments: [{ id: 'att', file_name: 'f.txt' }],
+ };
+
+ it('keeps every field not passed', () => {
+ const merged = mergeDraft({ current, changes: { subject: 'New' }, draft: 'abc' });
+ expect(merged).toEqual({
+ id: 'abc',
+ rich_text: true,
+ to: [{ email: '[email protected]', user_name: 'A' }],
+ cc: [{ email: '[email protected]' }],
+ subject: 'New',
+ content: '<p>Old</p>',
+ schedule_details: { time: '2026-11-30T18:40:00+05:30' },
+ attachments: [{ id: 'att', file_name: 'f.txt' }],
+ });
+ });
+
+ it('reads first, then PUTs /{module}/{id}/__email_drafts with the merged draft', async () => {
+ ok({ body: { __email_drafts: [current] } });
+ ok({ body: { __email_drafts: [{ code: 'SUCCESS', status: 'success', details: { id: 'abc' } }] } });
+ const out = await runAction({ action: updateEmailDraftAtomic, auth: AUTH_EU, propsValue: { ...DRAFT, module_api_name: 'Leads', record_id: '1', draft_id: 'abc', to: ['[email protected]'] } });
+ expect(call(0).url).toBe('https://www.zohoapis.eu/crm/v8/Leads/1/__email_drafts/abc');
+ expect(call(1).method).toBe('PUT');
+ expect(call(1).url).toBe('https://www.zohoapis.eu/crm/v8/Leads/1/__email_drafts');
+ expect(call(1).body.__email_drafts[0]).toMatchObject({ id: 'abc', from: '[email protected]', to: [{ email: '[email protected]' }], subject: 'Old subject', cc: [{ email: '[email protected]' }] });
+ expect(out).toMatchObject({ id: 'abc', status: 'success' });
+ });
+});
diff --git a/packages/pieces/community/zoho-crm/test/back-compat.test.ts b/packages/pieces/community/zoho-crm/test/back-compat.test.ts
new file mode 100644
index 00000000000..5ec0dd4e188
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/back-compat.test.ts
@@ -0,0 +1,61 @@
+import { Readable } from 'node:stream';
+import { PropertyType } from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { readFile } from '../src/lib/actions/read-file';
+import { newContact } from '../src/lib/triggers/new-contact';
+import { zohoCrm } from '../src/index';
+import { asPolling, call, captureWrites, memoryStore, ok, runAction, runTrigger, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const MAIN_CONTACT_FIELDS =
+ 'Owner,Email,$currency_symbol,$field_states,Other_Phone,Mailing_State,Other_State,$sharing_permission,Other_Country,Last_Activity_Time,Department,$state,Unsubscribed_Mode,$process_flow,Assistant,Mailing_Country,id,Reporting_To,$approval,Enrich_Status__s,Other_City,Created_Time,$wizard_connection_path,$editable,Home_Phone,Created_By,$zia_owner_assignment,Secondary_Email,Description,Vendor_Name,Mailing_Zip,$review_process,Twitter,Other_Zip,Mailing_Street,$canvas_id,Salutation,First_Name,Full_Name,Asst_Phone,Record_Image,Modified_By,$review,Skype_ID,Phone,Account_Name';
+const T0 = Date.parse('2026-09-29T10:00:00+00:00');
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('steps that exist on main keep their inputs and outputs', () => {
+ it('New Contact asks the same API version and fields as 0.3.1 and passes the record through unchanged', async () => {
+ const contact = {
+ id: '1',
+ Created_Time: new Date(T0 + 1000).toISOString().replace('.000Z', '+00:00'),
+ $state: 'save',
+ Owner: { name: 'Ann', id: '2', email: '[email protected]' },
+ Account_Name: { name: 'Acme', id: '3' },
+ $approval: { delegate: false, approve: false, reject: false, resubmit: false },
+ };
+ ok({ body: { data: [contact], info: { more_records: false } } });
+ const { store } = memoryStore();
+ await store.put('zoho_poll_cursor', { time: T0, ids: [] });
+ const out = await runTrigger({ trigger: asPolling(newContact), propsValue: { additional_fields: undefined }, store });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(call(0).url).toBe('https://www.zohoapis.com/crm/v4/Contacts');
+ expect(call(0).queryParams).toMatchObject({ fields: MAIN_CONTACT_FIELDS, per_page: '200', sort_by: 'Created_Time', sort_order: 'desc' });
+ expect(out).toEqual([contact]);
+ });
+
+ it('New Contact still accepts the empty input that 0.3.1 flows saved', () => {
+ expect(Object.keys(newContact.props)).toEqual(['additional_fields']);
+ expect(newContact.props.additional_fields.required).toBe(false);
+ });
+
+ it('Read File keeps its single url input and still returns the stored file reference', async () => {
+ expect(Object.keys(readFile.props)).toEqual(['url']);
+ expect(readFile.props.url.type).toBe(PropertyType.SHORT_TEXT);
+ ok({ body: Readable.from([Buffer.from('zip')]) });
+ const written = captureWrites();
+ const out = await runAction({ action: readFile, propsValue: { url: 'https://www.zohoapis.com/crm/bulk/v8/read/1/result' }, files: written.files });
+ expect(out).toBe('file://stored');
+ });
+
+ it('Custom API Call keeps its inputs', () => {
+ const action = zohoCrm.actions()['custom_api_call'];
+ expect(Object.keys(action.props)).toEqual(['url', 'method', 'headers', 'queryParams', 'body_type', 'body', 'response_is_binary', 'failsafe', 'timeout', 'followRedirects']);
+ });
+});
diff --git a/packages/pieces/community/zoho-crm/test/greptile-1.test.ts b/packages/pieces/community/zoho-crm/test/greptile-1.test.ts
new file mode 100644
index 00000000000..f61ac1a9585
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/greptile-1.test.ts
@@ -0,0 +1,84 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { readFile } from '../src/lib/actions/read-file';
+import { createRecordAtomic } from '../src/lib/actions/ai/records';
+import { updateEmailDraftAtomic } from '../src/lib/actions/ai/drafts';
+import { call, ok, runAction, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const CREATE_DEFAULTS = { additional_fields: undefined, triggers: undefined, skip_automation: false };
+const BIG_FIELDS = { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Big__c', data_type: 'bigint' }, { api_name: 'Amount__c', data_type: 'currency' }] };
+const DRAFT = { from: undefined, to: undefined, cc: undefined, bcc: undefined, subject: undefined, content: undefined, rich_text: undefined, reply_to: undefined };
+const CURRENT_DRAFT = { id: 'abc', from: '[email protected]', to: [{ email: '[email protected]' }], cc: [{ email: '[email protected]' }], bcc: [{ email: '[email protected]' }], subject: 'S', content: 'C', rich_text: true };
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('long integers and exact numbers', () => {
+ it('refuses a long integer that arrives as an already-rounded number', async () => {
+ ok({ body: BIG_FIELDS });
+ await expect(
+ runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Big__c: 123456789012345678 } } }),
+ ).rejects.toThrow(/pass long integers above 2\^53 as text/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses decimal text that cannot be sent exactly, and accepts exact values', async () => {
+ ok({ body: BIG_FIELDS });
+ await expect(
+ runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Amount__c: '12345678901234567.89' } } }),
+ ).rejects.toThrow(/sent exactly/);
+ ok({ body: BIG_FIELDS });
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Amount__c: '1234.50', Big__c: 42 } } });
+ expect(call(2).body.data[0]).toEqual({ Last_Name: 'Doe', Amount__c: 1234.5, Big__c: '42' });
+ });
+
+ it('refuses an unsafe number anywhere in an agent record before any request', async () => {
+ await expect(
+ runAction({ action: createRecordAtomic, propsValue: { module_api_name: 'Leads', data: { Last_Name: 'Doe', Big__c: 123456789012345678 }, skip_automation: false } }),
+ ).rejects.toThrow(/Big__c arrived as a number above 2\^53/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('Update Email Draft recipient lists', () => {
+ it('refuses an empty recipient list before any request, because Zoho silently keeps the old recipients', async () => {
+ for (const list of ['to', 'cc', 'bcc']) {
+ await expect(
+ runAction({ action: updateEmailDraftAtomic, propsValue: { ...DRAFT, module_api_name: 'Leads', record_id: '1', draft_id: 'abc', [list]: [] } }),
+ ).rejects.toThrow(new RegExp(`${list} is empty`));
+ }
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('keeps omitted recipient lists and replaces the ones passed', async () => {
+ ok({ body: { __email_drafts: [CURRENT_DRAFT] } });
+ ok({ body: { __email_drafts: [{ status: 'success', details: { id: 'abc' } }] } });
+ await runAction({ action: updateEmailDraftAtomic, propsValue: { ...DRAFT, module_api_name: 'Leads', record_id: '1', draft_id: 'abc', cc: ['[email protected]'] } });
+ expect(call(1).body.__email_drafts[0]).toMatchObject({ to: [{ email: '[email protected]' }], cc: [{ email: '[email protected]' }], bcc: [{ email: '[email protected]' }] });
+ });
+});
+
+describe('download redirects', () => {
+ it.each([
+ 'https://169.254.169.254/latest/meta-data/',
+ 'https://127.0.0.1/x',
+ 'https://localhost/x',
+ 'https://10.0.0.5/x',
+ 'https://[::1]/x',
+ 'https://cdn.example-storage.net/object?sig=abc',
+ 'https://www.zohoapis.eu/crm/v8/org',
+ 'https://download.zoho.com:8443/v2/crm/1/f.zip',
+ ])('refuses a redirect to %s before requesting it', async (location) => {
+ ok({ body: undefined, status: 302, headers: { location } });
+ await expect(runAction({ action: readFile, propsValue: { url: 'https://www.zohoapis.com/crm/bulk/v8/read/1/result' } })).rejects.toThrow(/stopped/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/pieces/community/zoho-crm/test/helpers.ts b/packages/pieces/community/zoho-crm/test/helpers.ts
new file mode 100644
index 00000000000..0c2a9982d39
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/helpers.ts
@@ -0,0 +1,178 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ InputPropertyMap,
+ PropertyContext,
+ StaticPropsValue,
+ Store,
+ TestOrRunHookContext,
+ TriggerHookContext,
+ TriggerStrategy,
+ createMockActionContext,
+ createMockPollingTriggerContext,
+} from '@activepieces/pieces-framework';
+import { Readable } from 'node:stream';
+import { vi } from 'vitest';
+import { zohoCrmAuth } from '../src/lib/auth';
+import type { ZohoAuth } from '../src/lib/common/client';
+
+export const sendRequest = vi.fn();
+
+export function mockHttpClient() {
+ return {
+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },
+ };
+}
+
+export function ok({ body, status = 200, headers = {} }: { body: unknown; status?: number; headers?: Record<string, unknown> }) {
+ sendRequest.mockResolvedValueOnce({ status, headers, body });
+}
+
+export function captureWrites(): { files: ActionContext['files']; calls: { fileName: string; streamed: boolean; content: string }[] } {
+ const calls: { fileName: string; streamed: boolean; content: string }[] = [];
+ const write = async ({ fileName, data }: { fileName: string; data: Buffer | Readable }): Promise<string> => {
+ const streamed = !Buffer.isBuffer(data);
+ const chunks: Buffer[] = [];
+ if (Buffer.isBuffer(data)) {
+ chunks.push(data);
+ } else {
+ for await (const chunk of data) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
+ }
+ }
+ calls.push({ fileName, streamed, content: Buffer.concat(chunks).toString() });
+ return 'file://stored';
+ };
+ return { files: { write, upload: async () => ({ id: 'f', url: 'file://stored' }) }, calls };
+}
+
+export function httpError({ status, body }: { status: number; body: unknown }): Error {
+ return Object.assign(new Error(`HTTP ${status}`), { response: { status, body } });
+}
+
+export function call(index: number) {
+ return sendRequest.mock.calls[index][0];
+}
+
+export function memoryStore(): { store: Store; read: (key: string) => unknown } {
+ const map = new Map<string, string>();
+ const store: Store = {
+ put: async (key, value) => {
+ map.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async (key) => {
+ const raw = map.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key) => {
+ map.delete(key);
+ },
+ };
+ return {
+ store,
+ read: (key) => {
+ const raw = map.get(key);
+ return raw === undefined ? undefined : JSON.parse(raw);
+ },
+ };
+}
+
+export function runAction<Props extends InputPropertyMap>({
+ action,
+ propsValue,
+ files,
+ auth = AUTH,
+}: {
+ action: { props: Props; run: (context: ActionContext<typeof zohoCrmAuth, Props>) => Promise<unknown> };
+ propsValue: StaticPropsValue<Props>;
+ files?: ActionContext['files'];
+ auth?: ZohoAuth;
+}): Promise<unknown> {
+ const base = createMockActionContext<Props>({ propsValue });
+ return action.run({ ...base, auth, files: files ?? base.files });
+}
+
+export function asPolling<T extends { type: TriggerStrategy }>(trigger: T): Extract<T, { type: TriggerStrategy.POLLING }> {
+ if (!isPolling(trigger)) {
+ throw new Error('not a polling trigger');
+ }
+ return trigger;
+}
+
+export function runTrigger<Props extends InputPropertyMap>({
+ trigger,
+ propsValue,
+ store,
+}: {
+ trigger: PollingTriggerLike<Props>;
+ propsValue: StaticPropsValue<Props>;
+ store: Store;
+}): Promise<unknown[]> {
+ return trigger.run(triggerContext({ propsValue, store }));
+}
+
+export function enableTrigger<Props extends InputPropertyMap>({
+ trigger,
+ propsValue,
+ store,
+ isRepublish,
+}: {
+ trigger: PollingTriggerLike<Props>;
+ propsValue: StaticPropsValue<Props>;
+ store: Store;
+ isRepublish?: boolean;
+}): Promise<void> {
+ return trigger.onEnable(triggerContext({ propsValue, store, isRepublish }));
+}
+
+export function propertyContext(): PropertyContext {
+ const base = createMockActionContext({ propsValue: {} });
+ return { server: base.server, project: base.project, flows: base.flows, connections: base.connections };
+}
+
+function isPolling<T extends { type: TriggerStrategy }>(trigger: T): trigger is Extract<T, { type: TriggerStrategy.POLLING }> {
+ return trigger.type === TriggerStrategy.POLLING;
+}
+
+function triggerContext<Props extends InputPropertyMap>({
+ propsValue,
+ store,
+ isRepublish,
+}: {
+ propsValue: StaticPropsValue<Props>;
+ store: Store;
+ isRepublish?: boolean;
+}): TestOrRunHookContext<typeof zohoCrmAuth, Props, TriggerStrategy.POLLING> {
+ const base = createMockActionContext<Props>({ propsValue });
+ return {
+ ...createMockPollingTriggerContext<Props>({ propsValue }),
+ auth: AUTH,
+ store,
+ files: base.files,
+ isRepublish,
+ };
+}
+
+type PollingTriggerLike<Props extends InputPropertyMap> = {
+ props: Props;
+ run: (context: TestOrRunHookContext<typeof zohoCrmAuth, Props, TriggerStrategy.POLLING>) => Promise<unknown[]>;
+ onEnable: (context: TriggerHookContext<typeof zohoCrmAuth, Props, TriggerStrategy.POLLING>) => Promise<void>;
+};
+
+export const AUTH = {
+ type: AppConnectionType.OAUTH2,
+ access_token: 'tok-123',
+ client_id: 'client',
+ client_secret: 'secret',
+ redirect_url: 'https://localhost/redirect',
+ token_type: 'Bearer',
+ claimed_at: 0,
+ refresh_token: 'refresh',
+ scope: 'ZohoCRM.modules.ALL',
+ token_url: 'https://accounts.zoho.com/oauth/v2/token',
+ data: { api_domain: 'https://www.zohoapis.com' },
+ props: { location: 'zoho.com' },
+} satisfies ZohoAuth;
+
+export const AUTH_EU: ZohoAuth = { ...AUTH, data: { api_domain: 'https://www.zohoapis.eu' }, props: { location: 'zoho.eu' } };
diff --git a/packages/pieces/community/zoho-crm/test/regressions.test.ts b/packages/pieces/community/zoho-crm/test/regressions.test.ts
new file mode 100644
index 00000000000..e6eb550bfba
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/regressions.test.ts
@@ -0,0 +1,193 @@
+import { PropertyType } from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { addTagsToRecordAction } from '../src/lib/actions/add-tags-to-record';
+import { convertLeadAction } from '../src/lib/actions/convert-lead';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { getRecordAction } from '../src/lib/actions/get-record';
+import { updateRecordAction } from '../src/lib/actions/update-record';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { updatedRecordTrigger } from '../src/lib/triggers/updated-record';
+import { AUTH, asPolling, call, enableTrigger, httpError, memoryStore, ok, propertyContext, runAction, runTrigger, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const CURSOR_KEY = 'zoho_poll_cursor';
+const CREATE_DEFAULTS = { additional_fields: undefined, triggers: undefined, skip_automation: false };
+const CONVERT_DEFAULTS = {
+ account_id: undefined, contact_id: undefined, overwrite: false, assign_to: undefined, notify_lead_owner: false, notify_new_entity_owner: false,
+ create_deal: false, deal_name: undefined, deal_stage: undefined, deal_closing_date: undefined, deal_amount: undefined, deal_pipeline: undefined, deal_extra: undefined,
+};
+const UPDATE_DEFAULTS = { additional_fields: undefined, skip_automation: false };
+const T0 = Date.parse('2026-09-29T10:00:00+00:00');
+const PAGE_SIZE = 200;
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Array props sent as a JSON string (dynamic value toggle)', () => {
+ it('update_record clears every field named in a JSON-string Clear Fields list', async () => {
+ ok({ body: { fields: [{ api_name: 'Phone', data_type: 'phone' }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '111' } }] } });
+ await runAction({
+ action: updateRecordAction,
+ propsValue: { ...UPDATE_DEFAULTS, module: 'Leads', record_id: '111', fields: {}, clear_fields: ['["Phone", "Custom_Field__c"]'] },
+ });
+ expect(call(1).body).toEqual({ data: [{ Phone: null, Custom_Field__c: null }] });
+ });
+
+ it('add_tags_to_record keeps a comma inside a tag name given as a JSON array', async () => {
+ ok({ body: { tags: [] } });
+ ok({ body: { tags: [{ status: 'success', details: { id: '1' } }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '111' } }] } });
+ await runAction({ action: addTagsToRecordAction, propsValue: { module: 'Leads', record_id: '111', tags: undefined, new_tags: ['["Q4, EMEA"]'] } });
+ expect(call(1).body).toEqual({ tags: [{ name: 'Q4, EMEA' }] });
+ expect(call(2).body.tags).toEqual([{ name: 'Q4, EMEA' }]);
+ });
+
+ it('create_record reads a multi-select picklist given as a JSON array string', async () => {
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Interests__c', data_type: 'multiselectpicklist' }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Interests__c: '["A", "B, C"]' } } });
+ expect(call(1).body.data[0]).toEqual({ Last_Name: 'Doe', Interests__c: ['A', 'B, C'] });
+ });
+});
+
+describe('field metadata failures', () => {
+ it('create_record fails instead of sending unconverted values when the field list returns a 500', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 500, body: { code: 'INTERNAL_ERROR', message: 'boom' } }));
+ await expect(
+ runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Annual_Revenue: '10' } } }),
+ ).rejects.toThrow(/INTERNAL_ERROR/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('create_record still works with raw values when the user may not read field metadata', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 403, body: { code: 'NO_PERMISSION', message: 'permission denied' } }));
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe' } } });
+ expect(call(1).body).toEqual({ data: [{ Last_Name: 'Doe' }] });
+ });
+});
+
+describe('convert_lead pickers', () => {
+ it('offers accounts, contacts and owners as dropdowns', async () => {
+ const props = convertLeadAction.props;
+ expect(props.account_id.type).toBe(PropertyType.DROPDOWN);
+ expect(props.contact_id.type).toBe(PropertyType.DROPDOWN);
+ expect(props.assign_to.type).toBe(PropertyType.DROPDOWN);
+ });
+
+ it('lists every active user across pages for the owner dropdown', async () => {
+ ok({ body: { users: [{ id: '1', full_name: 'Ann', email: '[email protected]' }], info: { more_records: true } } });
+ ok({ body: { users: [{ id: '2', full_name: 'Bob' }], info: { more_records: false } } });
+ const state = await convertLeadAction.props.assign_to.options({ auth: AUTH }, propertyContext());
+ expect(state.options).toEqual([
+ { label: 'Ann ([email protected])', value: '1' },
+ { label: 'Bob', value: '2' },
+ ]);
+ expect(call(0).queryParams).toMatchObject({ type: 'ActiveUsers', page: '1' });
+ expect(call(1).queryParams).toMatchObject({ page: '2' });
+ });
+});
+
+describe('convert_lead into an existing record', () => {
+ it('explains Zoho\'s matching rule when the account does not match the lead', async () => {
+ sendRequest.mockRejectedValueOnce(
+ httpError({ status: 400, body: { data: [{ code: 'INVALID_DATA', status: 'error', message: "Account data doesn't match perfectly with the Lead data", details: { api_name: 'id' } }] } }),
+ );
+ await expect(
+ runAction({ action: convertLeadAction, propsValue: { ...CONVERT_DEFAULTS, lead_id: '1', account_id: '2' } }),
+ ).rejects.toThrow(/Account data doesn't match the lead\. Zoho links an existing account only when the lead's Company equals the account name/);
+ });
+});
+
+describe('get_record output', () => {
+ it('describes the record id and times and exposes every field', () => {
+ const fields = getRecordAction.outputSchema?.fields ?? [];
+ expect(fields.map((f) => f.key)).toEqual(['id', 'Created_Time', 'Modified_Time', 'record']);
+ expect(fields[3]).toMatchObject({ value: '', dynamicKey: true });
+ });
+});
+
+describe('polling bursts larger than one poll can read', () => {
+ it('new_record emits every record of a 6,000-record burst across polls, once each', async () => {
+ const server = fakeLeads({ count: 6000 });
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ const propsValue = { module: 'Leads', fields: ['Email'] };
+ const first = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ server.prepend({ count: 3 });
+ const second = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ const third = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ const fourth = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ const emitted = [...first, ...second, ...third, ...fourth].map(idOf);
+ expect(new Set(emitted).size).toBe(emitted.length);
+ expect(emitted).toHaveLength(6003);
+ expect(fourth).toEqual([]);
+ });
+
+ it('updated_record restarts from the top when Zoho rejects a stored page token, without re-emitting', async () => {
+ const server = fakeLeads({ count: 5400, modified: true });
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ const propsValue = { module: 'Leads', fields: ['Email'], include_new: true };
+ const first = await runTrigger({ trigger: asPolling(updatedRecordTrigger), propsValue, store });
+ server.expireTokens();
+ const rest = [
+ ...(await runTrigger({ trigger: asPolling(updatedRecordTrigger), propsValue, store })),
+ ...(await runTrigger({ trigger: asPolling(updatedRecordTrigger), propsValue, store })),
+ ];
+ const emitted = [...first, ...rest].map(idOf);
+ expect(first).toHaveLength(5000);
+ expect(new Set(emitted).size).toBe(5400);
+ expect(emitted).toHaveLength(5400);
+ });
+});
+
+function idOf(record: unknown): string {
+ if (typeof record === 'object' && record !== null && 'id' in record && typeof record.id === 'string') {
+ return record.id;
+ }
+ throw new Error('record without id');
+}
+
+function fakeLeads({ count, modified = false }: { count: number; modified?: boolean }) {
+ const timeField = modified ? 'Modified_Time' : 'Created_Time';
+ const make = ({ index }: { index: number }) => {
+ const time = new Date(T0 + (index + 1) * 1000).toISOString().replace('.000Z', '+00:00');
+ return { id: `r${index}`, Created_Time: modified ? '2026-01-01T00:00:00+00:00' : time, Modified_Time: time };
+ };
+ let records = Array.from({ length: count }, (_, index) => make({ index })).reverse();
+ let generation = 0;
+ let next = count;
+ sendRequest.mockImplementation(async (request: { url: string; queryParams: Record<string, string> }) => {
+ const token = request.queryParams['page_token'];
+ const [tokenGeneration, tokenPage] = (token ?? '').split(':');
+ if (token !== undefined && Number(tokenGeneration) !== generation) {
+ throw httpError({ status: 400, body: { code: 'INVALID_DATA', message: 'page_token expired' } });
+ }
+ const page = token !== undefined ? Number(tokenPage) : Number(request.queryParams['page']);
+ if (token === undefined && page > 10) {
+ throw httpError({ status: 400, body: { code: 'INVALID_DATA', message: 'use page_token beyond 2000 records' } });
+ }
+ const data = records.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
+ const more = page * PAGE_SIZE < records.length;
+ expect(request.queryParams['sort_by']).toBe(timeField);
+ return { status: 200, headers: {}, body: { data, info: { more_records: more, next_page_token: more ? `${generation}:${page + 1}` : null } } };
+ });
+ return {
+ prepend: ({ count: extra }: { count: number }) => {
+ const fresh = Array.from({ length: extra }, (_, i) => make({ index: next + i })).reverse();
+ next += extra;
+ records = [...fresh, ...records];
+ },
+ expireTokens: () => {
+ generation += 1;
+ },
+ };
+}
diff --git a/packages/pieces/community/zoho-crm/test/review-2.test.ts b/packages/pieces/community/zoho-crm/test/review-2.test.ts
new file mode 100644
index 00000000000..74c7e238c93
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/review-2.test.ts
@@ -0,0 +1,177 @@
+import { Readable } from 'node:stream';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { convertLeadAction } from '../src/lib/actions/convert-lead';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { downloadAttachmentAtomic } from '../src/lib/actions/ai/related-attachments';
+import { newContact } from '../src/lib/triggers/new-contact';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { AUTH, asPolling, call, captureWrites, enableTrigger, memoryStore, ok, propertyContext, runAction, runTrigger, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const CURSOR_KEY = 'zoho_poll_cursor';
+const T0 = Date.parse('2026-09-29T10:00:00+00:00');
+const CREATE_DEFAULTS = { additional_fields: undefined, triggers: undefined, skip_automation: false };
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('a second with more than 5,000 records that is still open when first read', () => {
+ it('emits records stamped later in that second, even though Zoho sorts them before the saved page token', async () => {
+ const second = T0 + 60_000;
+ const zoho = keysetZoho({ serverTime: second + 500 });
+ zoho.add({ count: 5100, time: second });
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ const propsValue = { module: 'Leads', fields: ['Email'] };
+ const emitted = new Set<string>();
+ const first = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ first.forEach((r) => emitted.add(idOf(r)));
+ zoho.add({ count: 300, time: second });
+ zoho.setServerTime(second + 120_000);
+ for (let poll = 0; poll < 4; poll++) {
+ const out = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ out.forEach((r) => emitted.add(idOf(r)));
+ }
+ expect(emitted.size).toBe(5400);
+ });
+
+ it('emits each record exactly once when the second had already closed at Zoho', async () => {
+ const second = T0 + 60_000;
+ const zoho = keysetZoho({ serverTime: second + 5_000 });
+ zoho.add({ count: 5400, time: second });
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ const propsValue = { module: 'Leads', fields: ['Email'] };
+ const emitted: string[] = [];
+ for (let poll = 0; poll < 4; poll++) {
+ emitted.push(...(await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store })).map(idOf));
+ }
+ expect(emitted).toHaveLength(5400);
+ expect(new Set(emitted).size).toBe(5400);
+ });
+});
+
+describe('New Contact upgraded from 0.3.x', () => {
+ it('continues from the old lastPoll instead of skipping contacts created since then', async () => {
+ const { store, read } = memoryStore();
+ await store.put('lastPoll', T0);
+ await enableTrigger({ trigger: asPolling(newContact), propsValue: { additional_fields: undefined }, store, isRepublish: true });
+ expect(read(CURSOR_KEY)).toEqual({ time: T0 + 1, ids: [] });
+ expect(read('lastPoll')).toBeUndefined();
+ ok({
+ body: {
+ data: [
+ { id: 'new', Created_Time: new Date(T0 + 1000).toISOString().replace('.000Z', '+00:00') },
+ { id: 'old', Created_Time: new Date(T0).toISOString().replace('.000Z', '+00:00') },
+ ],
+ info: { more_records: false },
+ },
+ });
+ const out = await runTrigger({ trigger: asPolling(newContact), propsValue: { additional_fields: undefined }, store });
+ expect(out.map(idOf)).toEqual(['new']);
+ });
+});
+
+describe('record pickers', () => {
+ it('say when only the 200 most recent records are listed', async () => {
+ ok({ body: { fields: [{ api_name: 'Account_Name' }] } });
+ ok({ body: { data: [{ id: '1', Account_Name: 'Acme' }], info: { more_records: true } } });
+ const state = await convertLeadAction.props.account_id.options({ auth: AUTH }, propertyContext());
+ expect(state.options).toEqual([{ label: 'Acme (1)', value: '1' }]);
+ expect(state.placeholder).toMatch(/most recently modified records; map a record id/);
+ });
+});
+
+describe('field values', () => {
+ it('refuses a date with trailing text and keeps the date part of a full date-time as written', async () => {
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Day__c', data_type: 'date' }] } });
+ await expect(
+ runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Day__c: '2026-10-01abc' } } }),
+ ).rejects.toThrow(/yyyy-MM-dd/);
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Day__c', data_type: 'date' }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Day__c: '2026-10-01T01:00:00+03:00' } } });
+ expect(call(2).body.data[0].Day__c).toBe('2026-10-01');
+ });
+
+ it('sends long integers as the digit string Zoho expects and refuses more than 18 digits', async () => {
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Big__c', data_type: 'bigint' }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Big__c: '12345' } } });
+ expect(call(1).body.data[0].Big__c).toBe('12345');
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Big__c', data_type: 'bigint' }] } });
+ await expect(
+ runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Big__c: '9007199254740993123' } } }),
+ ).rejects.toThrow(/18 digits/);
+ expect(sendRequest).toHaveBeenCalledTimes(3);
+ });
+});
+
+describe('downloaded file names', () => {
+ it.each([
+ ["attachment; filename*=UTF-8'en'..%2F..%2Fetc%2Fpasswd", 'passwd'],
+ ['attachment; filename="../../report\u0007.pdf"', 'report.pdf'],
+ ['attachment; filename=".."', 'attachment-2'],
+ ])('turns %s into a plain file name', async (disposition, expected) => {
+ ok({ body: Readable.from([Buffer.from('x')]), headers: { 'content-disposition': disposition } });
+ const written = captureWrites();
+ await runAction({ action: downloadAttachmentAtomic, propsValue: { module_api_name: 'Leads', record_id: '1', attachment_id: '2' }, files: written.files });
+ expect(written.calls[0].fileName).toBe(expected);
+ });
+});
+
+function keysetZoho({ serverTime }: { serverTime: number }) {
+ let records: { id: string; Created_Time: string; key: number; time: number }[] = [];
+ let nextId = 1000;
+ let now = serverTime;
+ const stamp = (time: number) => new Date(time).toISOString().replace('.000Z', '+00:00');
+ const order = () =>
+ [...records].sort((a, b) => (b.time !== a.time ? b.time - a.time : b.key - a.key));
+ sendRequest.mockImplementation(async (request: { queryParams: Record<string, string> }) => {
+ const perPage = Number(request.queryParams['per_page'] ?? 200);
+ const token = request.queryParams['page_token'];
+ const sorted = order();
+ let start = 0;
+ if (token !== undefined) {
+ const [time, key] = token.split(':');
+ start = sorted.findIndex((r) => r.time < Number(time) || (r.time === Number(time) && r.key < Number(key)));
+ if (start === -1) start = sorted.length;
+ }
+ const slice = sorted.slice(start, start + perPage);
+ const more = start + perPage < sorted.length;
+ const last = slice[slice.length - 1];
+ return {
+ status: 200,
+ headers: { date: new Date(now).toUTCString() },
+ body: {
+ data: slice.map((r) => ({ id: r.id, Created_Time: r.Created_Time })),
+ info: { more_records: more, next_page_token: more && last ? `${last.time}:${last.key}` : null },
+ },
+ };
+ });
+ return {
+ add: ({ count, time }: { count: number; time: number }) => {
+ const fresh = Array.from({ length: count }, () => {
+ nextId += 1;
+ return { id: `r${nextId}`, Created_Time: stamp(time), key: nextId, time };
+ });
+ records = [...records, ...fresh];
+ },
+ setServerTime: (time: number) => {
+ now = time;
+ },
+ };
+}
+
+function idOf(record: unknown): string {
+ if (typeof record === 'object' && record !== null && 'id' in record && typeof record.id === 'string') {
+ return record.id;
+ }
+ throw new Error('record without id');
+}
diff --git a/packages/pieces/community/zoho-crm/test/review-fixes.test.ts b/packages/pieces/community/zoho-crm/test/review-fixes.test.ts
new file mode 100644
index 00000000000..685aaaa7cbc
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/review-fixes.test.ts
@@ -0,0 +1,223 @@
+import { Readable } from 'node:stream';
+import { PropertyType } from '@activepieces/pieces-framework';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { addTagsToRecordAction } from '../src/lib/actions/add-tags-to-record';
+import { convertLeadAction } from '../src/lib/actions/convert-lead';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { readFile } from '../src/lib/actions/read-file';
+import { updateRecordAction } from '../src/lib/actions/update-record';
+import { upsertRecordAction } from '../src/lib/actions/upsert-record';
+import { downloadAttachmentAtomic, listRelatedRecordsAtomic } from '../src/lib/actions/ai/related-attachments';
+import { listNotesAtomic } from '../src/lib/actions/ai/notes-tags';
+import { updateRecordAtomic, upsertRecordAtomic } from '../src/lib/actions/ai/records';
+import { newContact } from '../src/lib/triggers/new-contact';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { zohoCrm } from '../src/index';
+import { asPolling, call, captureWrites, enableTrigger, httpError, memoryStore, ok, propertyContext, runAction, runTrigger, sendRequest, AUTH } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const CURSOR_KEY = 'zoho_poll_cursor';
+const T0 = Date.parse('2026-09-29T10:00:00+00:00');
+const STORE_VALUE_MAX_BYTES = 512 * 1024;
+const CREATE_DEFAULTS = { additional_fields: undefined, triggers: undefined, skip_automation: false };
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('polling: records that share one second', () => {
+ it('emits every record of a 12,000-record import stamped with the same second, once each, and keeps the cursor under the store limit', async () => {
+ const stamp = new Date(T0 + 5000).toISOString().replace('.000Z', '+00:00');
+ const records = Array.from({ length: 12000 }, (_, i) => ({ id: `s${i}`, Created_Time: stamp, Email: null }));
+ serveRecords({ records });
+ const { store, read } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ const propsValue = { module: 'Leads', fields: ['Email'] };
+ const emitted: string[] = [];
+ const cursorSizes: number[] = [];
+ for (let poll = 0; poll < 4; poll++) {
+ const out = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ emitted.push(...out.map(idOf));
+ cursorSizes.push(JSON.stringify(read(CURSOR_KEY)).length);
+ }
+ expect(emitted).toHaveLength(12000);
+ expect(new Set(emitted).size).toBe(12000);
+ expect(Math.max(...cursorSizes)).toBeLessThan(STORE_VALUE_MAX_BYTES);
+ });
+
+ it('seeds the cursor at a whole second of Zoho\'s clock, so records created in the enable second are not skipped', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(T0 + 4123);
+ ok({ body: undefined, status: 204, headers: { date: new Date(T0 + 1000).toUTCString() } });
+ const { store, read } = memoryStore();
+ await enableTrigger({ trigger: asPolling(newRecordTrigger), propsValue: { module: 'Leads', fields: undefined }, store });
+ expect(read(CURSOR_KEY)).toEqual({ time: T0 + 1000, ids: [] });
+ });
+});
+
+describe('triggers: fields and metadata', () => {
+ it('refuses more than 47 picked fields when the flow is published', async () => {
+ const { store } = memoryStore();
+ const fields = Array.from({ length: 48 }, (_, i) => `F${i}`);
+ await expect(enableTrigger({ trigger: asPolling(newRecordTrigger), propsValue: { module: 'Leads', fields }, store })).rejects.toThrow(/at most 47/);
+ });
+
+ it('reads the default field list once, not on every poll', async () => {
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ ok({ body: { fields: [{ api_name: 'Last_Name' }] } });
+ ok({ body: undefined, status: 204 });
+ ok({ body: undefined, status: 204 });
+ const propsValue = { module: 'Leads', fields: undefined };
+ await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue, store });
+ const fieldCalls = sendRequest.mock.calls.filter(([request]) => String(request.url).endsWith('/settings/fields'));
+ expect(fieldCalls).toHaveLength(1);
+ });
+
+ it('New Contact pages back to its last check instead of reading only the newest 200', async () => {
+ const records = Array.from({ length: 450 }, (_, i) => ({ id: `c${i}`, Created_Time: new Date(T0 + (450 - i) * 1000).toISOString().replace('.000Z', '+00:00') }));
+ serveRecords({ records });
+ const { store } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ await store.put('lastPoll', T0);
+ const out = await runTrigger({ trigger: asPolling(newContact), propsValue: { additional_fields: undefined }, store });
+ expect(out).toHaveLength(450);
+ });
+});
+
+describe('Read File and Download Attachment', () => {
+ it.each([
+ 'https://www.zohoapis.com/crm/v7/functions/fn/actions/execute?auth_type=apikey&zapikey=attacker',
+ 'https://files.zohopublic.com/public/x.zip',
+ 'https://www.zohoapis.eu/crm/v8/org',
+ ])('refuses %s for a US connection before any request', async (url) => {
+ await expect(runAction({ action: readFile, propsValue: { url } })).rejects.toThrow(/Refusing to send the Zoho CRM token/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('Read File streams into the file store instead of buffering', async () => {
+ ok({ body: Readable.from([Buffer.from('zip')]) });
+ const written = captureWrites();
+ await runAction({ action: readFile, propsValue: { url: 'https://download-accl.zoho.com/v2/crm/1/backup/f.zip' }, files: written.files });
+ expect(call(0).responseType).toBe('stream');
+ expect(written.calls).toEqual([{ fileName: 'f.zip', streamed: true, content: 'zip' }]);
+ });
+
+ it('Download Attachment streams, reports the size, and destroys the source when the store refuses the file', async () => {
+ ok({ body: Readable.from([Buffer.from('%PDF-1')]), headers: { 'content-disposition': 'attachment; filename="p.pdf"', 'content-type': 'application/pdf' } });
+ const written = captureWrites();
+ const propsValue = { module_api_name: 'Leads', record_id: '1', attachment_id: '2' };
+ const out = await runAction({ action: downloadAttachmentAtomic, propsValue, files: written.files });
+ expect(call(0)).toMatchObject({ url: 'https://www.zohoapis.com/crm/v8/Leads/1/Attachments/2', responseType: 'stream', followRedirects: false });
+ expect(out).toEqual({ file: 'file://stored', file_name: 'p.pdf', size: 6, content_type: 'application/pdf' });
+ const source = Readable.from([Buffer.from('a'), Buffer.from('b')]);
+ ok({ body: source });
+ const tooBig = { write: async () => Promise.reject(new Error('File size exceeds the limit')), upload: vi.fn() };
+ await expect(runAction({ action: downloadAttachmentAtomic, propsValue, files: tooBig })).rejects.toThrow(/exceeds the limit/);
+ expect(source.destroyed).toBe(true);
+ });
+});
+
+describe('Custom API Call', () => {
+ it('does not send the token to a full URL on another host', async () => {
+ const action = zohoCrm.actions()['custom_api_call'];
+ const propsValue = { url: { url: 'https://attacker.example/collect' }, method: 'GET', headers: {}, queryParams: {} };
+ await expect(runAction({ action, propsValue })).rejects.toThrow(/only to https:\/\/www\.zohoapis\.com/);
+ });
+});
+
+describe('field types', () => {
+ it('asks for dates as yyyy-MM-dd text, so the engine does not shift them to UTC', async () => {
+ ok({ body: { fields: [{ api_name: 'Birthday__c', data_type: 'date' }, { api_name: 'Big__c', data_type: 'bigint' }] } });
+ const props = await createRecordAction.props.fields.props({ auth: AUTH, module: 'Leads' }, propertyContext());
+ expect(props['Birthday__c'].type).toBe(PropertyType.SHORT_TEXT);
+ expect(convertLeadAction.props.deal_closing_date.type).toBe(PropertyType.SHORT_TEXT);
+ });
+
+ it('sends a long integer beyond 2^53 with every digit', async () => {
+ ok({ body: { fields: [{ api_name: 'Last_Name', data_type: 'text' }, { api_name: 'Big__c', data_type: 'bigint' }] } });
+ ok({ body: { data: [{ status: 'success', details: { id: '9' } }] }, status: 201 });
+ await runAction({ action: createRecordAction, propsValue: { ...CREATE_DEFAULTS, module: 'Leads', fields: { Last_Name: 'Doe', Big__c: '900719925474099312' } } });
+ expect(call(1).body.data[0].Big__c).toBe('900719925474099312');
+ });
+
+ it('refuses an impossible date instead of sending it', async () => {
+ const propsValue = {
+ lead_id: '1', account_id: undefined, contact_id: undefined, overwrite: false, assign_to: undefined, notify_lead_owner: false, notify_new_entity_owner: false,
+ create_deal: true, deal_name: 'D', deal_stage: 'Qualification', deal_closing_date: '2026-13-01', deal_amount: undefined, deal_pipeline: undefined, deal_extra: undefined,
+ };
+ await expect(runAction({ action: convertLeadAction, propsValue })).rejects.toThrow(/yyyy-MM-dd/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('metadata and inputs', () => {
+ it('does not claim update and upsert are idempotent', () => {
+ for (const action of [updateRecordAction, upsertRecordAction, updateRecordAtomic, upsertRecordAtomic]) {
+ expect(action.aiMetadata?.idempotent).toBe(false);
+ }
+ });
+
+ it('refuses pages past the 2,000-item window before any request', async () => {
+ await expect(
+ runAction({ action: listNotesAtomic, propsValue: { parent_module: 'Leads', parent_id: '1', page: 11, per_page: 200 } }),
+ ).rejects.toThrow(/2,000/);
+ await expect(
+ runAction({
+ action: listRelatedRecordsAtomic,
+ propsValue: { module_api_name: 'Accounts', record_id: '1', related_list_api_name: 'Contacts', fields: ['id'], page: 11, per_page: 200, page_token: undefined },
+ }),
+ ).rejects.toThrow(/2,000/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('checks the tag count before creating any tag', async () => {
+ const newTags = Array.from({ length: 11 }, (_, i) => `T${i}`);
+ await expect(runAction({ action: addTagsToRecordAction, propsValue: { module: 'Leads', record_id: '1', tags: undefined, new_tags: newTags } })).rejects.toThrow(/at most 10/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('keeps the users already read when a later page of the Owner dropdown fails', async () => {
+ ok({ body: { users: [{ id: '1', full_name: 'Ann' }], info: { more_records: true } } });
+ sendRequest.mockRejectedValueOnce(httpError({ status: 500, body: { code: 'INTERNAL_ERROR', message: 'boom' } }));
+ const state = await convertLeadAction.props.assign_to.options({ auth: AUTH }, propertyContext());
+ expect(state.options).toEqual([{ label: 'Ann', value: '1' }]);
+ expect(state.disabled).toBe(false);
+ expect(state.placeholder).toMatch(/first 1 users/);
+ });
+
+ it('names the parameter Zoho complains about', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 400, body: { code: 'INVALID_DATA', message: 'invalid data', details: { param_name: 'sort_by' } } }));
+ await expect(runAction({ action: listNotesAtomic, propsValue: { parent_module: undefined, parent_id: undefined, page: undefined, per_page: undefined } })).rejects.toThrow(/parameter: sort_by/);
+ });
+});
+
+function serveRecords({ records, serverTime = T0 + 3_600_000 }: { records: Record<string, unknown>[]; serverTime?: number }) {
+ sendRequest.mockImplementation(async (request: { queryParams: Record<string, string> }) => {
+ const token = request.queryParams['page_token'];
+ const perPage = Number(request.queryParams['per_page'] ?? 200);
+ const page = token !== undefined ? Number(token) : Number(request.queryParams['page'] ?? 1);
+ if (token === undefined && page * perPage > 2000) {
+ throw httpError({ status: 400, body: { code: 'DISCRETE_PAGINATION_LIMIT_EXCEEDED', message: 'use page_token' } });
+ }
+ const data = records.slice((page - 1) * perPage, page * perPage);
+ const more = page * perPage < records.length;
+ return { status: 200, headers: { date: new Date(serverTime).toUTCString() }, body: { data, info: { more_records: more, next_page_token: more ? String(page + 1) : null } } };
+ });
+}
+
+function idOf(record: unknown): string {
+ if (typeof record === 'object' && record !== null && 'id' in record && typeof record.id === 'string') {
+ return record.id;
+ }
+ throw new Error('record without id');
+}
diff --git a/packages/pieces/community/zoho-crm/test/zoho-crm.test.ts b/packages/pieces/community/zoho-crm/test/zoho-crm.test.ts
new file mode 100644
index 00000000000..0fe362cb2ec
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/test/zoho-crm.test.ts
@@ -0,0 +1,464 @@
+import { PropertyType } from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { tokenHosts, zohoTokenUrl } from '../src/lib/common/host-guard';
+import { readFile } from '../src/lib/actions/read-file';
+import { contactFieldsParam, newContact } from '../src/lib/triggers/new-contact';
+import { newRecordTrigger } from '../src/lib/triggers/new-record';
+import { isUpdateOnly, updatedRecordTrigger } from '../src/lib/triggers/updated-record';
+import { collectSince, CURSOR_KEY, PollCursor, ZohoRecord } from '../src/lib/common/polling';
+import { buildFieldProps, buildRecordPayload, convertFieldValue, FIELDS_JSON_KEY, fieldsJsonFallbackProp, isApiReadOnly } from '../src/lib/common/fields';
+import { defaultFieldSelection, ZohoField } from '../src/lib/common/metadata';
+import { flattenAttachment } from '../src/lib/common/flatten';
+import { buildMultipart, deleteRecord, updateRecord } from '../src/lib/common/records';
+import { customApiAuthHeaders, getApiDomain, stringList, toZohoError, unwrapWriteItem } from '../src/lib/common/client';
+import { createRecordAction } from '../src/lib/actions/create-record';
+import { updateRecordAction } from '../src/lib/actions/update-record';
+import { zohoCrm } from '../src/index';
+import { AUTH, asPolling, call, captureWrites, enableTrigger, httpError, memoryStore, ok, propertyContext, runAction, runTrigger, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const LEAD_FIELDS: ZohoField[] = [
+ { api_name: 'Last_Name', data_type: 'text', system_mandatory: true, field_label: 'Last Name' },
+ { api_name: 'Email', data_type: 'email' },
+ { api_name: 'Annual_Revenue', data_type: 'currency' },
+ { api_name: 'Email_Opt_Out', data_type: 'boolean' },
+ { api_name: 'Birth_Date__c', data_type: 'date' },
+ { api_name: 'Next_Call__c', data_type: 'datetime' },
+ { api_name: 'Lead_Status', data_type: 'picklist', pick_list_values: [{ display_value: '-None-', actual_value: '-None-' }, { display_value: 'Contacted', actual_value: 'Contacted' }] },
+ { api_name: 'Interests__c', data_type: 'multiselectpicklist', pick_list_values: [{ actual_value: 'A' }, { actual_value: 'B' }] },
+ { api_name: 'Account__c', data_type: 'lookup', lookup: { module: { api_name: 'Accounts' } } },
+ { api_name: 'Owner', data_type: 'ownerlookup' },
+ { api_name: 'Notes__c', data_type: 'textarea' },
+ { api_name: 'Score__c', data_type: 'formula', read_only: true },
+ { api_name: 'Items', data_type: 'subform' },
+ { api_name: 'Created_Time', data_type: 'datetime', read_only: true },
+ { api_name: 'Hidden__c', data_type: 'text', visible: false },
+];
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('token host guard', () => {
+ const US = tokenHosts('https://www.zohoapis.com');
+ it.each([
+ 'https://www.zohoapis.com/crm/v8/org',
+ 'https://www.zohoapis.com/crm/bulk/v2/read/1/result',
+ 'https://download-accl.zoho.com/v2/crm/123/backup/1/file.zip',
+ 'https://download.zoho.com/v2/crm/123/backup/1/file.zip',
+ ])('allows %s for a US connection', (url) => {
+ expect(zohoTokenUrl({ raw: url, hosts: US })).not.toBeNull();
+ });
+
+ it.each([
+ 'https://www.zohoapis.com/crm/v7/functions/fn/actions/execute?auth_type=apikey&zapikey=x',
+ 'https://www.zohoapis.com/crm/v7/%66unctions/fn/actions/execute',
+ 'https://www.zohoapis.com/oauth/v2/token',
+ 'https://accounts.zoho.com/oauth/v2/token',
+ 'https://www.zohoapis.eu/crm/v8/org',
+ 'https://download-accl.zoho.eu/v2/crm/1/backup/f.zip',
+ 'https://files.zohopublic.com/crm/x',
+ 'https://x.zohoexternal.com/crm/x',
+ 'https://zoho.com.evil.io/crm/x',
+ 'https://www.zohoapis.com.attacker.net/crm/x',
+ 'http://www.zohoapis.com/crm/v8/org',
+ 'https://user:[email protected]/crm/v8/org',
+ 'https://www.zohoapis.com:8443/crm/v8/org',
+ '//www.zohoapis.com/crm/v8/org',
+ 'not a url',
+ ])('refuses %s for a US connection', (url) => {
+ expect(zohoTokenUrl({ raw: url, hosts: US })).toBeNull();
+ });
+
+ it('builds the list from the connection data centre', () => {
+ expect(tokenHosts('https://www.zohoapis.eu')).toEqual({ apiHost: 'www.zohoapis.eu', downloadHosts: ['download-accl.zoho.eu', 'download.zoho.eu'] });
+ expect(tokenHosts('https://www.zohoapis.ca').downloadHosts).toEqual(['download-accl.zohocloud.ca', 'download.zohocloud.ca']);
+ expect(tokenHosts('https://www.zohoapis.com.au').downloadHosts).toEqual(['download-accl.zoho.com.au', 'download.zoho.com.au']);
+ });
+});
+
+describe('read-file download', () => {
+ it('refuses a non-Zoho URL before any request', async () => {
+ await expect(runAction({ action: readFile, propsValue: { url: 'https://attacker.example/steal' } })).rejects.toThrow(/Refusing to send the Zoho CRM token/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('streams from the Zoho host with the token and no automatic redirects', async () => {
+ ok({ body: Readable.from([Buffer.from('ab'), Buffer.from('c')]) });
+ const written = captureWrites();
+ const out = await runAction({ action: readFile, propsValue: { url: 'https://download-accl.zoho.com/v2/crm/1/backup/Leads_001.zip?x=1' }, files: written.files });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(call(0)).toMatchObject({ headers: { Authorization: 'Zoho-oauthtoken tok-123' }, followRedirects: false, responseType: 'stream' });
+ expect(out).toBe('file://stored');
+ expect(written.calls).toEqual([{ fileName: 'Leads_001.zip', streamed: true, content: 'abc' }]);
+ });
+
+ it('follows redirects only between this connection\'s Zoho CRM file hosts, keeping the token there', async () => {
+ ok({ body: undefined, status: 302, headers: { location: 'https://download.zoho.com/v2/crm/1/signed?x=1' } });
+ ok({ body: Buffer.from('bytes') });
+ const written = captureWrites();
+ await runAction({ action: readFile, propsValue: { url: 'https://download-accl.zoho.com/v2/crm/1/backup/f.zip' }, files: written.files });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(call(1)).toMatchObject({ url: 'https://download.zoho.com/v2/crm/1/signed?x=1', headers: { Authorization: 'Zoho-oauthtoken tok-123' } });
+ expect(written.calls[0].content).toBe('bytes');
+ sendRequest.mockReset();
+ ok({ body: undefined, status: 302, headers: { location: 'http://download.zoho.com/v2/crm/1/f.zip' } });
+ await expect(runAction({ action: readFile, propsValue: { url: 'https://download-accl.zoho.com/v2/crm/1/backup/f.zip' } })).rejects.toThrow(/non-https/);
+ });
+});
+
+describe('new_contact fixes', () => {
+ it('requests the same 46 fields when no extras are chosen', () => {
+ const fields = contactFieldsParam(undefined).split(',');
+ expect(fields).toHaveLength(46);
+ expect(fields[0]).toBe('Owner');
+ expect(fields[45]).toBe('Account_Name');
+ });
+
+ it('adds at most 4 extras, deduped', () => {
+ const fields = contactFieldsParam(['Email', 'C1__c', 'C2__c', 'C3__c', 'C4__c', 'C5__c', 'C1__c']).split(',');
+ expect(fields).toHaveLength(50);
+ expect(fields.slice(46)).toEqual(['C1__c', 'C2__c', 'C3__c', 'C4__c']);
+ });
+
+ it('sends per_page (not perPage) and survives a 204', async () => {
+ const { store } = memoryStore();
+ await store.put('lastPoll', 0);
+ ok({ body: undefined, status: 204 });
+ const out = await runTrigger({ trigger: asPolling(newContact), propsValue: { additional_fields: undefined }, store });
+ expect(out).toEqual([]);
+ expect(call(0).queryParams.per_page).toBe('200');
+ expect(call(0).queryParams.perPage).toBeUndefined();
+ });
+});
+
+describe('polling cursor', () => {
+ const T0 = Date.parse('2026-09-29T10:00:00+00:00');
+ const rec = ({ id, secondsAfter }: { id: string; secondsAfter: number }): ZohoRecord => ({
+ id,
+ Created_Time: new Date(T0 + secondsAfter * 1000).toISOString().replace('.000Z', '+00:00'),
+ });
+ const onePage = ({ records }: { records: ZohoRecord[] }) => async () => ({ records, more: false });
+
+ it('stops at the checkpoint and returns oldest first', async () => {
+ const r = await collectSince({
+ cursor: { time: T0, ids: [] },
+ timeField: 'Created_Time',
+ fetchPage: async () => ({ records: [rec({ id: '3', secondsAfter: 30 }), rec({ id: '2', secondsAfter: 20 }), rec({ id: '1', secondsAfter: -5 })], more: true, nextPageToken: 't2' }),
+ });
+ expect(r.records.map((x) => x.id)).toEqual(['2', '3']);
+ expect(r.cursor).toEqual({ time: T0 + 30000, ids: ['3'] });
+ expect(r.truncated).toBe(false);
+ });
+
+ it('keeps same-second records not emitted yet, skips those already emitted', async () => {
+ const cursor: PollCursor = { time: T0, ids: ['a'] };
+ const r = await collectSince({ cursor, timeField: 'Created_Time', fetchPage: onePage({ records: [rec({ id: 'b', secondsAfter: 0 }), rec({ id: 'a', secondsAfter: 0 })] }) });
+ expect(r.records.map((x) => x.id)).toEqual(['b']);
+ expect(r.cursor).toEqual({ time: T0, ids: ['a', 'b'] });
+ });
+
+ it('pages with next_page_token until it passes the checkpoint', async () => {
+ const fetchPage = vi.fn(async ({ pageToken }: { pageToken?: string }) =>
+ pageToken === undefined
+ ? { records: [rec({ id: '4', secondsAfter: 40 }), rec({ id: '3', secondsAfter: 30 })], more: true, nextPageToken: 't2' }
+ : { records: [rec({ id: '2', secondsAfter: 20 }), rec({ id: '1', secondsAfter: -1 })], more: true, nextPageToken: 't3' },
+ );
+ const r = await collectSince({ cursor: { time: T0, ids: [] }, timeField: 'Created_Time', fetchPage });
+ expect(fetchPage).toHaveBeenCalledTimes(2);
+ expect(fetchPage.mock.calls[1][0]).toEqual({ pageToken: 't2' });
+ expect(r.records.map((x) => x.id)).toEqual(['2', '3', '4']);
+ });
+
+ it('keeps a backlog instead of skipping records when the page budget runs out', async () => {
+ const fetchPage = vi.fn(async ({ pageToken }: { pageToken?: string }) => {
+ const page = pageToken === undefined ? 1 : Number(pageToken);
+ return { records: [rec({ id: `p${page}`, secondsAfter: 1000 - page })], more: true, nextPageToken: String(page + 1) };
+ });
+ const r = await collectSince({ cursor: { time: T0, ids: [] }, timeField: 'Created_Time', fetchPage, maxPages: 3 });
+ expect(fetchPage).toHaveBeenCalledTimes(3);
+ expect(r.truncated).toBe(true);
+ expect(r.records.map((x) => x.id)).toEqual(['p3', 'p2', 'p1']);
+ expect(r.cursor).toEqual({
+ time: T0,
+ ids: [],
+ backlog: { pageToken: '4', top: { time: T0 + 999000, ids: ['p1'] }, floor: { time: T0 + 997000, ids: ['p3'] } },
+ });
+ });
+
+ it('fails loudly when Zoho reports more records without a page token', async () => {
+ await expect(
+ collectSince({ cursor: { time: T0, ids: [] }, timeField: 'Created_Time', fetchPage: async () => ({ records: [rec({ id: '1', secondsAfter: 5 })], more: true }) }),
+ ).rejects.toThrow(/next_page_token/);
+ });
+
+ it('leaves the cursor alone when nothing is new', async () => {
+ const cursor = { time: T0, ids: ['x'] };
+ const r = await collectSince({ cursor, timeField: 'Created_Time', fetchPage: onePage({ records: [] }) });
+ expect(r.cursor).toBe(cursor);
+ });
+
+ it('new_record trigger: sorts by Created_Time, stores the cursor, re-poll emits nothing', async () => {
+ const { store, read } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ ok({ body: { fields: [{ api_name: 'Last_Name' }, { api_name: 'Custom__c' }] } });
+ ok({ body: { data: [rec({ id: '2', secondsAfter: 20 }), rec({ id: '1', secondsAfter: 10 })], info: { more_records: false } } });
+ const out = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue: { module: 'Leads', fields: undefined }, store });
+ expect(out.map(idOf)).toEqual(['1', '2']);
+ const q = call(1).queryParams;
+ expect(call(1).url).toBe('https://www.zohoapis.com/crm/v8/Leads');
+ expect(q).toMatchObject({ sort_by: 'Created_Time', sort_order: 'desc', per_page: '200', page: '1' });
+ expect(q.fields.split(',')).toEqual(expect.arrayContaining(['id', 'Created_Time', 'Modified_Time', 'Last_Name', 'Custom__c']));
+ expect(read(CURSOR_KEY)).toEqual({ time: T0 + 20000, ids: ['2'] });
+ ok({ body: { data: [rec({ id: '2', secondsAfter: 20 }), rec({ id: '1', secondsAfter: 10 })], info: { more_records: false } } });
+ const again = await runTrigger({ trigger: asPolling(newRecordTrigger), propsValue: { module: 'Leads', fields: undefined }, store });
+ expect(again).toEqual([]);
+ expect(sendRequest).toHaveBeenCalledTimes(3);
+ expect(call(2).url).toBe('https://www.zohoapis.com/crm/v8/Leads');
+ });
+
+ it('updated_record skips records only created, unless include_new', async () => {
+ const created = { id: '1', Created_Time: '2026-09-29T10:00:05+00:00', Modified_Time: '2026-09-29T10:00:05+00:00' };
+ const edited = { id: '2', Created_Time: '2026-09-28T10:00:00+00:00', Modified_Time: '2026-09-29T10:00:06+00:00' };
+ expect(isUpdateOnly(created)).toBe(false);
+ expect(isUpdateOnly(edited)).toBe(true);
+ const { store, read } = memoryStore();
+ await store.put(CURSOR_KEY, { time: T0, ids: [] });
+ ok({ body: { data: [edited, created], info: { more_records: false } } });
+ const out = await runTrigger({ trigger: asPolling(updatedRecordTrigger), propsValue: { module: 'Leads', fields: ['Email'], include_new: false }, store });
+ expect(out.map(idOf)).toEqual(['2']);
+ expect(call(0).queryParams.sort_by).toBe('Modified_Time');
+ expect(read(CURSOR_KEY)).toEqual({ time: Date.parse('2026-09-29T10:00:06+00:00'), ids: ['2'] });
+ });
+
+ it('onEnable keeps an existing cursor on republish', async () => {
+ const { store, read } = memoryStore();
+ await store.put(CURSOR_KEY, { time: 5, ids: [] });
+ await enableTrigger({ trigger: asPolling(newRecordTrigger), propsValue: { module: 'Leads', fields: undefined }, store, isRepublish: true });
+ expect(read(CURSOR_KEY)).toEqual({ time: 5, ids: [] });
+ });
+});
+
+describe('field mapping', () => {
+ it('maps data types to props and skips non-writable fields', () => {
+ const props = buildFieldProps({ fields: LEAD_FIELDS, mode: 'create' });
+ expect(Object.keys(props)).toEqual([
+ 'Last_Name', 'Email', 'Annual_Revenue', 'Email_Opt_Out', 'Birth_Date__c', 'Next_Call__c',
+ 'Lead_Status', 'Interests__c', 'Account__c', 'Owner', 'Notes__c',
+ ]);
+ expect(props['Last_Name'].required).toBe(true);
+ expect(props['Annual_Revenue'].type).toBe('NUMBER');
+ expect(props['Email_Opt_Out'].type).toBe('STATIC_DROPDOWN');
+ expect(props['Birth_Date__c'].type).toBe('SHORT_TEXT');
+ expect(props['Next_Call__c'].type).toBe('DATE_TIME');
+ expect(props['Interests__c'].type).toBe('STATIC_MULTI_SELECT_DROPDOWN');
+ expect(props['Notes__c'].type).toBe('LONG_TEXT');
+ const status = props['Lead_Status'];
+ if (status.type !== PropertyType.STATIC_DROPDOWN) {
+ throw new Error('Lead_Status is not a static dropdown');
+ }
+ expect(status.options.options.map((o) => o.value)).toEqual(['Contacted']);
+ });
+
+ it('marks nothing required on update', () => {
+ const props = buildFieldProps({ fields: LEAD_FIELDS, mode: 'update' });
+ expect(Object.values(props).every((p) => p.required === false)).toBe(true);
+ });
+
+ it('converts values to the Zoho format', () => {
+ const convert = ({ api, value }: { api: string; value: unknown }) => convertFieldValue({ field: LEAD_FIELDS.find((x) => x.api_name === api), value });
+ expect(convert({ api: 'Annual_Revenue', value: '1200.5' })).toBe(1200.5);
+ expect(convert({ api: 'Email_Opt_Out', value: 'false' })).toBe(false);
+ expect(convert({ api: 'Birth_Date__c', value: '2026-10-01T00:00:00.000Z' })).toBe('2026-10-01');
+ expect(convert({ api: 'Next_Call__c', value: '2026-10-01T09:00:00.000Z' })).toBe('2026-10-01T09:00:00+00:00');
+ expect(convert({ api: 'Next_Call__c', value: '2026-10-01T09:00:00+02:00' })).toBe('2026-10-01T09:00:00+02:00');
+ expect(convert({ api: 'Account__c', value: '5725767000000524157' })).toEqual({ id: '5725767000000524157' });
+ expect(convert({ api: 'Interests__c', value: 'A, B' })).toEqual(['A', 'B']);
+ expect(() => convert({ api: 'Annual_Revenue', value: 'abc' })).toThrow(/number/);
+ expect(convertFieldValue({ field: undefined, value: 'raw' })).toBe('raw');
+ });
+
+ it('keeps 19-digit ids as strings', () => {
+ const lookup = LEAD_FIELDS.find((x) => x.api_name === 'Account__c');
+ expect(convertFieldValue({ field: lookup, value: '9007199254740993123' })).toEqual({ id: '9007199254740993123' });
+ });
+
+ it('falls back to a JSON "fields" prop and reads it back', () => {
+ const props = fieldsJsonFallbackProp({ reason: 'HTTP 500', mode: 'create' });
+ expect(Object.keys(props)).toEqual([FIELDS_JSON_KEY]);
+ expect(props[FIELDS_JSON_KEY].type).toBe('JSON');
+ const payload = buildRecordPayload({ dynamicValues: { [FIELDS_JSON_KEY]: { Last_Name: 'Doe' } }, fields: undefined });
+ expect(payload).toEqual({ Last_Name: 'Doe' });
+ });
+
+ it('dynamic props fall back when metadata fails to load', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 500, body: { code: 'INTERNAL_ERROR', message: 'boom' } }));
+ const props = await createRecordAction.props.fields.props({ auth: AUTH, module: 'Leads' }, propertyContext());
+ expect(Object.keys(props)).toEqual([FIELDS_JSON_KEY]);
+ });
+});
+
+describe('partial updates', () => {
+ it('omits blank values, sends clears as null, dedicated props win over extra JSON', () => {
+ const payload = buildRecordPayload({
+ dynamicValues: { Email: '[email protected]', Lead_Status: undefined, Notes__c: '', Interests__c: [], Email_Opt_Out: 'false' },
+ fields: LEAD_FIELDS,
+ extraFields: { Email: '[email protected]', Custom__c: 'k' },
+ clearFields: ['Phone'],
+ });
+ expect(payload).toEqual({ Email: '[email protected]', Custom__c: 'k', Email_Opt_Out: false, Phone: null });
+ });
+
+ it('update_record sends only the set fields via PUT /{module}/{id}', async () => {
+ ok({ body: { fields: LEAD_FIELDS } });
+ ok({ body: { data: [{ code: 'SUCCESS', status: 'success', message: 'record updated', details: { id: '111', Modified_Time: '2026-09-29T10:00:00+02:00' } }] } });
+ const out = await runAction({
+ action: updateRecordAction,
+ propsValue: { module: 'Leads', record_id: '111', fields: { Email: '[email protected]', Last_Name: '' }, clear_fields: [], additional_fields: undefined, skip_automation: false },
+ });
+ expect(call(1).method).toBe('PUT');
+ expect(call(1).url).toBe('https://www.zohoapis.com/crm/v8/Leads/111');
+ expect(call(1).body).toEqual({ data: [{ Email: '[email protected]' }] });
+ expect(out).toMatchObject({ id: '111', status: 'success', module: 'Leads' });
+ });
+
+ it('refuses an empty update', async () => {
+ await expect(updateRecord({ auth: AUTH, module: 'Leads', id: '1', record: {} })).rejects.toThrow(/no fields/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('adds $append_values for multi-select appends', async () => {
+ ok({ body: { data: [{ status: 'success', details: { id: '1' } }] } });
+ await updateRecord({ auth: AUTH, module: 'Leads', id: '1', record: { Interests__c: ['C'] }, appendMultiSelect: ['Interests__c'] });
+ expect(call(0).body.data[0]).toEqual({ Interests__c: ['C'], $append_values: { Interests__c: true } });
+ });
+});
+
+describe('writes and errors', () => {
+ it('create_record passes trigger [] when automation is skipped', async () => {
+ ok({ body: { fields: LEAD_FIELDS } });
+ ok({ body: { data: [{ code: 'SUCCESS', status: 'success', details: { id: '9', Created_By: { id: '5', name: 'Jane' } } }] }, status: 201 });
+ const out = await runAction({ action: createRecordAction, propsValue: { module: 'Leads', fields: { Last_Name: 'Doe', Annual_Revenue: '10' }, additional_fields: undefined, triggers: undefined, skip_automation: true } });
+ expect(call(1).body).toEqual({ data: [{ Last_Name: 'Doe', Annual_Revenue: 10 }], trigger: [] });
+ expect(out).toMatchObject({ id: '9', created_by_name: 'Jane' });
+ });
+
+ it('throws on a per-record error inside a 207', () => {
+ expect(() => unwrapWriteItem({ body: { data: [{ code: 'INVALID_DATA', status: 'error', message: 'invalid data', details: { api_name: 'Email' } }] } })).toThrow(
+ /INVALID_DATA.*field: Email/,
+ );
+ });
+
+ it('maps OAUTH_SCOPE_MISMATCH to a reconnect hint', () => {
+ const e = toZohoError(httpError({ status: 401, body: { code: 'OAUTH_SCOPE_MISMATCH', message: 'invalid oauth scope' } }));
+ expect(e.message).toMatch(/OAUTH_SCOPE_MISMATCH \(HTTP 401\).*scope/);
+ });
+
+ it('names a 429 without a Zoho code as TOO_MANY_REQUESTS', () => {
+ const e = toZohoError(httpError({ status: 429, body: { message: 'slow down' } }));
+ expect(e.message).toMatch(/^Zoho CRM TOO_MANY_REQUESTS \(HTTP 429\): slow down/);
+ });
+
+ it('custom API call refuses a connection without api_domain, else sends Zoho-oauthtoken', () => {
+ expect(() => customApiAuthHeaders({ auth: { access_token: 't', data: {} }, url: '/org' })).toThrow(/Reconnect/);
+ const eu = { access_token: 't', data: { api_domain: 'https://www.zohoapis.eu' } };
+ expect(customApiAuthHeaders({ auth: eu, url: '/org' })).toEqual({ Authorization: 'Zoho-oauthtoken t' });
+ expect(customApiAuthHeaders({ auth: eu, url: 'https://www.zohoapis.eu/crm/v8/org' })).toEqual({ Authorization: 'Zoho-oauthtoken t' });
+ for (const url of ['https://evil.example/x', 'https://www.zohoapis.eu.evil.io/x', 'http://www.zohoapis.eu/crm/v8/org', 'https://www.zohoapis.com/crm/v8/org']) {
+ expect(() => customApiAuthHeaders({ auth: eu, url })).toThrow(/only to https:\/\/www\.zohoapis\.eu/);
+ }
+ });
+
+ it('falls back to the documented API domain for the location when api_domain is missing', () => {
+ expect(getApiDomain({ data: { api_domain: 'https://www.zohoapis.eu/' }, props: { location: 'zoho.com' } })).toBe('https://www.zohoapis.eu');
+ expect(getApiDomain({ data: {}, props: { location: 'zoho.com' } })).toBe('https://www.zohoapis.com');
+ expect(getApiDomain({ data: {}, props: { location: 'zohocloud.ca' } })).toBe('https://www.zohoapis.ca');
+ expect(() => getApiDomain({ data: {}, props: { location: 'zoho.evil' } })).toThrow(/Reconnect/);
+ });
+
+ it('registers every action and trigger', () => {
+ expect(Object.keys(zohoCrm.actions())).toEqual(expect.arrayContaining(['read-file', 'create_record', 'update_record', 'get_record', 'upsert_record', 'delete_record', 'convert_lead', 'add_note', 'add_tags_to_record', 'upload_attachment', 'custom_api_call']));
+ expect(Object.keys(zohoCrm.triggers()).sort()).toEqual(['new_contact', 'new_record', 'updated_record']);
+ });
+});
+
+describe('list inputs', () => {
+ it('parses a JSON array string, a JSON string inside an array, and plain comma text', () => {
+ expect(stringList('["a, b", "c"]')).toEqual(['a, b', 'c']);
+ expect(stringList(['["x"]', 'y'])).toEqual(['x', 'y']);
+ expect(stringList('a, b')).toEqual(['a', 'b']);
+ expect(stringList(['[VIP]'])).toEqual(['[VIP]']);
+ expect(stringList(undefined)).toEqual([]);
+ });
+});
+
+describe('multipart encoder', () => {
+ it('builds a file part and a text part', () => {
+ const { body, contentType } = buildMultipart({
+ parts: [{ name: 'file', filename: 'a"b.txt', data: Buffer.from('hi') }, { name: 'title', data: 'T' }],
+ boundary: 'BOUND',
+ });
+ expect(contentType).toBe('multipart/form-data; boundary=BOUND');
+ const text = body.toString();
+ expect(text).toContain('Content-Disposition: form-data; name="file"; filename="a_b.txt"\r\nContent-Type: application/octet-stream\r\n\r\nhi\r\n');
+ expect(text).toContain('name="title"\r\n\r\nT\r\n');
+ expect(text.endsWith('--BOUND--\r\n')).toBe(true);
+ });
+});
+
+describe('tier-2 fixes', () => {
+ it('default field selection keeps custom fields when a module has more than 50 fields', () => {
+ const standard: ZohoField[] = Array.from({ length: 60 }, (_, i) => ({ api_name: `Std_${i}` }));
+ const fields: ZohoField[] = [
+ { api_name: 'id' },
+ { api_name: 'Latitude' },
+ { api_name: 'Locked__s' },
+ ...standard,
+ { api_name: 'AP_Text', custom_field: true },
+ { api_name: 'Hidden_Custom', custom_field: true, visible: false },
+ ];
+ const picked = defaultFieldSelection({ fields });
+ expect(picked).toHaveLength(50);
+ expect(picked.slice(0, 3)).toEqual(['id', 'AP_Text', 'Std_0']);
+ expect(picked).not.toContain('Latitude');
+ expect(picked).not.toContain('Hidden_Custom');
+ });
+
+ it('offers Owner in the record form although Zoho marks it field_read_only', () => {
+ const props = buildFieldProps({ fields: [{ api_name: 'Owner', data_type: 'ownerlookup', field_read_only: true }, { api_name: 'Locked', data_type: 'text', field_read_only: true }], mode: 'create' });
+ expect(Object.keys(props)).toEqual(['Owner']);
+ expect(isApiReadOnly({ api_name: 'Owner', data_type: 'ownerlookup', read_only: true })).toBe(true);
+ });
+
+ it('explains a delete of a missing or already-deleted record', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 400, body: { data: [{ code: 'INVALID_DATA', status: 'error', message: 'record not deleted', details: {} }] } }));
+ await expect(deleteRecord({ auth: AUTH, module: 'Leads', id: '1' })).rejects.toThrow(/could not delete Leads record 1; it does not exist or was already deleted/);
+ });
+
+ it('hints at WorkDrive when file attachments are not enabled', () => {
+ const e = toZohoError(httpError({ status: 400, body: { code: 'INTEGRATION_NOT_ENABLED', message: 'This action requires WorkDrive integration.' } }));
+ expect(e.message).toMatch(/INTEGRATION_NOT_ENABLED.*WorkDrive.*attach a link/);
+ });
+
+ it('flattens link attachments with type and link_url', () => {
+ expect(flattenAttachment({ id: '1', File_Name: 'Site', Size: '0', $type: 'Link URL', $link_url: 'https://x.test/', $file_id: null })).toMatchObject({
+ size: 0,
+ type: 'Link URL',
+ link_url: 'https://x.test/',
+ file_id: null,
+ });
+ });
+});
+
+function idOf(record: unknown): string {
+ if (typeof record === 'object' && record !== null && 'id' in record && typeof record.id === 'string') {
+ return record.id;
+ }
+ throw new Error('record without id');
+}
diff --git a/packages/pieces/community/zoho-crm/vitest.config.ts b/packages/pieces/community/zoho-crm/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/zoho-crm/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'),
+ },
+ },
+})