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(close): let agents manage leads, deals, tasks, activities and sequences (#16629)

Odai Ahmad334989a0b02f
diff --git a/bun.lock b/bun.lock
index 0509c20bdab..a3b6da5100f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2043,7 +2043,7 @@
},
"packages/pieces/community/close": {
"name": "@activepieces/piece-close",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -2052,6 +2052,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/cloudconvert": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 9d701e181ed..28b93f43564 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Close 0.3.0: Find Lead and Find Contact drop the "Starts With" and "Ends With" match options
+
+Find Lead and Find Contact no longer offer the **Starts With** and **Ends With** match options. They never worked: Close's search ignored them, so a step using one did not filter as its label said. A step upgraded to Close 0.3.0 with one of these options saved fails validation until a supported option is picked.
+
+The New Lead, New Contact and other Close webhook triggers now drop duplicate deliveries of the same Close event, so a flow runs once per event. Opportunity **Value** is now labelled as cents, which is what Close always expected.
+
+#### What you need to do
+
+Steps keep running on the version they were built with until you upgrade them. When you upgrade a Find Lead or Find Contact step that used Starts With or Ends With, switch its Match Type to **All Words (any order)** or **Exact Phrase**.
+
#### Snowflake 0.4.0: Update Row needs a WHERE condition, stricter limits, query timeout and stage paths
From Snowflake 0.4.0 several actions validate their inputs where they used to pass them straight to Snowflake:
@@ -127,6 +137,7 @@ Most code steps keep working unchanged: sources are transpiled to CommonJS, so N
- **Custom deployments** that do not use the official Docker images must provide a Deno binary and point `AP_DENO_PATH` at it; without it every code step fails at spawn.
To find affected steps after upgrading, search your logs for the structured `Code step failed` warning — it carries the flow run, flow version, project, step name, the runtime that executed the step (`codeRuntime: deno|legacy`), and the error message, so you can group failures by step and error. To pin a misbehaving step to the legacy runtime while you fix it (available on every edition), set `AP_API_KEY` in your environment and call `POST /v1/admin/flows/revert-from-deno` with the `api-key` header and a body of exactly one of `flowIds`, `projectId`, or `platformId`; this sets `useDeno: false` on the affected steps, and `migrate-to-deno` moves them back.
+
#### Each chat keeps the AI model and key it started on
A chat used to run on whatever key was the **Default AI key** at the time of each message. Now a chat remembers the key and model it first ran on. Changing the Default AI key affects new chats only. An existing chat moves to the new default only when its key is deleted, or no longer covers the chat's project or model.
diff --git a/packages/pieces/community/close/.babelrc b/packages/pieces/community/close/.babelrc
new file mode 100644
index 00000000000..fc2ad0f36c4
--- /dev/null
+++ b/packages/pieces/community/close/.babelrc
@@ -0,0 +1,3 @@
+{
+ "presets": [["@nx/js/babel", { "useBuiltIns": "usage" }]]
+}
diff --git a/packages/pieces/community/close/package.json b/packages/pieces/community/close/package.json
index d46a624523c..f7fb965f27d 100644
--- a/packages/pieces/community/close/package.json
+++ b/packages/pieces/community/close/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-close",
- "version": "0.2.1",
+ "version": "0.3.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/close/src/i18n/translation.json b/packages/pieces/community/close/src/i18n/translation.json
index d628c5c3d40..90115e93d64 100644
--- a/packages/pieces/community/close/src/i18n/translation.json
+++ b/packages/pieces/community/close/src/i18n/translation.json
@@ -1,17 +1,94 @@
{
"Sales automation and CRM integration for Close": "Sales automation and CRM integration for Close",
- "Your Close CRM API key for authentication.": "Your Close CRM API key for authentication.",
+ "Your Close API key. In Close go to Settings → Developer → API Keys and create a key.": "Your Close API key. In Close go to Settings → Developer → API Keys and create a key.",
"Create Lead": "Create Lead",
"Create Contact": "Create Contact",
"Find Lead": "Find Lead",
"Create Opportunity": "Create Opportunity",
"Find Contact": "Find Contact",
+ "Create Note": "Create Note",
+ "Create Task": "Create Task",
+ "Delete Activity": "Delete Activity",
+ "Delete Contact": "Delete Contact",
+ "Delete Lead": "Delete Lead",
+ "Delete Opportunity": "Delete Opportunity",
+ "Delete Task": "Delete Task",
+ "Get Activity": "Get Activity",
+ "Get Contact": "Get Contact",
+ "Get Current User": "Get Current User",
+ "Get Lead": "Get Lead",
+ "Get Opportunity": "Get Opportunity",
+ "Get Task": "Get Task",
+ "List Activities": "List Activities",
+ "List Custom Activity Types": "List Custom Activity Types",
+ "List Custom Fields": "List Custom Fields",
+ "List Lead Statuses": "List Lead Statuses",
+ "List Opportunities": "List Opportunities",
+ "List Pipelines": "List Pipelines",
+ "List Sequence Subscriptions": "List Sequence Subscriptions",
+ "List Sequences": "List Sequences",
+ "List Smart Views": "List Smart Views",
+ "List Tasks": "List Tasks",
+ "List Users": "List Users",
+ "Log Call": "Log Call",
+ "Log Email": "Log Email",
+ "Merge Leads": "Merge Leads",
+ "Pause Sequence Subscription": "Pause Sequence Subscription",
+ "Search Contacts": "Search Contacts",
+ "Search Leads": "Search Leads",
+ "Send SMS": "Send SMS",
+ "Subscribe Contact to Sequence": "Subscribe Contact to Sequence",
+ "Update Contact": "Update Contact",
+ "Update Lead": "Update Lead",
+ "Update Note": "Update Note",
+ "Update Opportunity": "Update Opportunity",
+ "Update Task": "Update Task",
"Custom API Call": "Custom API Call",
"Creates a new lead.": "Creates a new lead.",
"Creates a new contact.": "Creates a new contact.",
"Search for leads with advanced filtering options": "Search for leads with advanced filtering options",
"Create a new opportunity.": "Create a new opportunity.",
"Search for contacts by name, email, or other criteria with advanced filtering": "Search for contacts by name, email, or other criteria with advanced filtering",
+ "Add a contact person to a lead.": "Add a contact person to a lead.",
+ "Create a lead (company), optionally with a first contact.": "Create a lead (company), optionally with a first contact.",
+ "Add a note to a lead in Close.": "Add a note to a lead in Close.",
+ "Create an opportunity (deal) on a lead.": "Create an opportunity (deal) on a lead.",
+ "Create a to-do task on a lead.": "Create a to-do task on a lead.",
+ "Permanently delete a note, call, email, SMS or meeting.": "Permanently delete a note, call, email, SMS or meeting.",
+ "Permanently delete a contact person from its lead.": "Permanently delete a contact person from its lead.",
+ "Permanently delete a lead with its contacts, opportunities, tasks and activities.": "Permanently delete a lead with its contacts, opportunities, tasks and activities.",
+ "Permanently delete a opportunity.": "Permanently delete a opportunity.",
+ "Permanently delete a task.": "Permanently delete a task.",
+ "Get one note, call, email, SMS or meeting by ID.": "Get one note, call, email, SMS or meeting by ID.",
+ "Get one contact by its ID.": "Get one contact by its ID.",
+ "Get the Close user who owns the API key.": "Get the Close user who owns the API key.",
+ "Get one lead by its ID.": "Get one lead by its ID.",
+ "Get one opportunity by ID.": "Get one opportunity by ID.",
+ "Get one task by ID.": "Get one task by ID.",
+ "List notes, calls, emails, SMS and meetings, newest first.": "List notes, calls, emails, SMS and meetings, newest first.",
+ "List the custom activity types defined in Close.": "List the custom activity types defined in Close.",
+ "List the custom fields for leads, contacts, opportunities or activities.": "List the custom fields for leads, contacts, opportunities or activities.",
+ "List the lead statuses defined in Close.": "List the lead statuses defined in Close.",
+ "List opportunities with optional filters.": "List opportunities with optional filters.",
+ "List opportunity pipelines and their statuses.": "List opportunity pipelines and their statuses.",
+ "List sequence subscriptions for a sequence, contact or lead.": "List sequence subscriptions for a sequence, contact or lead.",
+ "List email/call sequences (workflows).": "List email/call sequences (workflows).",
+ "List saved Smart Views.": "List saved Smart Views.",
+ "List tasks with optional filters.": "List tasks with optional filters.",
+ "List the users in your Close organization.": "List the users in your Close organization.",
+ "Record a call made outside Close on a lead.": "Record a call made outside Close on a lead.",
+ "Record an email that was already sent or received, without sending anything.": "Record an email that was already sent or received, without sending anything.",
+ "Merge a duplicate lead into another lead.": "Merge a duplicate lead into another lead.",
+ "Pause a contact sequence subscription.": "Pause a contact sequence subscription.",
+ "Find contacts by text and/or lead.": "Find contacts by text and/or lead.",
+ "Find leads by text and/or status.": "Find leads by text and/or status.",
+ "Send a real text message (not just a log entry) to a lead from a Close phone number.": "Send a real text message (not just a log entry) to a lead from a Close phone number.",
+ "Enroll a contact in a Close sequence (workflow).": "Enroll a contact in a Close sequence (workflow).",
+ "Change the name, title, email, phone or custom fields of a contact.": "Change the name, title, email, phone or custom fields of a contact.",
+ "Change the name, status, website, description or custom fields of a lead.": "Change the name, status, website, description or custom fields of a lead.",
+ "Replace the text of a note in Close.": "Replace the text of a note in Close.",
+ "Change fields on an opportunity.": "Change fields on an opportunity.",
+ "Change, reassign or complete a task.": "Change, reassign or complete a task.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Lead Name": "Lead Name",
"URL": "URL",
@@ -38,15 +115,70 @@
"Opportunity Name": "Opportunity Name",
"Notes": "Notes",
"Confidence %": "Confidence %",
- "Value": "Value",
+ "Value (cents)": "Value (cents)",
"Value Period": "Value Period",
"Contact ID": "Contact ID",
"User": "User",
+ "Lead ID": "Lead ID",
+ "Email": "Email",
+ "Phone": "Phone",
+ "Website": "Website",
+ "Lead Status ID": "Lead Status ID",
+ "Contact Name": "Contact Name",
+ "Contact Title": "Contact Title",
+ "Contact Email": "Contact Email",
+ "Contact Phone": "Contact Phone",
+ "Note": "Note",
+ "Activity At": "Activity At",
+ "Status ID": "Status ID",
+ "Owner User ID": "Owner User ID",
+ "Close Date": "Close Date",
+ "Text": "Text",
+ "Assigned To (user ID)": "Assigned To (user ID)",
+ "Due": "Due",
+ "Complete": "Complete",
+ "Activity Type": "Activity Type",
+ "Activity ID": "Activity ID",
+ "Opportunity ID": "Opportunity ID",
+ "Task ID": "Task ID",
+ "User ID": "User ID",
+ "Created After": "Created After",
+ "Created Before": "Created Before",
+ "Limit": "Limit",
+ "Skip": "Skip",
+ "Object Type": "Object Type",
+ "Status Type": "Status Type",
+ "Close Date From": "Close Date From",
+ "Close Date To": "Close Date To",
+ "Sequence ID": "Sequence ID",
+ "Type": "Type",
+ "Due From": "Due From",
+ "Due To": "Due To",
+ "Include Inbox Notifications": "Include Inbox Notifications",
+ "View": "View",
+ "Direction": "Direction",
+ "Duration (seconds)": "Duration (seconds)",
+ "Subject": "Subject",
+ "Body": "Body",
+ "To": "To",
+ "Sender": "Sender",
+ "Source Lead ID": "Source Lead ID",
+ "Destination Lead ID": "Destination Lead ID",
+ "Subscription ID": "Subscription ID",
+ "Exact Phrase": "Exact Phrase",
+ "Cursor": "Cursor",
+ "From (Close number)": "From (Close number)",
+ "To (phone)": "To (phone)",
+ "Message": "Message",
+ "Sender Email Account ID": "Sender Email Account ID",
+ "Sender Name": "Sender Name",
+ "Sender Email": "Sender Email",
+ "Calls Assigned To (user IDs)": "Calls Assigned To (user IDs)",
+ "Note ID": "Note ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
- "Body": "Body",
"Response is Binary": "Response is Binary",
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
@@ -56,8 +188,52 @@
"A descriptive name for the opportunity.": "A descriptive name for the opportunity.",
"Additional details about the opportunity.": "Additional details about the opportunity.",
"The probability of winning this opportunity (0-100).": "The probability of winning this opportunity (0-100).",
+ "Monetary value in cents of your organization currency, e.g. 340000 for $3,400.00.": "Monetary value in cents of your organization currency, e.g. 340000 for $3,400.00.",
"The period for the opportunity value.": "The period for the opportunity value.",
"The ID of the contact associated with this opportunity.": "The ID of the contact associated with this opportunity.",
+ "lead_... the contact belongs to. Leave empty to create a new lead.": "lead_... the contact belongs to. Leave empty to create a new lead.",
+ "Object of cf_... id to value.": "Object of cf_... id to value.",
+ "Company or lead name.": "Company or lead name.",
+ "stat_... from List Lead Statuses.": "stat_... from List Lead Statuses.",
+ "Lead to attach the opportunity to (lead_...).": "Lead to attach the opportunity to (lead_...).",
+ "Opportunity status ID (stat_...). Use List Pipelines to find IDs.": "Opportunity status ID (stat_...). Use List Pipelines to find IDs.",
+ "Contact on the lead (cont_...).": "Contact on the lead (cont_...).",
+ "User who owns the opportunity (user_...).": "User who owns the opportunity (user_...).",
+ "Whole number of cents, e.g. 340000 for 3,400.00.": "Whole number of cents, e.g. 340000 for 3,400.00.",
+ "one_time, monthly or annual.": "one_time, monthly or annual.",
+ "0 to 100.": "0 to 100.",
+ "Expected (or won) close date, e.g. 2026-11-30.": "Expected (or won) close date, e.g. 2026-11-30.",
+ "Object of custom field ID (cf_...) to value.": "Object of custom field ID (cf_...) to value.",
+ "lead_...": "lead_...",
+ "user_...": "user_...",
+ "YYYY-MM-DD or ISO 8601 date-time.": "YYYY-MM-DD or ISO 8601 date-time.",
+ "cont_...": "cont_...",
+ "oppo_...": "oppo_...",
+ "task_...": "task_...",
+ "active, won or lost.": "active, won or lost.",
+ "YYYY-MM-DD, inclusive.": "YYYY-MM-DD, inclusive.",
+ "1 to 100, default 100.": "1 to 100, default 100.",
+ "nextSkip from the previous page.": "nextSkip from the previous page.",
+ "1-100, default 100": "1-100, default 100",
+ "Use nextSkip from the previous call.": "Use nextSkip from the previous call.",
+ "true or false; leave empty for both.": "true or false; leave empty for both.",
+ "ISO 8601 date or date-time, inclusive.": "ISO 8601 date or date-time, inclusive.",
+ "Also return inbox items like opportunity_due or missed_call.": "Also return inbox items like opportunity_due or missed_call.",
+ "inbox, future or archive.": "inbox, future or archive.",
+ "lead_... to merge away (it is deleted).": "lead_... to merge away (it is deleted).",
+ "lead_... that is kept.": "lead_... that is kept.",
+ "Words to find, e.g. a name or email.": "Words to find, e.g. a name or email.",
+ "Match the words in order next to each other.": "Match the words in order next to each other.",
+ "Only contacts of this lead_...": "Only contacts of this lead_...",
+ "1 to 100, default 25.": "1 to 100, default 25.",
+ "nextCursor from the previous page.": "nextCursor from the previous page.",
+ "Words to find, e.g. company name or email.": "Words to find, e.g. company name or email.",
+ "emailacct_... from Get Current User.": "emailacct_... from Get Current User.",
+ "Replaces all emails on the contact.": "Replaces all emails on the contact.",
+ "Replaces all phones on the contact.": "Replaces all phones on the contact.",
+ "Replaces all URLs on the contact.": "Replaces all URLs on the contact.",
+ "Object of cf_... id to value; null clears a field.": "Object of cf_... id to value; null clears a field.",
+ "true or false; leave empty to keep.": "true or false; leave empty to keep.",
"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.",
@@ -67,16 +243,33 @@
"By Name": "By Name",
"By Contact Email": "By Contact Email",
"By Status": "By Status",
- "Contains": "Contains",
- "Exact Match": "Exact Match",
- "Starts With": "Starts With",
- "Ends With": "Ends With",
+ "All Words (any order)": "All Words (any order)",
"One-Time": "One-Time",
"Monthly": "Monthly",
"Annual": "Annual",
"By Email": "By Email",
"By Phone": "By Phone",
"By Lead ID": "By Lead ID",
+ "Call": "Call",
+ "SMS": "SMS",
+ "Meeting": "Meeting",
+ "lead": "lead",
+ "contact": "contact",
+ "opportunity": "opportunity",
+ "activity": "activity",
+ "shared": "shared",
+ "call": "call",
+ "email": "email",
+ "sms": "sms",
+ "meeting": "meeting",
+ "note": "note",
+ "whatsapp_message": "whatsapp_message",
+ "custom_activity": "custom_activity",
+ "form_submission": "form_submission",
+ "Outbound": "Outbound",
+ "Inbound": "Inbound",
+ "Sent (to the lead)": "Sent (to the lead)",
+ "Received (from the lead)": "Received (from the lead)",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
@@ -88,5 +281,6 @@
"New Opportunity Added": "New Opportunity Added",
"Triggers when a new lead is created.": "Triggers when a new lead is created.",
"Triggers when a new contact is created.": "Triggers when a new contact is created.",
- "Triggers when a new opportunity is created.": "Triggers when a new opportunity is created."
-}
\ No newline at end of file
+ "Triggers when a new opportunity is created.": "Triggers when a new opportunity is created.",
+ "Pass an empty string to clear it.": "Pass an empty string to clear it."
+}
diff --git a/packages/pieces/community/close/src/index.ts b/packages/pieces/community/close/src/index.ts
index bb5799dd2c8..73ff2eb7f99 100644
--- a/packages/pieces/community/close/src/index.ts
+++ b/packages/pieces/community/close/src/index.ts
@@ -1,8 +1,5 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import {
- createCustomApiCallAction,
- HttpMethod,
-} from '@activepieces/pieces-common';
+import { createPiece } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { createLead } from './lib/actions/create-lead';
import { findLead } from './lib/actions/find-lead';
import { newLeadAdded } from './lib/triggers/new-lead-added';
@@ -10,29 +7,126 @@ import { createOpportunity } from './lib/actions/create-opportunity';
import { createContact } from './lib/actions/create-contact';
import { newContactAdded } from './lib/triggers/new-contact-added';
import { findContact } from './lib/actions/find-contact';
-import { CLOSE_API_URL, closeApiCall } from './lib/common/client';
+import { CLOSE_API_URL, closeClient } from './lib/common/client';
import { newOpportunityAdded } from './lib/triggers/new-opportunity';
+import { createContactAi } from './lib/actions/ai/create-contact-ai';
+import { createLeadAi } from './lib/actions/ai/create-lead-ai';
+import { createNote } from './lib/actions/ai/create-note';
+import { createOpportunityAi } from './lib/actions/ai/create-opportunity-ai';
+import { createTask } from './lib/actions/ai/create-task';
+import { deleteActivity } from './lib/actions/ai/delete-activity';
+import { deleteContact } from './lib/actions/ai/delete-contact';
+import { deleteLead } from './lib/actions/ai/delete-lead';
+import { deleteOpportunity } from './lib/actions/ai/delete-opportunity';
+import { deleteTask } from './lib/actions/ai/delete-task';
+import { getActivity } from './lib/actions/ai/get-activity';
+import { getContact } from './lib/actions/ai/get-contact';
+import { getCurrentUser } from './lib/actions/ai/get-current-user';
+import { getLead } from './lib/actions/ai/get-lead';
+import { getOpportunity } from './lib/actions/ai/get-opportunity';
+import { getTask } from './lib/actions/ai/get-task';
+import { listActivities } from './lib/actions/ai/list-activities';
+import { listCustomActivityTypes } from './lib/actions/ai/list-custom-activity-types';
+import { listCustomFields } from './lib/actions/ai/list-custom-fields';
+import { listLeadStatuses } from './lib/actions/ai/list-lead-statuses';
+import { listOpportunities } from './lib/actions/ai/list-opportunities';
+import { listPipelines } from './lib/actions/ai/list-pipelines';
+import { listSequenceSubscriptions } from './lib/actions/ai/list-sequence-subscriptions';
+import { listSequences } from './lib/actions/ai/list-sequences';
+import { listSmartViews } from './lib/actions/ai/list-smart-views';
+import { listTasks } from './lib/actions/ai/list-tasks';
+import { listUsers } from './lib/actions/ai/list-users';
+import { logCall } from './lib/actions/ai/log-call';
+import { logEmail } from './lib/actions/ai/log-email';
+import { mergeLeads } from './lib/actions/ai/merge-leads';
+import { pauseSequenceSubscription } from './lib/actions/ai/pause-sequence-subscription';
+import { searchContacts } from './lib/actions/ai/search-contacts';
+import { searchLeads } from './lib/actions/ai/search-leads';
+import { sendSms } from './lib/actions/ai/send-sms';
+import { subscribeContactToSequence } from './lib/actions/ai/subscribe-contact-to-sequence';
+import { updateContact } from './lib/actions/ai/update-contact';
+import { updateLead } from './lib/actions/ai/update-lead';
+import { updateNote } from './lib/actions/ai/update-note';
+import { updateOpportunity } from './lib/actions/ai/update-opportunity';
+import { updateTask } from './lib/actions/ai/update-task';
import { closeAuth } from './lib/auth';
export const close = createPiece({
displayName: 'Close',
description: 'Sales automation and CRM integration for Close',
auth: closeAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/close.png',
- authors: ['Ani-4x', 'kishanprmr'],
+ authors: ['Ani-4x', 'kishanprmr', 'OdaiAhmed99'],
actions: [
createLead,
createContact,
findLead,
createOpportunity,
findContact,
+ createContactAi,
+ createLeadAi,
+ createNote,
+ createOpportunityAi,
+ createTask,
+ deleteActivity,
+ deleteContact,
+ deleteLead,
+ deleteOpportunity,
+ deleteTask,
+ getActivity,
+ getContact,
+ getCurrentUser,
+ getLead,
+ getOpportunity,
+ getTask,
+ listActivities,
+ listCustomActivityTypes,
+ listCustomFields,
+ listLeadStatuses,
+ listOpportunities,
+ listPipelines,
+ listSequenceSubscriptions,
+ listSequences,
+ listSmartViews,
+ listTasks,
+ listUsers,
+ logCall,
+ logEmail,
+ mergeLeads,
+ pauseSequenceSubscription,
+ searchContacts,
+ searchLeads,
+ sendSms,
+ subscribeContactToSequence,
+ updateContact,
+ updateLead,
+ updateNote,
+ updateOpportunity,
+ updateTask,
createCustomApiCallAction({
baseUrl: () => CLOSE_API_URL,
auth: closeAuth,
- authMapping: async (auth) => {
+ authMapping: async (auth, propsValue) => {
+ const urlProp = propsValue['url'];
+ const url = closeClient.isRecord(urlProp) && typeof urlProp['url'] === 'string' ? urlProp['url'].trim() : '';
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {
+ let parsed: URL | undefined;
+ try {
+ parsed = new URL(url);
+ } catch {
+ parsed = undefined;
+ }
+ const base = new URL(CLOSE_API_URL);
+ if (!parsed || parsed.username || parsed.password || parsed.origin !== base.origin || !(parsed.pathname === base.pathname || parsed.pathname.startsWith(`${base.pathname}/`))) {
+ throw new Error(`The URL must be relative or start with ${CLOSE_API_URL}/.`);
+ }
+ }
+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {
+ throw new Error('The URL must not contain ".." segments.');
+ }
return {
- Authorization: `Basic ${Buffer.from(`${auth}:`).toString('base64')}`,
+ Authorization: `Basic ${Buffer.from(`${closeClient.keyOf(auth)}:`).toString('base64')}`,
};
},
}),
diff --git a/packages/pieces/community/close/src/lib/actions/ai/create-contact-ai.ts b/packages/pieces/community/close/src/lib/actions/ai/create-contact-ai.ts
new file mode 100644
index 00000000000..acaa4c91985
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/create-contact-ai.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const createContactAi = createAction({
+ auth: closeAuth,
+ name: 'create_contact_ai',
+ classification: 'WRITE',
+ displayName: 'Create Contact',
+ description: 'Add a contact person to a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a Close contact (a person) on an existing lead given its lead id (lead_...), with optional title, email, phone and website. If no lead id is passed, Close creates a new lead named after the contact. Custom fields take cf_ ids from List Custom Fields. Calling it twice creates two contacts, so check with Search Contacts first.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.contact,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'lead_... the contact belongs to. Leave empty to create a new lead.', required: false }),
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ url: Property.ShortText({ displayName: 'Website', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of cf_... id to value.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const title = closeClient.optionalText(propsValue.title);
+ const email = closeClient.optionalText(propsValue.email);
+ const phone = closeClient.optionalText(propsValue.phone);
+ const url = closeClient.optionalText(propsValue.url);
+ const body = {
+ name: closeClient.requiredText({ value: propsValue.name, label: 'Name' }),
+ ...(leadId ? { lead_id: leadId } : {}),
+ ...(title ? { title } : {}),
+ ...(email ? { emails: [{ email, type: 'office' }] } : {}),
+ ...(phone ? { phones: [{ phone, type: 'office' }] } : {}),
+ ...(url ? { urls: [{ url, type: 'url' }] } : {}),
+ ...closeClient.customFieldsBody({ value: propsValue.customFields }),
+ };
+ const created = await closeClient.request({ auth, method: HttpMethod.POST, path: '/contact/', body });
+ return closeMappers.contact(created);
+ },
+});
+
+export { createContactAi };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/create-lead-ai.ts b/packages/pieces/community/close/src/lib/actions/ai/create-lead-ai.ts
new file mode 100644
index 00000000000..59230e20b74
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/create-lead-ai.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const createLeadAi = createAction({
+ auth: closeAuth,
+ name: 'create_lead_ai',
+ classification: 'WRITE',
+ displayName: 'Create Lead',
+ description: 'Create a lead (company), optionally with a first contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a new Close lead (a company or account) and returns it with its lead_ id. Optionally adds one contact person with email and phone in the same call. Status uses a lead status id from List Lead Statuses; omit it for the default status. Custom fields take cf_ ids from List Custom Fields. Calling it twice creates two leads, so search first with Search Leads.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.lead,
+ props: {
+ name: Property.ShortText({ displayName: 'Lead Name', description: 'Company or lead name.', required: true }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ url: Property.ShortText({ displayName: 'Website', required: false }),
+ statusId: Property.ShortText({ displayName: 'Lead Status ID', description: 'stat_... from List Lead Statuses.', required: false }),
+ contactName: Property.ShortText({ displayName: 'Contact Name', required: false }),
+ contactTitle: Property.ShortText({ displayName: 'Contact Title', required: false }),
+ contactEmail: Property.ShortText({ displayName: 'Contact Email', required: false }),
+ contactPhone: Property.ShortText({ displayName: 'Contact Phone', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of cf_... id to value.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const statusId = closeClient.optionalCloseId({ value: propsValue.statusId, label: 'Lead Status ID', prefix: 'stat' });
+ const contactName = closeClient.optionalText(propsValue.contactName);
+ const contactTitle = closeClient.optionalText(propsValue.contactTitle);
+ const contactEmail = closeClient.optionalText(propsValue.contactEmail);
+ const contactPhone = closeClient.optionalText(propsValue.contactPhone);
+ const hasContact = [contactName, contactTitle, contactEmail, contactPhone].some((v) => v !== undefined);
+ const body = {
+ name: closeClient.requiredText({ value: propsValue.name, label: 'Lead Name' }),
+ ...optional({ key: 'description', value: closeClient.optionalText(propsValue.description) }),
+ ...optional({ key: 'url', value: closeClient.optionalText(propsValue.url) }),
+ ...optional({ key: 'status_id', value: statusId }),
+ ...(hasContact
+ ? {
+ contacts: [
+ {
+ ...optional({ key: 'name', value: contactName }),
+ ...optional({ key: 'title', value: contactTitle }),
+ ...(contactEmail ? { emails: [{ email: contactEmail, type: 'office' }] } : {}),
+ ...(contactPhone ? { phones: [{ phone: contactPhone, type: 'office' }] } : {}),
+ },
+ ],
+ }
+ : {}),
+ ...closeClient.customFieldsBody({ value: propsValue.customFields }),
+ };
+ const created = await closeClient.request({ auth, method: HttpMethod.POST, path: '/lead/', body });
+ return closeMappers.lead(created);
+ },
+});
+
+function optional({ key, value }: { key: string; value: string | undefined }): Record<string, string> {
+ return value === undefined ? {} : { [key]: value };
+}
+
+export { createLeadAi };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/create-note.ts b/packages/pieces/community/close/src/lib/actions/ai/create-note.ts
new file mode 100644
index 00000000000..0e6eea0efc5
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/create-note.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const createNote = createAction({
+ auth: closeAuth,
+ name: 'create_note',
+ classification: 'WRITE',
+ displayName: 'Create Note',
+ description: 'Add a note to a lead in Close.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Adds a plain-text note activity to one Close lead (leadId, lead_...). Optional contactId (cont_...) ties it to a contact on that lead; optional activityAt (ISO 8601) backdates it. Creates a new note on every call. Returns the note activity.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: true }),
+ note: Property.LongText({ displayName: 'Note', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ activityAt: Property.DateTime({ displayName: 'Activity At', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const body = {
+ lead_id: closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ note: closeClient.requiredText({ value: propsValue.note, label: 'Note' }),
+ contact_id: closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ activity_at: closeClient.isoDateTime({ value: propsValue.activityAt, label: 'Activity At' }),
+ };
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/activity/note/',
+ body: Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined)),
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+export { createNote };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/create-opportunity-ai.ts b/packages/pieces/community/close/src/lib/actions/ai/create-opportunity-ai.ts
new file mode 100644
index 00000000000..91a7649c1d3
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/create-opportunity-ai.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function valuePeriodOf(value: unknown): string | undefined {
+ const period = closeClient.optionalText(value);
+ if (period === undefined) return undefined;
+ if (!['one_time', 'monthly', 'annual'].includes(period)) throw new Error('Value Period must be one_time, monthly or annual.');
+ return period;
+}
+
+function opportunityBody({ props }: { props: Record<string, unknown> }): Record<string, unknown> {
+ const body: Record<string, unknown> = {
+ status_id: closeClient.optionalCloseId({ value: props['statusId'], label: 'Status ID', prefix: 'stat' }),
+ contact_id: closeClient.optionalCloseId({ value: props['contactId'], label: 'Contact ID', prefix: 'cont' }),
+ user_id: closeClient.optionalCloseId({ value: props['userId'], label: 'Owner User ID', prefix: 'user' }),
+ value: closeClient.parseInteger({ value: props['valueCents'], label: 'Value (cents)', min: 0, max: Number.MAX_SAFE_INTEGER }),
+ value_period: valuePeriodOf(props['valuePeriod']),
+ confidence: closeClient.parseInteger({ value: props['confidence'], label: 'Confidence %', min: 0, max: 100 }),
+ note: closeClient.optionalText(props['note']),
+ date_won: closeClient.isoDate({ value: props['expectedCloseDate'], label: 'Close Date' }),
+ ...closeClient.customFieldsBody({ value: props['customFields'] }),
+ };
+ return Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));
+}
+
+const createOpportunityAi = createAction({
+ auth: closeAuth,
+ name: 'create_opportunity_ai',
+ classification: 'WRITE',
+ displayName: 'Create Opportunity',
+ description: 'Create an opportunity (deal) on a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a Close opportunity (deal) on an existing lead (lead_...). Value is a whole number of cents, e.g. 340000 for 3,400.00. Status ID (stat_...) comes from List Pipelines; when omitted Close uses the first active status. Each call creates a new opportunity.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.opportunity,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'Lead to attach the opportunity to (lead_...).', required: true }),
+ statusId: Property.ShortText({ displayName: 'Status ID', description: 'Opportunity status ID (stat_...). Use List Pipelines to find IDs.', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'Contact on the lead (cont_...).', required: false }),
+ userId: Property.ShortText({ displayName: 'Owner User ID', description: 'User who owns the opportunity (user_...).', required: false }),
+ valueCents: Property.Number({ displayName: 'Value (cents)', description: 'Whole number of cents, e.g. 340000 for 3,400.00.', required: false }),
+ valuePeriod: Property.ShortText({ displayName: 'Value Period', description: 'one_time, monthly or annual.', required: false }),
+ confidence: Property.Number({ displayName: 'Confidence %', description: '0 to 100.', required: false }),
+ note: Property.LongText({ displayName: 'Note', required: false }),
+ expectedCloseDate: Property.ShortText({ displayName: 'Close Date', description: 'Expected (or won) close date, e.g. 2026-11-30.', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of custom field ID (cf_...) to value.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const raw = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/opportunity/',
+ body: { lead_id: leadId, ...opportunityBody({ props: propsValue }) },
+ });
+ return closeMappers.opportunity(raw);
+ },
+});
+
+export { createOpportunityAi };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/create-task.ts b/packages/pieces/community/close/src/lib/actions/ai/create-task.ts
new file mode 100644
index 00000000000..0987ef7686b
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/create-task.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const createTask = createAction({
+ auth: closeAuth,
+ name: 'create_task',
+ classification: 'WRITE',
+ displayName: 'Create Task',
+ description: 'Create a to-do task on a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a Close to-do task on a lead (lead_...). Assignee (user_...) defaults to the API key user. Due date is a date (YYYY-MM-DD) or an ISO 8601 date-time; omit it for a task due today. Each call creates a new task.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.task,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'lead_...', required: true }),
+ text: Property.LongText({ displayName: 'Text', required: true }),
+ assignedTo: Property.ShortText({ displayName: 'Assigned To (user ID)', description: 'user_...', required: false }),
+ date: Property.ShortText({ displayName: 'Due', description: 'YYYY-MM-DD or ISO 8601 date-time.', required: false }),
+ isComplete: Property.Checkbox({ displayName: 'Complete', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const body = {
+ _type: 'lead',
+ lead_id: closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ text: closeClient.requiredText({ value: propsValue.text, label: 'Text' }),
+ assigned_to: closeClient.optionalCloseId({ value: propsValue.assignedTo, label: 'Assigned To', prefix: 'user' }),
+ date: closeClient.isoDate({ value: propsValue.date, label: 'Due' }),
+ is_complete: closeClient.parseBoolean({ value: propsValue.isComplete, label: 'Complete' }),
+ };
+ const raw = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/task/',
+ body: Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined)),
+ });
+ return closeMappers.task(raw);
+ },
+});
+
+export { createTask };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/delete-activity.ts b/packages/pieces/community/close/src/lib/actions/ai/delete-activity.ts
new file mode 100644
index 00000000000..7bbbbe141ec
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/delete-activity.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const ACTIVITY_TYPES = ['note', 'call', 'email', 'sms', 'meeting'];
+
+const deleteActivity = createAction({
+ auth: closeAuth,
+ name: 'delete_activity',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Activity',
+ description: 'Permanently delete a note, call, email, SMS or meeting.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes one Close activity by activityId (acti_...) and its type: note, call, email, sms or meeting. It cannot be undone and does not unsend an email or SMS that already went out. Repeating it on a deleted activity returns not found. Returns deleted true and the ID.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.deleted,
+ props: {
+ activityType: Property.StaticDropdown({
+ displayName: 'Activity Type',
+ required: true,
+ options: { options: [{ label: 'Note', value: 'note' }, { label: 'Call', value: 'call' }, { label: 'Email', value: 'email' }, { label: 'SMS', value: 'sms' }, { label: 'Meeting', value: 'meeting' }] },
+ }),
+ activityId: Property.ShortText({ displayName: 'Activity ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const activityType = closeClient.requiredText({ value: propsValue.activityType, label: 'Activity Type' }).toLowerCase();
+ if (!ACTIVITY_TYPES.includes(activityType)) throw new Error(`Activity Type must be one of: ${ACTIVITY_TYPES.join(', ')}.`);
+ const activityId = closeClient.closeId({ value: propsValue.activityId, label: 'Activity ID', prefix: 'acti' });
+ await closeClient.request({
+ auth,
+ method: HttpMethod.DELETE,
+ path: `/activity/${activityType}/${closeClient.pathId(activityId)}/`,
+ });
+ return { deleted: true, id: activityId };
+ },
+});
+
+export { deleteActivity };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/delete-contact.ts b/packages/pieces/community/close/src/lib/actions/ai/delete-contact.ts
new file mode 100644
index 00000000000..c62ac89bdb5
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/delete-contact.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const deleteContact = createAction({
+ auth: closeAuth,
+ name: 'delete_contact',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact',
+ description: 'Permanently delete a contact person from its lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes one Close contact by contact id (cont_...). The lead and its other contacts stay. This cannot be undone. Repeating it on an already-deleted contact returns not found.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.deleted,
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'cont_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const contactId = closeClient.closeId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' });
+ await closeClient.request({ auth, method: HttpMethod.DELETE, path: `/contact/${closeClient.pathId(contactId)}/` });
+ return { deleted: true, id: contactId };
+ },
+});
+
+export { deleteContact };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/delete-lead.ts b/packages/pieces/community/close/src/lib/actions/ai/delete-lead.ts
new file mode 100644
index 00000000000..42bc254f386
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/delete-lead.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const deleteLead = createAction({
+ auth: closeAuth,
+ name: 'delete_lead',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Lead',
+ description: 'Permanently delete a lead with its contacts, opportunities, tasks and activities.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes a Close lead by lead id (lead_...), together with all its contacts, opportunities, tasks and activities. This cannot be undone. Repeating it on an already-deleted lead returns not found.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.deleted,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'lead_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ await closeClient.request({ auth, method: HttpMethod.DELETE, path: `/lead/${closeClient.pathId(leadId)}/` });
+ return { deleted: true, id: leadId };
+ },
+});
+
+export { deleteLead };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/delete-opportunity.ts b/packages/pieces/community/close/src/lib/actions/ai/delete-opportunity.ts
new file mode 100644
index 00000000000..086225c9eb1
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/delete-opportunity.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const deleteOpportunity = createAction({
+ auth: closeAuth,
+ name: 'delete_opportunity',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Opportunity',
+ description: 'Permanently delete a opportunity.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes a Close opportunity by ID (oppo_...). This cannot be undone. Repeating it on a deleted opportunity returns not found.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.deleted,
+ props: {
+ opportunityId: Property.ShortText({ displayName: 'Opportunity ID', description: 'oppo_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = closeClient.closeId({ value: propsValue.opportunityId, label: 'Opportunity ID', prefix: 'oppo' });
+ await closeClient.request({ auth, method: HttpMethod.DELETE, path: `/opportunity/${closeClient.pathId(id)}/` });
+ return { deleted: true, id };
+ },
+});
+
+export { deleteOpportunity };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/delete-task.ts b/packages/pieces/community/close/src/lib/actions/ai/delete-task.ts
new file mode 100644
index 00000000000..fa8d16fd636
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/delete-task.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const deleteTask = createAction({
+ auth: closeAuth,
+ name: 'delete_task',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Task',
+ description: 'Permanently delete a task.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes a Close task by ID (task_...). This cannot be undone. Repeating it on a deleted task returns not found.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.deleted,
+ props: {
+ taskId: Property.ShortText({ displayName: 'Task ID', description: 'task_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = closeClient.closeId({ value: propsValue.taskId, label: 'Task ID', prefix: 'task' });
+ await closeClient.request({ auth, method: HttpMethod.DELETE, path: `/task/${closeClient.pathId(id)}/` });
+ return { deleted: true, id };
+ },
+});
+
+export { deleteTask };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-activity.ts b/packages/pieces/community/close/src/lib/actions/ai/get-activity.ts
new file mode 100644
index 00000000000..abffeec7b17
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-activity.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const ACTIVITY_TYPES = ['note', 'call', 'email', 'sms', 'meeting'];
+
+const getActivity = createAction({
+ auth: closeAuth,
+ name: 'get_activity',
+ classification: 'READ',
+ displayName: 'Get Activity',
+ description: 'Get one note, call, email, SMS or meeting by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Gets one Close activity by activityId (acti_...) and its type: note, call, email, sms or meeting (the type field from List Activities, lowercased). Throws if the ID does not exist for that type. Returns the activity.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ activityType: Property.StaticDropdown({
+ displayName: 'Activity Type',
+ required: true,
+ options: { options: [{ label: 'Note', value: 'note' }, { label: 'Call', value: 'call' }, { label: 'Email', value: 'email' }, { label: 'SMS', value: 'sms' }, { label: 'Meeting', value: 'meeting' }] },
+ }),
+ activityId: Property.ShortText({ displayName: 'Activity ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const activityType = closeClient.requiredText({ value: propsValue.activityType, label: 'Activity Type' }).toLowerCase();
+ if (!ACTIVITY_TYPES.includes(activityType)) throw new Error(`Activity Type must be one of: ${ACTIVITY_TYPES.join(', ')}.`);
+ const activityId = closeClient.closeId({ value: propsValue.activityId, label: 'Activity ID', prefix: 'acti' });
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/activity/${activityType}/${closeClient.pathId(activityId)}/`,
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+export { getActivity };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-contact.ts b/packages/pieces/community/close/src/lib/actions/ai/get-contact.ts
new file mode 100644
index 00000000000..d35d71d6e68
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-contact.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const getContact = createAction({
+ auth: closeAuth,
+ name: 'get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Get one contact by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Close contact by contact id (cont_...): name, title, lead id, all emails, phones and URLs, primary email and phone, and custom fields. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.contact,
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'cont_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const contactId = closeClient.closeId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' });
+ const body = await closeClient.request({ auth, method: HttpMethod.GET, path: `/contact/${closeClient.pathId(contactId)}/` });
+ return closeMappers.contact(body);
+ },
+});
+
+export { getContact };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-current-user.ts b/packages/pieces/community/close/src/lib/actions/ai/get-current-user.ts
new file mode 100644
index 00000000000..4939181b6c7
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-current-user.ts
@@ -0,0 +1,59 @@
+import { createAction, OutputSchema } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const ME_FIELDS = ['id', 'email', 'first_name', 'last_name', 'organizations', 'date_created', 'email_accounts'];
+
+const currentUserOutputSchema = {
+ fields: [
+ ...closeOutputSchemas.fields.user,
+ {
+ key: 'emailAccounts',
+ label: 'Email Accounts',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'Email Account ID', description: 'Pass as Sender Account ID when subscribing a contact to a sequence.' },
+ { key: 'type', label: 'Type' },
+ { key: 'emails', label: 'Sender Emails' },
+ ],
+ },
+ ],
+} satisfies OutputSchema;
+
+function emailAccount(raw: unknown) {
+ const a = closeMappers.recordOf(raw);
+ return {
+ id: closeMappers.str(a['id']),
+ type: closeMappers.str(a['_type']),
+ emails: closeMappers
+ .arrayOf(a['identities'])
+ .map((i) => closeMappers.str(closeMappers.recordOf(i)['email']))
+ .filter((v): v is string => v !== null),
+ };
+}
+
+export const getCurrentUser = createAction({
+ auth: closeAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User',
+ description: 'Get the Close user who owns the API key.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns the Close user that owns the connection API key: id (user_...), email, first/last name, organization IDs and the connected email accounts (emailacct_... IDs with their sender emails, needed by Subscribe Contact to Sequence). Never returns API keys or tokens. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: currentUserOutputSchema,
+ props: {},
+ async run({ auth }) {
+ const raw = await closeClient.request({ auth, method: HttpMethod.GET, path: '/me/', query: { _fields: ME_FIELDS } });
+ const me = closeMappers.recordOf(raw);
+ return {
+ ...closeMappers.user(me),
+ emailAccounts: closeMappers.arrayOf(me['email_accounts']).map(emailAccount),
+ };
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-lead.ts b/packages/pieces/community/close/src/lib/actions/ai/get-lead.ts
new file mode 100644
index 00000000000..7bf1da78310
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-lead.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const getLead = createAction({
+ auth: closeAuth,
+ name: 'get_lead',
+ classification: 'READ',
+ displayName: 'Get Lead',
+ description: 'Get one lead by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Close lead by lead id (lead_...): name, status, website, description, its contacts with emails and phones, opportunity ids, addresses, custom fields and an app link. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.lead,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'lead_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const body = await closeClient.request({ auth, method: HttpMethod.GET, path: `/lead/${closeClient.pathId(leadId)}/` });
+ return closeMappers.lead(body);
+ },
+});
+
+export { getLead };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-opportunity.ts b/packages/pieces/community/close/src/lib/actions/ai/get-opportunity.ts
new file mode 100644
index 00000000000..9c5c7bf10e3
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-opportunity.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const getOpportunity = createAction({
+ auth: closeAuth,
+ name: 'get_opportunity',
+ classification: 'READ',
+ displayName: 'Get Opportunity',
+ description: 'Get one opportunity by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Close opportunity by ID (oppo_...), including lead, status, owner, value in cents, confidence and close date. Use List Opportunities to find IDs.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.opportunity,
+ props: {
+ opportunityId: Property.ShortText({ displayName: 'Opportunity ID', description: 'oppo_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = closeClient.closeId({ value: propsValue.opportunityId, label: 'Opportunity ID', prefix: 'oppo' });
+ const raw = await closeClient.request({ auth, method: HttpMethod.GET, path: `/opportunity/${closeClient.pathId(id)}/` });
+ return closeMappers.opportunity(raw);
+ },
+});
+
+export { getOpportunity };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/get-task.ts b/packages/pieces/community/close/src/lib/actions/ai/get-task.ts
new file mode 100644
index 00000000000..68e3271efe4
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/get-task.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const getTask = createAction({
+ auth: closeAuth,
+ name: 'get_task',
+ classification: 'READ',
+ displayName: 'Get Task',
+ description: 'Get one task by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Close task by ID (task_...), including lead, assignee, text, due date and completion state. Use List Tasks to find IDs.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.task,
+ props: {
+ taskId: Property.ShortText({ displayName: 'Task ID', description: 'task_...', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = closeClient.closeId({ value: propsValue.taskId, label: 'Task ID', prefix: 'task' });
+ const raw = await closeClient.request({ auth, method: HttpMethod.GET, path: `/task/${closeClient.pathId(id)}/` });
+ return closeMappers.task(raw);
+ },
+});
+
+export { getTask };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-activities.ts b/packages/pieces/community/close/src/lib/actions/ai/list-activities.ts
new file mode 100644
index 00000000000..6221fa6bedc
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-activities.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const TYPE_NAMES: Record<string, string> = { note: 'Note', call: 'Call', email: 'Email', sms: 'SMS', meeting: 'Meeting' };
+
+const listActivities = createAction({
+ auth: closeAuth,
+ name: 'list_activities',
+ classification: 'SEARCH',
+ displayName: 'List Activities',
+ description: 'List notes, calls, emails, SMS and meetings, newest first.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close activities newest first, one page at a time. Filter by leadId (lead_...); type (note, call, email, sms, meeting), contactId and userId only work together with leadId. createdAfter/createdBefore (ISO 8601) filter by creation time. limit 1-100 (default 25); pass nextSkip from the result as skip for the next page. Returns items, count, hasMore, nextSkip.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.activities,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: false }),
+ type: Property.StaticDropdown({
+ displayName: 'Activity Type',
+ required: false,
+ options: { options: [{ label: 'Note', value: 'note' }, { label: 'Call', value: 'call' }, { label: 'Email', value: 'email' }, { label: 'SMS', value: 'sms' }, { label: 'Meeting', value: 'meeting' }] },
+ }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ userId: Property.ShortText({ displayName: 'User ID', required: false }),
+ createdAfter: Property.DateTime({ displayName: 'Created After', required: false }),
+ createdBefore: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: Property.Number({ displayName: 'Limit', required: false, defaultValue: 25 }),
+ skip: Property.Number({ displayName: 'Skip', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const typeKey = closeClient.optionalText(propsValue.type)?.toLowerCase();
+ const type = typeKey === undefined ? undefined : TYPE_NAMES[typeKey];
+ if (typeKey !== undefined && type === undefined) throw new Error(`Activity Type must be one of: ${Object.keys(TYPE_NAMES).join(', ')}.`);
+ const contactId = closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' });
+ const userId = closeClient.optionalCloseId({ value: propsValue.userId, label: 'User ID', prefix: 'user' });
+ if (leadId === undefined && (type !== undefined || contactId !== undefined || userId !== undefined)) {
+ throw new Error('Close only filters by Activity Type, Contact ID or User ID when Lead ID is also given.');
+ }
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 25;
+ const skip = closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 }) ?? 0;
+ const page = await closeClient.listPage({
+ auth,
+ path: '/activity/',
+ query: {
+ lead_id: leadId,
+ _type: type,
+ contact_id: contactId,
+ user_id: userId,
+ date_created__gt: closeClient.isoDateTime({ value: propsValue.createdAfter, label: 'Created After' }),
+ date_created__lt: closeClient.isoDateTime({ value: propsValue.createdBefore, label: 'Created Before' }),
+ },
+ limit,
+ skip,
+ });
+ return closeMappers.offsetPage({ items: page.items, hasMore: page.hasMore, nextSkip: page.nextSkip, map: closeMappers.activity });
+ },
+});
+
+export { listActivities };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-custom-activity-types.ts b/packages/pieces/community/close/src/lib/actions/ai/list-custom-activity-types.ts
new file mode 100644
index 00000000000..09218a03ab2
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-custom-activity-types.ts
@@ -0,0 +1,55 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function activityType(raw: unknown) {
+ const t = closeMappers.recordOf(raw);
+ return {
+ id: closeMappers.str(t['id']),
+ name: closeMappers.str(t['name']),
+ description: closeMappers.str(t['description']),
+ apiCreateOnly: t['api_create_only'] === true,
+ isArchived: t['is_archived'] === true,
+ fields: closeMappers.arrayOf(t['fields']).map((f) => ({
+ ...closeMappers.customField(f),
+ required: closeMappers.recordOf(f)['required'] === true,
+ })),
+ };
+}
+
+export const listCustomActivityTypes = createAction({
+ auth: closeAuth,
+ name: 'list_custom_activity_types',
+ classification: 'SEARCH',
+ displayName: 'List Custom Activity Types',
+ description: 'List the custom activity types defined in Close.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every custom activity type in the Close organization with id (actitype_...), name, description, whether it is archived or API-only, and its custom fields (id cf_..., name, type, required, choices). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.offsetPage({
+ itemsLabel: 'Custom Activity Types',
+ labelKey: 'name',
+ items: [
+ { key: 'id', label: 'Type ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'apiCreateOnly', label: 'API Only', format: 'boolean' },
+ { key: 'isArchived', label: 'Archived', format: 'boolean' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'name',
+ listItems: [...closeOutputSchemas.fields.customField, { key: 'required', label: 'Required', format: 'boolean' }],
+ },
+ ],
+ }),
+ props: {},
+ async run({ auth }) {
+ const { items, truncated } = await closeClient.listAll({ auth, path: '/custom_activity/' });
+ return closeMappers.offsetPage({ items, hasMore: truncated, nextSkip: null, map: activityType });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-custom-fields.ts b/packages/pieces/community/close/src/lib/actions/ai/list-custom-fields.ts
new file mode 100644
index 00000000000..513806c5e1b
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-custom-fields.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const OBJECT_TYPES = ['lead', 'contact', 'opportunity', 'activity', 'shared'];
+
+export const listCustomFields = createAction({
+ auth: closeAuth,
+ name: 'list_custom_fields',
+ classification: 'SEARCH',
+ displayName: 'List Custom Fields',
+ description: 'List the custom fields for leads, contacts, opportunities or activities.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists the custom fields defined for one Close object type (lead, contact, opportunity, activity, or shared fields used across types). Returns id (cf_...), name, type, description, whether it accepts multiple values and its choices. Pass the ids as keys in Custom Fields on create/update actions. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.customFields,
+ props: {
+ objectType: Property.StaticDropdown({
+ displayName: 'Object Type',
+ required: true,
+ defaultValue: 'lead',
+ options: { options: OBJECT_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const objectType = closeClient.requiredText({ value: propsValue.objectType, label: 'Object Type' });
+ if (!OBJECT_TYPES.includes(objectType)) throw new Error(`Object Type must be one of: ${OBJECT_TYPES.join(', ')}.`);
+ const { items, truncated } = await closeClient.listAll({ auth, path: `/custom_field/${objectType}/` });
+ return closeMappers.offsetPage({ items, hasMore: truncated, nextSkip: null, map: closeMappers.customField });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-lead-statuses.ts b/packages/pieces/community/close/src/lib/actions/ai/list-lead-statuses.ts
new file mode 100644
index 00000000000..3f85412ec39
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-lead-statuses.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+export const listLeadStatuses = createAction({
+ auth: closeAuth,
+ name: 'list_lead_statuses',
+ classification: 'SEARCH',
+ displayName: 'List Lead Statuses',
+ description: 'List the lead statuses defined in Close.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every lead status in the Close organization with id (stat_...) and label. Use the id as the status when creating or updating a lead. Returns all statuses in one call. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.statuses,
+ props: {},
+ async run({ auth }) {
+ const { items, truncated } = await closeClient.listAll({ auth, path: '/status/lead/' });
+ return closeMappers.offsetPage({ items, hasMore: truncated, nextSkip: null, map: closeMappers.status });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-opportunities.ts b/packages/pieces/community/close/src/lib/actions/ai/list-opportunities.ts
new file mode 100644
index 00000000000..ae4e91d362b
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-opportunities.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function statusTypeOf(value: unknown): string | undefined {
+ const type = closeClient.optionalText(value);
+ if (type === undefined) return undefined;
+ if (!['active', 'won', 'lost'].includes(type)) throw new Error('Status Type must be active, won or lost.');
+ return type;
+}
+
+const listOpportunities = createAction({
+ auth: closeAuth,
+ name: 'list_opportunities',
+ classification: 'SEARCH',
+ displayName: 'List Opportunities',
+ description: 'List opportunities with optional filters.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close opportunities one page at a time, newest first. Filter by lead (lead_...), owner (user_...), status (stat_...), status type (active, won or lost) and close date range (YYYY-MM-DD). Values are in cents. When hasMore is true, call again with skip set to nextSkip.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.opportunities,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: false }),
+ userId: Property.ShortText({ displayName: 'Owner User ID', required: false }),
+ statusId: Property.ShortText({ displayName: 'Status ID', required: false }),
+ statusType: Property.ShortText({ displayName: 'Status Type', description: 'active, won or lost.', required: false }),
+ closeDateFrom: Property.ShortText({ displayName: 'Close Date From', description: 'YYYY-MM-DD, inclusive.', required: false }),
+ closeDateTo: Property.ShortText({ displayName: 'Close Date To', description: 'YYYY-MM-DD, inclusive.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 100.', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'nextSkip from the previous page.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const page = await closeClient.listPage({
+ auth,
+ path: '/opportunity/',
+ query: {
+ lead_id: closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ user_id: closeClient.optionalCloseId({ value: propsValue.userId, label: 'Owner User ID', prefix: 'user' }),
+ status_id: closeClient.optionalCloseId({ value: propsValue.statusId, label: 'Status ID', prefix: 'stat' }),
+ status_type: statusTypeOf(propsValue.statusType),
+ date_won__gte: closeClient.isoDate({ value: propsValue.closeDateFrom, label: 'Close Date From' }),
+ date_won__lte: closeClient.isoDate({ value: propsValue.closeDateTo, label: 'Close Date To' }),
+ _order_by: '-date_created',
+ },
+ limit: closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: closeClient.MAX_PAGE_SIZE }),
+ skip: closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: Number.MAX_SAFE_INTEGER }),
+ });
+ return closeMappers.offsetPage({ ...page, map: closeMappers.opportunity });
+ },
+});
+
+export { listOpportunities };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-pipelines.ts b/packages/pieces/community/close/src/lib/actions/ai/list-pipelines.ts
new file mode 100644
index 00000000000..9e245a3bd99
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-pipelines.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+export const listPipelines = createAction({
+ auth: closeAuth,
+ name: 'list_pipelines',
+ classification: 'SEARCH',
+ displayName: 'List Pipelines',
+ description: 'List opportunity pipelines and their statuses.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every opportunity pipeline in the Close organization with id (pipe_...), name and its ordered opportunity statuses (id stat_..., label, type active/won/lost). Use a status id when creating or updating an opportunity. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.pipelines,
+ props: {},
+ async run({ auth }) {
+ const { items, truncated } = await closeClient.listAll({ auth, path: '/pipeline/' });
+ return closeMappers.offsetPage({ items, hasMore: truncated, nextSkip: null, map: closeMappers.pipeline });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-sequence-subscriptions.ts b/packages/pieces/community/close/src/lib/actions/ai/list-sequence-subscriptions.ts
new file mode 100644
index 00000000000..661e4177c6b
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-sequence-subscriptions.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+import { sequenceSubscriptionShape } from './subscribe-contact-to-sequence';
+
+export const listSequenceSubscriptions = createAction({
+ auth: closeAuth,
+ name: 'list_sequence_subscriptions',
+ classification: 'SEARCH',
+ displayName: 'List Sequence Subscriptions',
+ description: 'List sequence subscriptions for a sequence, contact or lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close sequence subscriptions filtered by at least one of sequence id (seq_...), contact id (cont_...) or lead id (lead_...). Returns subscription id (sub_...), sequence, contact, lead, sender and status (active, paused, finished, ...). Use the id with Pause Sequence Subscription. Paged with limit (1-100) and skip (use nextSkip). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.offsetPage({ itemsLabel: 'Subscriptions', labelKey: 'id', items: sequenceSubscriptionShape.fields }),
+ props: {
+ sequenceId: Property.ShortText({ displayName: 'Sequence ID', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 100', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'Use nextSkip from the previous call.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const query = {
+ sequence_id: closeClient.optionalCloseId({ value: propsValue.sequenceId, label: 'Sequence ID', prefix: 'seq' }),
+ contact_id: closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ lead_id: closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ };
+ if (!query.sequence_id && !query.contact_id && !query.lead_id) throw new Error('Provide at least one of Sequence ID, Contact ID or Lead ID.');
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 });
+ const skip = closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 });
+ const page = await closeClient.listPage({ auth, path: '/sequence_subscription/', query, limit, skip });
+ return closeMappers.offsetPage({ ...page, map: sequenceSubscriptionShape.map });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-sequences.ts b/packages/pieces/community/close/src/lib/actions/ai/list-sequences.ts
new file mode 100644
index 00000000000..361572a1d03
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-sequences.ts
@@ -0,0 +1,75 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function sequence(raw: unknown) {
+ const s = closeMappers.recordOf(raw);
+ const steps = closeMappers.arrayOf(s['steps']).map((step) => {
+ const r = closeMappers.recordOf(step);
+ return {
+ id: closeMappers.str(r['id']),
+ stepType: closeMappers.str(r['step_type']),
+ delaySeconds: closeMappers.num(r['delay']),
+ emailTemplateId: closeMappers.str(r['email_template_id']),
+ };
+ });
+ return {
+ id: closeMappers.str(s['id']),
+ name: closeMappers.str(s['name']),
+ status: closeMappers.str(s['status']),
+ timezone: closeMappers.str(s['timezone']),
+ stepCount: steps.length,
+ steps,
+ dateCreated: closeMappers.str(s['date_created']),
+ dateUpdated: closeMappers.str(s['date_updated']),
+ };
+}
+
+export const listSequences = createAction({
+ auth: closeAuth,
+ name: 'list_sequences',
+ classification: 'SEARCH',
+ displayName: 'List Sequences',
+ description: 'List email/call sequences (workflows).',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close sequences (workflows) with id (seq_...), name, status (active/paused), timezone and their steps (type email/call, delay in seconds, email template id). Use the id with Subscribe Contact to Sequence. Paged with limit (1-100) and skip (use nextSkip). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.offsetPage({
+ itemsLabel: 'Sequences',
+ labelKey: 'name',
+ items: [
+ { key: 'id', label: 'Sequence ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'timezone', label: 'Timezone' },
+ { key: 'stepCount', label: 'Steps', format: 'number' },
+ {
+ key: 'steps',
+ label: 'Step Details',
+ labelKey: 'stepType',
+ listItems: [
+ { key: 'id', label: 'Step ID' },
+ { key: 'stepType', label: 'Type' },
+ { key: 'delaySeconds', label: 'Delay (s)', format: 'number' },
+ { key: 'emailTemplateId', label: 'Email Template ID' },
+ ],
+ },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+ ],
+ }),
+ props: {
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 100', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'Use nextSkip from the previous call.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 });
+ const skip = closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 });
+ const page = await closeClient.listPage({ auth, path: '/sequence/', limit, skip });
+ return closeMappers.offsetPage({ ...page, map: sequence });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-smart-views.ts b/packages/pieces/community/close/src/lib/actions/ai/list-smart-views.ts
new file mode 100644
index 00000000000..1cf9a19d32a
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-smart-views.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const VIEW_TYPES = ['lead', 'contact', 'opportunity', 'call', 'email', 'sms', 'meeting', 'note', 'whatsapp_message', 'custom_activity', 'form_submission'];
+
+function smartView(raw: unknown) {
+ const v = closeMappers.recordOf(raw);
+ return {
+ id: closeMappers.str(v['id']),
+ name: closeMappers.str(v['name']),
+ type: closeMappers.str(v['type']),
+ description: closeMappers.str(v['description']),
+ isShared: v['is_shared'] === true,
+ userId: closeMappers.str(v['user_id']),
+ dateCreated: closeMappers.str(v['date_created']),
+ dateUpdated: closeMappers.str(v['date_updated']),
+ };
+}
+
+export const listSmartViews = createAction({
+ auth: closeAuth,
+ name: 'list_smart_views',
+ classification: 'SEARCH',
+ displayName: 'List Smart Views',
+ description: 'List saved Smart Views.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close Smart Views (saved searches) of one type, lead by default (also contact, opportunity, call, email, sms, meeting, note, whatsapp_message, custom_activity, form_submission). Returns id (save_...), name, type, description, whether it is shared and the owner user id. Paged with limit (1-100) and skip (use nextSkip). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.offsetPage({
+ itemsLabel: 'Smart Views',
+ labelKey: 'name',
+ items: [
+ { key: 'id', label: 'Smart View ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'description', label: 'Description' },
+ { key: 'isShared', label: 'Shared', format: 'boolean' },
+ { key: 'userId', label: 'Owner User ID' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+ ],
+ }),
+ props: {
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: false,
+ defaultValue: 'lead',
+ options: { options: VIEW_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 100', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'Use nextSkip from the previous call.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const type = closeClient.optionalText(propsValue.type) ?? 'lead';
+ if (!VIEW_TYPES.includes(type)) throw new Error(`Type must be one of: ${VIEW_TYPES.join(', ')}.`);
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 });
+ const skip = closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 });
+ const page = await closeClient.listPage({ auth, path: '/saved_search/', query: { type }, limit, skip });
+ return closeMappers.offsetPage({ ...page, map: smartView });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-tasks.ts b/packages/pieces/community/close/src/lib/actions/ai/list-tasks.ts
new file mode 100644
index 00000000000..494a02c1b10
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-tasks.ts
@@ -0,0 +1,58 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function viewOf(value: unknown): string | undefined {
+ const view = closeClient.optionalText(value);
+ if (view === undefined) return undefined;
+ if (!['inbox', 'future', 'archive'].includes(view)) throw new Error('View must be inbox, future or archive.');
+ return view;
+}
+
+const listTasks = createAction({
+ auth: closeAuth,
+ name: 'list_tasks',
+ classification: 'SEARCH',
+ displayName: 'List Tasks',
+ description: 'List tasks with optional filters.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists Close lead tasks one page at a time (set includeNotifications to true to also get inbox items such as opportunity_due or missed_call), ordered by due date. Filter by lead (lead_...), assignee (user_...), completion, due date range (ISO 8601) or view (inbox = due now, future = due later, archive = completed). When hasMore is true, call again with skip set to nextSkip.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.tasks,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: false }),
+ assignedTo: Property.ShortText({ displayName: 'Assigned To (user ID)', required: false }),
+ isComplete: Property.ShortText({ displayName: 'Complete', description: 'true or false; leave empty for both.', required: false }),
+ dueFrom: Property.ShortText({ displayName: 'Due From', description: 'ISO 8601 date or date-time, inclusive.', required: false }),
+ dueTo: Property.ShortText({ displayName: 'Due To', description: 'ISO 8601 date or date-time, inclusive.', required: false }),
+ includeNotifications: Property.Checkbox({ displayName: 'Include Inbox Notifications', description: 'Also return inbox items like opportunity_due or missed_call.', required: false, defaultValue: false }),
+ view: Property.ShortText({ displayName: 'View', description: 'inbox, future or archive.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 100.', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'nextSkip from the previous page.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const page = await closeClient.listPage({
+ auth,
+ path: '/task/',
+ query: {
+ lead_id: closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ assigned_to: closeClient.optionalCloseId({ value: propsValue.assignedTo, label: 'Assigned To', prefix: 'user' }),
+ is_complete: closeClient.parseBoolean({ value: propsValue.isComplete, label: 'Complete' }),
+ date__gte: closeClient.isoDate({ value: propsValue.dueFrom, label: 'Due From' }),
+ date__lte: closeClient.isoDate({ value: propsValue.dueTo, label: 'Due To' }),
+ _type: propsValue.includeNotifications === true ? 'all' : 'lead',
+ view: viewOf(propsValue.view),
+ _order_by: 'date',
+ },
+ limit: closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: closeClient.MAX_PAGE_SIZE }),
+ skip: closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: Number.MAX_SAFE_INTEGER }),
+ });
+ return closeMappers.offsetPage({ ...page, map: closeMappers.task });
+ },
+});
+
+export { listTasks };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/list-users.ts b/packages/pieces/community/close/src/lib/actions/ai/list-users.ts
new file mode 100644
index 00000000000..2809122ab56
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/list-users.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+export const listUsers = createAction({
+ auth: closeAuth,
+ name: 'list_users',
+ classification: 'SEARCH',
+ displayName: 'List Users',
+ description: 'List the users in your Close organization.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists the users (sales reps) in the Close organization with id (user_...), email, name and organization IDs. Use the ids to assign tasks or opportunities. Paged with limit (1-100) and skip (use nextSkip). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.users,
+ props: {
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 100', required: false }),
+ skip: Property.Number({ displayName: 'Skip', description: 'Use nextSkip from the previous call.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 });
+ const skip = closeClient.parseInteger({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 });
+ const page = await closeClient.listPage({ auth, path: '/user/', limit, skip });
+ return closeMappers.offsetPage({ ...page, map: closeMappers.user });
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/log-call.ts b/packages/pieces/community/close/src/lib/actions/ai/log-call.ts
new file mode 100644
index 00000000000..0fdf25ef962
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/log-call.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const logCall = createAction({
+ auth: closeAuth,
+ name: 'log_call',
+ classification: 'WRITE',
+ displayName: 'Log Call',
+ description: 'Record a call made outside Close on a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Logs a phone call that already happened outside Close as a completed call activity on one lead (leadId, lead_...). It does not place a call. Optional: contactId (cont_...), direction (outbound or inbound), durationSeconds (whole seconds), phone (E.164, e.g. +16505551234), note, activityAt (ISO 8601). Creates a new call activity on every call. Returns the call activity.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ direction: Property.StaticDropdown({
+ displayName: 'Direction',
+ required: false,
+ options: { options: [{ label: 'Outbound', value: 'outbound' }, { label: 'Inbound', value: 'inbound' }] },
+ }),
+ durationSeconds: Property.Number({ displayName: 'Duration (seconds)', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ note: Property.LongText({ displayName: 'Note', required: false }),
+ activityAt: Property.DateTime({ displayName: 'Activity At', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const direction = closeClient.optionalText(propsValue.direction);
+ if (direction !== undefined && direction !== 'outbound' && direction !== 'inbound') throw new Error('Direction must be outbound or inbound.');
+ const body = {
+ lead_id: closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ contact_id: closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ status: 'completed',
+ direction,
+ duration: closeClient.parseInteger({ value: propsValue.durationSeconds, label: 'Duration (seconds)', min: 0, max: 86400 }),
+ phone: closeClient.optionalText(propsValue.phone),
+ note: closeClient.optionalText(propsValue.note),
+ activity_at: closeClient.isoDateTime({ value: propsValue.activityAt, label: 'Activity At' }),
+ };
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/activity/call/',
+ body: Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined)),
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+export { logCall };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/log-email.ts b/packages/pieces/community/close/src/lib/actions/ai/log-email.ts
new file mode 100644
index 00000000000..f18bc87bc0e
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/log-email.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const logEmail = createAction({
+ auth: closeAuth,
+ name: 'log_email',
+ classification: 'WRITE',
+ displayName: 'Log Email',
+ description: 'Record an email that was already sent or received, without sending anything.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Records an email that already happened as an email activity on one Close lead (leadId, lead_...). It never sends an email. direction: sent (the user emailed the lead, status sent) or received (the lead emailed the user, status inbox; sender is then required). Pass subject and bodyText; optional to (list of addresses), sender ("Name <[email protected]>"), contactId (cont_...), activityAt (ISO 8601). Creates a new activity on every call. Returns the email activity.',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: true }),
+ direction: Property.StaticDropdown({
+ displayName: 'Direction',
+ required: true,
+ options: { options: [{ label: 'Sent (to the lead)', value: 'sent' }, { label: 'Received (from the lead)', value: 'received' }] },
+ }),
+ subject: Property.ShortText({ displayName: 'Subject', required: true }),
+ bodyText: Property.LongText({ displayName: 'Body', required: true }),
+ to: Property.Array({ displayName: 'To', required: false }),
+ sender: Property.ShortText({ displayName: 'Sender', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ activityAt: Property.DateTime({ displayName: 'Activity At', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const direction = closeClient.requiredText({ value: propsValue.direction, label: 'Direction' });
+ if (direction !== 'sent' && direction !== 'received') throw new Error('Direction must be sent or received.');
+ const sender = closeClient.optionalText(propsValue.sender);
+ if (direction === 'received' && sender === undefined) throw new Error('Sender is required for a received email.');
+ const body = {
+ lead_id: closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ status: direction === 'sent' ? 'sent' : 'inbox',
+ subject: closeClient.requiredText({ value: propsValue.subject, label: 'Subject' }),
+ body_text: closeClient.requiredText({ value: propsValue.bodyText, label: 'Body' }),
+ to: closeClient.stringList({ value: propsValue.to, label: 'To' }),
+ sender,
+ contact_id: closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ activity_at: closeClient.isoDateTime({ value: propsValue.activityAt, label: 'Activity At' }),
+ };
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/activity/email/',
+ body: Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined)),
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+export { logEmail };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/merge-leads.ts b/packages/pieces/community/close/src/lib/actions/ai/merge-leads.ts
new file mode 100644
index 00000000000..f559e1f2970
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/merge-leads.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const mergeLeads = createAction({
+ auth: closeAuth,
+ name: 'merge_leads',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Merge Leads',
+ description: 'Merge a duplicate lead into another lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Merges a duplicate Close lead (source, lead_...) into another lead (destination, lead_...). Contacts, opportunities, tasks and activities move to the destination and the source lead is deleted; this cannot be undone. Returns the destination lead after the merge. Repeating it fails because the source no longer exists.',
+ idempotent: false,
+ },
+ outputSchema: {
+ fields: [{ key: 'mergedSourceId', label: 'Merged Source Lead ID' }, ...closeOutputSchemas.fields.lead],
+ },
+ props: {
+ sourceLeadId: Property.ShortText({ displayName: 'Source Lead ID', description: 'lead_... to merge away (it is deleted).', required: true }),
+ destinationLeadId: Property.ShortText({ displayName: 'Destination Lead ID', description: 'lead_... that is kept.', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const source = closeClient.closeId({ value: propsValue.sourceLeadId, label: 'Source Lead ID', prefix: 'lead' });
+ const destination = closeClient.closeId({ value: propsValue.destinationLeadId, label: 'Destination Lead ID', prefix: 'lead' });
+ if (source === destination) throw new Error('Source and destination must be different leads.');
+ await closeClient.request({ auth, method: HttpMethod.POST, path: '/lead/merge/', body: { source, destination } });
+ const merged = await closeClient.request({ auth, method: HttpMethod.GET, path: `/lead/${closeClient.pathId(destination)}/` });
+ return { mergedSourceId: source, ...closeMappers.lead(merged) };
+ },
+});
+
+export { mergeLeads };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/pause-sequence-subscription.ts b/packages/pieces/community/close/src/lib/actions/ai/pause-sequence-subscription.ts
new file mode 100644
index 00000000000..9f49b1c99da
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/pause-sequence-subscription.ts
@@ -0,0 +1,32 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { sequenceSubscriptionShape } from './subscribe-contact-to-sequence';
+
+export const pauseSequenceSubscription = createAction({
+ auth: closeAuth,
+ name: 'pause_sequence_subscription',
+ classification: 'WRITE',
+ displayName: 'Pause Sequence Subscription',
+ description: 'Pause a contact sequence subscription.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Pauses one Close sequence subscription (sub_..., from List Sequence Subscriptions or Subscribe Contact to Sequence) so no further sequence steps run for that contact. Works on every Close plan. Returns the updated subscription with status paused. Pausing an already paused subscription leaves it paused.',
+ idempotent: true,
+ },
+ outputSchema: { fields: sequenceSubscriptionShape.fields },
+ props: {
+ subscriptionId: Property.ShortText({ displayName: 'Subscription ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = closeClient.closeId({ value: propsValue.subscriptionId, label: 'Subscription ID', prefix: 'sub' });
+ const raw = await closeClient.request({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/sequence_subscription/${closeClient.pathId(id)}/`,
+ body: { status: 'paused' },
+ });
+ return sequenceSubscriptionShape.map(raw);
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/search-contacts.ts b/packages/pieces/community/close/src/lib/actions/ai/search-contacts.ts
new file mode 100644
index 00000000000..eb04e7a70ec
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/search-contacts.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const CONTACT_FIELDS = ['id', 'lead_id', 'name', 'title', 'emails', 'phones', 'urls', 'custom', 'date_created', 'date_updated'];
+
+const searchContacts = createAction({
+ auth: closeAuth,
+ name: 'search_contacts',
+ classification: 'SEARCH',
+ displayName: 'Search Contacts',
+ description: 'Find contacts by text and/or lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Searches Close contacts (people), newest first. Text matches all words (or the exact phrase) across contact names, titles, emails, phones and other text fields. Optionally limit to one lead by lead id (lead_...). Returns up to Limit contacts (max 100); pass nextCursor back as Cursor within 30 seconds for the next page. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.contacts,
+ props: {
+ text: Property.ShortText({ displayName: 'Text', description: 'Words to find, e.g. a name or email.', required: false }),
+ exactPhrase: Property.Checkbox({ displayName: 'Exact Phrase', description: 'Match the words in order next to each other.', required: false, defaultValue: false }),
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'Only contacts of this lead_...', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 25.', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const text = closeClient.optionalText(propsValue.text);
+ const leadId = closeClient.optionalCloseId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const exact = closeClient.parseBoolean({ value: propsValue.exactPhrase, label: 'Exact Phrase' }) === true;
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 25;
+ const queries: Record<string, unknown>[] = [{ type: 'object_type', object_type: 'contact' }];
+ if (text !== undefined) queries.push({ type: 'text', value: text, mode: exact ? 'phrase' : 'full_words' });
+ if (leadId !== undefined) {
+ queries.push({
+ type: 'field_condition',
+ field: { type: 'regular_field', object_type: 'contact', field_name: 'lead_id' },
+ condition: { type: 'reference', reference_type: 'lead', object_ids: [leadId] },
+ });
+ }
+ const page = await closeClient.searchPage({
+ auth,
+ query: { type: 'and', queries },
+ fields: { contact: CONTACT_FIELDS },
+ sort: [{ field: { type: 'regular_field', object_type: 'contact', field_name: 'date_created' }, direction: 'desc' }],
+ limit,
+ cursor: closeClient.optionalText(propsValue.cursor),
+ });
+ return closeMappers.cursorPage({ ...page, map: closeMappers.contact });
+ },
+});
+
+export { searchContacts };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/search-leads.ts b/packages/pieces/community/close/src/lib/actions/ai/search-leads.ts
new file mode 100644
index 00000000000..8de73292044
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/search-leads.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const LEAD_FIELDS = ['id', 'display_name', 'name', 'description', 'url', 'status_id', 'status_label', 'contacts', 'opportunities', 'addresses', 'custom', 'created_by', 'date_created', 'date_updated'];
+
+const searchLeads = createAction({
+ auth: closeAuth,
+ name: 'search_leads',
+ classification: 'SEARCH',
+ displayName: 'Search Leads',
+ description: 'Find leads by text and/or status.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Searches Close leads, newest first. Text matches all words (or the exact phrase) across lead names, contacts, emails, phones and other text fields. Optionally filter by a stat_ lead status id from List Lead Statuses. Returns up to Limit leads (max 100) with contacts; pass nextCursor back as Cursor within 30 seconds for the next page. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.leads,
+ props: {
+ text: Property.ShortText({ displayName: 'Text', description: 'Words to find, e.g. company name or email.', required: false }),
+ exactPhrase: Property.Checkbox({ displayName: 'Exact Phrase', description: 'Match the words in order next to each other.', required: false, defaultValue: false }),
+ statusId: Property.ShortText({ displayName: 'Lead Status ID', description: 'stat_... from List Lead Statuses.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1 to 100, default 25.', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const text = closeClient.optionalText(propsValue.text);
+ const statusId = closeClient.optionalCloseId({ value: propsValue.statusId, label: 'Lead Status ID', prefix: 'stat' });
+ const exact = closeClient.parseBoolean({ value: propsValue.exactPhrase, label: 'Exact Phrase' }) === true;
+ const limit = closeClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 25;
+ const queries: Record<string, unknown>[] = [{ type: 'object_type', object_type: 'lead' }];
+ if (text !== undefined) queries.push({ type: 'text', value: text, mode: exact ? 'phrase' : 'full_words' });
+ if (statusId !== undefined) {
+ queries.push({
+ type: 'field_condition',
+ field: { type: 'regular_field', object_type: 'lead', field_name: 'status_id' },
+ condition: { type: 'reference', reference_type: 'status.lead', object_ids: [statusId] },
+ });
+ }
+ const page = await closeClient.searchPage({
+ auth,
+ query: { type: 'and', queries },
+ fields: { lead: LEAD_FIELDS },
+ sort: [{ field: { type: 'regular_field', object_type: 'lead', field_name: 'date_created' }, direction: 'desc' }],
+ limit,
+ cursor: closeClient.optionalText(propsValue.cursor),
+ });
+ return closeMappers.cursorPage({ ...page, map: closeMappers.lead });
+ },
+});
+
+export { searchLeads };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/send-sms.ts b/packages/pieces/community/close/src/lib/actions/ai/send-sms.ts
new file mode 100644
index 00000000000..395e96e6312
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/send-sms.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const sendSms = createAction({
+ auth: closeAuth,
+ name: 'send_sms',
+ classification: 'WRITE',
+ displayName: 'Send SMS',
+ description: 'Send a real text message (not just a log entry) to a lead from a Close phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Sends a real SMS right away (Close status outbox) from one of your Close phone numbers to a lead or contact, and records it on lead leadId (lead_...). The message reaches the recipient and costs Close SMS credit; it cannot be recalled. localPhone must be an internal Close number in E.164 (e.g. +16505551234); remotePhone is the recipient in E.164; text is the message. Optional contactId (cont_...). Each call sends another SMS. Returns the SMS activity (status outbox until delivered).',
+ idempotent: false,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', required: true }),
+ localPhone: Property.ShortText({ displayName: 'From (Close number)', required: true }),
+ remotePhone: Property.ShortText({ displayName: 'To (phone)', required: true }),
+ text: Property.LongText({ displayName: 'Message', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const body = {
+ lead_id: closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' }),
+ contact_id: closeClient.optionalCloseId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ status: 'outbox',
+ direction: 'outbound',
+ local_phone: e164({ value: propsValue.localPhone, label: 'From (Close number)' }),
+ remote_phone: e164({ value: propsValue.remotePhone, label: 'To (phone)' }),
+ text: closeClient.requiredText({ value: propsValue.text, label: 'Message' }),
+ };
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/activity/sms/',
+ body: Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined)),
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+function e164({ value, label }: { value: unknown; label: string }): string {
+ const text = closeClient.requiredText({ value, label }).replace(/[\s().-]/g, '');
+ if (!/^\+[1-9]\d{6,14}$/.test(text)) throw new Error(`${label} must be a phone number in E.164 format, e.g. +16505551234.`);
+ return text;
+}
+
+export { sendSms };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/subscribe-contact-to-sequence.ts b/packages/pieces/community/close/src/lib/actions/ai/subscribe-contact-to-sequence.ts
new file mode 100644
index 00000000000..98ff118be97
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/subscribe-contact-to-sequence.ts
@@ -0,0 +1,93 @@
+import { createAction, OutputSchemaField, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+
+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+const subscriptionFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Subscription ID', description: 'Close sequence subscription ID (sub_...).' },
+ { key: 'sequenceId', label: 'Sequence ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'contactEmail', label: 'Contact Email', format: 'email' },
+ { key: 'senderAccountId', label: 'Sender Account ID' },
+ { key: 'senderName', label: 'Sender Name' },
+ { key: 'senderEmail', label: 'Sender Email', format: 'email' },
+ { key: 'status', label: 'Status', description: 'active, paused, finished, goal, error, ...' },
+ { key: 'statusReason', label: 'Status Reason' },
+ { key: 'callsAssignedTo', label: 'Calls Assigned To (user IDs)' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+];
+
+function mapSubscription(raw: unknown) {
+ const s = closeMappers.recordOf(raw);
+ return {
+ id: closeMappers.str(s['id']),
+ sequenceId: closeMappers.str(s['sequence_id']),
+ contactId: closeMappers.str(s['contact_id']),
+ leadId: closeMappers.str(s['lead_id']),
+ contactEmail: closeMappers.str(s['contact_email']),
+ senderAccountId: closeMappers.str(s['sender_account_id']),
+ senderName: closeMappers.str(s['sender_name']),
+ senderEmail: closeMappers.str(s['sender_email']),
+ status: closeMappers.str(s['status']),
+ statusReason: closeMappers.str(s['status_reason']),
+ callsAssignedTo: closeMappers.arrayOf(s['calls_assigned_to']).filter((v): v is string => typeof v === 'string'),
+ dateCreated: closeMappers.str(s['date_created']),
+ dateUpdated: closeMappers.str(s['date_updated']),
+ };
+}
+
+function email({ value, label }: { value: unknown; label: string }): string {
+ const text = closeClient.requiredText({ value, label });
+ if (!EMAIL_RE.test(text)) throw new Error(`${label} must be an email address.`);
+ return text;
+}
+
+export const sequenceSubscriptionShape = { fields: subscriptionFields, map: mapSubscription };
+
+export const subscribeContactToSequence = createAction({
+ auth: closeAuth,
+ name: 'subscribe_contact_to_sequence',
+ classification: 'WRITE',
+ displayName: 'Subscribe Contact to Sequence',
+ description: 'Enroll a contact in a Close sequence (workflow).',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Subscribes one Close contact (cont_...) to a sequence (seq_..., from List Sequences) so the sequence starts emailing/calling them. Needs the contact email to send to and a sender: email account id (emailacct_...), sender name and sender email, all available from Get Current User. Optional calls assigned to user ids. Returns the new subscription (sub_...). Calling it twice creates a second enrollment or fails, so it is not idempotent.',
+ idempotent: false,
+ },
+ outputSchema: { fields: subscriptionFields },
+ props: {
+ sequenceId: Property.ShortText({ displayName: 'Sequence ID', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: true }),
+ contactEmail: Property.ShortText({ displayName: 'Contact Email', required: true }),
+ senderAccountId: Property.ShortText({ displayName: 'Sender Email Account ID', description: 'emailacct_... from Get Current User.', required: true }),
+ senderName: Property.ShortText({ displayName: 'Sender Name', required: true }),
+ senderEmail: Property.ShortText({ displayName: 'Sender Email', required: true }),
+ callsAssignedTo: Property.Array({ displayName: 'Calls Assigned To (user IDs)', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const callsAssignedTo = (closeClient.stringList({ value: propsValue.callsAssignedTo, label: 'Calls Assigned To' }) ?? []).map((value) =>
+ closeClient.closeId({ value, label: 'Calls Assigned To', prefix: 'user' }),
+ );
+ const raw = await closeClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/sequence_subscription/',
+ body: {
+ sequence_id: closeClient.closeId({ value: propsValue.sequenceId, label: 'Sequence ID', prefix: 'seq' }),
+ contact_id: closeClient.closeId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' }),
+ contact_email: email({ value: propsValue.contactEmail, label: 'Contact Email' }),
+ sender_account_id: closeClient.closeId({ value: propsValue.senderAccountId, label: 'Sender Email Account ID', prefix: 'emailacct' }),
+ sender_name: closeClient.requiredText({ value: propsValue.senderName, label: 'Sender Name' }),
+ sender_email: email({ value: propsValue.senderEmail, label: 'Sender Email' }),
+ ...(callsAssignedTo.length > 0 ? { calls_assigned_to: callsAssignedTo } : {}),
+ },
+ });
+ return mapSubscription(raw);
+ },
+});
diff --git a/packages/pieces/community/close/src/lib/actions/ai/update-contact.ts b/packages/pieces/community/close/src/lib/actions/ai/update-contact.ts
new file mode 100644
index 00000000000..92c3406321c
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/update-contact.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const updateContact = createAction({
+ auth: closeAuth,
+ name: 'update_contact',
+ classification: 'WRITE',
+ displayName: 'Update Contact',
+ description: 'Change the name, title, email, phone or custom fields of a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates an existing Close contact by contact id (cont_...). Only the fields you pass change; an empty Title clears it. Passing an email, phone or website replaces all of that kind on the contact with the single value given. Custom fields take cf_ ids from List Custom Fields; a null value clears that field. Returns the updated contact.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.contact,
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'cont_...', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ title: Property.ShortText({ displayName: 'Title', description: 'Pass an empty string to clear it.', required: false }),
+ email: Property.ShortText({ displayName: 'Email', description: 'Replaces all emails on the contact.', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', description: 'Replaces all phones on the contact.', required: false }),
+ url: Property.ShortText({ displayName: 'Website', description: 'Replaces all URLs on the contact.', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of cf_... id to value; null clears a field.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const contactId = closeClient.closeId({ value: propsValue.contactId, label: 'Contact ID', prefix: 'cont' });
+ const body: Record<string, unknown> = { ...closeClient.customFieldsBody({ value: propsValue.customFields }) };
+ const name = closeClient.optionalText(propsValue.name);
+ const title = closeClient.clearableText(propsValue.title);
+ const email = closeClient.optionalText(propsValue.email);
+ const phone = closeClient.optionalText(propsValue.phone);
+ const url = closeClient.optionalText(propsValue.url);
+ if (name !== undefined) body['name'] = name;
+ if (title !== undefined) body['title'] = title;
+ if (email !== undefined) body['emails'] = [{ email, type: 'office' }];
+ if (phone !== undefined) body['phones'] = [{ phone, type: 'office' }];
+ if (url !== undefined) body['urls'] = [{ url, type: 'url' }];
+ if (Object.keys(body).length === 0) throw new Error('Pass at least one field to update.');
+ const updated = await closeClient.request({ auth, method: HttpMethod.PUT, path: `/contact/${closeClient.pathId(contactId)}/`, body });
+ return closeMappers.contact(updated);
+ },
+});
+
+export { updateContact };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/update-lead.ts b/packages/pieces/community/close/src/lib/actions/ai/update-lead.ts
new file mode 100644
index 00000000000..07eea5f4d73
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/update-lead.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const updateLead = createAction({
+ auth: closeAuth,
+ name: 'update_lead',
+ classification: 'WRITE',
+ displayName: 'Update Lead',
+ description: 'Change the name, status, website, description or custom fields of a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates fields on an existing Close lead by lead id (lead_...). Only the fields you pass change; others are left as they are. An empty string clears Description or Website. Status takes a stat_ id from List Lead Statuses. Custom fields take cf_ ids from List Custom Fields; a null value clears that field. Contacts are not changed here; use Update Contact. Returns the updated lead.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.lead,
+ props: {
+ leadId: Property.ShortText({ displayName: 'Lead ID', description: 'lead_...', required: true }),
+ name: Property.ShortText({ displayName: 'Lead Name', required: false }),
+ description: Property.LongText({ displayName: 'Description', description: 'Pass an empty string to clear it.', required: false }),
+ url: Property.ShortText({ displayName: 'Website', description: 'Pass an empty string to clear it.', required: false }),
+ statusId: Property.ShortText({ displayName: 'Lead Status ID', description: 'stat_... from List Lead Statuses.', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of cf_... id to value; null clears a field.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const leadId = closeClient.closeId({ value: propsValue.leadId, label: 'Lead ID', prefix: 'lead' });
+ const body: Record<string, unknown> = { ...closeClient.customFieldsBody({ value: propsValue.customFields }) };
+ const name = closeClient.optionalText(propsValue.name);
+ const description = closeClient.clearableText(propsValue.description);
+ const url = closeClient.clearableText(propsValue.url);
+ const statusId = closeClient.optionalCloseId({ value: propsValue.statusId, label: 'Lead Status ID', prefix: 'stat' });
+ if (name !== undefined) body['name'] = name;
+ if (description !== undefined) body['description'] = description;
+ if (url !== undefined) body['url'] = url;
+ if (statusId !== undefined) body['status_id'] = statusId;
+ if (Object.keys(body).length === 0) throw new Error('Pass at least one field to update.');
+ const updated = await closeClient.request({ auth, method: HttpMethod.PUT, path: `/lead/${closeClient.pathId(leadId)}/`, body });
+ return closeMappers.lead(updated);
+ },
+});
+
+export { updateLead };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/update-note.ts b/packages/pieces/community/close/src/lib/actions/ai/update-note.ts
new file mode 100644
index 00000000000..d92d3f472ee
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/update-note.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const updateNote = createAction({
+ auth: closeAuth,
+ name: 'update_note',
+ classification: 'WRITE',
+ displayName: 'Update Note',
+ description: 'Replace the text of a note in Close.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Replaces the text of one existing Close note activity by noteId (acti_..., from Create Note or List Activities with type Note). Only notes can be edited with this tool. Returns the updated note activity.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.activity,
+ props: {
+ noteId: Property.ShortText({ displayName: 'Note ID', required: true }),
+ note: Property.LongText({ displayName: 'Note', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const noteId = closeClient.closeId({ value: propsValue.noteId, label: 'Note ID', prefix: 'acti' });
+ const note = closeClient.requiredText({ value: propsValue.note, label: 'Note' });
+ const result = await closeClient.request({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/activity/note/${closeClient.pathId(noteId)}/`,
+ body: { note },
+ });
+ return closeMappers.activity(result);
+ },
+});
+
+export { updateNote };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/update-opportunity.ts b/packages/pieces/community/close/src/lib/actions/ai/update-opportunity.ts
new file mode 100644
index 00000000000..da1a301d867
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/update-opportunity.ts
@@ -0,0 +1,68 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+function valuePeriodOf(value: unknown): string | undefined {
+ const period = closeClient.optionalText(value);
+ if (period === undefined) return undefined;
+ if (!['one_time', 'monthly', 'annual'].includes(period)) throw new Error('Value Period must be one_time, monthly or annual.');
+ return period;
+}
+
+function opportunityBody({ props }: { props: Record<string, unknown> }): Record<string, unknown> {
+ const body: Record<string, unknown> = {
+ status_id: closeClient.optionalCloseId({ value: props['statusId'], label: 'Status ID', prefix: 'stat' }),
+ contact_id: closeClient.optionalCloseId({ value: props['contactId'], label: 'Contact ID', prefix: 'cont' }),
+ user_id: closeClient.optionalCloseId({ value: props['userId'], label: 'Owner User ID', prefix: 'user' }),
+ value: closeClient.parseInteger({ value: props['valueCents'], label: 'Value (cents)', min: 0, max: Number.MAX_SAFE_INTEGER }),
+ value_period: valuePeriodOf(props['valuePeriod']),
+ confidence: closeClient.parseInteger({ value: props['confidence'], label: 'Confidence %', min: 0, max: 100 }),
+ note: closeClient.clearableText(props['note']),
+ date_won: closeClient.isoDate({ value: props['expectedCloseDate'], label: 'Close Date' }),
+ ...closeClient.customFieldsBody({ value: props['customFields'] }),
+ };
+ return Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));
+}
+
+const updateOpportunity = createAction({
+ auth: closeAuth,
+ name: 'update_opportunity',
+ classification: 'WRITE',
+ displayName: 'Update Opportunity',
+ description: 'Change fields on an opportunity.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates a Close opportunity (oppo_...). Only the fields you pass change; an empty Note clears it. Value is a whole number of cents. Set Status ID to a won or lost status (from List Pipelines) to close the deal. Repeating the same update gives the same result.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.opportunity,
+ props: {
+ opportunityId: Property.ShortText({ displayName: 'Opportunity ID', description: 'oppo_...', required: true }),
+ statusId: Property.ShortText({ displayName: 'Status ID', description: 'Opportunity status ID (stat_...). Use List Pipelines to find IDs.', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'Contact on the lead (cont_...).', required: false }),
+ userId: Property.ShortText({ displayName: 'Owner User ID', description: 'User who owns the opportunity (user_...).', required: false }),
+ valueCents: Property.Number({ displayName: 'Value (cents)', description: 'Whole number of cents, e.g. 340000 for 3,400.00.', required: false }),
+ valuePeriod: Property.ShortText({ displayName: 'Value Period', description: 'one_time, monthly or annual.', required: false }),
+ confidence: Property.Number({ displayName: 'Confidence %', description: '0 to 100.', required: false }),
+ note: Property.LongText({ displayName: 'Note', description: 'Pass an empty string to clear it.', required: false }),
+ expectedCloseDate: Property.ShortText({ displayName: 'Close Date', description: 'Expected (or won) close date, e.g. 2026-11-30.', required: false }),
+ customFields: Property.Json({ displayName: 'Custom Fields', description: 'Object of custom field ID (cf_...) to value.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const opportunityId = closeClient.closeId({ value: propsValue.opportunityId, label: 'Opportunity ID', prefix: 'oppo' });
+ const body = opportunityBody({ props: propsValue });
+ if (Object.keys(body).length === 0) throw new Error('Pass at least one field to update.');
+ const raw = await closeClient.request({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/opportunity/${closeClient.pathId(opportunityId)}/`,
+ body,
+ });
+ return closeMappers.opportunity(raw);
+ },
+});
+
+export { updateOpportunity };
diff --git a/packages/pieces/community/close/src/lib/actions/ai/update-task.ts b/packages/pieces/community/close/src/lib/actions/ai/update-task.ts
new file mode 100644
index 00000000000..a7493937e31
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/actions/ai/update-task.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../../auth';
+import { closeClient } from '../../common/client';
+import { closeMappers } from '../../common/mappers';
+import { closeOutputSchemas } from '../../common/output-schemas';
+
+const updateTask = createAction({
+ auth: closeAuth,
+ name: 'update_task',
+ classification: 'WRITE',
+ displayName: 'Update Task',
+ description: 'Change, reassign or complete a task.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates a Close task (task_...). Only the fields you pass change: text, assignee (user_...), due date (YYYY-MM-DD or ISO 8601 date-time) and complete (true or false). Use complete=true to mark it done. Repeating the same update gives the same result.',
+ idempotent: true,
+ },
+ outputSchema: closeOutputSchemas.task,
+ props: {
+ taskId: Property.ShortText({ displayName: 'Task ID', description: 'task_...', required: true }),
+ text: Property.LongText({ displayName: 'Text', required: false }),
+ assignedTo: Property.ShortText({ displayName: 'Assigned To (user ID)', description: 'user_...', required: false }),
+ date: Property.ShortText({ displayName: 'Due', description: 'YYYY-MM-DD or ISO 8601 date-time.', required: false }),
+ isComplete: Property.ShortText({ displayName: 'Complete', description: 'true or false; leave empty to keep.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const taskId = closeClient.closeId({ value: propsValue.taskId, label: 'Task ID', prefix: 'task' });
+ const fields = {
+ text: closeClient.optionalText(propsValue.text),
+ assigned_to: closeClient.optionalCloseId({ value: propsValue.assignedTo, label: 'Assigned To', prefix: 'user' }),
+ date: closeClient.isoDate({ value: propsValue.date, label: 'Due' }),
+ is_complete: closeClient.parseBoolean({ value: propsValue.isComplete, label: 'Complete' }),
+ };
+ const body = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
+ if (Object.keys(body).length === 0) throw new Error('Pass at least one field to update.');
+ const raw = await closeClient.request({ auth, method: HttpMethod.PUT, path: `/task/${closeClient.pathId(taskId)}/`, body });
+ return closeMappers.task(raw);
+ },
+});
+
+export { updateTask };
diff --git a/packages/pieces/community/close/src/lib/actions/create-contact.ts b/packages/pieces/community/close/src/lib/actions/create-contact.ts
index 549e2124b0a..154a450568b 100644
--- a/packages/pieces/community/close/src/lib/actions/create-contact.ts
+++ b/packages/pieces/community/close/src/lib/actions/create-contact.ts
@@ -1,9 +1,11 @@
+import { closeMappers } from '../common/mappers';
+import { closeOutputSchemas } from '../common/output-schemas';
import { Property, createAction } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { closeAuth } from '../auth';
import { CloseCRMContact } from '../common/types';
import { customFields, leadId } from '../common/props';
-import { closeApiCall } from '../common/client';
+import { CloseApiError, closeApiCall } from '../common/client';
export const createContact = createAction({
auth: closeAuth,
@@ -11,11 +13,12 @@ export const createContact = createAction({
classification: 'WRITE',
displayName: 'Create Contact',
description: 'Creates a new contact.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Creates a new contact attached to an existing lead in Close CRM, with optional phones, emails, URL, and custom fields. Use to add a person to a known lead. Requires the target lead ID and a contact name. Not idempotent; each call creates a new contact and repeating produces duplicates.',
idempotent: false,
},
+ outputSchema: closeOutputSchemas.raw.contact,
props: {
lead_id: leadId(),
name: Property.ShortText({
@@ -132,15 +135,12 @@ export const createContact = createAction({
body: payload,
});
- return response;
- } catch (error: any) {
- if (error.response?.status === 400) {
- throw new Error(`Bad request: ${JSON.stringify(error.response.body)}`);
+ return closeMappers.withCustomMap({ objectType: 'contact', record: response });
+ } catch (error) {
+ if (error instanceof CloseApiError && error.status === 404) {
+ throw new Error(`Lead not found with ID: ${lead_id}. ${error.message}`);
}
- if (error.response?.status === 404) {
- throw new Error(`Lead not found with ID: ${lead_id}`);
- }
- throw new Error(`Error creating contact: ${error.message}`);
+ throw error;
}
},
});
diff --git a/packages/pieces/community/close/src/lib/actions/create-lead.ts b/packages/pieces/community/close/src/lib/actions/create-lead.ts
index 88eb7231bca..81b661978d0 100644
--- a/packages/pieces/community/close/src/lib/actions/create-lead.ts
+++ b/packages/pieces/community/close/src/lib/actions/create-lead.ts
@@ -1,3 +1,4 @@
+import { closeOutputSchemas } from '../common/output-schemas';
import { Property, createAction } from '@activepieces/pieces-framework';
import { closeAuth } from '../auth';
import { HttpMethod } from '@activepieces/pieces-common';
@@ -10,11 +11,12 @@ export const createLead = createAction({
classification: 'WRITE',
displayName: 'Create Lead',
description: 'Creates a new lead.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Creates a new lead (company/account) in Close CRM, optionally with an inline list of contacts, custom fields, and an initial status. Use to add a prospect or account to the CRM. Each call creates a separate lead, so it is not idempotent; repeated calls produce duplicates. Lead name is required.',
idempotent: false,
},
+ outputSchema: closeOutputSchemas.raw.lead,
props: {
name: Property.ShortText({
displayName: 'Lead Name',
@@ -144,7 +146,7 @@ export const createLead = createAction({
};
});
- const payload: Record<string, any> = {
+ const payload: Record<string, unknown> = {
name,
url,
description,
diff --git a/packages/pieces/community/close/src/lib/actions/create-opportunity.ts b/packages/pieces/community/close/src/lib/actions/create-opportunity.ts
index 28591fda741..36d631a7766 100644
--- a/packages/pieces/community/close/src/lib/actions/create-opportunity.ts
+++ b/packages/pieces/community/close/src/lib/actions/create-opportunity.ts
@@ -1,8 +1,10 @@
+import { closeMappers } from '../common/mappers';
+import { closeOutputSchemas } from '../common/output-schemas';
import { Property, createAction } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { closeAuth } from '../auth';
import { customFields, leadId, statusId, userId } from '../common/props';
-import { closeApiCall } from '../common/client';
+import { CloseApiError, closeApiCall, closeClient } from '../common/client';
export const createOpportunity = createAction({
auth: closeAuth,
@@ -10,11 +12,12 @@ export const createOpportunity = createAction({
classification: 'WRITE',
displayName: 'Create Opportunity',
description: 'Create a new opportunity.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Creates a new opportunity (deal) on an existing lead in Close CRM, with optional value, value period, confidence, status, contact, and custom fields. Use to log a sales deal against a lead. Requires the lead ID and an opportunity status. Not idempotent; each call creates a separate opportunity.',
idempotent: false,
},
+ outputSchema: closeOutputSchemas.raw.opportunity,
props: {
lead_id: leadId(),
status_id: statusId('opportunity', true),
@@ -34,7 +37,8 @@ export const createOpportunity = createAction({
required: false,
}),
value: Property.Number({
- displayName: 'Value',
+ displayName: 'Value (cents)',
+ description: 'Monetary value in cents of your organization currency, e.g. 340000 for $3,400.00.',
required: false,
}),
value_period: Property.StaticDropdown({
@@ -62,6 +66,9 @@ export const createOpportunity = createAction({
const { lead_id, name, note, status_id, confidence, value, value_period, contact_id, user_id } =
context.propsValue;
+ closeClient.parseInteger({ value: confidence, label: 'Confidence %', min: 0, max: 100 });
+ closeClient.parseInteger({ value, label: 'Value (cents)', min: 0, max: Number.MAX_SAFE_INTEGER });
+
const customFields = context.propsValue.custom_fields ?? {};
const transformedCustomFields = Object.fromEntries(
@@ -91,15 +98,12 @@ export const createOpportunity = createAction({
body: opportunityData,
});
- return response;
- } catch (error: any) {
- if (error.response?.status === 400) {
- throw new Error(`Invalid request: ${JSON.stringify(error.response.body)}`);
- }
- if (error.response?.status === 404) {
- throw new Error(`Lead or related resource not found`);
+ return closeMappers.withCustomMap({ objectType: 'opportunity', record: response });
+ } catch (error) {
+ if (error instanceof CloseApiError && error.status === 404) {
+ throw new Error(`Lead or related resource not found. ${error.message}`);
}
- throw new Error(`Failed to create opportunity: ${error.message}`);
+ throw error;
}
},
});
diff --git a/packages/pieces/community/close/src/lib/actions/find-contact.ts b/packages/pieces/community/close/src/lib/actions/find-contact.ts
index 8eb97151d63..2d26cefdca1 100644
--- a/packages/pieces/community/close/src/lib/actions/find-contact.ts
+++ b/packages/pieces/community/close/src/lib/actions/find-contact.ts
@@ -1,8 +1,9 @@
+import { closeOutputSchemas } from '../common/output-schemas';
import { Property, createAction } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { closeAuth } from '../auth';
import { CloseCRMSearchQuery } from '../common/types';
-import { closeApiCall } from '../common/client';
+import { CloseApiError, closeApiCall } from '../common/client';
export const findContact = createAction({
auth: closeAuth,
@@ -10,11 +11,12 @@ export const findContact = createAction({
classification: 'SEARCH',
displayName: 'Find Contact',
description: 'Search for contacts by name, email, or other criteria with advanced filtering',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Searches contacts in Close CRM and returns all matching records (auto-paginated). The search type selects which field to match on — contact name, email, phone, or parent lead ID — and the match mode controls comparison. Use to resolve a contact by a known attribute (e.g. find a contact ID before attaching an opportunity). Read-only and idempotent. Requires a search query value.',
idempotent: true,
},
+ outputSchema: closeOutputSchemas.raw.contactSearch,
props: {
search_type: Property.StaticDropdown({
displayName: 'Search Type',
@@ -37,10 +39,9 @@ export const findContact = createAction({
required: false,
options: {
options: [
- { label: 'Contains', value: 'contains' },
- { label: 'Exact Match', value: 'exact' },
- { label: 'Starts With', value: 'starts' },
- { label: 'Ends With', value: 'ends' },
+ { label: 'All Words (any order)', value: 'contains' },
+ { label: 'Exact Phrase', value: 'exact' },
+
],
},
defaultValue: 'contains',
@@ -65,7 +66,7 @@ export const findContact = createAction({
do {
const response = await closeApiCall<{
cursor?: string;
- data: Record<string, any>[];
+ data: Record<string, unknown>[];
}>({
accessToken: context.auth.secret_text,
method: HttpMethod.POST,
@@ -88,14 +89,11 @@ export const findContact = createAction({
found: result.length > 0,
result,
};
- } catch (error: any) {
- if (error.response?.status === 400) {
- throw new Error(`Invalid search query: ${error.response.body?.error || 'Unknown error'}`);
+ } catch (error) {
+ if (error instanceof CloseApiError && error.status === 400) {
+ throw new Error(`Invalid search query. ${error.message}`);
}
- if (error.response?.status === 401) {
- throw new Error('Authentication failed. Please check your API key.');
- }
- throw new Error(`Failed to search contacts: ${error.message}`);
+ throw error;
}
},
});
@@ -108,6 +106,7 @@ function buildSearchQuery(params: {
include_fields: string[];
}): CloseCRMSearchQuery {
const { search_type, search_query, match_type, include_fields } = params;
+ const textMode = match_type === 'exact' ? 'phrase' : 'full_words';
const baseQuery = {
type: 'object_type',
@@ -127,7 +126,7 @@ function buildSearchQuery(params: {
},
condition: {
type: 'text',
- mode: 'full_words',
+ mode: textMode,
value: search_query,
},
};
@@ -184,9 +183,9 @@ function buildSearchQuery(params: {
field_name: 'lead_id',
},
condition: {
- type: 'text',
- mode: 'phrase', // Always exact match for IDs
- value: search_query,
+ type: 'reference',
+ reference_type: 'lead',
+ object_ids: [search_query.trim()],
},
};
break;
@@ -202,7 +201,7 @@ function buildSearchQuery(params: {
},
_fields: {
lead: ['id', 'name', 'status_label', 'contacts'],
- contact: ['id', 'name', 'emails', 'phones'],
+ contact: Array.from(new Set([...include_fields, 'lead_id', 'phones'])),
},
};
}
diff --git a/packages/pieces/community/close/src/lib/actions/find-lead.ts b/packages/pieces/community/close/src/lib/actions/find-lead.ts
index 0f4c41847f9..15ae1ea3209 100644
--- a/packages/pieces/community/close/src/lib/actions/find-lead.ts
+++ b/packages/pieces/community/close/src/lib/actions/find-lead.ts
@@ -1,8 +1,9 @@
+import { closeOutputSchemas } from '../common/output-schemas';
import { Property, createAction } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { closeAuth } from '../auth';
import { CloseCRMSearchQuery } from '../common/types';
-import { closeApiCall } from '../common/client';
+import { CloseApiError, closeApiCall } from '../common/client';
export const findLead = createAction({
auth: closeAuth,
@@ -10,11 +11,12 @@ export const findLead = createAction({
classification: 'SEARCH',
displayName: 'Find Lead',
description: 'Search for leads with advanced filtering options',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Searches leads in Close CRM and returns all matching records (auto-paginated). The search type selects which field to match on — lead name, a related contact email, or status label — and the match mode controls how the query string is compared. Use to look up leads by a known attribute before creating or updating related records. Read-only and idempotent. Requires a search query value.',
idempotent: true,
},
+ outputSchema: closeOutputSchemas.raw.leadSearch,
props: {
search_type: Property.StaticDropdown({
displayName: 'Search Type',
@@ -36,10 +38,9 @@ export const findLead = createAction({
required: false,
options: {
options: [
- { label: 'Contains', value: 'contains' },
- { label: 'Exact Match', value: 'exact' },
- { label: 'Starts With', value: 'starts' },
- { label: 'Ends With', value: 'ends' },
+ { label: 'All Words (any order)', value: 'contains' },
+ { label: 'Exact Phrase', value: 'exact' },
+
],
},
defaultValue: 'contains',
@@ -50,10 +51,22 @@ export const findLead = createAction({
try {
// Build the search query
+ const statusIds =
+ search_type === 'status'
+ ? await resolveLeadStatusIds({
+ accessToken: context.auth.secret_text,
+ label: search_query,
+ exact: match_type === 'exact',
+ })
+ : [];
+ if (search_type === 'status' && statusIds.length === 0) {
+ return { found: false, result: [] };
+ }
const searchQuery = buildLeadSearchQuery({
search_type,
search_query,
match_type: match_type || 'contains',
+ status_ids: statusIds,
});
let cursor: string | undefined;
@@ -63,7 +76,7 @@ export const findLead = createAction({
do {
const response = await closeApiCall<{
cursor?: string;
- data: Record<string, any>[];
+ data: Record<string, unknown>[];
}>({
accessToken: context.auth.secret_text,
method: HttpMethod.POST,
@@ -86,29 +99,40 @@ export const findLead = createAction({
found: result.length > 0,
result,
};
- } catch (error: any) {
- if (error.response?.status === 400) {
- throw new Error(`Invalid search query: ${error.response.body?.error || 'Unknown error'}`);
- }
- if (error.response?.status === 401) {
- throw new Error('Authentication failed. Please check your API key.');
+ } catch (error) {
+ if (error instanceof CloseApiError && error.status === 400) {
+ throw new Error(`Invalid search query. ${error.message}`);
}
- if (error.response?.status === 404) {
- throw new Error('No leads found matching your criteria.');
- }
- throw new Error(`Failed to search leads: ${error.message}`);
+
+ throw error;
}
},
});
-// Helper function to build the lead search query
+async function resolveLeadStatusIds({ accessToken, label, exact }: { accessToken: string; label: string; exact: boolean }): Promise<string[]> {
+ const response = await closeApiCall<{ data?: { id: string; label: string }[] }>({
+ accessToken,
+ method: HttpMethod.GET,
+ resourceUri: '/status/lead/',
+ });
+ const wanted = label.trim().toLowerCase();
+ return (response.data ?? [])
+ .filter((status) => {
+ const current = status.label.toLowerCase();
+ return exact ? current === wanted : current.includes(wanted);
+ })
+ .map((status) => status.id);
+}
+
function buildLeadSearchQuery(params: {
search_type: string;
search_query: string;
match_type: string;
custom_field_name?: string;
+ status_ids?: string[];
}): CloseCRMSearchQuery {
- const { search_type, search_query, match_type, custom_field_name } = params;
+ const { search_type, search_query, match_type, custom_field_name, status_ids } = params;
+ const textMode = match_type === 'exact' ? 'phrase' : 'full_words';
const baseQuery = {
type: 'object_type',
@@ -128,7 +152,7 @@ function buildLeadSearchQuery(params: {
},
condition: {
type: 'text',
- mode: 'full_words',
+ mode: textMode,
value: search_query,
},
};
@@ -166,12 +190,12 @@ function buildLeadSearchQuery(params: {
field: {
type: 'regular_field',
object_type: 'lead',
- field_name: 'status_label',
+ field_name: 'status_id',
},
condition: {
- type: 'text',
- mode: 'phrase',
- value: search_query,
+ type: 'reference',
+ reference_type: 'status.lead',
+ object_ids: status_ids ?? [],
},
};
break;
@@ -186,7 +210,7 @@ function buildLeadSearchQuery(params: {
},
condition: {
type: 'text',
- mode: 'full_words',
+ mode: textMode,
value: search_query,
},
};
diff --git a/packages/pieces/community/close/src/lib/auth.ts b/packages/pieces/community/close/src/lib/auth.ts
index 84a51862510..4545ce060f1 100644
--- a/packages/pieces/community/close/src/lib/auth.ts
+++ b/packages/pieces/community/close/src/lib/auth.ts
@@ -1,25 +1,20 @@
import { PieceAuth } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { closeApiCall } from './common/client';
+import { CloseApiError, closeClient } from './common/client';
export const closeAuth = PieceAuth.SecretText({
displayName: 'API Key',
- description: 'Your Close CRM API key for authentication.',
+ description: 'Your Close API key. In Close go to Settings → Developer → API Keys and create a key.',
required: true,
validate: async ({ auth }) => {
try {
- await closeApiCall({
- accessToken: auth,
- method: HttpMethod.GET,
- resourceUri: '/me/',
- });
-
+ await closeClient.request({ auth, method: HttpMethod.GET, path: '/me/', query: { _fields: 'id' } });
return { valid: true };
- } catch {
- return {
- valid: false,
- error: 'Invalid API key.',
- };
+ } catch (error) {
+ if (error instanceof CloseApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid credentials: Close rejected the API key. Create a new key in Settings → Developer → API Keys.' };
+ }
+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach Close.' };
}
},
});
diff --git a/packages/pieces/community/close/src/lib/common/client.ts b/packages/pieces/community/close/src/lib/common/client.ts
index d598d9bcc1c..6140b73c99a 100644
--- a/packages/pieces/community/close/src/lib/common/client.ts
+++ b/packages/pieces/community/close/src/lib/common/client.ts
@@ -1,81 +1,387 @@
import {
- AuthenticationType,
- httpClient,
- HttpMessageBody,
- HttpMethod,
- HttpRequest,
- QueryParams,
+ AuthenticationType,
+ httpClient,
+ HttpMethod,
+ QueryParams,
} from '@activepieces/pieces-common';
+export const CLOSE_API_URL = 'https://api.close.com/api/v1';
+
+const REQUEST_TIMEOUT_MS = 30_000;
+const MAX_RATE_LIMIT_RETRIES = 2;
+const MAX_RATE_LIMIT_WAIT_MS = 30_000;
+const DEFAULT_RATE_LIMIT_WAIT_MS = 2_000;
+const MAX_PAGE_SIZE = 100;
+const ID_RE = /^[A-Za-z0-9_-]+$/;
+
+export class CloseApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly responseBody: unknown,
+ ) {
+ super(message);
+ this.name = 'CloseApiError';
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function keyOf(auth: CloseAuthInput): string {
+ const raw = typeof auth === 'string' ? auth : isRecord(auth) ? auth['secret_text'] : undefined;
+ const key = typeof raw === 'string' ? raw.trim() : '';
+ if (key === '') throw new Error('The Close connection has no API key. Reconnect Close with an API key from Settings → Developer → API Keys.');
+ return key;
+}
+
+function hintFor(status: number): string {
+ if (status === 401) return ' The API key is invalid or revoked; reconnect Close.';
+ if (status === 402) return ' Your Close plan does not include this feature or a plan limit was reached.';
+ if (status === 403) return ' The API key user is not allowed to do this.';
+ if (status === 404) return ' Check the ID you passed.';
+ if (status === 429) return ' Close is rate limiting this API key; try again later.';
+ return '';
+}
+
+function fieldErrorsText(value: unknown): string | undefined {
+ if (!isRecord(value)) return undefined;
+ const parts = Object.entries(value).map(([field, err]) => `${field}: ${Array.isArray(err) ? err.join(', ') : typeof err === 'string' ? err : JSON.stringify(err)}`);
+ return parts.length > 0 ? parts.join('; ') : undefined;
+}
+
+function messageOf(body: unknown): string | undefined {
+ if (typeof body === 'string') return body.trim() === '' ? undefined : body.trim().slice(0, 300);
+ if (!isRecord(body)) return undefined;
+ const parts: string[] = [];
+ const err = body['error'];
+ if (typeof err === 'string' && err.trim()) parts.push(err.trim());
+ else if (isRecord(err) && typeof err['message'] === 'string') parts.push(err['message']);
+ const fieldErrors = fieldErrorsText(body['field-errors']);
+ if (fieldErrors) parts.push(fieldErrors);
+ const errors = body['errors'];
+ if (Array.isArray(errors) && errors.length > 0) parts.push(errors.map((e) => (typeof e === 'string' ? e : JSON.stringify(e))).join('; '));
+ if (parts.length === 0 && Object.keys(body).length > 0) parts.push(JSON.stringify(body).slice(0, 300));
+ return parts.length > 0 ? parts.join(' — ') : undefined;
+}
+
+function toApiError({ status, body }: { status: number; body: unknown }): CloseApiError {
+ const text = status >= 300 && status < 400 ? 'unexpected redirect' : messageOf(body) ?? 'request failed';
+ return new CloseApiError(`Close API error (${status}): ${text.replace(/\.+$/, '')}.${hintFor(status)}`, status, body);
+}
+
+function failureOf(error: unknown): { status: number; body: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'] } : null;
+}
+
+function rateLimitWaitMs(body: unknown): number {
+ const candidates = [isRecord(body) ? body['rate_reset'] : undefined, isRecord(body) && isRecord(body['error']) ? body['error']['rate_reset'] : undefined];
+ for (const c of candidates) {
+ const seconds = typeof c === 'number' ? c : typeof c === 'string' ? Number(c) : NaN;
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(Math.ceil(seconds * 1000), MAX_RATE_LIMIT_WAIT_MS);
+ }
+ return DEFAULT_RATE_LIMIT_WAIT_MS;
+}
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+function buildQuery(query?: CloseQuery): QueryParams {
+ const qs: QueryParams = {};
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value === undefined || value === null) continue;
+ qs[key] = Array.isArray(value) ? value.join(',') : String(value);
+ }
+ return qs;
+}
+
+function normalizePath(path: string): string {
+ if (!path.startsWith('/') || path.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(path)) {
+ throw new Error('Close request paths must be relative to the Close API (start with a single "/").');
+ }
+ if (path.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {
+ throw new Error('Close request paths must not contain ".." segments.');
+ }
+ return path;
+}
+
+async function request<T = unknown>({ auth, method, path, query, body }: CloseRequest): Promise<T> {
+ const apiKey = keyOf(auth);
+ const url = `${CLOSE_API_URL}${normalizePath(path)}`;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url,
+ authentication: { type: AuthenticationType.BASIC, username: apiKey, password: '' },
+ headers: { accept: 'application/json', ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
+ queryParams: buildQuery(query),
+ body,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ });
+ if (response.status < 200 || response.status >= 300) throw toApiError({ status: response.status, body: response.body });
+ return response.body;
+ } catch (error) {
+ if (error instanceof CloseApiError) throw error;
+ const failure = failureOf(error);
+ if (!failure) throw error;
+ if (failure.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await sleep(rateLimitWaitMs(failure.body));
+ continue;
+ }
+ throw toApiError(failure);
+ }
+ }
+}
+
+async function listPage<T = Record<string, unknown>>({ auth, path, query, limit, skip }: CloseListParams): Promise<ClosePage<T>> {
+ const pageSize = clampLimit(limit);
+ const offset = Math.max(0, Math.trunc(skip ?? 0));
+ const body = await request<{ data?: T[]; has_more?: boolean }>({
+ auth,
+ method: HttpMethod.GET,
+ path,
+ query: { ...query, _limit: pageSize, _skip: offset },
+ });
+ const items = Array.isArray(body?.data) ? body.data : [];
+ const hasMore = body?.has_more === true && items.length > 0;
+ return { items, hasMore, nextSkip: hasMore ? offset + items.length : null };
+}
+
+async function listAll<T = Record<string, unknown>>({ auth, path, query, maxItems = 1000 }: Omit<CloseListParams, 'limit' | 'skip'> & { maxItems?: number }): Promise<{ items: T[]; truncated: boolean }> {
+ const items: T[] = [];
+ let skip = 0;
+ for (;;) {
+ const page = await listPage<T>({ auth, path, query, skip, limit: MAX_PAGE_SIZE });
+ for (const item of page.items) {
+ if (items.length >= maxItems) return { items, truncated: true };
+ items.push(item);
+ }
+ if (!page.hasMore || page.nextSkip === null) return { items, truncated: false };
+ if (items.length >= maxItems) return { items, truncated: true };
+ skip = page.nextSkip;
+ }
+}
+
+async function searchPage<T = Record<string, unknown>>({ auth, query, fields, sort, limit, cursor }: CloseSearchParams): Promise<CloseCursorPage<T>> {
+ const body = await request<{ data?: T[]; cursor?: string | null }>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/data/search/',
+ body: {
+ query,
+ _limit: clampLimit(limit),
+ ...(cursor ? { cursor } : {}),
+ ...(fields ? { _fields: fields } : {}),
+ ...(sort ? { sort } : {}),
+ },
+ });
+ const items = Array.isArray(body?.data) ? body.data : [];
+ const next = typeof body?.cursor === 'string' && body.cursor !== '' ? body.cursor : null;
+ return { items, hasMore: next !== null, nextCursor: next };
+}
+
+async function searchAll<T = Record<string, unknown>>({ maxItems = 1000, ...params }: Omit<CloseSearchParams, 'cursor' | 'limit'> & { maxItems?: number }): Promise<{ items: T[]; truncated: boolean }> {
+ const items: T[] = [];
+ let cursor: string | null = null;
+ for (;;) {
+ const page: CloseCursorPage<T> = await searchPage<T>({ ...params, limit: MAX_PAGE_SIZE, cursor: cursor ?? undefined });
+ for (const item of page.items) {
+ if (items.length >= maxItems) return { items, truncated: true };
+ items.push(item);
+ }
+ if (!page.hasMore || page.items.length === 0) return { items, truncated: false };
+ if (items.length >= maxItems) return { items, truncated: true };
+ cursor = page.nextCursor;
+ }
+}
+
+function clampLimit(limit: unknown): number {
+ const n = typeof limit === 'string' ? Number(limit) : limit;
+ if (typeof n !== 'number' || !Number.isFinite(n)) return MAX_PAGE_SIZE;
+ return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.trunc(n)));
+}
+
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
+ if (typeof value !== 'string') return undefined;
+ const text = value.trim();
+ return text === '' ? undefined : text;
+}
+
+function clearableText(value: unknown): string | undefined {
+ if (typeof value === 'string') return value.trim();
+ return optionalText(value);
+}
+
+function requiredText({ value, label }: { value: unknown; label: string }): string {
+ const text = optionalText(value);
+ if (text === undefined) throw new Error(`${label} is required.`);
+ return text;
+}
+
+function closeId({ value, label, prefix }: { value: unknown; label: string; prefix?: string }): string {
+ const text = requiredText({ value, label });
+ if (!ID_RE.test(text) || (prefix !== undefined && !text.startsWith(`${prefix}_`))) {
+ throw new Error(`${label} must be a Close ID${prefix ? ` starting with "${prefix}_"` : ''}, e.g. ${prefix ?? 'lead'}_abc123.`);
+ }
+ return text;
+}
+
+function optionalCloseId({ value, label, prefix }: { value: unknown; label: string; prefix?: string }): string | undefined {
+ return optionalText(value) === undefined ? undefined : closeId({ value, label, prefix });
+}
+
+function parseInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return parsed;
+}
+
+function parseBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {
+ const v = Array.isArray(value) && value.length === 1 ? value[0] : value;
+ if (v === undefined || v === null || v === '') return undefined;
+ if (v === true || v === 'true') return true;
+ if (v === false || v === 'false') return false;
+ throw new Error(`${label} must be true or false.`);
+}
+
+function isoDateTime({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) return undefined;
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) throw new Error(`${label} must be an ISO 8601 date-time, e.g. 2026-10-18T12:00:00Z.`);
+ return new Date(time).toISOString();
+}
+
+function isoDate({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) return undefined;
+ if (/^\d{4}-\d{2}-\d{2}$/.test(text) && !Number.isNaN(Date.parse(`${text}T00:00:00Z`))) return text;
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) throw new Error(`${label} must be a date like 2026-10-18 or an ISO 8601 date-time.`);
+ return new Date(time).toISOString();
+}
+
+function plainObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ let parsed = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error(`${label} must be a JSON object.`);
+ }
+ }
+ if (!isRecord(parsed)) throw new Error(`${label} must be an object of key/value pairs.`);
+ return parsed;
+}
+
+function customFieldsBody({ value, label = 'Custom Fields' }: { value: unknown; label?: string }): Record<string, unknown> {
+ const obj = plainObject({ value, label }) ?? {};
+ const out: Record<string, unknown> = {};
+ for (const [key, v] of Object.entries(obj)) {
+ const id = key.startsWith('custom.') ? key.slice('custom.'.length) : key;
+ if (!/^cf_[A-Za-z0-9]+$/.test(id)) throw new Error(`${label}: "${key}" is not a custom field ID (expected cf_...). Use List Custom Fields to find IDs.`);
+ out[`custom.${id}`] = v;
+ }
+ return out;
+}
+
+function stringList({ value, label }: { value: unknown; label: string }): string[] | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : null;
+ if (raw === null) throw new Error(`${label} must be a list of text values.`);
+ const list = raw.map((v) => (typeof v === 'string' ? v.trim() : typeof v === 'number' ? String(v) : '')).filter((v) => v !== '');
+ return list;
+}
+
+function pathId(id: string): string {
+ return encodeURIComponent(id);
+}
+
+export const closeClient = {
+ request,
+ listPage,
+ listAll,
+ searchPage,
+ searchAll,
+ keyOf,
+ isRecord,
+ toApiError,
+ normalizePath,
+ optionalText,
+ clearableText,
+ requiredText,
+ closeId,
+ optionalCloseId,
+ parseInteger,
+ parseBoolean,
+ isoDateTime,
+ isoDate,
+ plainObject,
+ customFieldsBody,
+ stringList,
+ pathId,
+ MAX_PAGE_SIZE,
+};
+
+
export type CloseApiCallParams = {
- accessToken: string;
- method: HttpMethod;
- resourceUri: string;
- query?: Record<string, string | number | string[] | undefined>;
- body?: any;
+ accessToken: string;
+ method: HttpMethod;
+ resourceUri: string;
+ query?: Record<string, string | number | string[] | undefined>;
+ body?: unknown;
};
-export const CLOSE_API_URL = 'https://api.close.com/api/v1';
+export async function closeApiCall<T = unknown>({ accessToken, method, resourceUri, query, body }: CloseApiCallParams): Promise<T> {
+ return request<T>({ auth: accessToken, method, path: resourceUri, query, body });
+}
-export async function closeApiCall<T extends HttpMessageBody>({
- accessToken,
- method,
- resourceUri,
- query,
- body,
-}: CloseApiCallParams): Promise<T> {
- const qs: QueryParams = {};
-
- if (query) {
- for (const [key, value] of Object.entries(query)) {
- if (value !== null && value !== undefined) {
- qs[key] = String(value);
- }
- }
- }
- const request: HttpRequest = {
- method,
- url: CLOSE_API_URL + resourceUri,
- authentication: {
- type: AuthenticationType.BASIC,
- username: accessToken,
- password: '',
- },
- queryParams: qs,
- body,
- };
-
- const response = await httpClient.sendRequest<T>(request);
- return response.body;
-}
-
-export async function closePaginatedApiCall<T extends HttpMessageBody>({
- accessToken,
- method,
- resourceUri,
- query,
- body,
-}: CloseApiCallParams): Promise<T[]> {
- const resultData: T[] = [];
- const limit = 100;
- let skip = 0;
- let hasMore = true;
-
- do {
- const response = await closeApiCall<{ data: T[]; has_more: boolean }>({
- accessToken,
- method,
- resourceUri,
- query: { ...query, _limit: limit, _skip: skip },
- body,
- });
- const { data, has_more } = response;
- if (!data || data.length === 0) break;
-
- resultData.push(...data);
- hasMore = has_more;
- skip += limit;
- } while (hasMore);
-
- return resultData;
+export async function closePaginatedApiCall<T = Record<string, unknown>>({ accessToken, resourceUri, query }: CloseApiCallParams): Promise<T[]> {
+ const { items } = await listAll<T>({ auth: accessToken, path: resourceUri, query, maxItems: 5000 });
+ return items;
}
+
+
+export type CloseAuthInput = string | { secret_text: string };
+
+export type CloseQuery = Record<string, string | number | boolean | string[] | null | undefined>;
+
+export type CloseRequest = {
+ auth: CloseAuthInput;
+ method: HttpMethod;
+ path: string;
+ query?: CloseQuery;
+ body?: unknown;
+};
+
+export type CloseListParams = {
+ auth: CloseAuthInput;
+ path: string;
+ query?: CloseQuery;
+ limit?: number;
+ skip?: number;
+};
+
+export type CloseSearchParams = {
+ auth: CloseAuthInput;
+ query: Record<string, unknown>;
+ fields?: Record<string, string[]>;
+ sort?: unknown[];
+ limit?: number;
+ cursor?: string;
+};
+
+export type ClosePage<T> = { items: T[]; hasMore: boolean; nextSkip: number | null };
+export type CloseCursorPage<T> = { items: T[]; hasMore: boolean; nextCursor: string | null };
diff --git a/packages/pieces/community/close/src/lib/common/mappers.ts b/packages/pieces/community/close/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..be49394d6a2
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/common/mappers.ts
@@ -0,0 +1,233 @@
+import { closeClient } from './client';
+
+const APP_URL = 'https://app.close.com';
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return closeClient.isRecord(value) ? value : {};
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function str(value: unknown): string | null {
+ return typeof value === 'string' ? value : null;
+}
+
+function num(value: unknown): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+}
+
+function bool(value: unknown): boolean | null {
+ return typeof value === 'boolean' ? value : null;
+}
+
+function customOf(raw: Record<string, unknown>): Record<string, unknown> {
+ const fromPrefixed = Object.fromEntries(
+ Object.entries(raw)
+ .filter(([key]) => key.startsWith('custom.'))
+ .map(([key, value]) => [key.slice('custom.'.length), value]),
+ );
+ return { ...fromPrefixed };
+}
+
+function withCustomMap({ objectType, record }: { objectType: 'lead' | 'contact' | 'opportunity'; record: unknown }): unknown {
+ if (objectType === 'lead' || !closeClient.isRecord(record)) return record;
+ return { ...record, custom: customOf(record) };
+}
+
+function emails(value: unknown) {
+ return arrayOf(value).map((e) => {
+ const r = recordOf(e);
+ return { email: str(r['email']), type: str(r['type']) };
+ });
+}
+
+function phones(value: unknown) {
+ return arrayOf(value).map((p) => {
+ const r = recordOf(p);
+ return { phone: str(r['phone']), phoneFormatted: str(r['phone_formatted']), type: str(r['type']) };
+ });
+}
+
+function urls(value: unknown) {
+ return arrayOf(value).map((u) => {
+ const r = recordOf(u);
+ return { url: str(r['url']), type: str(r['type']) };
+ });
+}
+
+function contact(raw: unknown) {
+ const c = recordOf(raw);
+ return {
+ id: str(c['id']),
+ leadId: str(c['lead_id']),
+ name: str(c['name']),
+ title: str(c['title']),
+ emails: emails(c['emails']),
+ phones: phones(c['phones']),
+ urls: urls(c['urls']),
+ primaryEmail: str(recordOf(arrayOf(c['emails'])[0])['email']),
+ primaryPhone: str(recordOf(arrayOf(c['phones'])[0])['phone']),
+ custom: customOf(c),
+ dateCreated: str(c['date_created']),
+ dateUpdated: str(c['date_updated']),
+ };
+}
+
+function lead(raw: unknown) {
+ const l = recordOf(raw);
+ const id = str(l['id']);
+ return {
+ id,
+ name: str(l['display_name']) ?? str(l['name']),
+ description: str(l['description']),
+ url: str(l['url']),
+ statusId: str(l['status_id']),
+ statusLabel: str(l['status_label']),
+ contacts: arrayOf(l['contacts']).map(contact),
+ opportunityIds: arrayOf(l['opportunities']).map((o) => str(recordOf(o)['id'])).filter((v): v is string => v !== null),
+ addresses: arrayOf(l['addresses']).map(recordOf),
+ custom: { ...recordOf(l['custom']), ...customOf(l) },
+ createdBy: str(l['created_by']),
+ dateCreated: str(l['date_created']),
+ dateUpdated: str(l['date_updated']),
+ appUrl: id ? `${APP_URL}/lead/${encodeURIComponent(id)}/` : null,
+ };
+}
+
+function opportunity(raw: unknown) {
+ const o = recordOf(raw);
+ return {
+ id: str(o['id']),
+ leadId: str(o['lead_id']),
+ leadName: str(o['lead_name']),
+ contactId: str(o['contact_id']),
+ userId: str(o['user_id']),
+ userName: str(o['user_name']),
+ statusId: str(o['status_id']),
+ statusLabel: str(o['status_label']),
+ statusType: str(o['status_type']),
+ pipelineId: str(o['pipeline_id']),
+ pipelineName: str(o['pipeline_name']),
+ valueCents: num(o['value']),
+ valueCurrency: str(o['value_currency']),
+ valueFormatted: str(o['value_formatted']),
+ valuePeriod: str(o['value_period']),
+ confidence: num(o['confidence']),
+ note: str(o['note']),
+ dateWon: str(o['date_won']),
+ dateLost: str(o['date_lost']),
+ custom: customOf(o),
+ dateCreated: str(o['date_created']),
+ dateUpdated: str(o['date_updated']),
+ };
+}
+
+function task(raw: unknown) {
+ const t = recordOf(raw);
+ return {
+ id: str(t['id']),
+ type: str(t['_type']),
+ leadId: str(t['lead_id']),
+ leadName: str(t['lead_name']),
+ contactId: str(t['contact_id']),
+ assignedTo: str(t['assigned_to']),
+ assignedToName: str(t['assigned_to_name']),
+ text: str(t['text']),
+ date: str(t['date']),
+ isComplete: bool(t['is_complete']),
+ isDateless: bool(t['is_dateless']),
+ dateCreated: str(t['date_created']),
+ dateUpdated: str(t['date_updated']),
+ };
+}
+
+function activity(raw: unknown) {
+ const a = recordOf(raw);
+ const email = recordOf(a['envelope']);
+ return {
+ id: str(a['id']),
+ type: str(a['_type']),
+ leadId: str(a['lead_id']),
+ contactId: str(a['contact_id']),
+ userId: str(a['user_id']),
+ userName: str(a['user_name']),
+ direction: str(a['direction']),
+ status: str(a['status']),
+ subject: str(a['subject']) ?? str(a['title']) ?? str(email['subject']),
+ text: str(a['note']) ?? str(a['text']) ?? str(a['body_text']),
+ durationSeconds: num(a['duration']),
+ phone: str(a['phone']) ?? str(a['remote_phone']),
+ activityAt: str(a['activity_at']),
+ dateCreated: str(a['date_created']),
+ dateUpdated: str(a['date_updated']),
+ };
+}
+
+function user(raw: unknown) {
+ const u = recordOf(raw);
+ const name = [str(u['first_name']), str(u['last_name'])].filter((p): p is string => !!p && p.trim() !== '').join(' ').trim();
+ return {
+ id: str(u['id']),
+ email: str(u['email']),
+ firstName: str(u['first_name']),
+ lastName: str(u['last_name']),
+ name: name === '' ? null : name,
+ organizationIds: arrayOf(u['organizations']).map((o) => (typeof o === 'string' ? o : str(recordOf(o)['id']))).filter((v): v is string => v !== null),
+ dateCreated: str(u['date_created']),
+ };
+}
+
+function status(raw: unknown) {
+ const s = recordOf(raw);
+ return { id: str(s['id']), label: str(s['label']), type: str(s['type']), pipelineId: str(s['pipeline_id']) };
+}
+
+function pipeline(raw: unknown) {
+ const p = recordOf(raw);
+ return { id: str(p['id']), name: str(p['name']), statuses: arrayOf(p['statuses']).map(status) };
+}
+
+function customField(raw: unknown) {
+ const f = recordOf(raw);
+ return {
+ id: str(f['id']),
+ name: str(f['name']),
+ type: str(f['type']),
+ description: str(f['description']),
+ acceptsMultipleValues: f['accepts_multiple_values'] === true,
+ choices: arrayOf(f['choices']).filter((c): c is string => typeof c === 'string'),
+ };
+}
+
+function offsetPage<T>({ items, hasMore, nextSkip, map }: { items: unknown[]; hasMore: boolean; nextSkip: number | null; map: (item: unknown) => T }) {
+ const mapped = items.map(map);
+ return { items: mapped, count: mapped.length, hasMore, nextSkip };
+}
+
+function cursorPage<T>({ items, hasMore, nextCursor, map }: { items: unknown[]; hasMore: boolean; nextCursor: string | null; map: (item: unknown) => T }) {
+ const mapped = items.map(map);
+ return { items: mapped, count: mapped.length, hasMore, nextCursor };
+}
+
+export const closeMappers = {
+ withCustomMap,
+ lead,
+ contact,
+ opportunity,
+ task,
+ activity,
+ user,
+ status,
+ pipeline,
+ customField,
+ offsetPage,
+ cursorPage,
+ recordOf,
+ arrayOf,
+ str,
+ num,
+ bool,
+ APP_URL,
+};
diff --git a/packages/pieces/community/close/src/lib/common/output-schemas.ts b/packages/pieces/community/close/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..5538022f3c5
--- /dev/null
+++ b/packages/pieces/community/close/src/lib/common/output-schemas.ts
@@ -0,0 +1,362 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const emailFields: OutputSchemaField[] = [
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'type', label: 'Type' },
+];
+
+const phoneFields: OutputSchemaField[] = [
+ { key: 'phone', label: 'Phone' },
+ { key: 'phoneFormatted', label: 'Formatted' },
+ { key: 'type', label: 'Type' },
+];
+
+const urlFields: OutputSchemaField[] = [
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'type', label: 'Type' },
+];
+
+const contactFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Contact ID', description: 'Close contact ID (cont_...).' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'primaryEmail', label: 'Primary Email', format: 'email' },
+ { key: 'primaryPhone', label: 'Primary Phone' },
+ { key: 'emails', label: 'Emails', labelKey: 'email', listItems: emailFields },
+ { key: 'phones', label: 'Phones', labelKey: 'phone', listItems: phoneFields },
+ { key: 'urls', label: 'URLs', labelKey: 'url', listItems: urlFields },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+];
+
+const leadFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Lead ID', description: 'Close lead ID (lead_...).' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'url', label: 'Website', format: 'url' },
+ { key: 'statusId', label: 'Status ID' },
+ { key: 'statusLabel', label: 'Status' },
+ { key: 'contacts', label: 'Contacts', labelKey: 'name', listItems: contactFields },
+ { key: 'opportunityIds', label: 'Opportunity IDs' },
+ { key: 'addresses', label: 'Addresses' },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true },
+ { key: 'createdBy', label: 'Created By (user ID)' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+ { key: 'appUrl', label: 'Open in Close', format: 'url' },
+];
+
+const opportunityFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Opportunity ID', description: 'Close opportunity ID (oppo_...).' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'leadName', label: 'Lead Name' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'userId', label: 'Owner User ID' },
+ { key: 'userName', label: 'Owner' },
+ { key: 'statusId', label: 'Status ID' },
+ { key: 'statusLabel', label: 'Status' },
+ { key: 'statusType', label: 'Status Type', description: 'active, won or lost.' },
+ { key: 'pipelineId', label: 'Pipeline ID' },
+ { key: 'pipelineName', label: 'Pipeline' },
+ { key: 'valueCents', label: 'Value (cents)', format: 'number', description: 'Monetary value in cents of the organization currency.' },
+ { key: 'valueCurrency', label: 'Currency' },
+ { key: 'valueFormatted', label: 'Value (formatted)' },
+ { key: 'valuePeriod', label: 'Value Period' },
+ { key: 'confidence', label: 'Confidence %', format: 'number' },
+ { key: 'note', label: 'Note' },
+ { key: 'dateWon', label: 'Close Date', format: 'date', description: 'Won date, or the expected close date while active.' },
+ { key: 'dateLost', label: 'Lost Date', format: 'date' },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+];
+
+const taskFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Task ID' },
+ { key: 'type', label: 'Task Type' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'leadName', label: 'Lead Name' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'assignedTo', label: 'Assigned To (user ID)' },
+ { key: 'assignedToName', label: 'Assigned To' },
+ { key: 'text', label: 'Text' },
+ { key: 'date', label: 'Due', format: 'datetime' },
+ { key: 'isComplete', label: 'Complete', format: 'boolean' },
+ { key: 'isDateless', label: 'No Due Date', format: 'boolean' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+];
+
+const activityFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Activity ID', description: 'Close activity ID (acti_...).' },
+ { key: 'type', label: 'Activity Type', description: 'Note, Call, Email, SMS, Meeting, ...' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'userId', label: 'User ID' },
+ { key: 'userName', label: 'User' },
+ { key: 'direction', label: 'Direction' },
+ { key: 'status', label: 'Status' },
+ { key: 'subject', label: 'Subject / Title' },
+ { key: 'text', label: 'Text' },
+ { key: 'durationSeconds', label: 'Duration (s)', format: 'number' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'activityAt', label: 'Activity At', format: 'datetime' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+ { key: 'dateUpdated', label: 'Updated', format: 'datetime' },
+];
+
+const userFields: OutputSchemaField[] = [
+ { key: 'id', label: 'User ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'firstName', label: 'First Name' },
+ { key: 'lastName', label: 'Last Name' },
+ { key: 'name', label: 'Name' },
+ { key: 'organizationIds', label: 'Organization IDs' },
+ { key: 'dateCreated', label: 'Created', format: 'datetime' },
+];
+
+const statusFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Status ID' },
+ { key: 'label', label: 'Label' },
+ { key: 'type', label: 'Type' },
+ { key: 'pipelineId', label: 'Pipeline ID' },
+];
+
+const pipelineFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Pipeline ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'statuses', label: 'Statuses', labelKey: 'label', listItems: statusFields },
+];
+
+const customFieldFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Field ID', description: 'Pass as custom.<id> or as a key in Custom Fields.' },
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'description', label: 'Description' },
+ { key: 'acceptsMultipleValues', label: 'Multiple Values', format: 'boolean' },
+ { key: 'choices', label: 'Choices' },
+];
+
+function single({ fields }: { fields: OutputSchemaField[] }): OutputSchema {
+ return { fields };
+}
+
+function found({ fields }: { fields: OutputSchemaField[] }): OutputSchema {
+ return { fields: [{ key: 'found', label: 'Found', format: 'boolean' }, ...fields] };
+}
+
+function offsetPage({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label: itemsLabel, labelKey, listItems: items },
+ { key: 'count', label: 'Returned', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextSkip', label: 'Next Skip', format: 'number', description: 'Pass as skip to get the next page; null when there is none.' },
+ ],
+ };
+}
+
+function cursorPage({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label: itemsLabel, labelKey, listItems: items },
+ { key: 'count', label: 'Returned', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextCursor', label: 'Next Cursor', description: 'Pass as cursor within 30 seconds to get the next page; null when there is none.' },
+ ],
+ };
+}
+
+const deleted: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'id', label: 'ID' },
+ ],
+};
+
+const legacySearch: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'result', label: 'Results', listItems: [{ key: 'id', label: 'ID' }, { key: 'name', label: 'Name' }] },
+ ],
+};
+
+
+const rawEmailFields: OutputSchemaField[] = [
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'type', label: 'Type' },
+ { key: 'is_unsubscribed', label: 'Unsubscribed', format: 'boolean' },
+];
+
+const rawPhoneFields: OutputSchemaField[] = [
+ { key: 'phone', label: 'Phone' },
+ { key: 'phone_formatted', label: 'Formatted' },
+ { key: 'country', label: 'Country' },
+ { key: 'type', label: 'Type' },
+];
+
+const rawUrlFields: OutputSchemaField[] = [
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'type', label: 'Type' },
+];
+
+const rawIntegrationLinkFields: OutputSchemaField[] = [
+ { key: 'name', label: 'Name' },
+ { key: 'url', label: 'URL', format: 'url' },
+];
+
+const rawAuditFields: OutputSchemaField[] = [
+ { key: 'organization_id', label: 'Organization ID' },
+ { key: 'created_by', label: 'Created By (user ID)' },
+ { key: 'updated_by', label: 'Updated By (user ID)' },
+ { key: 'date_created', label: 'Created', format: 'datetime' },
+ { key: 'date_updated', label: 'Updated', format: 'datetime' },
+];
+
+const rawContactFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Contact ID', description: 'Close contact ID (cont_...).' },
+ { key: 'lead_id', label: 'Lead ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'display_name', label: 'Display Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'emails', label: 'Emails', labelKey: 'email', listItems: rawEmailFields },
+ { key: 'phones', label: 'Phones', labelKey: 'phone', listItems: rawPhoneFields },
+ { key: 'urls', label: 'URLs', labelKey: 'url', listItems: rawUrlFields },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true, description: 'Custom field values keyed by field ID (cf_...).' },
+ { key: 'integration_links', label: 'Integration Links', labelKey: 'name', listItems: rawIntegrationLinkFields },
+ ...rawAuditFields,
+];
+
+const rawLeadFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Lead ID', description: 'Close lead ID (lead_...).' },
+ { key: 'name', label: 'Name' },
+ { key: 'display_name', label: 'Display Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'url', label: 'Website', format: 'url' },
+ { key: 'status_id', label: 'Status ID' },
+ { key: 'status_label', label: 'Status' },
+ { key: 'contacts', label: 'Contacts', labelKey: 'name', listItems: rawContactFields },
+ { key: 'opportunities', label: 'Opportunities' },
+ { key: 'tasks', label: 'Tasks' },
+ { key: 'addresses', label: 'Addresses' },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true, description: 'Custom field values keyed by field name.' },
+ { key: 'integration_links', label: 'Integration Links', labelKey: 'name', listItems: rawIntegrationLinkFields },
+ { key: 'created_by_name', label: 'Created By' },
+ { key: 'updated_by_name', label: 'Updated By' },
+ ...rawAuditFields,
+];
+
+const rawOpportunityFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Opportunity ID', description: 'Close opportunity ID (oppo_...).' },
+ { key: 'lead_id', label: 'Lead ID' },
+ { key: 'lead_name', label: 'Lead Name' },
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'contact_name', label: 'Contact Name' },
+ { key: 'user_id', label: 'Owner User ID' },
+ { key: 'user_name', label: 'Owner' },
+ { key: 'status_id', label: 'Status ID' },
+ { key: 'status_label', label: 'Status' },
+ { key: 'status_display_name', label: 'Status Display Name' },
+ { key: 'status_type', label: 'Status Type', description: 'active, won or lost.' },
+ { key: 'pipeline_id', label: 'Pipeline ID' },
+ { key: 'pipeline_name', label: 'Pipeline' },
+ { key: 'value', label: 'Value (cents)', format: 'number' },
+ { key: 'value_currency', label: 'Currency' },
+ { key: 'value_formatted', label: 'Value (formatted)' },
+ { key: 'value_period', label: 'Value Period' },
+ { key: 'expected_value', label: 'Expected Value', format: 'number' },
+ { key: 'annualized_value', label: 'Annualized Value', format: 'number' },
+ { key: 'annualized_expected_value', label: 'Annualized Expected Value', format: 'number' },
+ { key: 'confidence', label: 'Confidence %', format: 'number' },
+ { key: 'note', label: 'Note' },
+ { key: 'date_won', label: 'Won Date', format: 'date' },
+ { key: 'date_lost', label: 'Lost Date', format: 'date' },
+ { key: 'attachments', label: 'Attachments' },
+ { key: 'custom', label: 'Custom Fields', dynamicKey: true, description: 'Custom field values keyed by field ID (cf_...).' },
+ { key: 'integration_links', label: 'Integration Links', labelKey: 'name', listItems: rawIntegrationLinkFields },
+ { key: 'created_by_name', label: 'Created By' },
+ { key: 'updated_by_name', label: 'Updated By' },
+ ...rawAuditFields,
+];
+
+const rawSearchLeadFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Lead ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'status_label', label: 'Status' },
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'emails', label: 'Emails', labelKey: 'email', listItems: rawEmailFields },
+ { key: 'phones', label: 'Phones', labelKey: 'phone', listItems: rawPhoneFields },
+ ],
+ },
+];
+
+const rawSearchContactFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'lead_id', label: 'Lead ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'emails', label: 'Emails', labelKey: 'email', listItems: rawEmailFields },
+ { key: 'phones', label: 'Phones', labelKey: 'phone', listItems: rawPhoneFields },
+];
+
+function rawSearch({ labelKey, items }: { labelKey: string; items: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'result', label: 'Results', labelKey, listItems: items },
+ ],
+ };
+}
+
+export const closeOutputSchemas = {
+ fields: {
+ lead: leadFields,
+ contact: contactFields,
+ opportunity: opportunityFields,
+ task: taskFields,
+ activity: activityFields,
+ user: userFields,
+ status: statusFields,
+ pipeline: pipelineFields,
+ customField: customFieldFields,
+ },
+ lead: single({ fields: leadFields }),
+ contact: single({ fields: contactFields }),
+ opportunity: single({ fields: opportunityFields }),
+ task: single({ fields: taskFields }),
+ activity: single({ fields: activityFields }),
+ user: single({ fields: userFields }),
+ pipeline: single({ fields: pipelineFields }),
+ foundLead: found({ fields: leadFields }),
+ foundContact: found({ fields: contactFields }),
+ leads: cursorPage({ itemsLabel: 'Leads', labelKey: 'name', items: leadFields }),
+ contacts: cursorPage({ itemsLabel: 'Contacts', labelKey: 'name', items: contactFields }),
+ leadsPage: offsetPage({ itemsLabel: 'Leads', labelKey: 'name', items: leadFields }),
+ contactsPage: offsetPage({ itemsLabel: 'Contacts', labelKey: 'name', items: contactFields }),
+ opportunities: offsetPage({ itemsLabel: 'Opportunities', labelKey: 'leadName', items: opportunityFields }),
+ tasks: offsetPage({ itemsLabel: 'Tasks', labelKey: 'text', items: taskFields }),
+ activities: offsetPage({ itemsLabel: 'Activities', labelKey: 'type', items: activityFields }),
+ users: offsetPage({ itemsLabel: 'Users', labelKey: 'email', items: userFields }),
+ pipelines: offsetPage({ itemsLabel: 'Pipelines', labelKey: 'name', items: pipelineFields }),
+ statuses: offsetPage({ itemsLabel: 'Statuses', labelKey: 'label', items: statusFields }),
+ customFields: offsetPage({ itemsLabel: 'Custom Fields', labelKey: 'name', items: customFieldFields }),
+ deleted,
+ legacySearch,
+ raw: {
+ lead: single({ fields: rawLeadFields }),
+ contact: single({ fields: rawContactFields }),
+ opportunity: single({ fields: rawOpportunityFields }),
+ leadSearch: rawSearch({ labelKey: 'name', items: rawSearchLeadFields }),
+ contactSearch: rawSearch({ labelKey: 'name', items: rawSearchContactFields }),
+ },
+ offsetPage,
+ cursorPage,
+};
diff --git a/packages/pieces/community/close/src/lib/common/props.ts b/packages/pieces/community/close/src/lib/common/props.ts
index 84723f1f6d0..7b7f81e64f7 100644
--- a/packages/pieces/community/close/src/lib/common/props.ts
+++ b/packages/pieces/community/close/src/lib/common/props.ts
@@ -107,22 +107,30 @@ export const statusId = (objectType: string, required = false) =>
};
}
- const response = await closePaginatedApiCall<{
- id: string;
- label: string;
- }>({
- accessToken: auth.secret_text,
- method: HttpMethod.GET,
- resourceUri: `/status/${objectType}/`,
- });
+ try {
+ const response = await closePaginatedApiCall<{
+ id: string;
+ label: string;
+ }>({
+ accessToken: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/status/${objectType}/`,
+ });
- return {
- disabled: false,
- options: response.map((status) => ({
- label: status.label,
- value: status.id,
- })),
- };
+ return {
+ disabled: false,
+ options: response.map((status) => ({
+ label: status.label,
+ value: status.id,
+ })),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: error instanceof Error ? error.message : 'Could not fetch statuses. Check your connection.',
+ };
+ }
},
});
@@ -202,7 +210,7 @@ export const userId = (required = false) =>
return {
disabled: true,
options: [],
- placeholder: 'Could not fetch uers. Check your connection.',
+ placeholder: error instanceof Error ? error.message : 'Could not fetch users. Check your connection.',
};
}
},
diff --git a/packages/pieces/community/close/src/lib/common/types.ts b/packages/pieces/community/close/src/lib/common/types.ts
index 2a06652ed5c..f8e6ba07888 100644
--- a/packages/pieces/community/close/src/lib/common/types.ts
+++ b/packages/pieces/community/close/src/lib/common/types.ts
@@ -88,7 +88,7 @@ export interface CloseCRMContact {
export interface CloseCRMSearchQuery {
query: {
type: string;
- queries: any[];
+ queries: unknown[];
};
_fields: {
contact: string[];
@@ -99,7 +99,7 @@ export interface CloseCRMSearchQuery {
export interface CloseCRMSearchQuery {
query: {
type: string;
- queries: any[];
+ queries: unknown[];
};
}
diff --git a/packages/pieces/community/close/src/lib/triggers/helpers.ts b/packages/pieces/community/close/src/lib/triggers/helpers.ts
index 8d1b63eed7b..92afcb72e7f 100644
--- a/packages/pieces/community/close/src/lib/triggers/helpers.ts
+++ b/packages/pieces/community/close/src/lib/triggers/helpers.ts
@@ -1,28 +1,134 @@
import crypto from 'crypto';
+import { DEDUPE_KEY_PROPERTY, TriggerHookContext, TriggerStrategy } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { closeAuth } from '../auth';
+import { CloseApiError, closeClient } from '../common/client';
+import { closeMappers } from '../common/mappers';
-export const verifySignature = (
- signatureKey?: string, // hex-encoded key
- timestamp?: string, // 'close-sig-timestamp' header
- rawBody?: any, // raw body as string
- signatureHash?: string, // 'close-sig-hash' header
-): boolean => {
- if (!signatureKey || !timestamp || !rawBody || !signatureHash) {
- return false;
- }
-
- try {
- const dataToHmac = timestamp + rawBody;
-
- const generatedHash = crypto
- .createHmac('sha256', Buffer.from(signatureKey, 'hex'))
- .update(dataToHmac, 'utf8')
- .digest('hex');
-
- return crypto.timingSafeEqual(
- Buffer.from(generatedHash, 'hex'),
- Buffer.from(signatureHash, 'hex'),
- );
- } catch (error) {
- return false;
- }
+const HOUR_MS = 60 * 60 * 1000;
+const SEEN_RETENTION_HOURS = 73;
+const MAX_BUCKETS_PER_RUN = 24;
+
+export const verifySignature = ({ signatureKey, timestamp, rawBody, signatureHash }: { signatureKey?: string; timestamp?: string; rawBody?: unknown; signatureHash?: string }): boolean => {
+ if (!signatureKey || !timestamp || !signatureHash || rawBody === undefined || rawBody === null) return false;
+ const body = typeof rawBody === 'string' ? rawBody : Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : '';
+ if (body === '' || !/^[0-9a-f]+$/i.test(signatureHash)) return false;
+ try {
+ const generated = crypto.createHmac('sha256', Buffer.from(signatureKey, 'hex')).update(timestamp + body, 'utf8').digest();
+ const received = Buffer.from(signatureHash, 'hex');
+ return received.length === generated.length && crypto.timingSafeEqual(generated, received);
+ } catch {
+ return false;
+ }
};
+
+export function closeCreatedTriggerHooks({ storeKey, objectType }: CreatedTriggerParams) {
+ return {
+ async onEnable(context: CloseHookContext) {
+ const created = await closeClient.request<{ id?: string; signature_key?: string }>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: '/webhook/',
+ body: { url: context.webhookUrl, events: [{ object_type: objectType, action: 'created' }] },
+ });
+ if (typeof created?.id !== 'string' || typeof created.signature_key !== 'string') {
+ throw new Error('Close did not return a webhook ID and signature key.');
+ }
+ try {
+ await context.store.put<WebhookState>(storeKey, { id: created.id, signatureKey: created.signature_key });
+ } catch (error) {
+ await deleteWebhook({ auth: context.auth, id: created.id }).catch(() => undefined);
+ throw error;
+ }
+ },
+ async onDisable(context: CloseHookContext) {
+ const state = await context.store.get<WebhookState>(storeKey);
+ if (state?.id) await deleteWebhook({ auth: context.auth, id: state.id });
+ await clearSeen({ store: context.store, storeKey });
+ await context.store.delete(storeKey);
+ await context.store.delete(`${storeKey}-seen`);
+ },
+ async run(context: CloseHookContext) {
+ const state = await context.store.get<WebhookState>(storeKey);
+ const headers = context.payload.headers ?? {};
+ if (!verifySignature({ signatureKey: state?.signatureKey, timestamp: headers['close-sig-timestamp'], rawBody: context.payload.rawBody, signatureHash: headers['close-sig-hash'] })) {
+ return [];
+ }
+ const event = closeClient.isRecord(context.payload.body) ? context.payload.body['event'] : undefined;
+ if (!closeClient.isRecord(event) || event['object_type'] !== objectType || event['action'] !== 'created') return [];
+ const objectId = typeof event['object_id'] === 'string' ? event['object_id'] : closeClient.isRecord(event['data']) && typeof event['data']['id'] === 'string' ? event['data']['id'] : undefined;
+ if (!objectId) return [];
+ const eventId = typeof event['id'] === 'string' ? event['id'] : objectId;
+ const seenKey = `${storeKey}-seen:${eventId}`;
+ if (await context.store.get<boolean>(seenKey)) return [];
+ const record = await closeClient.request({ auth: context.auth, method: HttpMethod.GET, path: `/${objectType}/${closeClient.pathId(objectId)}/` });
+ await context.store.put(seenKey, true);
+ await recordSeen({ store: context.store, storeKey, eventId, now: Date.now() }).catch(() => undefined);
+ const output = closeMappers.withCustomMap({ objectType, record });
+ return [closeClient.isRecord(output) ? { ...output, [DEDUPE_KEY_PROPERTY]: `close:${objectType}:${eventId}` } : output];
+ },
+ };
+}
+
+async function recordSeen({ store, storeKey, eventId, now }: { store: CloseStore; storeKey: string; eventId: string; now: number }): Promise<void> {
+ const hour = hourOf(now);
+ const ids = idsOf(await store.get<unknown>(bucketKey({ storeKey, hour })));
+ if (!ids.includes(eventId)) await store.put(bucketKey({ storeKey, hour }), [...ids, eventId]);
+ const hours = hoursOf(await store.get<unknown>(`${storeKey}-seen-hours`));
+ const expired = hours.filter((h) => h < hour - SEEN_RETENTION_HOURS).slice(0, MAX_BUCKETS_PER_RUN);
+ for (const h of expired) {
+ await deleteBucket({ store, storeKey, hour: h });
+ }
+ const kept = hours.filter((h) => !expired.includes(h) && h !== hour);
+ if (expired.length > 0 || !hours.includes(hour)) await store.put(`${storeKey}-seen-hours`, [...kept, hour]);
+}
+
+async function clearSeen({ store, storeKey }: { store: CloseStore; storeKey: string }): Promise<void> {
+ const hours = hoursOf(await store.get<unknown>(`${storeKey}-seen-hours`));
+ for (const h of hours) {
+ await deleteBucket({ store, storeKey, hour: h });
+ }
+ await store.delete(`${storeKey}-seen-hours`);
+}
+
+async function deleteBucket({ store, storeKey, hour }: { store: CloseStore; storeKey: string; hour: number }): Promise<void> {
+ const ids = idsOf(await store.get<unknown>(bucketKey({ storeKey, hour })));
+ await Promise.all(ids.map((id) => store.delete(`${storeKey}-seen:${id}`)));
+ await store.delete(bucketKey({ storeKey, hour }));
+}
+
+function hourOf(now: number): number {
+ return Math.floor(now / HOUR_MS);
+}
+
+function bucketKey({ storeKey, hour }: { storeKey: string; hour: number }): string {
+ return `${storeKey}-seen-hour:${hour}`;
+}
+
+function hoursOf(value: unknown): number[] {
+ return Array.isArray(value) ? value.filter((h): h is number => Number.isInteger(h)) : [];
+}
+
+function idsOf(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
+}
+
+async function deleteWebhook({ auth, id }: { auth: { secret_text: string }; id: string }): Promise<void> {
+ try {
+ await closeClient.request({ auth, method: HttpMethod.DELETE, path: `/webhook/${closeClient.pathId(id)}/` });
+ } catch (error) {
+ if (error instanceof CloseApiError && error.status === 404) return;
+ throw error;
+ }
+}
+
+type CloseStore = CloseHookContext['store'];
+
+type WebhookState = { id: string; signatureKey: string };
+
+type CreatedTriggerParams = {
+ storeKey: string;
+ objectType: 'lead' | 'contact' | 'opportunity';
+};
+
+type CloseHookContext = TriggerHookContext<typeof closeAuth, Record<string, never>, TriggerStrategy.WEBHOOK>;
diff --git a/packages/pieces/community/close/src/lib/triggers/new-contact-added.ts b/packages/pieces/community/close/src/lib/triggers/new-contact-added.ts
index e4d3132427f..fafc49d7535 100644
--- a/packages/pieces/community/close/src/lib/triggers/new-contact-added.ts
+++ b/packages/pieces/community/close/src/lib/triggers/new-contact-added.ts
@@ -1,94 +1,19 @@
-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { closeOutputSchemas } from '../common/output-schemas';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { closeAuth } from '../auth';
-import { CloseCRMContactWebhookPayload } from '../common/types';
-import { closeApiCall } from '../common/client';
-import { verifySignature } from './helpers';
-
-const TRIGGER_KEY = 'new-contact-trigger';
+import { closeCreatedTriggerHooks } from './helpers';
export const newContactAdded = createTrigger({
auth: closeAuth,
name: 'new_contact_added',
- classification: 'READ',
displayName: 'New Contact Added',
description: 'Triggers when a new contact is created.',
- aiMetadata: {
- description: 'Fires when a new contact (person) is created in Close CRM, via a registered webhook on the contact-created event. Emits the full contact record, including its parent lead ID. Use to react whenever a person is added to the CRM.',
- },
+ aiMetadata: { description: 'Fires when a new contact (person) is created in Close CRM, via a registered webhook on the contact-created event. Emits the full contact record, including its parent lead ID. Use to react whenever a person is added to the CRM. Close retries failed deliveries for up to 72 hours; repeated deliveries of the same event are ignored.' },
+ classification: 'READ',
type: TriggerStrategy.WEBHOOK,
props: {},
- async onEnable(context) {
- const response = await closeApiCall<{ id: string; signature_key: string }>({
- accessToken: context.auth.secret_text,
- method: HttpMethod.POST,
- resourceUri: '/webhook/',
- body: {
- url: context.webhookUrl,
- events: [
- {
- object_type: 'contact',
- action: 'created',
- },
- ],
- },
- });
-
- const { id, signature_key: signatureKey } = response;
- await context.store.put<{ id: string; signatureKey: string }>(TRIGGER_KEY, {
- id,
- signatureKey,
- });
- },
-
- async onDisable(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- if (triggerData?.id) {
- await closeApiCall({
- method: HttpMethod.DELETE,
- accessToken: context.auth.secret_text,
- resourceUri: `/webhook/${triggerData.id}`,
- });
- }
-
- await context.store.delete(TRIGGER_KEY);
- },
-
- async run(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- const signatureKey = triggerData?.signatureKey;
- const signatureHash = context.payload.headers['close-sig-hash'];
- const timestamp = context.payload.headers['close-sig-timestamp'];
- const rawBody = context.payload.rawBody;
-
- if (!verifySignature(signatureKey, timestamp, rawBody, signatureHash)) {
- return [];
- }
-
- const payload = context.payload.body as CloseCRMContactWebhookPayload;
-
- // Verify this is a lead creation event
- if (payload.event.object_type !== 'contact' || payload.event.action !== 'created') {
- return [];
- }
-
- const contact = await closeApiCall({
- accessToken: context.auth.secret_text,
- method: HttpMethod.GET,
- resourceUri: `/contact/${payload.event.data.id}/`,
- });
-
- return [contact];
- },
-
+ outputSchema: closeOutputSchemas.raw.contact,
+ ...closeCreatedTriggerHooks({ storeKey: 'new-contact-trigger', objectType: 'contact' }),
sampleData: {
created_by: 'user_QO3f0LQE6fMbrokdE2awZLgT7pRv57S1C8Zv5Uo30TN',
date_created: '2025-05-30T15:29:16.048000+00:00',
diff --git a/packages/pieces/community/close/src/lib/triggers/new-lead-added.ts b/packages/pieces/community/close/src/lib/triggers/new-lead-added.ts
index 55f18eeb656..2139bbf3c90 100644
--- a/packages/pieces/community/close/src/lib/triggers/new-lead-added.ts
+++ b/packages/pieces/community/close/src/lib/triggers/new-lead-added.ts
@@ -1,94 +1,19 @@
-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { closeOutputSchemas } from '../common/output-schemas';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { closeAuth } from '../auth';
-import { CloseCRMLeadWebhookPayload } from '../common/types';
-import { closeApiCall } from '../common/client';
-import { verifySignature } from './helpers';
-
-const TRIGGER_KEY = 'new-lead-trigger';
+import { closeCreatedTriggerHooks } from './helpers';
export const newLeadAdded = createTrigger({
auth: closeAuth,
name: 'new_lead_created',
- classification: 'READ',
displayName: 'New Lead Created',
description: 'Triggers when a new lead is created.',
- aiMetadata: {
- description: 'Fires when a new lead (company/account) is created in Close CRM, via a registered webhook on the lead-created event. Emits the full lead record. Use to start a flow whenever a prospect or account enters the CRM.',
- },
+ aiMetadata: { description: 'Fires when a new lead (company/account) is created in Close CRM, via a registered webhook on the lead-created event. Emits the full lead record. Use to start a flow whenever a prospect or account enters the CRM. Close retries failed deliveries for up to 72 hours; repeated deliveries of the same event are ignored.' },
+ classification: 'READ',
type: TriggerStrategy.WEBHOOK,
props: {},
- async onEnable(context) {
- const response = await closeApiCall<{ id: string; signature_key: string }>({
- accessToken: context.auth.secret_text,
- method: HttpMethod.POST,
- resourceUri: '/webhook/',
- body: {
- url: context.webhookUrl,
- events: [
- {
- object_type: 'lead',
- action: 'created',
- },
- ],
- },
- });
-
- const { id, signature_key: signatureKey } = response;
- await context.store.put<{ id: string; signatureKey: string }>(TRIGGER_KEY, {
- id,
- signatureKey,
- });
- },
-
- async onDisable(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- if (triggerData?.id) {
- await closeApiCall({
- method: HttpMethod.DELETE,
- accessToken: context.auth.secret_text,
- resourceUri: `/webhook/${triggerData.id}`,
- });
- }
-
- await context.store.delete(TRIGGER_KEY);
- },
-
- async run(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- const signatureKey = triggerData?.signatureKey;
- const signatureHash = context.payload.headers['close-sig-hash'];
- const timestamp = context.payload.headers['close-sig-timestamp'];
- const rawBody = context.payload.rawBody;
-
- if (!verifySignature(signatureKey, timestamp, rawBody, signatureHash)) {
- return [];
- }
-
- const payload = context.payload.body as CloseCRMLeadWebhookPayload;
-
- // Verify this is a lead creation event
- if (payload.event.object_type !== 'lead' || payload.event.action !== 'created') {
- return [];
- }
-
- const lead = await closeApiCall({
- accessToken: context.auth.secret_text ,
- method: HttpMethod.GET,
- resourceUri: `/lead/${payload.event.data.id}/`,
- });
-
- return [lead];
- },
-
+ outputSchema: closeOutputSchemas.raw.lead,
+ ...closeCreatedTriggerHooks({ storeKey: 'new-lead-trigger', objectType: 'lead' }),
sampleData: {
addresses: [],
contacts: [
diff --git a/packages/pieces/community/close/src/lib/triggers/new-opportunity.ts b/packages/pieces/community/close/src/lib/triggers/new-opportunity.ts
index 65e622858c5..8c7fcfc039a 100644
--- a/packages/pieces/community/close/src/lib/triggers/new-opportunity.ts
+++ b/packages/pieces/community/close/src/lib/triggers/new-opportunity.ts
@@ -1,94 +1,19 @@
-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { closeOutputSchemas } from '../common/output-schemas';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { closeAuth } from '../auth';
-import { CloseCRMOpportunityWebhookPayload } from '../common/types';
-import { closeApiCall } from '../common/client';
-import { verifySignature } from './helpers';
-
-const TRIGGER_KEY = 'new-opportunity-trigger';
+import { closeCreatedTriggerHooks } from './helpers';
export const newOpportunityAdded = createTrigger({
auth: closeAuth,
name: 'new_opportunity_added',
- classification: 'READ',
displayName: 'New Opportunity Added',
description: 'Triggers when a new opportunity is created.',
- aiMetadata: {
- description: 'Fires when a new opportunity (sales deal) is created in Close CRM, via a registered webhook on the opportunity-created event. Emits the full opportunity record, including its lead ID, value, and status. Use to react whenever a deal is opened.',
- },
+ aiMetadata: { description: 'Fires when a new opportunity (sales deal) is created in Close CRM, via a registered webhook on the opportunity-created event. Emits the full opportunity record, including its lead ID, value, and status. Use to react whenever a deal is opened. Close retries failed deliveries for up to 72 hours; repeated deliveries of the same event are ignored.' },
+ classification: 'READ',
type: TriggerStrategy.WEBHOOK,
props: {},
- async onEnable(context) {
- const response = await closeApiCall<{ id: string; signature_key: string }>({
- accessToken: context.auth.secret_text,
- method: HttpMethod.POST,
- resourceUri: '/webhook/',
- body: {
- url: context.webhookUrl,
- events: [
- {
- object_type: 'opportunity',
- action: 'created',
- },
- ],
- },
- });
-
- const { id, signature_key: signatureKey } = response;
- await context.store.put<{ id: string; signatureKey: string }>(TRIGGER_KEY, {
- id,
- signatureKey,
- });
- },
-
- async onDisable(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- if (triggerData?.id) {
- await closeApiCall({
- method: HttpMethod.DELETE,
- accessToken: context.auth.secret_text,
- resourceUri: `/webhook/${triggerData.id}`,
- });
- }
-
- await context.store.delete(TRIGGER_KEY);
- },
-
- async run(context) {
- const triggerData = await context.store.get<{
- id: string;
- signatureKey: string;
- }>(TRIGGER_KEY);
-
- const signatureKey = triggerData?.signatureKey;
- const signatureHash = context.payload.headers['close-sig-hash'];
- const timestamp = context.payload.headers['close-sig-timestamp'];
- const rawBody = context.payload.rawBody;
-
- if (!verifySignature(signatureKey, timestamp, rawBody, signatureHash)) {
- return [];
- }
-
- const payload = context.payload.body as CloseCRMOpportunityWebhookPayload;
-
- // Verify this is a lead creation event
- if (payload.event.object_type !== 'opportunity' || payload.event.action !== 'created') {
- return [];
- }
-
- const opportunity = await closeApiCall({
- accessToken: context.auth.secret_text ,
- method: HttpMethod.GET,
- resourceUri: `/opportunity/${payload.event.data.id}/`,
- });
-
- return [opportunity];
- },
-
+ outputSchema: closeOutputSchemas.raw.opportunity,
+ ...closeCreatedTriggerHooks({ storeKey: 'new-opportunity-trigger', objectType: 'opportunity' }),
sampleData: {
annualized_expected_value: 500,
annualized_value: 1000,
diff --git a/packages/pieces/community/close/test/activities-c.test.ts b/packages/pieces/community/close/test/activities-c.test.ts
new file mode 100644
index 00000000000..ff9ed847b85
--- /dev/null
+++ b/packages/pieces/community/close/test/activities-c.test.ts
@@ -0,0 +1,126 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createNote } from '../src/lib/actions/ai/create-note';
+import { deleteActivity } from '../src/lib/actions/ai/delete-activity';
+import { getActivity } from '../src/lib/actions/ai/get-activity';
+import { listActivities } from '../src/lib/actions/ai/list-activities';
+import { logCall } from '../src/lib/actions/ai/log-call';
+import { logEmail } from '../src/lib/actions/ai/log-email';
+import { sendSms } from '../src/lib/actions/ai/send-sms';
+import { updateNote } from '../src/lib/actions/ai/update-note';
+
+const auth = { secret_text: 'api_secret' };
+const BASE = 'https://api.close.com/api/v1';
+
+function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }) {
+ return Reflect.apply(Reflect.get(action, 'run'), undefined, [{ auth, propsValue }]);
+}
+
+function mock(body: unknown) {
+ return vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body });
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('metadata', () => {
+ it.each([createNote, updateNote, logCall, logEmail, sendSms, listActivities, getActivity, deleteActivity])('$name is ai with schema', (a) => {
+ expect(a.audience).toBe('ai');
+ expect(a.outputSchema).toBeDefined();
+ expect(a.aiMetadata?.description).toBeTruthy();
+ });
+ it('classifies by side effect', () => {
+ expect(deleteActivity.classification).toBe('DESTRUCTIVE');
+ expect(listActivities.classification).toBe('SEARCH');
+ expect(sendSms.classification).toBe('WRITE');
+ expect(sendSms.aiMetadata?.description).toMatch(/real SMS/);
+ });
+});
+
+describe('notes', () => {
+ it('creates a note', async () => {
+ const spy = mock({ id: 'acti_1', _type: 'Note', note: 'hi', lead_id: 'lead_1' });
+ const out = await run({ action: createNote, propsValue: { leadId: ' lead_1 ', note: 'hi' } });
+ const req = spy.mock.calls[0][0];
+ expect(req.url).toBe(`${BASE}/activity/note/`);
+ expect(req.method).toBe(HttpMethod.POST);
+ expect(req.body).toEqual({ lead_id: 'lead_1', note: 'hi' });
+ expect(out).toMatchObject({ id: 'acti_1', type: 'Note', text: 'hi', leadId: 'lead_1' });
+ });
+ it('rejects a bad lead id', async () => {
+ await expect(run({ action: createNote, propsValue: { leadId: 'cont_1', note: 'x' } })).rejects.toThrow('lead_');
+ });
+ it('updates a note', async () => {
+ const spy = mock({ id: 'acti_1', note: 'new' });
+ await run({ action: updateNote, propsValue: { noteId: 'acti_1', note: 'new' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ url: `${BASE}/activity/note/acti_1/`, method: HttpMethod.PUT, body: { note: 'new' } });
+ });
+});
+
+describe('logging', () => {
+ it('logs a completed call', async () => {
+ const spy = mock({ id: 'acti_2', _type: 'Call', duration: 60 });
+ const out = await run({ action: logCall, propsValue: { leadId: 'lead_1', direction: 'inbound', durationSeconds: 60, phone: '+16505551234' } });
+ expect(spy.mock.calls[0][0].body).toEqual({ lead_id: 'lead_1', status: 'completed', direction: 'inbound', duration: 60, phone: '+16505551234' });
+ expect(out).toMatchObject({ durationSeconds: 60 });
+ });
+ it('rejects a negative duration', async () => {
+ await expect(run({ action: logCall, propsValue: { leadId: 'lead_1', durationSeconds: -1 } })).rejects.toThrow('whole number');
+ });
+ it('logs a sent email with status sent', async () => {
+ const spy = mock({ id: 'acti_3', _type: 'Email' });
+ await run({ action: logEmail, propsValue: { leadId: 'lead_1', direction: 'sent', subject: 'S', bodyText: 'B', to: ['[email protected]'] } });
+ expect(spy.mock.calls[0][0].body).toEqual({ lead_id: 'lead_1', status: 'sent', subject: 'S', body_text: 'B', to: ['[email protected]'] });
+ });
+ it('logs a received email with status inbox and requires sender', async () => {
+ await expect(run({ action: logEmail, propsValue: { leadId: 'lead_1', direction: 'received', subject: 'S', bodyText: 'B' } })).rejects.toThrow('Sender');
+ const spy = mock({ id: 'acti_4' });
+ await run({ action: logEmail, propsValue: { leadId: 'lead_1', direction: 'received', subject: 'S', bodyText: 'B', sender: '[email protected]' } });
+ expect(spy.mock.calls[0][0].body).toMatchObject({ status: 'inbox', sender: '[email protected]' });
+ });
+});
+
+describe('sms', () => {
+ it('sends with status outbox', async () => {
+ const spy = mock({ id: 'acti_5', _type: 'SMS', status: 'outbox', text: 'yo', remote_phone: '+15555550100' });
+ const out = await run({ action: sendSms, propsValue: { leadId: 'lead_1', localPhone: '+1 (650) 555-1234', remotePhone: '+15555550100', text: 'yo' } });
+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/activity/sms/`);
+ expect(spy.mock.calls[0][0].body).toEqual({ lead_id: 'lead_1', status: 'outbox', direction: 'outbound', local_phone: '+16505551234', remote_phone: '+15555550100', text: 'yo' });
+ expect(out).toMatchObject({ status: 'outbox', phone: '+15555550100' });
+ });
+ it('rejects non-E.164 numbers before sending', async () => {
+ const spy = mock({});
+ await expect(run({ action: sendSms, propsValue: { leadId: 'lead_1', localPhone: '6505551234', remotePhone: '+15555550100', text: 'x' } })).rejects.toThrow('E.164');
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('read and delete', () => {
+ it('lists activities for a lead with type filter', async () => {
+ const spy = mock({ data: [{ id: 'acti_1', _type: 'Call' }], has_more: true });
+ const out = await run({ action: listActivities, propsValue: { leadId: 'lead_1', type: 'call', limit: 10 } });
+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/activity/`);
+ expect(spy.mock.calls[0][0].queryParams).toEqual({ lead_id: 'lead_1', _type: 'Call', _limit: '10', _skip: '0' });
+ expect(out).toMatchObject({ count: 1, hasMore: true, nextSkip: 1 });
+ });
+ it('refuses type filter without lead', async () => {
+ await expect(run({ action: listActivities, propsValue: { type: 'note' } })).rejects.toThrow('Lead ID');
+ });
+ it('gets an sms by type', async () => {
+ const spy = mock({ id: 'acti_9', _type: 'SMS' });
+ await run({ action: getActivity, propsValue: { activityType: 'sms', activityId: 'acti_9' } });
+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/activity/sms/acti_9/`);
+ });
+ it('rejects unknown types', async () => {
+ await expect(run({ action: getActivity, propsValue: { activityType: 'task', activityId: 'acti_9' } })).rejects.toThrow('Activity Type');
+ });
+ it('deletes a call', async () => {
+ const spy = mock({});
+ const out = await run({ action: deleteActivity, propsValue: { activityType: 'call', activityId: 'acti_2' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ url: `${BASE}/activity/call/acti_2/`, method: HttpMethod.DELETE });
+ expect(out).toEqual({ deleted: true, id: 'acti_2' });
+ });
+ it('surfaces a 404 on delete', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(Object.assign(new Error('http'), { response: { status: 404, body: { error: 'Not found' }, headers: {} } }));
+ await expect(run({ action: deleteActivity, propsValue: { activityType: 'note', activityId: 'acti_2' } })).rejects.toThrow('404');
+ });
+});
diff --git a/packages/pieces/community/close/test/close.test.ts b/packages/pieces/community/close/test/close.test.ts
new file mode 100644
index 00000000000..7007196953f
--- /dev/null
+++ b/packages/pieces/community/close/test/close.test.ts
@@ -0,0 +1,411 @@
+import crypto from 'crypto';
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { close } from '../src';
+import { closeAuth } from '../src/lib/auth';
+import { CloseApiError, closeClient } from '../src/lib/common/client';
+import { closeMappers } from '../src/lib/common/mappers';
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { verifySignature } from '../src/lib/triggers/helpers';
+
+const auth = { secret_text: 'api_secret' };
+
+function ok(body: unknown) {
+ return { status: 200, headers: {}, body };
+}
+
+function httpFailure({ status, body }: { status: number; body: unknown }) {
+ return Object.assign(new Error('http'), { response: { status, body, headers: {} } });
+}
+
+function mockSeq(...bodies: unknown[]) {
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ for (const b of bodies) {
+ if (b instanceof Error) spy.mockRejectedValueOnce(b);
+ else spy.mockResolvedValueOnce(ok(b));
+ }
+ return spy;
+}
+
+function action(name: string) {
+ const found = close.actions()[name];
+ if (!found) throw new Error(`missing ${name}`);
+ return found;
+}
+
+function run({ name, propsValue = {} }: { name: string; propsValue?: Record<string, unknown> }) {
+ return Reflect.apply(action(name).run, undefined, [{ auth, propsValue }]);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe('metadata', () => {
+ it('ai actions have outputSchema, aiMetadata and no dropdowns', () => {
+ for (const a of Object.values(close.actions())) {
+ if (a.audience !== 'ai') continue;
+ expect(a.outputSchema, a.name).toBeDefined();
+ expect(a.aiMetadata?.description, a.name).toBeTruthy();
+ for (const p of Object.values(a.props)) {
+ expect(['DROPDOWN', 'MULTI_SELECT_DROPDOWN', 'DYNAMIC']).not.toContain(Reflect.get(p, 'type'));
+ }
+ }
+ });
+ it('every action and trigger declares a non-empty outputSchema (except the generated custom API call)', () => {
+ const actions = Object.values(close.actions()).filter((a) => a.name !== 'custom_api_call');
+ const items = [...actions, ...Object.values(close.triggers())];
+ expect(actions.length).toBe(Object.keys(close.actions()).length - 1);
+ expect(items.length).toBeGreaterThan(0);
+ for (const item of items) {
+ expect(item.outputSchema?.fields?.length, item.name).toBeGreaterThan(0);
+ }
+ });
+
+ it('legacy actions are human only', () => {
+ for (const name of ['create_lead', 'create_contact', 'create_opportunity', 'find_lead', 'find_contact']) {
+ expect(action(name).audience, name).toBe('human');
+ }
+ });
+ it('no two ai actions share a name', () => {
+ const names = Object.values(close.actions()).map((a) => a.name);
+ expect(new Set(names).size).toBe(names.length);
+ });
+});
+
+describe('client', () => {
+ it('sends basic auth to the Close API with query params', async () => {
+ const spy = mockSeq({ id: 'user_1' });
+ await closeClient.request({ auth, method: HttpMethod.GET, path: '/me/', query: { _fields: 'id', skip: undefined } });
+ const req = spy.mock.calls[0][0];
+ expect(req.url).toBe('https://api.close.com/api/v1/me/');
+ expect(req.authentication).toEqual({ type: 'BASIC', username: 'api_secret', password: '' });
+ expect(req.queryParams).toEqual({ _fields: 'id' });
+ expect(req.followRedirects).toBe(false);
+ });
+ it('accepts a plain string key and rejects an empty one', async () => {
+ mockSeq({});
+ await closeClient.request({ auth: ' k ', method: HttpMethod.GET, path: '/me/' });
+ await expect(closeClient.request({ auth: ' ', method: HttpMethod.GET, path: '/me/' })).rejects.toThrow('no API key');
+ });
+ it('refuses absolute and traversal paths', async () => {
+ const spy = mockSeq();
+ await expect(closeClient.request({ auth, method: HttpMethod.GET, path: 'https://evil.io/x' })).rejects.toThrow();
+ await expect(closeClient.request({ auth, method: HttpMethod.GET, path: '//evil.io/x' })).rejects.toThrow();
+ await expect(closeClient.request({ auth, method: HttpMethod.GET, path: '/lead/../me/' })).rejects.toThrow();
+ expect(spy).not.toHaveBeenCalled();
+ });
+ it('surfaces the Close error and field errors', async () => {
+ mockSeq(httpFailure({ status: 400, body: { error: 'Invalid lead', 'field-errors': { name: 'required' } } }));
+ const err = await closeClient.request({ auth, method: HttpMethod.POST, path: '/lead/', body: {} }).catch((e) => e);
+ expect(err).toBeInstanceOf(CloseApiError);
+ expect(err.status).toBe(400);
+ expect(err.message).toContain('Invalid lead');
+ expect(err.message).toContain('name: required');
+ });
+ it('retries 429 with capped rate_reset wait, then succeeds', async () => {
+ vi.useFakeTimers();
+ const spy = mockSeq(httpFailure({ status: 429, body: { error: { rate_reset: 9999, message: 'slow down' } } }), { ok: true });
+ const promise = closeClient.request({ auth, method: HttpMethod.GET, path: '/me/' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ await expect(promise).resolves.toEqual({ ok: true });
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+ it('gives up after two 429 retries', async () => {
+ vi.useFakeTimers();
+ const limited = () => httpFailure({ status: 429, body: { rate_reset: 0.1 } });
+ mockSeq(limited(), limited(), limited());
+ const promise = closeClient.request({ auth, method: HttpMethod.GET, path: '/me/' }).catch((e) => e);
+ await vi.advanceTimersByTimeAsync(1000);
+ const err = await promise;
+ expect(err).toBeInstanceOf(CloseApiError);
+ expect(err.status).toBe(429);
+ });
+ it('listPage passes _skip/_limit and reports nextSkip', async () => {
+ const spy = mockSeq({ data: [{ id: 'a' }, { id: 'b' }], has_more: true });
+ const page = await closeClient.listPage({ auth, path: '/lead/', limit: 500, skip: 10 });
+ expect(spy.mock.calls[0][0].queryParams).toEqual({ _limit: '100', _skip: '10' });
+ expect(page).toEqual({ items: [{ id: 'a' }, { id: 'b' }], hasMore: true, nextSkip: 12 });
+ });
+ it('listAll stops at maxItems and reports truncation', async () => {
+ mockSeq({ data: [{ id: 1 }, { id: 2 }], has_more: true }, { data: [{ id: 3 }], has_more: true });
+ const all = await closeClient.listAll({ auth, path: '/lead/', maxItems: 3 });
+ expect(all).toEqual({ items: [{ id: 1 }, { id: 2 }, { id: 3 }], truncated: true });
+ const again = await (async () => {
+ mockSeq({ data: [{ id: 1 }], has_more: false });
+ return closeClient.listAll({ auth, path: '/lead/' });
+ })();
+ expect(again.truncated).toBe(false);
+ });
+ it('searchPage posts the query with cursor and fields', async () => {
+ const spy = mockSeq({ data: [{ id: 'lead_1' }], cursor: 'c2' });
+ const page = await closeClient.searchPage({ auth, query: { type: 'and', queries: [] }, fields: { lead: ['id'] }, cursor: 'c1', limit: 5 });
+ expect(spy.mock.calls[0][0].body).toEqual({ query: { type: 'and', queries: [] }, _limit: 5, cursor: 'c1', _fields: { lead: ['id'] } });
+ expect(page).toEqual({ items: [{ id: 'lead_1' }], hasMore: true, nextCursor: 'c2' });
+ });
+ it('validates inputs', () => {
+ expect(closeClient.closeId({ value: ' lead_abc ', label: 'Lead ID', prefix: 'lead' })).toBe('lead_abc');
+ expect(() => closeClient.closeId({ value: 'cont_abc', label: 'Lead ID', prefix: 'lead' })).toThrow('lead_');
+ expect(() => closeClient.closeId({ value: 'lead/../x', label: 'Lead ID' })).toThrow();
+ expect(closeClient.parseInteger({ value: '50', label: 'C', min: 0, max: 100 })).toBe(50);
+ expect(() => closeClient.parseInteger({ value: 101, label: 'C', min: 0, max: 100 })).toThrow();
+ expect(closeClient.parseBoolean({ value: ['true'], label: 'B' })).toBe(true);
+ expect(closeClient.customFieldsBody({ value: '{"cf_abc":1,"custom.cf_def":"x"}' })).toEqual({ 'custom.cf_abc': 1, 'custom.cf_def': 'x' });
+ expect(() => closeClient.customFieldsBody({ value: { name: 'x' } })).toThrow('cf_');
+ expect(closeClient.isoDate({ value: '2026-10-18', label: 'D' })).toBe('2026-10-18');
+ });
+});
+
+describe('mappers', () => {
+ it('maps a lead with custom fields and contacts', () => {
+ const lead = closeMappers.lead({
+ id: 'lead_1',
+ display_name: 'Acme',
+ 'custom.cf_x': 'y',
+ contacts: [{ id: 'cont_1', name: 'Jo', emails: [{ email: '[email protected]', type: 'office' }] }],
+ });
+ expect(lead.name).toBe('Acme');
+ expect(lead.custom).toEqual({ cf_x: 'y' });
+ expect(lead.contacts[0].primaryEmail).toBe('[email protected]');
+ expect(lead.appUrl).toBe('https://app.close.com/lead/lead_1/');
+ });
+ it('keeps opportunity value in cents', () => {
+ expect(closeMappers.opportunity({ id: 'oppo_1', value: 340000 }).valueCents).toBe(340000);
+ });
+});
+
+describe('auth', () => {
+ const validate = (key: string) => Reflect.apply(closeAuth.validate!, undefined, [{ auth: key }]);
+ it('calls GET /me/', async () => {
+ const spy = mockSeq({ id: 'user_1' });
+ await expect(validate('k')).resolves.toEqual({ valid: true });
+ expect(spy.mock.calls[0][0].url).toBe('https://api.close.com/api/v1/me/');
+ });
+ it('says invalid credentials only on 401', async () => {
+ mockSeq(httpFailure({ status: 401, body: { error: 'Unauthorized' } }));
+ expect((await validate('k')).error).toContain('Invalid credentials');
+ mockSeq(httpFailure({ status: 500, body: 'boom' }));
+ expect((await validate('k')).error).not.toContain('Invalid credentials');
+ });
+});
+
+describe('webhook triggers', () => {
+ const key = crypto.randomBytes(32).toString('hex');
+ const sign = ({ ts, body }: { ts: string; body: string }) => crypto.createHmac('sha256', Buffer.from(key, 'hex')).update(ts + body).digest('hex');
+
+ it('verifies signatures', () => {
+ const body = '{"a":1}';
+ expect(verifySignature({ signatureKey: key, timestamp: '123', rawBody: body, signatureHash: sign({ ts: '123', body: body }) })).toBe(true);
+ expect(verifySignature({ signatureKey: key, timestamp: '123', rawBody: body, signatureHash: sign({ ts: '124', body: body }) })).toBe(false);
+ expect(verifySignature({ signatureKey: key, timestamp: '123', rawBody: body, signatureHash: 'zz' })).toBe(false);
+ });
+
+ function makeStore(initial: Record<string, unknown> = {}) {
+ const data: Record<string, unknown> = { ...initial };
+ return {
+ data,
+ get: async (k: string) => data[k],
+ put: async (k: string, v: unknown) => {
+ data[k] = v;
+ },
+ delete: async (k: string) => {
+ delete data[k];
+ },
+ };
+ }
+
+ it('fetches the record once per event id', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const store = makeStore({ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key } });
+ const body = { event: { id: 'ev_1', object_type: 'lead', action: 'created', object_id: 'lead_1', data: { id: 'lead_1' } } };
+ const raw = JSON.stringify(body);
+ const payload = { body, rawBody: raw, headers: { 'close-sig-timestamp': '1', 'close-sig-hash': sign({ ts: '1', body: raw }) } };
+ const spy = mockSeq({ id: 'lead_1' });
+ const first = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload }]);
+ expect(first).toEqual([{ id: 'lead_1', [DEDUPE_KEY_PROPERTY]: 'close:lead:ev_1' }]);
+ expect(store.data['new-lead-trigger-seen:ev_1']).toBe(true);
+ expect(spy.mock.calls[0][0].url).toBe('https://api.close.com/api/v1/lead/lead_1/');
+ const second = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload }]);
+ expect(second).toEqual([]);
+ });
+
+ function delivery({ eventId, objectType, objectId }: { eventId: string; objectType: string; objectId: string }) {
+ const body = { event: { id: eventId, object_type: objectType, action: 'created', object_id: objectId } };
+ const raw = JSON.stringify(body);
+ return { body, rawBody: raw, headers: { 'close-sig-timestamp': '1', 'close-sig-hash': sign({ ts: '1', body: raw }) } };
+ }
+
+ it('overlapping deliveries of different events keep both seen markers', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const store = makeStore({ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key } });
+ mockSeq({ id: 'lead_1' }, { id: 'lead_2' });
+ await Promise.all([
+ Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_a', objectType: 'lead', objectId: 'lead_1' }) }]),
+ Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_b', objectType: 'lead', objectId: 'lead_2' }) }]),
+ ]);
+ expect(store.data['new-lead-trigger-seen:ev_a']).toBe(true);
+ expect(store.data['new-lead-trigger-seen:ev_b']).toBe(true);
+ const retry = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_a', objectType: 'lead', objectId: 'lead_1' }) }]);
+ expect(retry).toEqual([]);
+ });
+
+ it('a retry is still ignored after more than 200 newer events', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const store = makeStore({ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key } });
+ mockSeq(...Array.from({ length: 202 }, (_, i) => ({ id: `lead_${i}` })));
+ for (let i = 0; i < 202; i++) {
+ await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: `ev_${i}`, objectType: 'lead', objectId: `lead_${i}` }) }]);
+ }
+ const retry = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_0', objectType: 'lead', objectId: 'lead_0' }) }]);
+ expect(retry).toEqual([]);
+ });
+
+ it('drops event markers older than the retry window and clears them on disable', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const hour = Math.floor(Date.now() / 3600000);
+ const store = makeStore({
+ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key },
+ 'new-lead-trigger-seen:ev_old': true,
+ [`new-lead-trigger-seen-hour:${hour - 74}`]: ['ev_old'],
+ 'new-lead-trigger-seen-hours': [hour - 74],
+ });
+ mockSeq({ id: 'lead_1' });
+ await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_new', objectType: 'lead', objectId: 'lead_1' }) }]);
+ expect(store.data['new-lead-trigger-seen:ev_old']).toBeUndefined();
+ expect(store.data[`new-lead-trigger-seen-hour:${hour - 74}`]).toBeUndefined();
+ expect(store.data['new-lead-trigger-seen:ev_new']).toBe(true);
+ expect(store.data[`new-lead-trigger-seen-hour:${hour}`]).toEqual(['ev_new']);
+ expect(store.data['new-lead-trigger-seen-hours']).toEqual([hour]);
+ mockSeq({});
+ await Reflect.apply(trigger.onDisable, undefined, [{ auth, store }]);
+ expect(Object.keys(store.data).filter((k) => k.includes('-seen'))).toEqual([]);
+ });
+
+ it('onDisable clears buckets left by a trigger that went quiet long ago', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const hour = Math.floor(Date.now() / 3600000);
+ const store = makeStore({
+ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key },
+ 'new-lead-trigger-seen:ev_q': true,
+ [`new-lead-trigger-seen-hour:${hour - 500}`]: ['ev_q'],
+ 'new-lead-trigger-seen-hours': [hour - 500],
+ });
+ const get = vi.fn(store.get);
+ store.get = get;
+ mockSeq({});
+ await Reflect.apply(trigger.onDisable, undefined, [{ auth, store }]);
+ expect(Object.keys(store.data).filter((k) => k.includes('-seen'))).toEqual([]);
+ expect(get.mock.calls.length).toBeLessThan(5);
+ });
+
+ it('a failing index write does not block the run', async () => {
+ const trigger = close.triggers()['new_lead_created'];
+ const store = makeStore({ 'new-lead-trigger': { id: 'whsub_1', signatureKey: key } });
+ const put = store.put;
+ store.put = async (k: string, v: unknown) => {
+ if (k.includes('-seen-hour:')) throw new Error('value too large');
+ await put(k, v);
+ };
+ mockSeq({ id: 'lead_1' });
+ const out = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_x', objectType: 'lead', objectId: 'lead_1' }) }]);
+ expect(out).toHaveLength(1);
+ expect(store.data['new-lead-trigger-seen:ev_x']).toBe(true);
+ });
+
+ it('opportunity and contact records expose custom.cf_ values under custom', async () => {
+ const trigger = close.triggers()['new_opportunity_added'];
+ const store = makeStore({ 'new-opportunity-trigger': { id: 'whsub_1', signatureKey: key } });
+ mockSeq({ id: 'oppo_1', 'custom.cf_abc': 'Gold' });
+ const out = await Reflect.apply(trigger.run, undefined, [{ auth, store, payload: delivery({ eventId: 'ev_o', objectType: 'opportunity', objectId: 'oppo_1' }) }]);
+ expect(out[0]['custom.cf_abc']).toBe('Gold');
+ expect(out[0].custom).toEqual({ cf_abc: 'Gold' });
+ const fields = (schema: unknown) => (Reflect.get(Object(schema), 'fields') ?? []).map((f: { key: string }) => f.key);
+ expect(fields(trigger.outputSchema)).toContain('custom');
+ expect(fields(close.triggers()['new_contact_added'].outputSchema)).toContain('custom');
+ expect(closeMappers.withCustomMap({ objectType: 'contact', record: { id: 'cont_1', 'custom.cf_x': 1 } })).toEqual({ id: 'cont_1', 'custom.cf_x': 1, custom: { cf_x: 1 } });
+ });
+
+ it('update actions send an explicit empty string to clear text fields', async () => {
+ const spy = mockSeq({ id: 'lead_1' }, { id: 'cont_1' }, { id: 'oppo_1' });
+ await run({ name: 'update_lead', propsValue: { leadId: 'lead_1', description: '', url: '' } });
+ await run({ name: 'update_contact', propsValue: { contactId: 'cont_1', title: '' } });
+ await run({ name: 'update_opportunity', propsValue: { opportunityId: 'oppo_1', note: '' } });
+ expect(spy.mock.calls[0][0].body).toEqual({ description: '', url: '' });
+ expect(spy.mock.calls[1][0].body).toEqual({ title: '' });
+ expect(spy.mock.calls[2][0].body).toEqual({ note: '' });
+ await expect(run({ name: 'update_lead', propsValue: { leadId: 'lead_1' } })).rejects.toThrow('Pass at least one field');
+ });
+
+ it('onDisable treats 404 as deleted and keeps state on other errors', async () => {
+ const trigger = close.triggers()['new_contact_added'];
+ const store = makeStore({ 'new-contact-trigger': { id: 'whsub_1', signatureKey: key } });
+ mockSeq(httpFailure({ status: 500, body: 'x' }));
+ await expect(Reflect.apply(trigger.onDisable, undefined, [{ auth, store }])).rejects.toThrow();
+ expect(store.data['new-contact-trigger']).toBeDefined();
+ const spy = mockSeq(httpFailure({ status: 404, body: {} }));
+ await Reflect.apply(trigger.onDisable, undefined, [{ auth, store }]);
+ expect(spy.mock.calls[0][0].url).toBe('https://api.close.com/api/v1/webhook/whsub_1/');
+ expect(store.data['new-contact-trigger']).toBeUndefined();
+ });
+
+ it('onEnable deletes the webhook when the store write fails', async () => {
+ const trigger = close.triggers()['new_opportunity_added'];
+ const store = { ...makeStore(), put: async () => { throw new Error('store down'); } };
+ const spy = mockSeq({ id: 'whsub_9', signature_key: key }, {});
+ await expect(Reflect.apply(trigger.onEnable, undefined, [{ auth, store, webhookUrl: 'https://hook' }])).rejects.toThrow('store down');
+ expect(spy.mock.calls[0][0].body).toEqual({ url: 'https://hook', events: [{ object_type: 'opportunity', action: 'created' }] });
+ expect(spy.mock.calls[1][0].method).toBe(HttpMethod.DELETE);
+ });
+});
+
+describe('legacy actions', () => {
+ it('find_contact by lead id uses a reference condition', async () => {
+ const spy = mockSeq({ data: [{ id: 'cont_1' }], cursor: null });
+ const out = await run({ name: 'find_contact', propsValue: { search_type: 'lead_id', search_query: 'lead_1', match_type: 'exact' } });
+ expect(out.found).toBe(true);
+ const cond = spy.mock.calls[0][0].body.query.queries[1].condition;
+ expect(cond).toEqual({ type: 'reference', reference_type: 'lead', object_ids: ['lead_1'] });
+ });
+ it('find_lead applies the exact match mode', async () => {
+ const spy = mockSeq({ data: [], cursor: null });
+ await run({ name: 'find_lead', propsValue: { search_type: 'name', search_query: 'Acme Inc', match_type: 'exact' } });
+ expect(spy.mock.calls[0][0].body.query.queries[1].condition.mode).toBe('phrase');
+ });
+ it.each([
+ ['find_contact', 'email', '[email protected]'],
+ ['find_contact', 'phone', '+15550100'],
+ ['find_lead', 'contact_email', '[email protected]'],
+ ])('%s by %s keeps phrase matching on the default match type', async (name, search_type, search_query) => {
+ const spy = mockSeq({ data: [], cursor: null });
+ await run({ name, propsValue: { search_type, search_query, match_type: 'contains' } });
+ const body = JSON.stringify(spy.mock.calls[0][0].body);
+ expect(body).toContain('"mode":"phrase"');
+ expect(body).not.toContain('full_words');
+ });
+ it('find_lead by status resolves an exact label to a status reference', async () => {
+ const statuses = { data: [{ id: 'stat_pot', label: 'Potential' }, { id: 'stat_bad', label: 'Bad Fit' }] };
+ const spy = mockSeq(statuses, { data: [{ id: 'lead_1' }], cursor: null });
+ const out = await run({ name: 'find_lead', propsValue: { search_type: 'status', search_query: 'Potential', match_type: 'exact' } });
+ expect(out.found).toBe(true);
+ expect(spy.mock.calls[0][0].url).toContain('/status/lead/');
+ expect(spy.mock.calls[1][0].body.query.queries[1].condition).toEqual({ type: 'reference', reference_type: 'status.lead', object_ids: ['stat_pot'] });
+ });
+ it('find_lead by status contains matches label substrings case-insensitively', async () => {
+ const statuses = { data: [{ id: 'stat_pot', label: 'Potential' }, { id: 'stat_pot2', label: 'Very Potential' }, { id: 'stat_bad', label: 'Bad Fit' }] };
+ const spy = mockSeq(statuses, { data: [], cursor: null });
+ await run({ name: 'find_lead', propsValue: { search_type: 'status', search_query: 'potent', match_type: 'contains' } });
+ expect(spy.mock.calls[1][0].body.query.queries[1].condition.object_ids).toEqual(['stat_pot', 'stat_pot2']);
+ });
+ it('find_lead by status returns found false without searching when no label matches', async () => {
+ const spy = mockSeq({ data: [{ id: 'stat_pot', label: 'Potential' }] });
+ const out = await run({ name: 'find_lead', propsValue: { search_type: 'status', search_query: 'Nope', match_type: 'exact' } });
+ expect(out).toEqual({ found: false, result: [] });
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+ it('create_opportunity rejects confidence above 100 before calling Close', async () => {
+ const spy = mockSeq();
+ await expect(run({ name: 'create_opportunity', propsValue: { lead_id: 'lead_1', status_id: 'stat_1', confidence: 150 } })).rejects.toThrow('Confidence');
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/close/test/config-sequences-d.test.ts b/packages/pieces/community/close/test/config-sequences-d.test.ts
new file mode 100644
index 00000000000..e8948f01f99
--- /dev/null
+++ b/packages/pieces/community/close/test/config-sequences-d.test.ts
@@ -0,0 +1,210 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { getCurrentUser } from '../src/lib/actions/ai/get-current-user';
+import { listUsers } from '../src/lib/actions/ai/list-users';
+import { listLeadStatuses } from '../src/lib/actions/ai/list-lead-statuses';
+import { listPipelines } from '../src/lib/actions/ai/list-pipelines';
+import { listCustomFields } from '../src/lib/actions/ai/list-custom-fields';
+import { listCustomActivityTypes } from '../src/lib/actions/ai/list-custom-activity-types';
+import { listSmartViews } from '../src/lib/actions/ai/list-smart-views';
+import { listSequences } from '../src/lib/actions/ai/list-sequences';
+import { subscribeContactToSequence } from '../src/lib/actions/ai/subscribe-contact-to-sequence';
+import { listSequenceSubscriptions } from '../src/lib/actions/ai/list-sequence-subscriptions';
+import { pauseSequenceSubscription } from '../src/lib/actions/ai/pause-sequence-subscription';
+
+const auth = { secret_text: 'api_secret' };
+
+const all = [
+ getCurrentUser,
+ listUsers,
+ listLeadStatuses,
+ listPipelines,
+ listCustomFields,
+ listCustomActivityTypes,
+ listSmartViews,
+ listSequences,
+ subscribeContactToSequence,
+ listSequenceSubscriptions,
+ pauseSequenceSubscription,
+];
+
+function mockSeq(...bodies: unknown[]) {
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ for (const body of bodies) spy.mockResolvedValueOnce({ status: 200, headers: {}, body });
+ return spy;
+}
+
+function run({ action, propsValue = {} }: { action: (typeof all)[number]; propsValue?: Record<string, unknown> }) {
+ return Reflect.apply(action.run, undefined, [{ auth, propsValue }]);
+}
+
+function sent(spy: ReturnType<typeof mockSeq>) {
+ return spy.mock.calls[0][0];
+}
+
+const subscription = {
+ id: 'sub_1',
+ sequence_id: 'seq_1',
+ contact_id: 'cont_1',
+ lead_id: 'lead_1',
+ contact_email: '[email protected]',
+ sender_account_id: 'emailacct_1',
+ sender_name: 'John',
+ sender_email: '[email protected]',
+ status: 'active',
+ status_reason: null,
+ calls_assigned_to: ['user_1'],
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('group D metadata', () => {
+ it('all are ai actions with outputSchema, aiMetadata and unique names', () => {
+ const names = new Set<string>();
+ for (const a of all) {
+ expect(a.audience, a.name).toBe('ai');
+ expect(a.outputSchema, a.name).toBeDefined();
+ expect(a.aiMetadata?.description, a.name).toBeTruthy();
+ expect(names.has(a.name)).toBe(false);
+ names.add(a.name);
+ }
+ expect(names.size).toBe(11);
+ });
+ it('classifications match side effects', () => {
+ expect(getCurrentUser.classification).toBe('READ');
+ expect(subscribeContactToSequence.classification).toBe('WRITE');
+ expect(pauseSequenceSubscription.classification).toBe('WRITE');
+ for (const a of [listUsers, listLeadStatuses, listPipelines, listCustomFields, listCustomActivityTypes, listSmartViews, listSequences, listSequenceSubscriptions]) {
+ expect(a.classification, a.name).toBe('SEARCH');
+ }
+ });
+});
+
+describe('get_current_user', () => {
+ it('requests only safe fields and never returns keys', async () => {
+ const spy = mockSeq({
+ id: 'user_1',
+ email: '[email protected]',
+ first_name: 'Ann',
+ last_name: 'Lee',
+ organizations: [{ id: 'orga_1' }],
+ api_key: 'secret_should_not_leak',
+ email_accounts: [{ id: 'emailacct_1', _type: 'google', identities: [{ email: '[email protected]', name: 'Ann' }], oauth_token: 'tok' }],
+ });
+ const out = await run({ action: getCurrentUser });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/me/');
+ expect(sent(spy).queryParams?._fields).toBe('id,email,first_name,last_name,organizations,date_created,email_accounts');
+ expect(out).toMatchObject({ id: 'user_1', name: 'Ann Lee', organizationIds: ['orga_1'], emailAccounts: [{ id: 'emailacct_1', type: 'google', emails: ['[email protected]'] }] });
+ expect(JSON.stringify(out)).not.toMatch(/secret_should_not_leak|tok"/);
+ });
+});
+
+describe('list actions', () => {
+ it('list_users pages with limit and skip', async () => {
+ const spy = mockSeq({ data: [{ id: 'user_1', first_name: 'A' }], has_more: true });
+ const out = await run({ action: listUsers, propsValue: { limit: 1, skip: 5 } });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/user/');
+ expect(sent(spy).queryParams).toMatchObject({ _limit: '1', _skip: '5' });
+ expect(out).toMatchObject({ count: 1, hasMore: true, nextSkip: 6 });
+ });
+ it('list_users rejects a bad limit', async () => {
+ await expect(run({ action: listUsers, propsValue: { limit: 500 } })).rejects.toThrow(/Limit/);
+ });
+ it('list_lead_statuses', async () => {
+ const spy = mockSeq({ data: [{ id: 'stat_1', label: 'Potential' }], has_more: false });
+ const out = await run({ action: listLeadStatuses });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/status/lead/');
+ expect(out).toMatchObject({ items: [{ id: 'stat_1', label: 'Potential' }], hasMore: false });
+ });
+ it('list_pipelines maps statuses', async () => {
+ mockSeq({ data: [{ id: 'pipe_1', name: 'Sales', statuses: [{ id: 'stat_w', label: 'Won', type: 'won' }] }], has_more: false });
+ const out = await run({ action: listPipelines });
+ expect(out).toMatchObject({ items: [{ id: 'pipe_1', statuses: [{ id: 'stat_w', type: 'won' }] }] });
+ });
+ it('list_custom_fields uses the object type path and validates it', async () => {
+ const spy = mockSeq({ data: [{ id: 'cf_1', name: 'Owner', type: 'user', choices: ['a'] }], has_more: false });
+ const out = await run({ action: listCustomFields, propsValue: { objectType: 'opportunity' } });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/custom_field/opportunity/');
+ expect(out).toMatchObject({ items: [{ id: 'cf_1', choices: ['a'] }] });
+ await expect(run({ action: listCustomFields, propsValue: { objectType: '../x' } })).rejects.toThrow(/Object Type/);
+ });
+ it('list_custom_activity_types handles a response without has_more', async () => {
+ const spy = mockSeq({ data: [{ id: 'actitype_1', name: 'Signup', fields: [{ id: 'cf_1', name: 'Email', required: true }] }] });
+ const out = await run({ action: listCustomActivityTypes });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/custom_activity/');
+ expect(out).toMatchObject({ count: 1, items: [{ id: 'actitype_1', fields: [{ id: 'cf_1', required: true }] }] });
+ });
+ it('list_smart_views defaults type to lead', async () => {
+ const spy = mockSeq({ data: [{ id: 'save_1', name: 'All Leads', type: 'lead', is_shared: true }], has_more: false });
+ const out = await run({ action: listSmartViews });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/saved_search/');
+ expect(sent(spy).queryParams).toMatchObject({ type: 'lead' });
+ expect(out).toMatchObject({ items: [{ id: 'save_1', isShared: true }] });
+ });
+ it('list_sequences maps steps', async () => {
+ const spy = mockSeq({ data: [{ id: 'seq_1', name: 'S', status: 'active', steps: [{ id: 'seqstep_1', step_type: 'email', delay: 86400 }] }], has_more: false });
+ const out = await run({ action: listSequences });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/sequence/');
+ expect(out).toMatchObject({ items: [{ id: 'seq_1', stepCount: 1, steps: [{ stepType: 'email', delaySeconds: 86400 }] }] });
+ });
+});
+
+describe('sequence subscriptions', () => {
+ const subscribeProps = {
+ sequenceId: 'seq_1',
+ contactId: 'cont_1',
+ contactEmail: '[email protected]',
+ senderAccountId: 'emailacct_1',
+ senderName: 'John',
+ senderEmail: '[email protected]',
+ callsAssignedTo: ['user_1'],
+ };
+ it('subscribe posts the documented body', async () => {
+ const spy = mockSeq(subscription);
+ const out = await run({ action: subscribeContactToSequence, propsValue: subscribeProps });
+ expect(sent(spy).method).toBe(HttpMethod.POST);
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/sequence_subscription/');
+ expect(sent(spy).body).toEqual({
+ sequence_id: 'seq_1',
+ contact_id: 'cont_1',
+ contact_email: '[email protected]',
+ sender_account_id: 'emailacct_1',
+ sender_name: 'John',
+ sender_email: '[email protected]',
+ calls_assigned_to: ['user_1'],
+ });
+ expect(out).toMatchObject({ id: 'sub_1', status: 'active', callsAssignedTo: ['user_1'] });
+ });
+ it('subscribe validates IDs and emails before calling Close', async () => {
+ const spy = mockSeq(subscription);
+ await expect(run({ action: subscribeContactToSequence, propsValue: { ...subscribeProps, sequenceId: 'cont_1' } })).rejects.toThrow(/seq_/);
+ await expect(run({ action: subscribeContactToSequence, propsValue: { ...subscribeProps, senderEmail: 'nope' } })).rejects.toThrow(/email/);
+ expect(spy).not.toHaveBeenCalled();
+ });
+ it('list subscriptions requires a filter', async () => {
+ const spy = mockSeq({ data: [], has_more: false });
+ await expect(run({ action: listSequenceSubscriptions })).rejects.toThrow(/at least one/);
+ expect(spy).not.toHaveBeenCalled();
+ });
+ it('list subscriptions filters by contact', async () => {
+ const spy = mockSeq({ data: [subscription], has_more: false });
+ const out = await run({ action: listSequenceSubscriptions, propsValue: { contactId: 'cont_1' } });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/sequence_subscription/');
+ expect(sent(spy).queryParams).toMatchObject({ contact_id: 'cont_1' });
+ expect(sent(spy).queryParams?.sequence_id).toBeUndefined();
+ expect(out).toMatchObject({ count: 1, items: [{ id: 'sub_1' }] });
+ });
+ it('pause sends PUT status paused', async () => {
+ const spy = mockSeq({ ...subscription, status: 'paused', status_reason: 'manual' });
+ const out = await run({ action: pauseSequenceSubscription, propsValue: { subscriptionId: 'sub_1' } });
+ expect(sent(spy).method).toBe(HttpMethod.PUT);
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/sequence_subscription/sub_1/');
+ expect(sent(spy).body).toEqual({ status: 'paused' });
+ expect(out).toMatchObject({ status: 'paused', statusReason: 'manual' });
+ });
+ it('pause rejects a non-subscription ID', async () => {
+ await expect(run({ action: pauseSequenceSubscription, propsValue: { subscriptionId: '../x' } })).rejects.toThrow(/Subscription ID/);
+ });
+});
diff --git a/packages/pieces/community/close/test/leads-contacts-a.test.ts b/packages/pieces/community/close/test/leads-contacts-a.test.ts
new file mode 100644
index 00000000000..6662626ccb6
--- /dev/null
+++ b/packages/pieces/community/close/test/leads-contacts-a.test.ts
@@ -0,0 +1,173 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createContactAi } from '../src/lib/actions/ai/create-contact-ai';
+import { createLeadAi } from '../src/lib/actions/ai/create-lead-ai';
+import { deleteContact } from '../src/lib/actions/ai/delete-contact';
+import { deleteLead } from '../src/lib/actions/ai/delete-lead';
+import { getContact } from '../src/lib/actions/ai/get-contact';
+import { getLead } from '../src/lib/actions/ai/get-lead';
+import { mergeLeads } from '../src/lib/actions/ai/merge-leads';
+import { searchContacts } from '../src/lib/actions/ai/search-contacts';
+import { searchLeads } from '../src/lib/actions/ai/search-leads';
+import { updateContact } from '../src/lib/actions/ai/update-contact';
+import { updateLead } from '../src/lib/actions/ai/update-lead';
+
+const auth = { secret_text: 'api_key' };
+const BASE = 'https://api.close.com/api/v1';
+
+function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }) {
+ return Reflect.apply(Reflect.get(action, 'run'), undefined, [{ auth, propsValue }]);
+}
+
+function mock(...bodies: unknown[]) {
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ for (const body of bodies) spy.mockResolvedValueOnce({ status: 200, headers: {}, body });
+ return spy;
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+const all = [createLeadAi, getLead, updateLead, deleteLead, searchLeads, mergeLeads, createContactAi, getContact, updateContact, deleteContact, searchContacts];
+
+describe('metadata', () => {
+ it.each(all)('$name is ai with schema', (a) => {
+ expect(a.audience).toBe('ai');
+ expect(a.outputSchema).toBeDefined();
+ expect(a.aiMetadata?.description).toBeTruthy();
+ });
+ it('uses the planned names', () => {
+ expect(all.map((a) => a.name)).toEqual(['create_lead_ai', 'get_lead', 'update_lead', 'delete_lead', 'search_leads', 'merge_leads', 'create_contact_ai', 'get_contact', 'update_contact', 'delete_contact', 'search_contacts']);
+ });
+});
+
+describe('leads', () => {
+ it('creates a lead with a nested contact and custom fields', async () => {
+ const spy = mock({ id: 'lead_1', display_name: 'Acme', status_label: 'Potential' });
+ const out = await run({ action: createLeadAi, propsValue: { name: ' Acme ', statusId: 'stat_1', contactName: 'Jo', contactEmail: '[email protected]', customFields: { cf_a: 'x' } } });
+ const req = spy.mock.calls[0][0];
+ expect(req.method).toBe(HttpMethod.POST);
+ expect(req.url).toBe(`${BASE}/lead/`);
+ expect(req.body).toEqual({ name: 'Acme', status_id: 'stat_1', contacts: [{ name: 'Jo', emails: [{ email: '[email protected]', type: 'office' }] }], 'custom.cf_a': 'x' });
+ expect(out).toMatchObject({ id: 'lead_1', name: 'Acme', appUrl: 'https://app.close.com/lead/lead_1/' });
+ });
+ it('creates a lead without contacts', async () => {
+ const spy = mock({ id: 'lead_1' });
+ await run({ action: createLeadAi, propsValue: { name: 'Acme' } });
+ expect(spy.mock.calls[0][0].body).toEqual({ name: 'Acme' });
+ });
+ it('rejects a bad status id', async () => {
+ await expect(run({ action: createLeadAi, propsValue: { name: 'A', statusId: 'lead_1' } })).rejects.toThrow('stat_');
+ });
+ it('gets a lead', async () => {
+ const spy = mock({ id: 'lead_1', name: 'Acme', contacts: [{ id: 'cont_1', emails: [{ email: '[email protected]' }] }] });
+ const out = await run({ action: getLead, propsValue: { leadId: 'lead_1' } });
+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/lead/lead_1/`);
+ expect(out.contacts[0]).toMatchObject({ id: 'cont_1', primaryEmail: '[email protected]' });
+ });
+ it('rejects a path-traversal lead id', async () => {
+ await expect(run({ action: getLead, propsValue: { leadId: '../me' } })).rejects.toThrow('Close ID');
+ });
+ it('updates only given lead fields', async () => {
+ const spy = mock({ id: 'lead_1' });
+ await run({ action: updateLead, propsValue: { leadId: 'lead_1', statusId: 'stat_2', customFields: { 'custom.cf_b': null } } });
+ const req = spy.mock.calls[0][0];
+ expect(req.method).toBe(HttpMethod.PUT);
+ expect(req.url).toBe(`${BASE}/lead/lead_1/`);
+ expect(req.body).toEqual({ status_id: 'stat_2', 'custom.cf_b': null });
+ });
+ it('refuses an empty lead update', async () => {
+ await expect(run({ action: updateLead, propsValue: { leadId: 'lead_1' } })).rejects.toThrow('at least one');
+ });
+ it('deletes a lead', async () => {
+ const spy = mock({});
+ const out = await run({ action: deleteLead, propsValue: { leadId: 'lead_1' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ method: HttpMethod.DELETE, url: `${BASE}/lead/lead_1/` });
+ expect(out).toEqual({ deleted: true, id: 'lead_1' });
+ });
+ it('merges leads and returns the destination', async () => {
+ const spy = mock({}, { id: 'lead_d', name: 'Kept' });
+ const out = await run({ action: mergeLeads, propsValue: { sourceLeadId: 'lead_s', destinationLeadId: 'lead_d' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ method: HttpMethod.POST, url: `${BASE}/lead/merge/`, body: { source: 'lead_s', destination: 'lead_d' } });
+ expect(spy.mock.calls[1][0].url).toBe(`${BASE}/lead/lead_d/`);
+ expect(out).toMatchObject({ mergedSourceId: 'lead_s', id: 'lead_d', name: 'Kept' });
+ });
+ it('refuses merging a lead into itself', async () => {
+ await expect(run({ action: mergeLeads, propsValue: { sourceLeadId: 'lead_1', destinationLeadId: 'lead_1' } })).rejects.toThrow('different');
+ });
+ it('searches leads by text and status', async () => {
+ const spy = mock({ data: [{ id: 'lead_1', display_name: 'Acme' }], cursor: 'c2' });
+ const out = await run({ action: searchLeads, propsValue: { text: 'acme', exactPhrase: true, statusId: 'stat_1', limit: 10 } });
+ const req = spy.mock.calls[0][0];
+ expect(req.url).toBe(`${BASE}/data/search/`);
+ expect(req.body).toMatchObject({
+ _limit: 10,
+ query: { type: 'and', queries: [
+ { type: 'object_type', object_type: 'lead' },
+ { type: 'text', value: 'acme', mode: 'phrase' },
+ { type: 'field_condition', condition: { type: 'reference', object_ids: ['stat_1'] } },
+ ] },
+ });
+ expect(out).toMatchObject({ count: 1, hasMore: true, nextCursor: 'c2', items: [{ id: 'lead_1', name: 'Acme' }] });
+ });
+ it('passes the cursor and defaults limit', async () => {
+ const spy = mock({ data: [], cursor: null });
+ const out = await run({ action: searchLeads, propsValue: { cursor: 'c2' } });
+ expect(spy.mock.calls[0][0].body).toMatchObject({ _limit: 25, cursor: 'c2' });
+ expect(out).toMatchObject({ count: 0, hasMore: false, nextCursor: null });
+ });
+ it('rejects an out-of-range limit', async () => {
+ await expect(run({ action: searchLeads, propsValue: { limit: 500 } })).rejects.toThrow('1 to 100');
+ });
+});
+
+describe('contacts', () => {
+ it('creates a contact on a lead', async () => {
+ const spy = mock({ id: 'cont_1', lead_id: 'lead_1', name: 'Jo' });
+ const out = await run({ action: createContactAi, propsValue: { leadId: 'lead_1', name: 'Jo', email: '[email protected]', phone: '+15550100' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({
+ method: HttpMethod.POST,
+ url: `${BASE}/contact/`,
+ body: { name: 'Jo', lead_id: 'lead_1', emails: [{ email: '[email protected]', type: 'office' }], phones: [{ phone: '+15550100', type: 'office' }] },
+ });
+ expect(out).toMatchObject({ id: 'cont_1', leadId: 'lead_1' });
+ });
+ it('requires a name', async () => {
+ await expect(run({ action: createContactAi, propsValue: { name: ' ' } })).rejects.toThrow('Name is required');
+ });
+ it('gets a contact', async () => {
+ const spy = mock({ id: 'cont_1', phones: [{ phone: '+1', phone_formatted: '+1', type: 'mobile' }], 'custom.cf_x': 'v' });
+ const out = await run({ action: getContact, propsValue: { contactId: 'cont_1' } });
+ expect(spy.mock.calls[0][0].url).toBe(`${BASE}/contact/cont_1/`);
+ expect(out).toMatchObject({ primaryPhone: '+1', custom: { cf_x: 'v' } });
+ });
+ it('updates a contact replacing emails', async () => {
+ const spy = mock({ id: 'cont_1' });
+ await run({ action: updateContact, propsValue: { contactId: 'cont_1', title: 'CEO', email: '[email protected]' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ method: HttpMethod.PUT, url: `${BASE}/contact/cont_1/`, body: { title: 'CEO', emails: [{ email: '[email protected]', type: 'office' }] } });
+ });
+ it('refuses an empty contact update', async () => {
+ await expect(run({ action: updateContact, propsValue: { contactId: 'cont_1' } })).rejects.toThrow('at least one');
+ });
+ it('deletes a contact', async () => {
+ const spy = mock({});
+ const out = await run({ action: deleteContact, propsValue: { contactId: 'cont_1' } });
+ expect(spy.mock.calls[0][0]).toMatchObject({ method: HttpMethod.DELETE, url: `${BASE}/contact/cont_1/` });
+ expect(out).toEqual({ deleted: true, id: 'cont_1' });
+ });
+ it('rejects a lead id as contact id', async () => {
+ await expect(run({ action: deleteContact, propsValue: { contactId: 'lead_1' } })).rejects.toThrow('cont_');
+ });
+ it('searches contacts within a lead', async () => {
+ const spy = mock({ data: [{ id: 'cont_1', name: 'Jo' }] });
+ const out = await run({ action: searchContacts, propsValue: { text: 'jo', leadId: 'lead_1' } });
+ expect(spy.mock.calls[0][0].body).toMatchObject({
+ _fields: { contact: expect.arrayContaining(['id', 'emails']) },
+ query: { queries: [
+ { object_type: 'contact' },
+ { type: 'text', value: 'jo', mode: 'full_words' },
+ { condition: { type: 'reference', reference_type: 'lead', object_ids: ['lead_1'] } },
+ ] },
+ });
+ expect(out).toMatchObject({ count: 1, hasMore: false, items: [{ id: 'cont_1', name: 'Jo' }] });
+ });
+});
diff --git a/packages/pieces/community/close/test/opportunities-tasks-b.test.ts b/packages/pieces/community/close/test/opportunities-tasks-b.test.ts
new file mode 100644
index 00000000000..be43aa478a1
--- /dev/null
+++ b/packages/pieces/community/close/test/opportunities-tasks-b.test.ts
@@ -0,0 +1,143 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createOpportunityAi } from '../src/lib/actions/ai/create-opportunity-ai';
+import { getOpportunity } from '../src/lib/actions/ai/get-opportunity';
+import { updateOpportunity } from '../src/lib/actions/ai/update-opportunity';
+import { deleteOpportunity } from '../src/lib/actions/ai/delete-opportunity';
+import { listOpportunities } from '../src/lib/actions/ai/list-opportunities';
+import { createTask } from '../src/lib/actions/ai/create-task';
+import { getTask } from '../src/lib/actions/ai/get-task';
+import { updateTask } from '../src/lib/actions/ai/update-task';
+import { deleteTask } from '../src/lib/actions/ai/delete-task';
+import { listTasks } from '../src/lib/actions/ai/list-tasks';
+
+const auth = { secret_text: 'api_secret' };
+
+const rawOpp = { id: 'oppo_1', lead_id: 'lead_1', value: 340000, value_period: 'one_time', status_type: 'active', 'custom.cf_a': 'x' };
+const rawTask = { id: 'task_1', _type: 'lead', lead_id: 'lead_1', text: 'Call', is_complete: false };
+
+function mock(...bodies: unknown[]) {
+ const spy = vi.spyOn(httpClient, 'sendRequest');
+ for (const body of bodies) spy.mockResolvedValueOnce({ status: 200, headers: {}, body });
+ return spy;
+}
+
+function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }) {
+ return Reflect.apply(Reflect.get(action, 'run'), undefined, [{ auth, propsValue }]);
+}
+
+function sent(spy: ReturnType<typeof mock>) {
+ return spy.mock.calls[0][0];
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('metadata', () => {
+ const all = [createOpportunityAi, getOpportunity, updateOpportunity, deleteOpportunity, listOpportunities, createTask, getTask, updateTask, deleteTask, listTasks];
+ it('all are ai actions with outputSchema and aiMetadata', () => {
+ for (const a of all) {
+ expect(a.audience, a.name).toBe('ai');
+ expect(a.outputSchema, a.name).toBeDefined();
+ expect(a.aiMetadata?.description, a.name).toBeTruthy();
+ }
+ });
+ it('classifications match side effects', () => {
+ expect(createOpportunityAi.classification).toBe('WRITE');
+ expect(deleteTask.classification).toBe('DESTRUCTIVE');
+ expect(listTasks.classification).toBe('SEARCH');
+ expect(getOpportunity.classification).toBe('READ');
+ });
+});
+
+describe('opportunities', () => {
+ it('create posts integer cents and maps valueCents', async () => {
+ const spy = mock(rawOpp);
+ const out = await run({ action: createOpportunityAi, propsValue: { leadId: 'lead_1', valueCents: 340000, valuePeriod: 'one_time', expectedCloseDate: '2026-11-30', customFields: { cf_a: 'x' } } });
+ const req = sent(spy);
+ expect(req.method).toBe(HttpMethod.POST);
+ expect(req.url).toBe('https://api.close.com/api/v1/opportunity/');
+ expect(req.body).toEqual({ lead_id: 'lead_1', value: 340000, value_period: 'one_time', date_won: '2026-11-30', 'custom.cf_a': 'x' });
+ expect(out.valueCents).toBe(340000);
+ expect(out.custom).toEqual({ cf_a: 'x' });
+ });
+ it('create rejects fractional cents and bad period', async () => {
+ await expect(run({ action: createOpportunityAi, propsValue: { leadId: 'lead_1', valueCents: 12.5 } })).rejects.toThrow('Value (cents)');
+ await expect(run({ action: createOpportunityAi, propsValue: { leadId: 'lead_1', valuePeriod: 'weekly' } })).rejects.toThrow('Value Period');
+ });
+ it('get uses the opportunity path', async () => {
+ const spy = mock(rawOpp);
+ const out = await run({ action: getOpportunity, propsValue: { opportunityId: 'oppo_1' } });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/opportunity/oppo_1/');
+ expect(out.id).toBe('oppo_1');
+ });
+ it('get rejects wrong prefix', async () => {
+ await expect(run({ action: getOpportunity, propsValue: { opportunityId: 'lead_1' } })).rejects.toThrow('oppo_');
+ });
+ it('update sends only passed fields with PUT', async () => {
+ const spy = mock(rawOpp);
+ await run({ action: updateOpportunity, propsValue: { opportunityId: 'oppo_1', statusId: 'stat_won', confidence: 90 } });
+ expect(sent(spy).method).toBe(HttpMethod.PUT);
+ expect(sent(spy).body).toEqual({ status_id: 'stat_won', confidence: 90 });
+ });
+ it('update with no fields fails before calling', async () => {
+ const spy = mock();
+ await expect(run({ action: updateOpportunity, propsValue: { opportunityId: 'oppo_1' } })).rejects.toThrow('at least one');
+ expect(spy).not.toHaveBeenCalled();
+ });
+ it('delete returns deleted', async () => {
+ const spy = mock({});
+ expect(await run({ action: deleteOpportunity, propsValue: { opportunityId: 'oppo_1' } })).toEqual({ deleted: true, id: 'oppo_1' });
+ expect(sent(spy).method).toBe(HttpMethod.DELETE);
+ });
+ it('list passes filters and pages', async () => {
+ const spy = mock({ data: [rawOpp], has_more: true });
+ const out = await run({ action: listOpportunities, propsValue: { statusType: 'won', closeDateFrom: '2026-01-01', limit: 10, skip: 20 } });
+ expect(sent(spy).queryParams).toMatchObject({ status_type: 'won', date_won__gte: '2026-01-01', _limit: '10', _skip: '20' });
+ expect(out).toMatchObject({ count: 1, hasMore: true, nextSkip: 21 });
+ });
+});
+
+describe('tasks', () => {
+ it('create posts a lead task', async () => {
+ const spy = mock(rawTask);
+ const out = await run({ action: createTask, propsValue: { leadId: 'lead_1', text: ' Call ', date: '2026-10-20' } });
+ expect(sent(spy).body).toEqual({ _type: 'lead', lead_id: 'lead_1', text: 'Call', date: '2026-10-20' });
+ expect(out.isComplete).toBe(false);
+ });
+ it('create requires text', async () => {
+ await expect(run({ action: createTask, propsValue: { leadId: 'lead_1', text: ' ' } })).rejects.toThrow('Text is required');
+ });
+ it('get maps task', async () => {
+ const spy = mock(rawTask);
+ const out = await run({ action: getTask, propsValue: { taskId: 'task_1' } });
+ expect(sent(spy).url).toBe('https://api.close.com/api/v1/task/task_1/');
+ expect(out.type).toBe('lead');
+ });
+ it('update completes a task', async () => {
+ const spy = mock({ ...rawTask, is_complete: true });
+ const out = await run({ action: updateTask, propsValue: { taskId: 'task_1', isComplete: 'true' } });
+ expect(sent(spy).body).toEqual({ is_complete: true });
+ expect(out.isComplete).toBe(true);
+ });
+ it('update rejects bad boolean', async () => {
+ await expect(run({ action: updateTask, propsValue: { taskId: 'task_1', isComplete: 'yes' } })).rejects.toThrow('true or false');
+ });
+ it('delete returns deleted', async () => {
+ mock({});
+ expect(await run({ action: deleteTask, propsValue: { taskId: 'task_1' } })).toEqual({ deleted: true, id: 'task_1' });
+ });
+ it('list sends lead type by default and view', async () => {
+ const spy = mock({ data: [rawTask], has_more: false });
+ const out = await run({ action: listTasks, propsValue: { view: 'inbox', isComplete: 'false' } });
+ expect(sent(spy).queryParams).toMatchObject({ _type: 'lead', view: 'inbox', is_complete: 'false' });
+ expect(out).toMatchObject({ count: 1, hasMore: false, nextSkip: null });
+ });
+ it('list sends _type all when includeNotifications is on', async () => {
+ const spy = mock({ data: [rawTask], has_more: false });
+ await run({ action: listTasks, propsValue: { leadId: 'lead_1', includeNotifications: true } });
+ expect(sent(spy).queryParams).toMatchObject({ _type: 'all', lead_id: 'lead_1' });
+ });
+ it('list rejects bad view', async () => {
+ await expect(run({ action: listTasks, propsValue: { view: 'today' } })).rejects.toThrow('View');
+ });
+});
diff --git a/packages/pieces/community/close/vitest.config.ts b/packages/pieces/community/close/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/close/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ 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'),
+ },
+ },
+})