AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(freshsales): manage contacts, accounts, deals, tasks and appointments, and trigger flows on new and updated records (#16770)
Odai Ahmad453cd41d806e
diff --git a/bun.lock b/bun.lockindex fc63080771b..ab93831a4d3 100644--- a/bun.lock+++ b/bun.lock@@ -3573,7 +3573,7 @@},"packages/pieces/community/freshsales": {"name": "@activepieces/piece-freshsales",- "version": "0.5.2",+ "version": "0.6.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3582,6 +3582,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/freshservice": {diff --git a/packages/pieces/community/freshsales/package.json b/packages/pieces/community/freshsales/package.jsonindex 1e8b7750ce7..64e9b770aaa 100644--- a/packages/pieces/community/freshsales/package.json+++ b/packages/pieces/community/freshsales/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-freshsales",- "version": "0.5.2",+ "version": "0.6.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/freshsales/src/i18n/translation.json b/packages/pieces/community/freshsales/src/i18n/translation.jsonindex b2a29754761..146ec8b6606 100644--- a/packages/pieces/community/freshsales/src/i18n/translation.json+++ b/packages/pieces/community/freshsales/src/i18n/translation.json@@ -1,13 +1,87 @@{"Sales CRM software": "Sales CRM software","Bundle alias": "Bundle alias",- "Your Freshsales bundle alias (e.g. https://<alias>.myfreshworks.com)": "Your Freshsales bundle alias (e.g. https://<alias>.myfreshworks.com)",+ "Alias or URL, e.g. acme or https://acme.myfreshworks.com": "Alias or URL, e.g. acme or https://acme.myfreshworks.com","API Key": "API Key",- "The API Key supplied by Freshsales": "The API Key supplied by Freshsales",- "\nTo obtain your API key and bundle alias, follow these steps:\n\n1. Log in to your Freshsales account.\n2. Click on your profile icon in the top-right corner of the screen and select **Settings** from the dropdown menu.\n3. In the settings menu, select **API Settings** from the left-hand navigation panel.\n4. You should now see your API key displayed on the screen. If you don't see an API key.\n5. Copy the alias e.g **https://<alias>.myfreshworks.com**\n": "\nTo obtain your API key and bundle alias, follow these steps:\n\n1. Log in to your Freshsales account.\n2. Click on your profile icon in the top-right corner of the screen and select **Settings** from the dropdown menu.\n3. In the settings menu, select **API Settings** from the left-hand navigation panel.\n4. You should now see your API key displayed on the screen. If you don't see an API key.\n5. Copy the alias e.g **https://<alias>.myfreshworks.com**\n",+ "The API key from Settings > API Settings": "The API key from Settings > API Settings",+ "\nConnect your Freshsales (Freshworks CRM) account:\n\n1. Log in to Freshsales and look at the address bar: **https://<alias>.myfreshworks.com**. The part before `.myfreshworks.com` is your alias.\n2. Click your profile icon in the top-right corner and select **Settings**.\n3. Open **API Settings** (under Personal settings).\n4. Copy the API key shown on that page. If no key is shown, ask your Freshsales admin to enable API access for your user.\n5. Paste the alias (e.g. `acme`, or the full URL) and the API key be": "\nConnect your Freshsales (Freshworks CRM) account:\n\n1. Log in to Freshsales and look at the address bar: **https://<alias>.myfreshworks.com**. The part before `.myfreshworks.com` is your alias.\n2. Click your profile icon in the top-right corner and select **Settings**.\n3. Open **API Settings** (under Personal settings).\n4. Copy the API key shown on that page. If no key is shown, ask your Freshsales admin to enable API access for your user.\n5. Paste the alias (e.g. `acme`, or the full URL) and the API key below.\n","Create Contact": "Create Contact",+ "Update Contact": "Update Contact",+ "Create or Update Contact": "Create or Update Contact",+ "Get Contact": "Get Contact",+ "Find Contact by Email": "Find Contact by Email",+ "Delete Contact": "Delete Contact",+ "Forget Contact (GDPR)": "Forget Contact (GDPR)",+ "Create Account": "Create Account",+ "Update Account": "Update Account",+ "Get Account": "Get Account",+ "Find Account by Name": "Find Account by Name",+ "Delete Account": "Delete Account",+ "Create Deal": "Create Deal",+ "Update Deal": "Update Deal",+ "Get Deal": "Get Deal",+ "Delete Deal": "Delete Deal",+ "Search Records": "Search Records",+ "List Records in View": "List Records in View",+ "Filtered Search": "Filtered Search",+ "Create Task": "Create Task",+ "Update Task": "Update Task",+ "Get Task": "Get Task",+ "Delete Task": "Delete Task",+ "List Tasks": "List Tasks",+ "Add Note": "Add Note",+ "Update Note": "Update Note",+ "Delete Note": "Delete Note",+ "Create Appointment": "Create Appointment",+ "Get Appointment": "Get Appointment",+ "Update Appointment": "Update Appointment",+ "Delete Appointment": "Delete Appointment",+ "Log Sales Activity": "Log Sales Activity",+ "Add Contacts to Marketing List": "Add Contacts to Marketing List",+ "Remove Contacts from Marketing List": "Remove Contacts from Marketing List",+ "List Users": "List Users",+ "List Pipelines and Stages": "List Pipelines and Stages",+ "List Field Options": "List Field Options",+ "Get Fields": "Get Fields","Custom API Call": "Custom API Call","Add new contact in Freshsales CRM": "Add new contact in Freshsales CRM",+ "Update fields of an existing contact": "Update fields of an existing contact",+ "Update the contact with this email, or create it": "Update the contact with this email, or create it",+ "Get a contact by its ID": "Get a contact by its ID",+ "Look up a contact by exact email address": "Look up a contact by exact email address",+ "Delete a contact by its ID": "Delete a contact by its ID",+ "Permanently erase a contact and all its data": "Permanently erase a contact and all its data",+ "Create a new account (company)": "Create a new account (company)",+ "Update fields of an existing account": "Update fields of an existing account",+ "Get an account by its ID": "Get an account by its ID",+ "Look up accounts by exact name": "Look up accounts by exact name",+ "Delete an account by its ID": "Delete an account by its ID",+ "Create a new deal": "Create a new deal",+ "Update a deal or move it to another stage": "Update a deal or move it to another stage",+ "Get a deal by its ID": "Get a deal by its ID",+ "Delete a deal by its ID": "Delete a deal by its ID",+ "Search contacts, accounts and deals by keyword": "Search contacts, accounts and deals by keyword",+ "List contacts, accounts or deals from a saved view": "List contacts, accounts or deals from a saved view",+ "Find contacts, accounts or deals matching field filters": "Find contacts, accounts or deals matching field filters",+ "Create a task linked to a contact, account or deal": "Create a task linked to a contact, account or deal",+ "Update a task or mark it completed": "Update a task or mark it completed",+ "Get a task by its ID": "Get a task by its ID",+ "Delete a task by its ID": "Delete a task by its ID",+ "List tasks by status (open, overdue, completed...)": "List tasks by status (open, overdue, completed...)",+ "Add a note to a contact, account or deal": "Add a note to a contact, account or deal",+ "Change the text of an existing note": "Change the text of an existing note",+ "Delete a note by its ID": "Delete a note by its ID",+ "Schedule an appointment, optionally linked to a record": "Schedule an appointment, optionally linked to a record",+ "Get an appointment by its ID": "Get an appointment by its ID",+ "Change an existing appointment": "Change an existing appointment",+ "Delete a appointment by its ID": "Delete a appointment by its ID",+ "Log a call, meeting or other sales activity": "Log a call, meeting or other sales activity",+ "Add contacts to a marketing list": "Add contacts to a marketing list",+ "Remove contacts from a marketing list": "Remove contacts from a marketing list",+ "List Freshsales users (owners) with their IDs": "List Freshsales users (owners) with their IDs",+ "List deal pipelines with their stages": "List deal pipelines with their stages",+ "List options such as territories or lead sources": "List options such as territories or lead sources",+ "List the fields (incl. custom cf_ fields) of a record type": "List the fields (incl. custom cf_ fields) of a record type","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","First name": "First name","Last name": "Last name",@@ -20,18 +94,71 @@"State": "State","Zip code": "Zip code","Country": "Country",- "Territory id": "Territory id",- "Owner id": "Owner id",+ "Territory": "Territory",+ "Owner": "Owner","Subscription status": "Subscription status",+ "Contact Status": "Contact Status",+ "Lifecycle Stage": "Lifecycle Stage",+ "Lead Source": "Lead Source",+ "Sales account id": "Sales account id","Medium": "Medium",- "Campaign id": "Campaign id",+ "Campaign": "Campaign","Keyword": "Keyword","Timezone": "Timezone","Facebook": "Facebook","Twitter": "Twitter","Linkedin": "Linkedin",- "Contact status id": "Contact status id",- "Sales account id": "Sales account id",+ "Custom Fields": "Custom Fields",+ "Contact ID": "Contact ID",+ "Name": "Name",+ "Website": "Website",+ "Phone": "Phone",+ "Industry Type": "Industry Type",+ "Business Type": "Business Type",+ "Number of Employees": "Number of Employees",+ "Annual Revenue": "Annual Revenue",+ "Parent Account ID": "Parent Account ID",+ "Account ID": "Account ID",+ "Account Name": "Account Name",+ "Delete Linked Contacts and Deals": "Delete Linked Contacts and Deals",+ "Amount": "Amount",+ "Currency": "Currency",+ "Pipeline": "Pipeline",+ "Deal Stage": "Deal Stage",+ "Deal Type": "Deal Type",+ "Expected Close": "Expected Close",+ "Probability (%)": "Probability (%)",+ "Deal ID": "Deal ID",+ "Search Term": "Search Term",+ "Record Types": "Record Types",+ "Limit": "Limit",+ "Record Type": "Record Type",+ "View": "View",+ "Page": "Page",+ "Per Page": "Per Page",+ "Filters": "Filters",+ "Title": "Title",+ "Description": "Description",+ "Due Date": "Due Date",+ "Related To": "Related To",+ "Related Record ID": "Related Record ID",+ "Task ID": "Task ID",+ "Status": "Status",+ "Filter": "Filter",+ "Note": "Note",+ "Note ID": "Note ID",+ "Start": "Start",+ "End": "End",+ "Time Zone": "Time Zone",+ "Location": "Location",+ "All Day": "All Day",+ "Appointment ID": "Appointment ID",+ "Activity Type": "Activity Type",+ "Outcome": "Outcome",+ "Notes": "Notes",+ "Marketing List": "Marketing List",+ "Contact IDs": "Contact IDs",+ "Option Type": "Option Type","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -43,33 +170,154 @@"Follow redirects": "Follow redirects","First name of the contact": "First name of the contact","Last name of the contact": "Last name of the contact",- "Designation of the contact in the account they belong to": "Designation of the contact in the account they belong to",+ "Job title of the contact": "Job title of the contact","Primary email address of the contact": "Primary email address of the contact","Work phone number of the contact": "Work phone number of the contact","Mobile phone number of the contact": "Mobile phone number of the contact",- "Address of the contact": "Address of the contact",- "City that the contact belongs to": "City that the contact belongs to",- "State that the contact belongs to": "State that the contact belongs to",- "Zipcode of the region that the contact belongs to": "Zipcode of the region that the contact belongs to",- "Country that the contact belongs to": "Country that the contact belongs to",- "ID of the territory that the contact belongs to": "ID of the territory that the contact belongs to",- "ID of the user to whom the contact has been assigned": "ID of the user to whom the contact has been assigned",- "Status of subscription that the contact is in.": "Status of subscription that the contact is in.",- "The medium that led your contact to your website/web app": "The medium that led your contact to your website/web app",- "The campaign that led your contact to your web app.": "The campaign that led your contact to your web app.",- "The keywords that the contact used to reach your website/web app": "The keywords that the contact used to reach your website/web app",- "Timezone that the contact belongs to": "Timezone that the contact belongs to",+ "Street address of the contact": "Street address of the contact",+ "City of the contact": "City of the contact",+ "State of the contact": "State of the contact",+ "Zip code of the contact": "Zip code of the contact",+ "Country of the contact": "Country of the contact",+ "The territory the record belongs to": "The territory the record belongs to",+ "The Freshsales user who owns the record": "The Freshsales user who owns the record",+ "Email subscription status of the contact": "Email subscription status of the contact",+ "The status of the contact": "The status of the contact",+ "The lifecycle stage of the contact": "The lifecycle stage of the contact",+ "Where the record came from": "Where the record came from",+ "ID of the primary account of the contact": "ID of the primary account of the contact",+ "Account to make primary; other linked accounts are kept": "Account to make primary; other linked accounts are kept",+ "Medium that led the contact to you": "Medium that led the contact to you",+ "The campaign that brought the record": "The campaign that brought the record",+ "Keywords the contact used to find you": "Keywords the contact used to find you",+ "Time zone of the contact": "Time zone of the contact","Facebook username of the contact": "Facebook username of the contact","Twitter username of the contact": "Twitter username of the contact",- "LinkedIn account of the contact": "LinkedIn account of the contact",- "ID of the contact status that the contact belongs to": "ID of the contact status that the contact belongs to",- "ID of the primary account that the contact belongs to": "ID of the primary account that the contact belongs to",+ "LinkedIn profile of the contact": "LinkedIn profile of the contact",+ "Custom field values keyed by API name (cf_...)": "Custom field values keyed by API name (cf_...)",+ "ID of the contact to update": "ID of the contact to update",+ "ID of the contact to fetch": "ID of the contact to fetch",+ "Exact email address to look up": "Exact email address to look up",+ "ID of the contact to delete": "ID of the contact to delete",+ "ID of the contact to erase for good": "ID of the contact to erase for good",+ "Name of the account": "Name of the account",+ "Website of the account": "Website of the account",+ "Phone number of the account": "Phone number of the account",+ "Street address of the account": "Street address of the account",+ "City of the account": "City of the account",+ "State of the account": "State of the account",+ "Zip code of the account": "Zip code of the account",+ "Country of the account": "Country of the account",+ "Industry of the account": "Industry of the account",+ "Business type of the account": "Business type of the account",+ "Employee count": "Employee count",+ "Yearly revenue of the account": "Yearly revenue of the account",+ "ID of the parent account": "ID of the parent account",+ "ID of the account to update": "ID of the account to update",+ "ID of the account to fetch": "ID of the account to fetch",+ "Exact account name to look up": "Exact account name to look up",+ "ID of the account to delete": "ID of the account to delete",+ "Also delete the contacts and deals of this account": "Also delete the contacts and deals of this account",+ "Name of the deal": "Name of the deal",+ "Deal value": "Deal value",+ "ID of the account the deal belongs to": "ID of the account the deal belongs to",+ "Deal currency (defaults to the account currency)": "Deal currency (defaults to the account currency)",+ "The deal pipeline": "The deal pipeline",+ "Stage of the deal; pick a pipeline first to narrow it": "Stage of the deal; pick a pipeline first to narrow it",+ "The type of the deal": "The type of the deal",+ "Expected close date": "Expected close date",+ "Win probability from 0 to 100": "Win probability from 0 to 100",+ "ID of the deal to update": "ID of the deal to update",+ "ID of the deal to fetch": "ID of the deal to fetch",+ "ID of the deal to delete": "ID of the deal to delete",+ "Text to search for": "Text to search for",+ "Types to search; leave empty to search all": "Types to search; leave empty to search all",+ "Maximum results to return (1-100)": "Maximum results to return (1-100)",+ "Which records to list": "Which records to list",+ "Saved view to list; leave empty for the \"All\" view": "Saved view to list; leave empty for the \"All\" view",+ "Page number, starting at 1": "Page number, starting at 1",+ "Records per page (1-100)": "Records per page (1-100)",+ "Which records to search": "Which records to search",+ "All filters must match": "All filters must match",+ "Title of the task": "Title of the task",+ "Details of the task": "Details of the task",+ "When the task is due": "When the task is due",+ "User the task is assigned to": "User the task is assigned to",+ "Type of the record this is linked to": "Type of the record this is linked to",+ "ID of the contact, account or deal": "ID of the contact, account or deal",+ "ID of the task to update": "ID of the task to update",+ "New title of the task": "New title of the task",+ "New details of the task": "New details of the task",+ "New due date": "New due date",+ "Open or completed": "Open or completed",+ "ID of the task to fetch": "ID of the task to fetch",+ "ID of the task to delete": "ID of the task to delete",+ "Which tasks to list": "Which tasks to list",+ "Text of the note": "Text of the note",+ "ID of the note to update": "ID of the note to update",+ "New text of the note": "New text of the note",+ "ID of the note to delete": "ID of the note to delete",+ "Title of the appointment": "Title of the appointment",+ "Start date and time": "Start date and time",+ "End date and time": "End date and time",+ "Time zone of the appointment": "Time zone of the appointment",+ "Where it takes place": "Where it takes place",+ "Details of the appointment": "Details of the appointment",+ "Whether it lasts all day": "Whether it lasts all day",+ "ID of the appointment to fetch": "ID of the appointment to fetch",+ "ID of the appointment to update": "ID of the appointment to update",+ "New title of the appointment": "New title of the appointment",+ "New start date and time": "New start date and time",+ "New end date and time": "New end date and time",+ "New details of the appointment": "New details of the appointment",+ "Whether it lasts all day; leave empty to keep": "Whether it lasts all day; leave empty to keep",+ "ID of the appointment to delete": "ID of the appointment to delete",+ "Title of the activity": "Title of the activity",+ "The sales activity type": "The sales activity type",+ "Outcome of the activity (depends on the type)": "Outcome of the activity (depends on the type)",+ "User who did the activity": "User who did the activity",+ "Notes about the activity": "Notes about the activity",+ "Where it took place": "Where it took place",+ "The marketing list to change": "The marketing list to change",+ "IDs of the contacts to add": "IDs of the contacts to add",+ "IDs of the contacts to remove": "IDs of the contacts to remove",+ "Which picklist to list": "Which picklist to list",+ "Which record type to describe": "Which record type to describe","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.","On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.","Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).","Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "Unsubscribed": "Unsubscribed",+ "Subscribed": "Subscribed",+ "Reported as spam": "Reported as spam",+ "Not sure": "Not sure",+ "Contacts": "Contacts",+ "Accounts": "Accounts",+ "Deals": "Deals",+ "Contact": "Contact",+ "Account": "Account",+ "Deal": "Deal",+ "Open": "Open",+ "Completed": "Completed",+ "Due today": "Due today",+ "Due tomorrow": "Due tomorrow",+ "Overdue": "Overdue",+ "Yes": "Yes",+ "No": "No",+ "Territories": "Territories",+ "Contact Statuses": "Contact Statuses",+ "Lifecycle Stages": "Lifecycle Stages",+ "Lead Sources": "Lead Sources",+ "Campaigns": "Campaigns",+ "Currencies": "Currencies",+ "Deal Types": "Deal Types",+ "Deal Reasons": "Deal Reasons",+ "Industry Types": "Industry Types",+ "Business Types": "Business Types",+ "Sales Activity Types": "Sales Activity Types",+ "Sales Activities": "Sales Activities","GET": "GET","POST": "POST","PATCH": "PATCH",@@ -77,5 +325,15 @@"DELETE": "DELETE","HEAD": "HEAD","Request": "Request",- "Data to send": "Data to send"+ "Data to send": "Data to send",+ "New Contact": "New Contact",+ "Updated Contact": "Updated Contact",+ "New Deal": "New Deal",+ "Updated Deal": "Updated Deal",+ "New Account": "New Account",+ "Triggers when a new contact is created": "Triggers when a new contact is created",+ "Triggers when a contact is created or updated": "Triggers when a contact is created or updated",+ "Triggers when a new deal is created": "Triggers when a new deal is created",+ "Triggers when a deal is created or updated (e.g. stage change)": "Triggers when a deal is created or updated (e.g. stage change)",+ "Triggers when a new account is created": "Triggers when a new account is created"}\ No newline at end of filediff --git a/packages/pieces/community/freshsales/src/index.ts b/packages/pieces/community/freshsales/src/index.tsindex 405be1769f2..361221e595c 100644--- a/packages/pieces/community/freshsales/src/index.ts+++ b/packages/pieces/community/freshsales/src/index.ts@@ -1,44 +1,111 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- PieceAuth,- Property,- createPiece,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';-import { freshSalesCreateContact } from './lib/actions/create-contact';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { freshsalesAuth } from './lib/auth';--const markdownDescription = `-To obtain your API key and bundle alias, follow these steps:--1. Log in to your Freshsales account.-2. Click on your profile icon in the top-right corner of the screen and select **Settings** from the dropdown menu.-3. In the settings menu, select **API Settings** from the left-hand navigation panel.-4. You should now see your API key displayed on the screen. If you don't see an API key.-5. Copy the alias e.g **https://<alias>.myfreshworks.com**-`;+import { freshsalesClient } from './lib/common/client';+import { addNote } from './lib/actions/add-note';+import { createAccount } from './lib/actions/create-account';+import { createAppointment } from './lib/actions/create-appointment';+import { freshSalesCreateContact } from './lib/actions/create-contact';+import { createDeal } from './lib/actions/create-deal';+import { createTask } from './lib/actions/create-task';+import { deleteContact } from './lib/actions/delete-contact';+import { deleteDeal } from './lib/actions/delete-deal';+import { findAccountByName } from './lib/actions/find-account-by-name';+import { findContactByEmail } from './lib/actions/find-contact-by-email';+import { getAccount } from './lib/actions/get-account';+import { getContact } from './lib/actions/get-contact';+import { getCustomFields } from './lib/actions/get-custom-fields';+import { getDeal } from './lib/actions/get-deal';+import { listFieldOptions } from './lib/actions/list-field-options';+import { listPipelines } from './lib/actions/list-pipelines';+import { listRecords } from './lib/actions/list-records';+import { listTasks } from './lib/actions/list-tasks';+import { listUsers } from './lib/actions/list-users';+import { logSalesActivity } from './lib/actions/log-sales-activity';+import { searchRecords } from './lib/actions/search-records';+import { updateAccount } from './lib/actions/update-account';+import { updateContact } from './lib/actions/update-contact';+import { updateDeal } from './lib/actions/update-deal';+import { updateTask } from './lib/actions/update-task';+import { deleteAccount } from './lib/actions/delete-account';+import { forgetContact } from './lib/actions/forget-contact';+import { getTask } from './lib/actions/get-task';+import { deleteTask } from './lib/actions/delete-task';+import { updateNote } from './lib/actions/update-note';+import { deleteNote } from './lib/actions/delete-note';+import { getAppointment } from './lib/actions/get-appointment';+import { updateAppointment } from './lib/actions/update-appointment';+import { deleteAppointment } from './lib/actions/delete-appointment';+import { filteredSearch } from './lib/actions/filtered-search';+import { addContactsToList } from './lib/actions/add-contacts-to-list';+import { removeContactsFromList } from './lib/actions/remove-contacts-from-list';+import { upsertContact } from './lib/actions/upsert-contact';+import { newAccount } from './lib/triggers/new-account';+import { newContact } from './lib/triggers/new-contact';+import { newDeal } from './lib/triggers/new-deal';+import { updatedContact } from './lib/triggers/updated-contact';+import { updatedDeal } from './lib/triggers/updated-deal';export const freshsales = createPiece({displayName: 'Freshsales',description: 'Sales CRM software',-- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/freshsales.png',categories: [PieceCategory.SALES_AND_CRM],- authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud"],+ authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'OdaiAhmed99'],auth: freshsalesAuth,actions: [freshSalesCreateContact,+ updateContact,+ upsertContact,+ getContact,+ findContactByEmail,+ deleteContact,+ forgetContact,+ createAccount,+ updateAccount,+ getAccount,+ findAccountByName,+ deleteAccount,+ createDeal,+ updateDeal,+ getDeal,+ deleteDeal,+ searchRecords,+ listRecords,+ filteredSearch,+ createTask,+ updateTask,+ getTask,+ deleteTask,+ listTasks,+ addNote,+ updateNote,+ deleteNote,+ createAppointment,+ getAppointment,+ updateAppointment,+ deleteAppointment,+ logSalesActivity,+ addContactsToList,+ removeContactsFromList,+ listUsers,+ listPipelines,+ listFieldOptions,+ getCustomFields,createCustomApiCallAction({- baseUrl: (auth) =>- `https://${- (auth as { username: string }).username- }.myfreshworks.com/crm/sales/api`,+ baseUrl: (auth) => (auth ? freshsalesClient.getBaseUrl(auth.username) : ''),auth: freshsalesAuth,authMapping: async (auth) => ({- Authorization: `Token token=${(auth.password)}`,+ Authorization: `Token token=${auth.password.trim()}`,}),}),],- triggers: [],+ triggers: [+ newContact,+ updatedContact,+ newDeal,+ updatedDeal,+ newAccount,+ ],});diff --git a/packages/pieces/community/freshsales/src/lib/actions/add-contacts-to-list.ts b/packages/pieces/community/freshsales/src/lib/actions/add-contacts-to-list.tsnew file mode 100644index 00000000000..5ab471e4027--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/add-contacts-to-list.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { marketingListUpdateOutputSchema } from '../output-schemas';++export const addContactsToList = createAction({+ auth: freshsalesAuth,+ name: 'add_contacts_to_list',+ displayName: 'Add Contacts to Marketing List',+ description: 'Add contacts to a marketing list',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds one or more existing Freshsales contacts (numeric IDs) to a marketing list picked from the Marketing List options. Contacts already in the list stay there, so repeating the call is safe.',+ idempotent: true,+ },+ outputSchema: marketingListUpdateOutputSchema,+ props: {+ list_id: freshsalesProps.marketingList(),+ contact_ids: Property.Array({+ displayName: 'Contact IDs',+ description: 'IDs of the contacts to add',+ required: true,+ }),+ },+ async run(context) {+ const listId = freshsalesClient.requireId({+ value: context.propsValue.list_id,+ field: 'Marketing List',+ });+ const ids = context.propsValue.contact_ids.map((value) =>+ freshsalesClient.requireId({ value, field: 'Contact ID' })+ );+ if (ids.length === 0) {+ throw new Error('Provide at least one Contact ID.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/lists/${listId}/add_contacts`,+ body: { ids },+ });+ const message =+ freshsalesClient.isRecord(response) && typeof response['message'] === 'string'+ ? response['message']+ : null;+ return { list_id: listId, contact_ids: ids, message };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/add-note.ts b/packages/pieces/community/freshsales/src/lib/actions/add-note.tsnew file mode 100644index 00000000000..79fa65d4b85--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/add-note.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { noteOutputSchema } from '../output-schemas';++export const addNote = createAction({+ auth: freshsalesAuth,+ name: 'add_note',+ displayName: 'Add Note',+ description: 'Add a note to a contact, account or deal',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Adds a text note to a Freshsales contact, account or deal (Related To + Related Record ID). Returns the note with its ID. Not idempotent: each call adds another note.',+ idempotent: false,+ },+ outputSchema: noteOutputSchema,+ props: {+ description: Property.LongText({+ displayName: 'Note',+ description: 'Text of the note',+ required: true,+ }),+ targetable_type: freshsalesProps.targetableType({ required: true }),+ targetable_id: freshsalesProps.targetableId({ required: true }),+ },+ async run(context) {+ const note = {+ description: context.propsValue.description,+ targetable_type: context.propsValue.targetable_type,+ targetable_id: freshsalesClient.requireId({+ value: context.propsValue.targetable_id,+ field: 'Related Record ID',+ }),+ };+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/notes',+ body: { note },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'note' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/create-account.ts b/packages/pieces/community/freshsales/src/lib/actions/create-account.tsnew file mode 100644index 00000000000..7731f21ce51--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/create-account.ts@@ -0,0 +1,115 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { accountOutputSchema } from '../output-schemas';++export const createAccount = createAction({+ auth: freshsalesAuth,+ name: 'create_account',+ displayName: 'Create Account',+ description: 'Create a new account (company)',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a new Freshsales account (company) and returns it with its ID. Name is required. Not idempotent: each call creates a new account; check with Find Account by Name first to avoid duplicates.',+ idempotent: false,+ },+ outputSchema: accountOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Name of the account',+ placeholder: 'Acme Inc',+ required: true,+ }),+ website: Property.ShortText({+ displayName: 'Website',+ description: 'Website of the account',+ placeholder: 'https://acme.com',+ required: false,+ }),+ phone: Property.ShortText({+ displayName: 'Phone',+ description: 'Phone number of the account',+ required: false,+ }),+ address: Property.ShortText({+ displayName: 'Address',+ description: 'Street address of the account',+ required: false,+ }),+ city: Property.ShortText({+ displayName: 'City',+ description: 'City of the account',+ required: false,+ }),+ state: Property.ShortText({+ displayName: 'State',+ description: 'State of the account',+ required: false,+ }),+ zipcode: Property.ShortText({+ displayName: 'Zip code',+ description: 'Zip code of the account',+ required: false,+ }),+ country: Property.ShortText({+ displayName: 'Country',+ description: 'Country of the account',+ required: false,+ }),+ industry_type_id: freshsalesProps.industryType(),+ business_type_id: freshsalesProps.businessType(),+ number_of_employees: Property.Number({+ displayName: 'Number of Employees',+ description: 'Employee count',+ required: false,+ }),+ annual_revenue: Property.Number({+ displayName: 'Annual Revenue',+ description: 'Yearly revenue of the account',+ required: false,+ }),+ owner_id: freshsalesProps.owner({ required: false }),+ territory_id: freshsalesProps.territory(),+ parent_sales_account_id: Property.ShortText({+ displayName: 'Parent Account ID',+ description: 'ID of the parent account',+ placeholder: '16000123456',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const salesAccount = freshsalesRecords.buildAccountBody({+ name: context.propsValue.name,+ website: context.propsValue.website,+ phone: context.propsValue.phone,+ address: context.propsValue.address,+ city: context.propsValue.city,+ state: context.propsValue.state,+ zipcode: context.propsValue.zipcode,+ country: context.propsValue.country,+ industry_type_id: context.propsValue.industry_type_id,+ business_type_id: context.propsValue.business_type_id,+ number_of_employees: context.propsValue.number_of_employees,+ annual_revenue: context.propsValue.annual_revenue,+ owner_id: context.propsValue.owner_id,+ territory_id: context.propsValue.territory_id,+ parent_sales_account_id: context.propsValue.parent_sales_account_id,+ custom_fields: context.propsValue.custom_fields,+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/sales_accounts',+ query: { include: freshsalesRecords.RECORD_INCLUDES.sales_accounts },+ body: { sales_account: salesAccount },+ });+ return freshsalesClient.unwrap({ body: response, key: 'sales_account' });+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/create-appointment.ts b/packages/pieces/community/freshsales/src/lib/actions/create-appointment.tsnew file mode 100644index 00000000000..f394b0d1c6e--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/create-appointment.ts@@ -0,0 +1,99 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { appointmentOutputSchema } from '../output-schemas';++export const createAppointment = createAction({+ auth: freshsalesAuth,+ name: 'create_appointment',+ displayName: 'Create Appointment',+ description: 'Schedule an appointment, optionally linked to a record',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a Freshsales appointment with a start and end time, optionally linked to a contact, account or deal. Returns the appointment with its ID. Not idempotent: each call creates a new appointment.',+ idempotent: false,+ },+ outputSchema: appointmentOutputSchema,+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Title of the appointment',+ placeholder: 'Demo call',+ required: true,+ }),+ from_date: Property.DateTime({+ displayName: 'Start',+ description: 'Start date and time',+ required: true,+ }),+ end_date: Property.DateTime({+ displayName: 'End',+ description: 'End date and time',+ required: true,+ }),+ time_zone: Property.ShortText({+ displayName: 'Time Zone',+ description: 'Time zone of the appointment',+ placeholder: 'Eastern Time (US & Canada)',+ required: false,+ }),+ location: Property.ShortText({+ displayName: 'Location',+ description: 'Where it takes place',+ placeholder: 'Zoom',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Details of the appointment',+ required: false,+ }),+ is_allday: Property.Checkbox({+ displayName: 'All Day',+ description: 'Whether it lasts all day',+ required: false,+ }),+ targetable_type: freshsalesProps.targetableType({ required: false }),+ targetable_id: freshsalesProps.targetableId({ required: false }),+ },+ async run(context) {+ const fromDate = freshsalesClient.toIsoDate(context.propsValue.from_date);+ const endDate = freshsalesClient.toIsoDate(context.propsValue.end_date);+ if (fromDate && endDate && endDate < fromDate) {+ throw new Error('End must be after Start.');+ }+ const targetableId = freshsalesClient.toId({+ value: context.propsValue.targetable_id,+ field: 'Related Record ID',+ });+ const targetableType = context.propsValue.targetable_type;+ if ((targetableId === undefined) !== (targetableType === undefined || targetableType === null)) {+ throw new Error('Provide both Related To and Related Record ID, or neither.');+ }+ const appointment = freshsalesClient.pickDefined({+ title: context.propsValue.title,+ from_date: fromDate,+ end_date: endDate,+ time_zone: context.propsValue.time_zone,+ location: context.propsValue.location,+ description: context.propsValue.description,+ is_allday: context.propsValue.is_allday,+ targetable_type: targetableType,+ targetable_id: targetableId,+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/appointments',+ body: { appointment },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'appointment' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/create-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/create-contact.tsindex 6011ac4f8f1..56427b25537 100644--- a/packages/pieces/community/freshsales/src/lib/actions/create-contact.ts+++ b/packages/pieces/community/freshsales/src/lib/actions/create-contact.ts@@ -1,22 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';-import {- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { createContactOutputSchema } from '../output-schemas';export const freshSalesCreateContact = createAction({auth: freshsalesAuth,name: 'freshsales_create_contact',- classification: 'WRITE',displayName: 'Create Contact',description: 'Add new contact in Freshsales CRM',audience: 'both',+ classification: 'WRITE',aiMetadata: {- description: 'Creates a new contact record in Freshsales CRM with the given details (email is required; name, phone, address, social handles, owner/territory/account IDs, and marketing attribution fields are optional). Use when an agent needs to add a person to the CRM. Not idempotent: each call creates a new contact and may produce duplicates if repeated.',+ description:+ 'Creates a new contact in Freshsales and returns it with its ID. Email is required; owner, territory, status, lifecycle stage and lead source take IDs from the dropdowns or the List Field Options tool; Sales account id links the contact to an account as primary. Custom Fields is a JSON object keyed by cf_ API names. Not idempotent: each call creates a new contact; use Upsert Contact to avoid duplicates.',idempotent: false,},+ outputSchema: createContactOutputSchema,props: {first_name: Property.ShortText({displayName: 'First name',@@ -30,12 +32,13 @@ export const freshSalesCreateContact = createAction({}),job_title: Property.ShortText({displayName: 'Job title',- description: 'Designation of the contact in the account they belong to',+ description: 'Job title of the contact',required: false,}),email: Property.ShortText({displayName: 'Email',description: 'Primary email address of the contact',+ placeholder: '[email protected]',required: true,}),work_number: Property.ShortText({@@ -50,63 +53,65 @@ export const freshSalesCreateContact = createAction({}),address: Property.ShortText({displayName: 'Address',- description: 'Address of the contact',+ description: 'Street address of the contact',required: false,}),city: Property.ShortText({displayName: 'City',- description: 'City that the contact belongs to',+ description: 'City of the contact',required: false,}),state: Property.ShortText({displayName: 'State',- description: 'State that the contact belongs to',+ description: 'State of the contact',required: false,}),zipcode: Property.ShortText({displayName: 'Zip code',- description: 'Zipcode of the region that the contact belongs to',+ description: 'Zip code of the contact',required: false,}),country: Property.ShortText({displayName: 'Country',- description: 'Country that the contact belongs to',- required: false,- }),- territory_id: Property.ShortText({- displayName: 'Territory id',- description: 'ID of the territory that the contact belongs to',+ description: 'Country of the contact',required: false,}),- owner_id: Property.ShortText({- displayName: 'Owner id',- description: 'ID of the user to whom the contact has been assigned',+ territory_id: freshsalesProps.territory(),+ owner_id: freshsalesProps.owner({ required: false }),+ subscription_status: Property.StaticDropdown({+ displayName: 'Subscription status',+ description: 'Email subscription status of the contact',required: false,+ options: {+ disabled: false,+ options: freshsalesRecords.SUBSCRIPTION_STATUS_OPTIONS,+ },}),- subscription_status: Property.ShortText({- displayName: 'Subscription status',- description: 'Status of subscription that the contact is in.',+ contact_status_id: freshsalesProps.contactStatus(),+ lifecycle_stage_id: freshsalesProps.lifecycleStage(),+ lead_source_id: freshsalesProps.leadSource(),+ sales_account_id: Property.ShortText({+ displayName: 'Sales account id',+ description: 'ID of the primary account of the contact',+ placeholder: '16000123456',required: false,}),medium: Property.ShortText({displayName: 'Medium',- description: 'The medium that led your contact to your website/web app',- required: false,- }),- campaign_id: Property.ShortText({- displayName: 'Campaign id',- description: 'The campaign that led your contact to your web app.',+ description: 'Medium that led the contact to you',+ placeholder: 'email',required: false,}),+ campaign_id: freshsalesProps.campaign(),keyword: Property.ShortText({displayName: 'Keyword',- description:- 'The keywords that the contact used to reach your website/web app',+ description: 'Keywords the contact used to find you',required: false,}),time_zone: Property.ShortText({displayName: 'Timezone',- description: 'Timezone that the contact belongs to',+ description: 'Time zone of the contact',+ placeholder: 'Eastern Time (US & Canada)',required: false,}),facebook: Property.ShortText({@@ -121,40 +126,50 @@ export const freshSalesCreateContact = createAction({}),linkedin: Property.ShortText({displayName: 'Linkedin',- description: 'LinkedIn account of the contact',- required: false,- }),- contact_status_id: Property.ShortText({- displayName: 'Contact status id',- description: 'ID of the contact status that the contact belongs to',- required: false,- }),- sales_account_id: Property.ShortText({- displayName: 'Sales account id',- description: 'ID of the primary account that the contact belongs to',+ description: 'LinkedIn profile of the contact',required: false,}),+ custom_fields: freshsalesProps.customFields(),},async run(context) {- const contact = context.propsValue;-- const request: HttpRequest = {+ const contact = freshsalesRecords.buildContactBody({+ first_name: context.propsValue.first_name,+ last_name: context.propsValue.last_name,+ job_title: context.propsValue.job_title,+ email: context.propsValue.email,+ work_number: context.propsValue.work_number,+ mobile_number: context.propsValue.mobile_number,+ address: context.propsValue.address,+ city: context.propsValue.city,+ state: context.propsValue.state,+ zipcode: context.propsValue.zipcode,+ country: context.propsValue.country,+ territory_id: context.propsValue.territory_id,+ owner_id: context.propsValue.owner_id,+ subscription_status: context.propsValue.subscription_status,+ contact_status_id: context.propsValue.contact_status_id,+ lifecycle_stage_id: context.propsValue.lifecycle_stage_id,+ lead_source_id: context.propsValue.lead_source_id,+ sales_account_id: context.propsValue.sales_account_id,+ custom_fields: context.propsValue.custom_fields,+ medium: context.propsValue.medium,+ campaign_id: context.propsValue.campaign_id,+ keyword: context.propsValue.keyword,+ time_zone: context.propsValue.time_zone,+ facebook: context.propsValue.facebook,+ twitter: context.propsValue.twitter,+ linkedin: context.propsValue.linkedin,+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,method: HttpMethod.POST,- url: `https://${context.auth.username}.myfreshworks.com/crm/sales/api/contacts`,- body: {- contact,- },- headers: {- Authorization: `Token token=${context.auth.password}`,- },- };-- const result = await httpClient.sendRequest(request);-- if (result.status == 200) {- return result.body;- } else {- return result;- }+ path: '/api/contacts',+ query: { include: freshsalesRecords.RECORD_INCLUDES.contacts },+ body: { contact },+ });+ const created = freshsalesRecords.shapeContact(+ freshsalesClient.unwrap({ body: response, key: 'contact' })+ );+ return { ...created, contact: created };},});diff --git a/packages/pieces/community/freshsales/src/lib/actions/create-deal.ts b/packages/pieces/community/freshsales/src/lib/actions/create-deal.tsnew file mode 100644index 00000000000..bf51931fabb--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/create-deal.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { dealOutputSchema } from '../output-schemas';++export const createDeal = createAction({+ auth: freshsalesAuth,+ name: 'create_deal',+ displayName: 'Create Deal',+ description: 'Create a new deal',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a new Freshsales deal and returns it with its ID. Name and Amount are required; pipeline, stage, owner and currency take IDs (see List Pipelines and Stages, List Users). Not idempotent: each call creates a new deal.',+ idempotent: false,+ },+ outputSchema: dealOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Name of the deal',+ placeholder: 'Acme renewal 2026',+ required: true,+ }),+ amount: Property.Number({+ displayName: 'Amount',+ description: 'Deal value',+ required: true,+ }),+ sales_account_id: Property.ShortText({+ displayName: 'Account ID',+ description: 'ID of the account the deal belongs to',+ placeholder: '16000123456',+ required: false,+ }),+ currency_id: freshsalesProps.currency(),+ deal_pipeline_id: freshsalesProps.dealPipeline(),+ deal_stage_id: freshsalesProps.dealStage(),+ deal_type_id: freshsalesProps.dealType(),+ owner_id: freshsalesProps.owner({ required: false }),+ territory_id: freshsalesProps.territory(),+ lead_source_id: freshsalesProps.leadSource(),+ expected_close: Property.DateTime({+ displayName: 'Expected Close',+ description: 'Expected close date',+ required: false,+ }),+ probability: Property.Number({+ displayName: 'Probability (%)',+ description: 'Win probability from 0 to 100',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const deal = freshsalesRecords.buildDealBody({+ name: context.propsValue.name,+ amount: context.propsValue.amount,+ sales_account_id: context.propsValue.sales_account_id,+ currency_id: context.propsValue.currency_id,+ deal_pipeline_id: context.propsValue.deal_pipeline_id,+ deal_stage_id: context.propsValue.deal_stage_id,+ deal_type_id: context.propsValue.deal_type_id,+ owner_id: context.propsValue.owner_id,+ territory_id: context.propsValue.territory_id,+ lead_source_id: context.propsValue.lead_source_id,+ expected_close: context.propsValue.expected_close,+ probability: context.propsValue.probability,+ custom_fields: context.propsValue.custom_fields,+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/deals',+ query: { include: freshsalesRecords.RECORD_INCLUDES.deals },+ body: { deal },+ });+ return freshsalesRecords.shapeDeal(freshsalesClient.unwrap({ body: response, key: 'deal' }));+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/create-task.ts b/packages/pieces/community/freshsales/src/lib/actions/create-task.tsnew file mode 100644index 00000000000..18bed21942f--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/create-task.ts@@ -0,0 +1,65 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { taskOutputSchema } from '../output-schemas';++export const createTask = createAction({+ auth: freshsalesAuth,+ name: 'create_task',+ displayName: 'Create Task',+ description: 'Create a task linked to a contact, account or deal',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a Freshsales task linked to a contact, account or deal (Related To + Related Record ID) with a due date and owner. Returns the task with its ID. Not idempotent: each call creates a new task.',+ idempotent: false,+ },+ outputSchema: taskOutputSchema,+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Title of the task',+ placeholder: 'Follow up on proposal',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Details of the task',+ required: false,+ }),+ due_date: Property.DateTime({+ displayName: 'Due Date',+ description: 'When the task is due',+ required: true,+ }),+ owner_id: freshsalesProps.owner({ required: true, description: 'User the task is assigned to' }),+ targetable_type: freshsalesProps.targetableType({ required: true }),+ targetable_id: freshsalesProps.targetableId({ required: true }),+ },+ async run(context) {+ const task = freshsalesClient.pickDefined({+ title: context.propsValue.title,+ description: context.propsValue.description,+ due_date: freshsalesClient.toIsoDate(context.propsValue.due_date),+ owner_id: freshsalesClient.requireId({ value: context.propsValue.owner_id, field: 'Owner' }),+ targetable_type: context.propsValue.targetable_type,+ targetable_id: freshsalesClient.requireId({+ value: context.propsValue.targetable_id,+ field: 'Related Record ID',+ }),+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/tasks',+ body: { task },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'task' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-account.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-account.tsnew file mode 100644index 00000000000..b6a43b35bb1--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-account.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteAccount = createAction({+ auth: freshsalesAuth,+ name: 'delete_account',+ displayName: 'Delete Account',+ description: 'Delete an account by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales account (sales account) by numeric ID. With Delete Linked Contacts and Deals on, its contacts and deals are deleted too. A second call for the same ID fails with a not-found error. Confirm the ID with Get Account first.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ account_id: Property.ShortText({+ displayName: 'Account ID',+ description: 'ID of the account to delete',+ placeholder: '16000123456',+ required: true,+ }),+ delete_associated: Property.Checkbox({+ displayName: 'Delete Linked Contacts and Deals',+ description: 'Also delete the contacts and deals of this account',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.account_id,+ field: 'Account ID',+ });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/sales_accounts/${id}`,+ query: context.propsValue.delete_associated+ ? { delete_associated_contacts_deals: 'true' }+ : undefined,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-appointment.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-appointment.tsnew file mode 100644index 00000000000..49a9af61e33--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-appointment.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteAppointment = createAction({+ auth: freshsalesAuth,+ name: 'delete_appointment',+ displayName: 'Delete Appointment',+ description: 'Delete a appointment by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales appointment by numeric ID. A second call for the same ID fails with a not-found error. Confirm the ID with Get Appointment first.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ appointment_id: Property.ShortText({+ displayName: 'Appointment ID',+ description: 'ID of the appointment to delete',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.appointment_id,+ field: 'Appointment ID',+ });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/appointments/${id}`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-contact.tsnew file mode 100644index 00000000000..3f232023ec2--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-contact.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteContact = createAction({+ auth: freshsalesAuth,+ name: 'delete_contact',+ displayName: 'Delete Contact',+ description: 'Delete a contact by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales contact by numeric ID. A second call for the same ID fails with a not-found error. Confirm the ID with Get Contact first.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ contact_id: Property.ShortText({+ displayName: 'Contact ID',+ description: 'ID of the contact to delete',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.contact_id, field: 'Contact ID' });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/contacts/${id}`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-deal.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-deal.tsnew file mode 100644index 00000000000..e8ea491c373--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-deal.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteDeal = createAction({+ auth: freshsalesAuth,+ name: 'delete_deal',+ displayName: 'Delete Deal',+ description: 'Delete a deal by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales deal by numeric ID. A second call for the same ID fails with a not-found error. Confirm the ID with Get Deal first.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ deal_id: Property.ShortText({+ displayName: 'Deal ID',+ description: 'ID of the deal to delete',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.deal_id, field: 'Deal ID' });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/deals/${id}`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-note.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-note.tsnew file mode 100644index 00000000000..00dd86c4d1d--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-note.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteNote = createAction({+ auth: freshsalesAuth,+ name: 'delete_note',+ displayName: 'Delete Note',+ description: 'Delete a note by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales note by numeric ID. A second call for the same ID fails with a not-found error.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ note_id: Property.ShortText({+ displayName: 'Note ID',+ description: 'ID of the note to delete',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.note_id,+ field: 'Note ID',+ });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/notes/${id}`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/delete-task.ts b/packages/pieces/community/freshsales/src/lib/actions/delete-task.tsnew file mode 100644index 00000000000..5fde09c1783--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/delete-task.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const deleteTask = createAction({+ auth: freshsalesAuth,+ name: 'delete_task',+ displayName: 'Delete Task',+ description: 'Delete a task by its ID',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently deletes a Freshsales task by numeric ID. A second call for the same ID fails with a not-found error. Confirm the ID with Get Task first.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description: 'ID of the task to delete',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.task_id,+ field: 'Task ID',+ });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/tasks/${id}`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/filtered-search.ts b/packages/pieces/community/freshsales/src/lib/actions/filtered-search.tsnew file mode 100644index 00000000000..6f215f07316--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/filtered-search.ts@@ -0,0 +1,145 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords, RecordEntity } from '../common/records';+import { FILTER_OPERATORS } from '../common/props';+import { filteredSearchOutputSchema } from '../output-schemas';++export const filteredSearch = createAction({+ auth: freshsalesAuth,+ name: 'filtered_search',+ displayName: 'Filtered Search',+ description: 'Find contacts, accounts or deals matching field filters',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Finds contacts, accounts or deals whose fields match ALL given filters (exact value match, not free text). Each filter is attribute (API field name, e.g. first_name, job_title, contact_email.email, name, amount, created_at, or a cf_ custom field from Get Custom Fields), operator (is_in / is_not_in for values, is_after / is_before for dates) and value; comma-separate several values. An unknown attribute may be ignored by Freshsales, so check the names first. Use Search Records for a free-text name/email search and List Records in View for a saved view. Returns records, page, total and has_more; call again with Page + 1 while has_more is true.',+ idempotent: true,+ },+ outputSchema: filteredSearchOutputSchema,+ props: {+ entity: Property.StaticDropdown({+ displayName: 'Record Type',+ description: 'Which records to search',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Contacts', value: 'contact' },+ { label: 'Accounts', value: 'sales_account' },+ { label: 'Deals', value: 'deal' },+ ],+ },+ }),+ filters: Property.Array({+ displayName: 'Filters',+ description: 'All filters must match',+ required: true,+ properties: {+ attribute: Property.ShortText({+ displayName: 'Field',+ description: 'API field name, e.g. first_name or cf_plan',+ required: true,+ }),+ operator: Property.StaticDropdown({+ displayName: 'Operator',+ description: 'How to compare the field',+ required: true,+ defaultValue: 'is_in',+ options: { disabled: false, options: FILTER_OPERATORS },+ }),+ value: Property.ShortText({+ displayName: 'Value',+ description: 'Comma-separate several values; dates as YYYY-MM-DD',+ required: true,+ }),+ },+ }),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1',+ required: false,+ defaultValue: 1,+ }),+ per_page: Property.Number({+ displayName: 'Per Page',+ description: 'Records per page (1-100)',+ required: false,+ defaultValue: 25,+ }),+ },+ async run(context) {+ const entity = ENTITY_KEYS[String(context.propsValue.entity)];+ if (entity === undefined) {+ throw new Error('Record Type must be contact, sales_account or deal.');+ }+ const page = context.propsValue.page ?? 1;+ const perPage = context.propsValue.per_page ?? 25;+ if (!Number.isInteger(page) || page < 1) {+ throw new Error('Page must be a whole number of 1 or more.');+ }+ if (!Number.isInteger(perPage) || perPage < 1 || perPage > 100) {+ throw new Error('Per Page must be a whole number between 1 and 100.');+ }+ const filterRule = context.propsValue.filters.map((filter, index) =>+ toFilterRule({ filter, position: index + 1 })+ );+ if (filterRule.length === 0) {+ throw new Error('Add at least one filter.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `/api/filtered_search/${entity.path}`,+ body: { filter_rule: filterRule, page, per_page: perPage },+ });+ const records = freshsalesClient+ .readArray({ body: response, key: entity.key })+ .filter((item) => freshsalesClient.isRecord(item))+ .map((record) => freshsalesRecords.shapeRecord({ entity: entity.key, record }));+ const meta = freshsalesClient.readMeta(response);+ const hasMore =+ meta.total !== undefined ? page * perPage < meta.total : records.length === perPage;+ return { records, page, total: meta.total ?? null, has_more: hasMore };+ },+});++const ENTITY_KEYS: Record<string, { path: string; key: RecordEntity } | undefined> = {+ contact: { path: 'contact', key: 'contacts' },+ sales_account: { path: 'sales_account', key: 'sales_accounts' },+ deal: { path: 'deal', key: 'deals' },+};++function toFilterRule({+ filter,+ position,+}: {+ filter: unknown;+ position: number;+}): { attribute: string; operator: string; value: unknown } {+ if (!freshsalesClient.isRecord(filter)) {+ throw new Error(`Filter ${position} must have Field, Operator and Value.`);+ }+ const attribute = String(filter['attribute'] ?? '').trim();+ const operator = String(filter['operator'] ?? '').trim();+ const raw = String(filter['value'] ?? '').trim();+ if (attribute.length === 0 || raw.length === 0) {+ throw new Error(`Filter ${position} needs a Field and a Value.`);+ }+ if (!FILTER_OPERATORS.some((option) => option.value === operator)) {+ throw new Error(+ `Filter ${position} operator must be one of: ${FILTER_OPERATORS.map((o) => o.value).join(', ')}.`+ );+ }+ if (operator === 'is_in' || operator === 'is_not_in') {+ const values = raw+ .split(',')+ .map((part) => part.trim())+ .filter((part) => part.length > 0);+ return { attribute, operator, value: values.length === 1 ? values[0] : values };+ }+ const date = freshsalesClient.toIsoDate(raw);+ return { attribute, operator, value: date === undefined ? raw : date.slice(0, 10) };+}diff --git a/packages/pieces/community/freshsales/src/lib/actions/find-account-by-name.ts b/packages/pieces/community/freshsales/src/lib/actions/find-account-by-name.tsnew file mode 100644index 00000000000..37b34059cba--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/find-account-by-name.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { findAccountOutputSchema } from '../output-schemas';++export const findAccountByName = createAction({+ auth: freshsalesAuth,+ name: 'find_account_by_name',+ displayName: 'Find Account by Name',+ description: 'Look up accounts by exact name',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Looks up Freshsales accounts whose name exactly matches the given text. Returns found and the list of matching accounts (may be empty). Use it to get an account ID before Create Deal or Create Contact.',+ idempotent: true,+ },+ outputSchema: findAccountOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Account Name',+ description: 'Exact account name to look up',+ placeholder: 'Acme Inc',+ required: true,+ }),+ },+ async run(context) {+ const name = context.propsValue.name.trim();+ if (name.length === 0) {+ throw new Error('Account Name is required.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: '/api/lookup',+ query: { q: name, f: 'name', entities: 'sales_account' },+ });+ const group = freshsalesClient.isRecord(response) ? response['sales_accounts'] : undefined;+ const accounts = freshsalesClient+ .readArray({ body: group, key: 'sales_accounts' })+ .filter((item) => freshsalesClient.isRecord(item));+ return { found: accounts.length > 0, accounts };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/find-contact-by-email.ts b/packages/pieces/community/freshsales/src/lib/actions/find-contact-by-email.tsnew file mode 100644index 00000000000..34d10928980--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/find-contact-by-email.ts@@ -0,0 +1,60 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { findContactOutputSchema } from '../output-schemas';++export const findContactByEmail = createAction({+ auth: freshsalesAuth,+ name: 'find_contact_by_email',+ displayName: 'Find Contact by Email',+ description: 'Look up a contact by exact email address',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Looks up a Freshsales contact by exact email address. Returns found true with the first matching contact, or found false with contact null when nobody has that email. Use it to get a contact ID before Update Contact or Add Note.',+ idempotent: true,+ },+ outputSchema: findContactOutputSchema,+ props: {+ email: Property.ShortText({+ displayName: 'Email',+ description: 'Exact email address to look up',+ placeholder: '[email protected]',+ required: true,+ }),+ },+ async run(context) {+ const email = context.propsValue.email.trim();+ if (email.length === 0) {+ throw new Error('Email is required.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: '/api/lookup',+ query: { q: email, f: 'email', entities: 'contact' },+ });+ const group = freshsalesClient.isRecord(response) ? response['contacts'] : undefined;+ const contacts = freshsalesClient.readArray({ body: group, key: 'contacts' });+ const first = contacts.find((item) => freshsalesClient.isRecord(item));+ if (!freshsalesClient.isRecord(first)) {+ return { found: false, contact: null };+ }+ const id = freshsalesClient.requireId({ value: first['id'], field: 'Contact ID' });+ const detail = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/contacts/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.contacts },+ });+ return {+ found: true,+ contact: freshsalesRecords.shapeContact(+ freshsalesClient.unwrap({ body: detail, key: 'contact' })+ ),+ };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/forget-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/forget-contact.tsnew file mode 100644index 00000000000..373d3818103--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/forget-contact.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { deleteOutputSchema } from '../output-schemas';++export const forgetContact = createAction({+ auth: freshsalesAuth,+ name: 'forget_contact',+ displayName: 'Forget Contact (GDPR)',+ description: 'Permanently erase a contact and all its data',+ audience: 'both',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'IRREVERSIBLE GDPR erase: hard-deletes a Freshsales contact by numeric ID together with all its associated data (notes, activities, emails); it cannot be restored. Use only when the person asked to be forgotten; for a normal removal use Delete Contact instead. A second call for the same ID fails with a not-found error.',+ idempotent: true,+ },+ outputSchema: deleteOutputSchema,+ props: {+ contact_id: Property.ShortText({+ displayName: 'Contact ID',+ description: 'ID of the contact to erase for good',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.contact_id,+ field: 'Contact ID',+ });+ await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/api/contacts/${id}/forget`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-account.ts b/packages/pieces/community/freshsales/src/lib/actions/get-account.tsnew file mode 100644index 00000000000..c5c18294232--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-account.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { accountOutputSchema } from '../output-schemas';++export const getAccount = createAction({+ auth: freshsalesAuth,+ name: 'get_account',+ displayName: 'Get Account',+ description: 'Get an account by its ID',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fetches one Freshsales account (sales account) by numeric ID. Fails with a not-found error if the ID does not exist. Use Find Account by Name when you only know the name.',+ idempotent: true,+ },+ outputSchema: accountOutputSchema,+ props: {+ sales_account_id: Property.ShortText({+ displayName: 'Account ID',+ description: 'ID of the account to fetch',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.sales_account_id, field: 'Account ID' });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/sales_accounts/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.sales_accounts },+ });+ return freshsalesClient.unwrap({ body: response, key: 'sales_account' });+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-appointment.ts b/packages/pieces/community/freshsales/src/lib/actions/get-appointment.tsnew file mode 100644index 00000000000..84979fe21b6--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-appointment.ts@@ -0,0 +1,43 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { appointmentOutputSchema } from '../output-schemas';++export const getAppointment = createAction({+ auth: freshsalesAuth,+ name: 'get_appointment',+ displayName: 'Get Appointment',+ description: 'Get an appointment by its ID',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fetches one Freshsales appointment by numeric ID, including title, start and end times, location and the linked record. Fails with a not-found error if the ID does not exist.',+ idempotent: true,+ },+ outputSchema: appointmentOutputSchema,+ props: {+ appointment_id: Property.ShortText({+ displayName: 'Appointment ID',+ description: 'ID of the appointment to fetch',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.appointment_id,+ field: 'Appointment ID',+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/appointments/${id}`,+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'appointment' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/get-contact.tsnew file mode 100644index 00000000000..91ccd07e9a0--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-contact.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { getContactOutputSchema } from '../output-schemas';++export const getContact = createAction({+ auth: freshsalesAuth,+ name: 'get_contact',+ displayName: 'Get Contact',+ description: 'Get a contact by its ID',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fetches one Freshsales contact by numeric ID, including its linked accounts. Fails with a not-found error if the ID does not exist. Use Find Contact by Email when you only know the email.',+ idempotent: true,+ },+ outputSchema: getContactOutputSchema,+ props: {+ contact_id: Property.ShortText({+ displayName: 'Contact ID',+ description: 'ID of the contact to fetch',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.contact_id, field: 'Contact ID' });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/contacts/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.contacts },+ });+ return freshsalesRecords.shapeContact(freshsalesClient.unwrap({ body: response, key: 'contact' }));+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-custom-fields.ts b/packages/pieces/community/freshsales/src/lib/actions/get-custom-fields.tsnew file mode 100644index 00000000000..59670b9307c--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-custom-fields.ts@@ -0,0 +1,59 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { customFieldsOutputSchema } from '../output-schemas';++export const getCustomFields = createAction({+ auth: freshsalesAuth,+ name: 'get_custom_fields',+ displayName: 'Get Fields',+ description: 'List the fields (incl. custom cf_ fields) of a record type',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Lists the fields of Freshsales contacts, accounts, deals or sales activities with API name, label, type, required flag and choices. Use it to learn custom field API names (cf_...) and allowed values before passing Custom Fields to create or update tools.',+ idempotent: true,+ },+ outputSchema: customFieldsOutputSchema,+ props: {+ entity: Property.StaticDropdown({+ displayName: 'Record Type',+ description: 'Which record type to describe',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Contacts', value: 'contacts' },+ { label: 'Accounts', value: 'sales_accounts' },+ { label: 'Deals', value: 'deals' },+ { label: 'Sales Activities', value: 'sales_activities' },+ ],+ },+ }),+ },+ async run(context) {+ const entity = context.propsValue.entity;+ if (!['contacts', 'sales_accounts', 'deals', 'sales_activities'].includes(entity)) {+ throw new Error(`Unsupported Record Type "${entity}".`);+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/settings/${entity}/fields`,+ });+ const fields = freshsalesClient+ .readArray({ body: response, key: 'fields' })+ .filter((item) => freshsalesClient.isRecord(item))+ .map((field) => ({+ name: field['name'],+ label: field['label'],+ type: field['type'],+ required: field['required'] === true,+ is_custom: typeof field['name'] === 'string' && field['name'].startsWith('cf_'),+ choices: Array.isArray(field['choices']) ? field['choices'] : [],+ }));+ return { fields };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-deal.ts b/packages/pieces/community/freshsales/src/lib/actions/get-deal.tsnew file mode 100644index 00000000000..4ac62a67835--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-deal.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { dealOutputSchema } from '../output-schemas';++export const getDeal = createAction({+ auth: freshsalesAuth,+ name: 'get_deal',+ displayName: 'Get Deal',+ description: 'Get a deal by its ID',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fetches one Freshsales deal by numeric ID, including amount, pipeline, stage and owner IDs. Fails with a not-found error if the ID does not exist. Use Search Records to find a deal ID by name.',+ idempotent: true,+ },+ outputSchema: dealOutputSchema,+ props: {+ deal_id: Property.ShortText({+ displayName: 'Deal ID',+ description: 'ID of the deal to fetch',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.deal_id, field: 'Deal ID' });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/deals/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.deals },+ });+ return freshsalesRecords.shapeDeal(freshsalesClient.unwrap({ body: response, key: 'deal' }));+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/get-task.ts b/packages/pieces/community/freshsales/src/lib/actions/get-task.tsnew file mode 100644index 00000000000..78b6dcce62f--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/get-task.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { taskOutputSchema } from '../output-schemas';++export const getTask = createAction({+ auth: freshsalesAuth,+ name: 'get_task',+ displayName: 'Get Task',+ description: 'Get a task by its ID',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fetches one Freshsales task by numeric ID, including title, due date, status (0 open, 1 done), owner and the linked record. Fails with a not-found error if the ID does not exist. Use List Tasks to find task IDs.',+ idempotent: true,+ },+ outputSchema: taskOutputSchema,+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description: 'ID of the task to fetch',+ placeholder: '16000123456',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.task_id, field: 'Task ID' });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/tasks/${id}`,+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'task' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/list-field-options.ts b/packages/pieces/community/freshsales/src/lib/actions/list-field-options.tsnew file mode 100644index 00000000000..3d69bd9d106--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/list-field-options.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesProps } from '../common/props';+import { listFieldOptionsOutputSchema } from '../output-schemas';++export const listFieldOptions = createAction({+ auth: freshsalesAuth,+ name: 'list_field_options',+ displayName: 'List Field Options',+ description: 'List options such as territories or lead sources',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the id and name of every option for one Freshsales picklist (territories, contact statuses, lifecycle stages, lead sources, campaigns, currencies, deal types, deal reasons, industry types, business types, sales activity types). Use it to resolve a name to the ID needed by create and update tools.',+ idempotent: true,+ },+ outputSchema: listFieldOptionsOutputSchema,+ props: {+ option_type: Property.StaticDropdown({+ displayName: 'Option Type',+ description: 'Which picklist to list',+ required: true,+ options: { disabled: false, options: freshsalesProps.SELECTOR_TYPES },+ }),+ },+ async run(context) {+ const optionType = context.propsValue.option_type;+ if (!freshsalesProps.SELECTOR_TYPES.some((option) => option.value === optionType)) {+ throw new Error(`Unsupported Option Type "${optionType}".`);+ }+ const items = await freshsalesProps.fetchSelector({+ auth: context.auth,+ path: `/api/selector/${optionType}`,+ });+ return { items: items.map((item) => ({ id: item.id, name: item.name })) };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/list-pipelines.ts b/packages/pieces/community/freshsales/src/lib/actions/list-pipelines.tsnew file mode 100644index 00000000000..866dab2fd18--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/list-pipelines.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesProps } from '../common/props';+import { listPipelinesOutputSchema } from '../output-schemas';++export const listPipelines = createAction({+ auth: freshsalesAuth,+ name: 'list_pipelines',+ displayName: 'List Pipelines and Stages',+ description: 'List deal pipelines with their stages',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every Freshsales deal pipeline with its stages (id, name, position). Use it to resolve a pipeline or stage name to the IDs needed by Create Deal and Update Deal.',+ idempotent: true,+ },+ outputSchema: listPipelinesOutputSchema,+ props: {+ },+ async run(context) {+ const pipelines = await freshsalesProps.fetchSelector({+ auth: context.auth,+ path: '/api/selector/deal_pipelines',+ });+ const result = [];+ for (const pipeline of pipelines) {+ const stages = await freshsalesProps.fetchSelector({+ auth: context.auth,+ path: `/api/selector/deal_pipelines/${encodeURIComponent(pipeline.id)}/deal_stages`,+ });+ result.push({+ id: pipeline.id,+ name: pipeline.name,+ stages: stages.map((stage) => ({+ id: stage.id,+ name: stage.name,+ position: stage.position ?? null,+ })),+ });+ }+ return { pipelines: result };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/list-records.ts b/packages/pieces/community/freshsales/src/lib/actions/list-records.tsnew file mode 100644index 00000000000..6f9d47f109b--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/list-records.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { listRecordsOutputSchema } from '../output-schemas';++export const listRecords = createAction({+ auth: freshsalesAuth,+ name: 'list_records',+ displayName: 'List Records in View',+ description: 'List contacts, accounts or deals from a saved view',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists one page of contacts, accounts or deals from a saved Freshsales view (the All view when View is empty), newest updated first. Returns records, page, total and has_more; call again with Page + 1 while has_more is true.',+ idempotent: true,+ },+ outputSchema: listRecordsOutputSchema,+ props: {+ entity: Property.StaticDropdown({+ displayName: 'Record Type',+ description: 'Which records to list',+ required: true,+ options: { disabled: false, options: freshsalesProps.ENTITY_OPTIONS },+ }),+ view_id: freshsalesProps.view(),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1',+ required: false,+ defaultValue: 1,+ }),+ per_page: Property.Number({+ displayName: 'Per Page',+ description: 'Records per page (1-100)',+ required: false,+ defaultValue: 25,+ }),+ },+ async run(context) {+ const entity = context.propsValue.entity;+ if (!freshsalesRecords.isRecordEntity(entity)) {+ throw new Error('Record Type must be contacts, sales_accounts or deals.');+ }+ const page = context.propsValue.page ?? 1;+ const perPage = context.propsValue.per_page ?? 25;+ if (!Number.isInteger(page) || page < 1) {+ throw new Error('Page must be a whole number of 1 or more.');+ }+ if (!Number.isInteger(perPage) || perPage < 1 || perPage > 100) {+ throw new Error('Per Page must be a whole number between 1 and 100.');+ }+ const viewId =+ freshsalesClient.toId({ value: context.propsValue.view_id, field: 'View' }) ??+ (await freshsalesProps.findDefaultViewId({ auth: context.auth, entity }));+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/${entity}/view/${viewId}`,+ query: {+ page: String(page),+ per_page: String(perPage),+ sort: 'updated_at',+ sort_type: 'desc',+ include: freshsalesRecords.RECORD_INCLUDES[entity],+ },+ });+ const records = freshsalesClient+ .readArray({ body: response, key: entity })+ .filter((item) => freshsalesClient.isRecord(item))+ .map((record) => freshsalesRecords.shapeRecord({ entity, record }));+ const meta = freshsalesClient.readMeta(response);+ const hasMore =+ meta.total_pages !== undefined+ ? page < meta.total_pages+ : meta.total !== undefined+ ? page * perPage < meta.total+ : records.length === perPage;+ return { records, page, total: meta.total ?? null, has_more: hasMore };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/list-tasks.ts b/packages/pieces/community/freshsales/src/lib/actions/list-tasks.tsnew file mode 100644index 00000000000..229e2422190--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/list-tasks.ts@@ -0,0 +1,69 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { listTasksOutputSchema } from '../output-schemas';++export const listTasks = createAction({+ auth: freshsalesAuth,+ name: 'list_tasks',+ displayName: 'List Tasks',+ description: 'List tasks by status (open, overdue, completed...)',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists one page of Freshsales tasks matching a filter (open, due today, due tomorrow, overdue or completed). Returns tasks, page and has_more; call again with Page + 1 while has_more is true.',+ idempotent: true,+ },+ outputSchema: listTasksOutputSchema,+ props: {+ filter: Property.StaticDropdown({+ displayName: 'Filter',+ description: 'Which tasks to list',+ required: true,+ defaultValue: 'open',+ options: {+ disabled: false,+ options: [+ { label: 'Open', value: 'open' },+ { label: 'Due today', value: 'due today' },+ { label: 'Due tomorrow', value: 'due tomorrow' },+ { label: 'Overdue', value: 'overdue' },+ { label: 'Completed', value: 'completed' },+ ],+ },+ }),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1',+ required: false,+ defaultValue: 1,+ }),+ },+ async run(context) {+ const page = context.propsValue.page ?? 1;+ if (!Number.isInteger(page) || page < 1) {+ throw new Error('Page must be a whole number of 1 or more.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: '/api/tasks',+ query: { filter: context.propsValue.filter, page: String(page) },+ });+ const tasks = freshsalesClient+ .readArray({ body: response, key: 'tasks' })+ .filter((item) => freshsalesClient.isRecord(item))+ .map((item) => freshsalesRecords.shapeTargetable(item));+ const meta = freshsalesClient.readMeta(response);+ const hasMore =+ meta.total_pages !== undefined+ ? page < meta.total_pages+ : meta.total !== undefined+ ? page * 25 < meta.total+ : tasks.length === 25;+ return { tasks, page, has_more: hasMore };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/list-users.ts b/packages/pieces/community/freshsales/src/lib/actions/list-users.tsnew file mode 100644index 00000000000..6e5aae9e033--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/list-users.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesProps } from '../common/props';+import { listUsersOutputSchema } from '../output-schemas';++export const listUsers = createAction({+ auth: freshsalesAuth,+ name: 'list_users',+ displayName: 'List Users',+ description: 'List Freshsales users (owners) with their IDs',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists all Freshsales users who can own records, with id, name and email. Use it to resolve a person name or email to the Owner ID needed by create and update tools.',+ idempotent: true,+ },+ outputSchema: listUsersOutputSchema,+ props: {+ },+ async run(context) {+ const items = await freshsalesProps.fetchSelector({+ auth: context.auth,+ path: '/api/selector/owners',+ });+ return {+ users: items.map((item) => ({ id: item.id, name: item.name, email: item.email ?? null })),+ };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/log-sales-activity.ts b/packages/pieces/community/freshsales/src/lib/actions/log-sales-activity.tsnew file mode 100644index 00000000000..c7c3138f6b8--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/log-sales-activity.ts@@ -0,0 +1,93 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { salesActivityOutputSchema } from '../output-schemas';++export const logSalesActivity = createAction({+ auth: freshsalesAuth,+ name: 'log_sales_activity',+ displayName: 'Log Sales Activity',+ description: 'Log a call, meeting or other sales activity',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Logs a Freshsales sales activity (type from List Field Options with sales_activity_types) on a contact, account or deal, with start and end time and owner. Returns the activity with its ID. Not idempotent: each call logs another activity.',+ idempotent: false,+ },+ outputSchema: salesActivityOutputSchema,+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Title of the activity',+ placeholder: 'Discovery call',+ required: true,+ }),+ sales_activity_type_id: freshsalesProps.salesActivityType(),+ sales_activity_outcome_id: freshsalesProps.salesActivityOutcome(),+ start_date: Property.DateTime({+ displayName: 'Start',+ description: 'Start date and time',+ required: true,+ }),+ end_date: Property.DateTime({+ displayName: 'End',+ description: 'End date and time',+ required: true,+ }),+ owner_id: freshsalesProps.owner({ required: true, description: 'User who did the activity' }),+ targetable_type: freshsalesProps.targetableType({ required: true }),+ targetable_id: freshsalesProps.targetableId({ required: true }),+ notes: Property.LongText({+ displayName: 'Notes',+ description: 'Notes about the activity',+ required: false,+ }),+ location: Property.ShortText({+ displayName: 'Location',+ description: 'Where it took place',+ placeholder: 'Office',+ required: false,+ }),+ },+ async run(context) {+ const startDate = freshsalesClient.toIsoDate(context.propsValue.start_date);+ const endDate = freshsalesClient.toIsoDate(context.propsValue.end_date);+ if (startDate && endDate && endDate < startDate) {+ throw new Error('End must be after Start.');+ }+ const salesActivity = freshsalesClient.pickDefined({+ title: context.propsValue.title,+ sales_activity_type_id: freshsalesClient.requireId({+ value: context.propsValue.sales_activity_type_id,+ field: 'Activity Type',+ }),+ sales_activity_outcome_id: freshsalesClient.toId({+ value: context.propsValue.sales_activity_outcome_id,+ field: 'Outcome',+ }),+ start_date: startDate,+ end_date: endDate,+ owner_id: freshsalesClient.requireId({ value: context.propsValue.owner_id, field: 'Owner' }),+ targetable_type: context.propsValue.targetable_type,+ targetable_id: freshsalesClient.requireId({+ value: context.propsValue.targetable_id,+ field: 'Related Record ID',+ }),+ notes: context.propsValue.notes,+ location: context.propsValue.location,+ });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/sales_activities',+ body: { sales_activity: salesActivity },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'sales_activity' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/remove-contacts-from-list.ts b/packages/pieces/community/freshsales/src/lib/actions/remove-contacts-from-list.tsnew file mode 100644index 00000000000..5d62880e894--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/remove-contacts-from-list.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { marketingListUpdateOutputSchema } from '../output-schemas';++export const removeContactsFromList = createAction({+ auth: freshsalesAuth,+ name: 'remove_contacts_from_list',+ displayName: 'Remove Contacts from Marketing List',+ description: 'Remove contacts from a marketing list',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Removes one or more Freshsales contacts (numeric IDs) from a marketing list picked from the Marketing List options. The contacts themselves are not deleted. Repeating the call is safe.',+ idempotent: true,+ },+ outputSchema: marketingListUpdateOutputSchema,+ props: {+ list_id: freshsalesProps.marketingList(),+ contact_ids: Property.Array({+ displayName: 'Contact IDs',+ description: 'IDs of the contacts to remove',+ required: true,+ }),+ },+ async run(context) {+ const listId = freshsalesClient.requireId({+ value: context.propsValue.list_id,+ field: 'Marketing List',+ });+ const ids = context.propsValue.contact_ids.map((value) =>+ freshsalesClient.requireId({ value, field: 'Contact ID' })+ );+ if (ids.length === 0) {+ throw new Error('Provide at least one Contact ID.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/lists/${listId}/remove_contacts`,+ body: { ids },+ });+ const message =+ freshsalesClient.isRecord(response) && typeof response['message'] === 'string'+ ? response['message']+ : null;+ return { list_id: listId, contact_ids: ids, message };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/search-records.ts b/packages/pieces/community/freshsales/src/lib/actions/search-records.tsnew file mode 100644index 00000000000..57263afca82--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/search-records.ts@@ -0,0 +1,69 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { searchRecordsOutputSchema } from '../output-schemas';++export const searchRecords = createAction({+ auth: freshsalesAuth,+ name: 'search_records',+ displayName: 'Search Records',+ description: 'Search contacts, accounts and deals by keyword',+ audience: 'both',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Full-text search across Freshsales contacts, accounts and deals (choose which types). Returns up to Limit matches with id, type, name and email. Use it to find a record ID by partial name; use Get Contact/Account/Deal for full details.',+ idempotent: true,+ },+ outputSchema: searchRecordsOutputSchema,+ props: {+ query: Property.ShortText({+ displayName: 'Search Term',+ description: 'Text to search for',+ placeholder: 'acme',+ required: true,+ }),+ entities: Property.StaticMultiSelectDropdown({+ displayName: 'Record Types',+ description: 'Types to search; leave empty to search all',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Contacts', value: 'contact' },+ { label: 'Accounts', value: 'sales_account' },+ { label: 'Deals', value: 'deal' },+ ],+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum results to return (1-100)',+ required: false,+ defaultValue: 25,+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (query.length === 0) {+ throw new Error('Search Term is required.');+ }+ const limit = context.propsValue.limit ?? 25;+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {+ throw new Error('Limit must be a whole number between 1 and 100.');+ }+ const entities = context.propsValue.entities ?? [];+ const include = entities.length > 0 ? entities.join(',') : 'contact,sales_account,deal';+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: '/api/search',+ query: { q: query, include, per_page: String(limit) },+ });+ const results = Array.isArray(response)+ ? response.filter((item) => freshsalesClient.isRecord(item))+ : [];+ return { results, count: results.length };+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-account.ts b/packages/pieces/community/freshsales/src/lib/actions/update-account.tsnew file mode 100644index 00000000000..ee01b003be4--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-account.ts@@ -0,0 +1,125 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { accountOutputSchema } from '../output-schemas';++export const updateAccount = createAction({+ auth: freshsalesAuth,+ name: 'update_account',+ displayName: 'Update Account',+ description: 'Update fields of an existing account',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing Freshsales account by numeric ID. Only the fields you provide are changed. Returns the updated account. Idempotent: repeating the call with the same values gives the same result.',+ idempotent: true,+ },+ outputSchema: accountOutputSchema,+ props: {+ sales_account_id: Property.ShortText({+ displayName: 'Account ID',+ description: 'ID of the account to update',+ placeholder: '16000123456',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Name of the account',+ placeholder: 'Acme Inc',+ required: false,+ }),+ website: Property.ShortText({+ displayName: 'Website',+ description: 'Website of the account',+ placeholder: 'https://acme.com',+ required: false,+ }),+ phone: Property.ShortText({+ displayName: 'Phone',+ description: 'Phone number of the account',+ required: false,+ }),+ address: Property.ShortText({+ displayName: 'Address',+ description: 'Street address of the account',+ required: false,+ }),+ city: Property.ShortText({+ displayName: 'City',+ description: 'City of the account',+ required: false,+ }),+ state: Property.ShortText({+ displayName: 'State',+ description: 'State of the account',+ required: false,+ }),+ zipcode: Property.ShortText({+ displayName: 'Zip code',+ description: 'Zip code of the account',+ required: false,+ }),+ country: Property.ShortText({+ displayName: 'Country',+ description: 'Country of the account',+ required: false,+ }),+ industry_type_id: freshsalesProps.industryType(),+ business_type_id: freshsalesProps.businessType(),+ number_of_employees: Property.Number({+ displayName: 'Number of Employees',+ description: 'Employee count',+ required: false,+ }),+ annual_revenue: Property.Number({+ displayName: 'Annual Revenue',+ description: 'Yearly revenue of the account',+ required: false,+ }),+ owner_id: freshsalesProps.owner({ required: false }),+ territory_id: freshsalesProps.territory(),+ parent_sales_account_id: Property.ShortText({+ displayName: 'Parent Account ID',+ description: 'ID of the parent account',+ placeholder: '16000123456',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.sales_account_id, field: 'Account ID' });+ const salesAccount = freshsalesRecords.buildAccountBody({+ name: context.propsValue.name,+ website: context.propsValue.website,+ phone: context.propsValue.phone,+ address: context.propsValue.address,+ city: context.propsValue.city,+ state: context.propsValue.state,+ zipcode: context.propsValue.zipcode,+ country: context.propsValue.country,+ industry_type_id: context.propsValue.industry_type_id,+ business_type_id: context.propsValue.business_type_id,+ number_of_employees: context.propsValue.number_of_employees,+ annual_revenue: context.propsValue.annual_revenue,+ owner_id: context.propsValue.owner_id,+ territory_id: context.propsValue.territory_id,+ parent_sales_account_id: context.propsValue.parent_sales_account_id,+ custom_fields: context.propsValue.custom_fields,+ });+ if (Object.keys(salesAccount).length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/sales_accounts/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.sales_accounts },+ body: { sales_account: salesAccount },+ });+ return freshsalesClient.unwrap({ body: response, key: 'sales_account' });+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-appointment.ts b/packages/pieces/community/freshsales/src/lib/actions/update-appointment.tsnew file mode 100644index 00000000000..c5ac232a130--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-appointment.ts@@ -0,0 +1,118 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { appointmentOutputSchema } from '../output-schemas';++export const updateAppointment = createAction({+ auth: freshsalesAuth,+ name: 'update_appointment',+ displayName: 'Update Appointment',+ description: 'Change an existing appointment',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing Freshsales appointment by numeric ID (reschedule, rename, move, relink). Only the fields you provide are changed. Idempotent: repeating the call with the same values gives the same result.',+ idempotent: true,+ },+ outputSchema: appointmentOutputSchema,+ props: {+ appointment_id: Property.ShortText({+ displayName: 'Appointment ID',+ description: 'ID of the appointment to update',+ placeholder: '16000123456',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'New title of the appointment',+ required: false,+ }),+ from_date: Property.DateTime({+ displayName: 'Start',+ description: 'New start date and time',+ required: false,+ }),+ end_date: Property.DateTime({+ displayName: 'End',+ description: 'New end date and time',+ required: false,+ }),+ time_zone: Property.ShortText({+ displayName: 'Time Zone',+ description: 'Time zone of the appointment',+ placeholder: 'Eastern Time (US & Canada)',+ required: false,+ }),+ location: Property.ShortText({+ displayName: 'Location',+ description: 'Where it takes place',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New details of the appointment',+ required: false,+ }),+ is_allday: Property.StaticDropdown({+ displayName: 'All Day',+ description: 'Whether it lasts all day; leave empty to keep',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Yes', value: 'true' },+ { label: 'No', value: 'false' },+ ],+ },+ }),+ targetable_type: freshsalesProps.targetableType({ required: false }),+ targetable_id: freshsalesProps.targetableId({ required: false }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({+ value: context.propsValue.appointment_id,+ field: 'Appointment ID',+ });+ const fromDate = freshsalesClient.toIsoDate(context.propsValue.from_date);+ const endDate = freshsalesClient.toIsoDate(context.propsValue.end_date);+ if (fromDate && endDate && endDate < fromDate) {+ throw new Error('End must be after Start.');+ }+ const targetableId = freshsalesClient.toId({+ value: context.propsValue.targetable_id,+ field: 'Related Record ID',+ });+ const targetableType = context.propsValue.targetable_type;+ if ((targetableId === undefined) !== (targetableType === undefined || targetableType === null)) {+ throw new Error('Provide both Related To and Related Record ID, or neither.');+ }+ const allDay = context.propsValue.is_allday;+ const appointment = freshsalesClient.pickDefined({+ title: context.propsValue.title,+ from_date: fromDate,+ end_date: endDate,+ time_zone: context.propsValue.time_zone,+ location: context.propsValue.location,+ description: context.propsValue.description,+ is_allday: allDay === 'true' ? true : allDay === 'false' ? false : undefined,+ targetable_type: targetableType,+ targetable_id: targetableId,+ });+ if (Object.keys(appointment).length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/appointments/${id}`,+ body: { appointment },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'appointment' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/update-contact.tsnew file mode 100644index 00000000000..d1c8623121b--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-contact.ts@@ -0,0 +1,160 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { contactOutputSchema } from '../output-schemas';++export const updateContact = createAction({+ auth: freshsalesAuth,+ name: 'update_contact',+ displayName: 'Update Contact',+ description: 'Update fields of an existing contact',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing Freshsales contact by its numeric ID. Only the fields you provide are changed; empty fields are left as they are. Returns the updated contact. Idempotent: repeating the call with the same values gives the same result.',+ idempotent: true,+ },+ outputSchema: contactOutputSchema,+ props: {+ contact_id: Property.ShortText({+ displayName: 'Contact ID',+ description: 'ID of the contact to update',+ placeholder: '16000123456',+ required: true,+ }),+ first_name: Property.ShortText({+ displayName: 'First name',+ description: 'First name of the contact',+ required: false,+ }),+ last_name: Property.ShortText({+ displayName: 'Last name',+ description: 'Last name of the contact',+ required: false,+ }),+ job_title: Property.ShortText({+ displayName: 'Job title',+ description: 'Job title of the contact',+ required: false,+ }),+ email: Property.ShortText({+ displayName: 'Email',+ description: 'Primary email address of the contact',+ placeholder: '[email protected]',+ required: false,+ }),+ work_number: Property.ShortText({+ displayName: 'Work number',+ description: 'Work phone number of the contact',+ required: false,+ }),+ mobile_number: Property.ShortText({+ displayName: 'Mobile number',+ description: 'Mobile phone number of the contact',+ required: false,+ }),+ address: Property.ShortText({+ displayName: 'Address',+ description: 'Street address of the contact',+ required: false,+ }),+ city: Property.ShortText({+ displayName: 'City',+ description: 'City of the contact',+ required: false,+ }),+ state: Property.ShortText({+ displayName: 'State',+ description: 'State of the contact',+ required: false,+ }),+ zipcode: Property.ShortText({+ displayName: 'Zip code',+ description: 'Zip code of the contact',+ required: false,+ }),+ country: Property.ShortText({+ displayName: 'Country',+ description: 'Country of the contact',+ required: false,+ }),+ territory_id: freshsalesProps.territory(),+ owner_id: freshsalesProps.owner({ required: false }),+ subscription_status: Property.StaticDropdown({+ displayName: 'Subscription status',+ description: 'Email subscription status of the contact',+ required: false,+ options: {+ disabled: false,+ options: freshsalesRecords.SUBSCRIPTION_STATUS_OPTIONS,+ },+ }),+ contact_status_id: freshsalesProps.contactStatus(),+ lifecycle_stage_id: freshsalesProps.lifecycleStage(),+ lead_source_id: freshsalesProps.leadSource(),+ sales_account_id: Property.ShortText({+ displayName: 'Sales account id',+ description: 'Account to make primary; other linked accounts are kept',+ placeholder: '16000123456',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const contactId = freshsalesClient.requireId({ value: context.propsValue.contact_id, field: 'Contact ID' });+ const contact = freshsalesRecords.buildContactBody({+ first_name: context.propsValue.first_name,+ last_name: context.propsValue.last_name,+ job_title: context.propsValue.job_title,+ email: context.propsValue.email,+ work_number: context.propsValue.work_number,+ mobile_number: context.propsValue.mobile_number,+ address: context.propsValue.address,+ city: context.propsValue.city,+ state: context.propsValue.state,+ zipcode: context.propsValue.zipcode,+ country: context.propsValue.country,+ territory_id: context.propsValue.territory_id,+ owner_id: context.propsValue.owner_id,+ subscription_status: context.propsValue.subscription_status,+ contact_status_id: context.propsValue.contact_status_id,+ lifecycle_stage_id: context.propsValue.lifecycle_stage_id,+ lead_source_id: context.propsValue.lead_source_id,+ sales_account_id: context.propsValue.sales_account_id,+ custom_fields: context.propsValue.custom_fields,+ });+ if (Object.keys(contact).length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ const primaryAccountId = freshsalesClient.toId({+ value: context.propsValue.sales_account_id,+ field: 'Account ID',+ });+ if (primaryAccountId !== undefined) {+ const current = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/api/contacts/${contactId}`,+ query: { include: 'sales_accounts' },+ });+ contact['sales_accounts'] = freshsalesRecords.mergeSalesAccounts({+ existingIds: freshsalesRecords.readSalesAccountIds(current),+ primaryId: primaryAccountId,+ });+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/contacts/${contactId}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.contacts },+ body: { contact },+ });+ return freshsalesRecords.shapeContact(+ freshsalesClient.unwrap({ body: response, key: 'contact' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-deal.ts b/packages/pieces/community/freshsales/src/lib/actions/update-deal.tsnew file mode 100644index 00000000000..05988fe6df7--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-deal.ts@@ -0,0 +1,94 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { dealOutputSchema } from '../output-schemas';++export const updateDeal = createAction({+ auth: freshsalesAuth,+ name: 'update_deal',+ displayName: 'Update Deal',+ description: 'Update a deal or move it to another stage',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing Freshsales deal by numeric ID, including moving it to another stage. Only the fields you provide are changed. Returns the updated deal. Idempotent: repeating the call with the same values gives the same result.',+ idempotent: true,+ },+ outputSchema: dealOutputSchema,+ props: {+ deal_id: Property.ShortText({+ displayName: 'Deal ID',+ description: 'ID of the deal to update',+ placeholder: '16000123456',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Name of the deal',+ placeholder: 'Acme renewal 2026',+ required: false,+ }),+ amount: Property.Number({+ displayName: 'Amount',+ description: 'Deal value',+ required: false,+ }),+ sales_account_id: Property.ShortText({+ displayName: 'Account ID',+ description: 'ID of the account the deal belongs to',+ placeholder: '16000123456',+ required: false,+ }),+ currency_id: freshsalesProps.currency(),+ deal_pipeline_id: freshsalesProps.dealPipeline(),+ deal_stage_id: freshsalesProps.dealStage(),+ deal_type_id: freshsalesProps.dealType(),+ owner_id: freshsalesProps.owner({ required: false }),+ territory_id: freshsalesProps.territory(),+ lead_source_id: freshsalesProps.leadSource(),+ expected_close: Property.DateTime({+ displayName: 'Expected Close',+ description: 'Expected close date',+ required: false,+ }),+ probability: Property.Number({+ displayName: 'Probability (%)',+ description: 'Win probability from 0 to 100',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.deal_id, field: 'Deal ID' });+ const deal = freshsalesRecords.buildDealBody({+ name: context.propsValue.name,+ amount: context.propsValue.amount,+ sales_account_id: context.propsValue.sales_account_id,+ currency_id: context.propsValue.currency_id,+ deal_pipeline_id: context.propsValue.deal_pipeline_id,+ deal_stage_id: context.propsValue.deal_stage_id,+ deal_type_id: context.propsValue.deal_type_id,+ owner_id: context.propsValue.owner_id,+ territory_id: context.propsValue.territory_id,+ lead_source_id: context.propsValue.lead_source_id,+ expected_close: context.propsValue.expected_close,+ probability: context.propsValue.probability,+ custom_fields: context.propsValue.custom_fields,+ });+ if (Object.keys(deal).length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/deals/${id}`,+ query: { include: freshsalesRecords.RECORD_INCLUDES.deals },+ body: { deal },+ });+ return freshsalesRecords.shapeDeal(freshsalesClient.unwrap({ body: response, key: 'deal' }));+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-note.ts b/packages/pieces/community/freshsales/src/lib/actions/update-note.tsnew file mode 100644index 00000000000..dd38a536275--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-note.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { noteOutputSchema } from '../output-schemas';++export const updateNote = createAction({+ auth: freshsalesAuth,+ name: 'update_note',+ displayName: 'Update Note',+ description: 'Change the text of an existing note',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Replaces the text of an existing Freshsales note by numeric note ID (the ID returned by Add Note). Idempotent: repeating the call with the same text gives the same result.',+ idempotent: true,+ },+ outputSchema: noteOutputSchema,+ props: {+ note_id: Property.ShortText({+ displayName: 'Note ID',+ description: 'ID of the note to update',+ placeholder: '16000123456',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Note',+ description: 'New text of the note',+ required: true,+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.note_id, field: 'Note ID' });+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/notes/${id}`,+ body: { note: { description: context.propsValue.description } },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'note' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/update-task.ts b/packages/pieces/community/freshsales/src/lib/actions/update-task.tsnew file mode 100644index 00000000000..e0f7a9514a9--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/update-task.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesRecords } from '../common/records';+import { freshsalesProps } from '../common/props';+import { taskOutputSchema } from '../output-schemas';++export const updateTask = createAction({+ auth: freshsalesAuth,+ name: 'update_task',+ displayName: 'Update Task',+ description: 'Update a task or mark it completed',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates an existing Freshsales task by numeric ID; set Status to Completed to close it. Only the fields you provide are changed. Idempotent: repeating the call with the same values gives the same result.',+ idempotent: true,+ },+ outputSchema: taskOutputSchema,+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description: 'ID of the task to update',+ placeholder: '16000123456',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'New title of the task',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New details of the task',+ required: false,+ }),+ due_date: Property.DateTime({+ displayName: 'Due Date',+ description: 'New due date',+ required: false,+ }),+ owner_id: freshsalesProps.owner({ required: false, description: 'User the task is assigned to' }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Open or completed',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Open', value: '0' },+ { label: 'Completed', value: '1' },+ ],+ },+ }),+ },+ async run(context) {+ const id = freshsalesClient.requireId({ value: context.propsValue.task_id, field: 'Task ID' });+ const status = context.propsValue.status;+ if (status !== undefined && status !== null && status !== '0' && status !== '1') {+ throw new Error('Status must be 0 (open) or 1 (completed).');+ }+ const task = freshsalesClient.pickDefined({+ title: context.propsValue.title,+ description: context.propsValue.description,+ due_date: freshsalesClient.toIsoDate(context.propsValue.due_date),+ owner_id: freshsalesClient.toId({ value: context.propsValue.owner_id, field: 'Owner' }),+ status: status === undefined || status === null ? undefined : Number(status),+ });+ if (Object.keys(task).length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `/api/tasks/${id}`,+ body: { task },+ });+ return freshsalesRecords.shapeTargetable(+ freshsalesClient.unwrap({ body: response, key: 'task' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/actions/upsert-contact.ts b/packages/pieces/community/freshsales/src/lib/actions/upsert-contact.tsnew file mode 100644index 00000000000..6a061d9b8a8--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/actions/upsert-contact.ts@@ -0,0 +1,138 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from '../common/client';+import { freshsalesProps } from '../common/props';+import { freshsalesRecords } from '../common/records';+import { contactOutputSchema } from '../output-schemas';++export const upsertContact = createAction({+ auth: freshsalesAuth,+ name: 'upsert_contact',+ displayName: 'Create or Update Contact',+ description: 'Update the contact with this email, or create it',+ audience: 'both',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a contact, or updates the existing contact that has the same email address (Freshsales upsert keyed on emails). Use this instead of Create Contact when the contact may already exist. Idempotent: a second call with the same email updates the same contact and does not create a duplicate.',+ idempotent: true,+ },+ outputSchema: contactOutputSchema,+ props: {+ first_name: Property.ShortText({+ displayName: 'First name',+ description: 'First name of the contact',+ required: false,+ }),+ last_name: Property.ShortText({+ displayName: 'Last name',+ description: 'Last name of the contact',+ required: false,+ }),+ job_title: Property.ShortText({+ displayName: 'Job title',+ description: 'Job title of the contact',+ required: false,+ }),+ email: Property.ShortText({+ displayName: 'Email',+ description: 'Primary email address of the contact',+ placeholder: '[email protected]',+ required: true,+ }),+ work_number: Property.ShortText({+ displayName: 'Work number',+ description: 'Work phone number of the contact',+ required: false,+ }),+ mobile_number: Property.ShortText({+ displayName: 'Mobile number',+ description: 'Mobile phone number of the contact',+ required: false,+ }),+ address: Property.ShortText({+ displayName: 'Address',+ description: 'Street address of the contact',+ required: false,+ }),+ city: Property.ShortText({+ displayName: 'City',+ description: 'City of the contact',+ required: false,+ }),+ state: Property.ShortText({+ displayName: 'State',+ description: 'State of the contact',+ required: false,+ }),+ zipcode: Property.ShortText({+ displayName: 'Zip code',+ description: 'Zip code of the contact',+ required: false,+ }),+ country: Property.ShortText({+ displayName: 'Country',+ description: 'Country of the contact',+ required: false,+ }),+ territory_id: freshsalesProps.territory(),+ owner_id: freshsalesProps.owner({ required: false }),+ subscription_status: Property.StaticDropdown({+ displayName: 'Subscription status',+ description: 'Email subscription status of the contact',+ required: false,+ options: {+ disabled: false,+ options: freshsalesRecords.SUBSCRIPTION_STATUS_OPTIONS,+ },+ }),+ contact_status_id: freshsalesProps.contactStatus(),+ lifecycle_stage_id: freshsalesProps.lifecycleStage(),+ lead_source_id: freshsalesProps.leadSource(),+ sales_account_id: Property.ShortText({+ displayName: 'Sales account id',+ description: 'ID of the primary account of the contact',+ placeholder: '16000123456',+ required: false,+ }),+ custom_fields: freshsalesProps.customFields(),+ },+ async run(context) {+ const contact = freshsalesRecords.buildContactBody({+ first_name: context.propsValue.first_name,+ last_name: context.propsValue.last_name,+ job_title: context.propsValue.job_title,+ email: context.propsValue.email,+ work_number: context.propsValue.work_number,+ mobile_number: context.propsValue.mobile_number,+ address: context.propsValue.address,+ city: context.propsValue.city,+ state: context.propsValue.state,+ zipcode: context.propsValue.zipcode,+ country: context.propsValue.country,+ territory_id: context.propsValue.territory_id,+ owner_id: context.propsValue.owner_id,+ subscription_status: context.propsValue.subscription_status,+ contact_status_id: context.propsValue.contact_status_id,+ lifecycle_stage_id: context.propsValue.lifecycle_stage_id,+ lead_source_id: context.propsValue.lead_source_id,+ sales_account_id: context.propsValue.sales_account_id,+ custom_fields: context.propsValue.custom_fields,+ });+ const email = String(contact['email'] ?? '');+ if (email.length === 0) {+ throw new Error('Email is required to create or update a contact.');+ }+ const response = await freshsalesClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/api/contacts/upsert',+ query: { include: freshsalesRecords.RECORD_INCLUDES.contacts },+ body: { unique_identifier: { emails: email }, contact },+ });+ return freshsalesRecords.shapeContact(+ freshsalesClient.unwrap({ body: response, key: 'contact' })+ );+ },+});diff --git a/packages/pieces/community/freshsales/src/lib/auth.ts b/packages/pieces/community/freshsales/src/lib/auth.tsindex d296c874953..3c0d056904d 100644--- a/packages/pieces/community/freshsales/src/lib/auth.ts+++ b/packages/pieces/community/freshsales/src/lib/auth.ts@@ -1,27 +1,55 @@+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { freshsalesClient } from './common/client';const markdownDescription = `-To obtain your API key and bundle alias, follow these steps:+Connect your Freshsales (Freshworks CRM) account:-1. Log in to your Freshsales account.-2. Click on your profile icon in the top-right corner of the screen and select **Settings** from the dropdown menu.-3. In the settings menu, select **API Settings** from the left-hand navigation panel.-4. You should now see your API key displayed on the screen. If you don't see an API key.-5. Copy the alias e.g **https://<alias>.myfreshworks.com**+1. Log in to Freshsales and look at the address bar: **https://<alias>.myfreshworks.com**. The part before \`.myfreshworks.com\` is your alias.+2. Click your profile icon in the top-right corner and select **Settings**.+3. Open **API Settings** (under Personal settings).+4. Copy the API key shown on that page. If no key is shown, ask your Freshsales admin to enable API access for your user.+5. Paste the alias (e.g. \`acme\`, or the full URL) and the API key below.`;export const freshsalesAuth = PieceAuth.BasicAuth({+ displayName: 'Freshsales Connection',description: markdownDescription,username: Property.ShortText({displayName: 'Bundle alias',- description:- 'Your Freshsales bundle alias (e.g. https://<alias>.myfreshworks.com)',+ description: 'Alias or URL, e.g. acme or https://acme.myfreshworks.com',required: true,}),password: Property.ShortText({displayName: 'API Key',- description: 'The API Key supplied by Freshsales',+ description: 'The API key from Settings > API Settings',required: true,}),required: true,+ validate: async ({ auth }) => {+ try {+ freshsalesClient.normalizeAlias(auth.username);+ } catch (error) {+ return {+ valid: false,+ error: error instanceof Error ? error.message : 'Invalid alias.',+ };+ }+ try {+ await freshsalesClient.request({+ auth,+ method: HttpMethod.GET,+ path: '/api/selector/owners',+ });+ return { valid: true };+ } catch (error) {+ return {+ valid: false,+ error:+ error instanceof Error+ ? error.message+ : 'Could not connect to Freshsales. Check the alias and API key.',+ };+ }+ },});diff --git a/packages/pieces/community/freshsales/src/lib/common/client.ts b/packages/pieces/community/freshsales/src/lib/common/client.tsnew file mode 100644index 00000000000..40046fe6fbe--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/common/client.ts@@ -0,0 +1,263 @@+import {+ httpClient,+ HttpError,+ HttpMethod,+ QueryParams,+} from '@activepieces/pieces-common';++export const freshsalesClient = {+ normalizeAlias,+ getBaseUrl,+ getAuthHeaders,+ request,+ pickDefined,+ toId,+ requireId,+ toCustomFields,+ toIsoDate,+ unwrap,+ readArray,+ readMeta,+ isRecord,+ isNotFound,+};++export class FreshsalesApiError extends Error {+ readonly status: number;++ constructor({ status, message }: { status: number; message: string }) {+ super(message);+ this.name = 'FreshsalesApiError';+ this.status = status;+ }+}++const HOST_SUFFIX = '.myfreshworks.com';+const ALIAS_PATTERN = /^[a-z0-9][a-z0-9-]*$/;++function normalizeAlias(input: string): string {+ const withoutScheme = input.trim().toLowerCase().replace(/^https?:\/\//, '');+ const host = withoutScheme.split(/[/?#]/)[0];+ const slug = host.endsWith(HOST_SUFFIX)+ ? host.slice(0, -HOST_SUFFIX.length)+ : host;+ if (!ALIAS_PATTERN.test(slug)) {+ throw new Error(+ 'Invalid Freshsales alias. Enter the part before .myfreshworks.com, e.g. "acme".'+ );+ }+ return slug;+}++function getCrmRootUrl(alias: string): string {+ return `https://${normalizeAlias(alias)}${HOST_SUFFIX}/crm/sales`;+}++function getBaseUrl(alias: string): string {+ return `${getCrmRootUrl(alias)}/api`;+}++function getAuthHeaders(auth: FreshsalesAuthValue): Record<string, string> {+ return {+ Authorization: `Token token=${auth.password.trim()}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function extractVendorMessage(body: unknown): string | undefined {+ if (typeof body === 'string' && body.length > 0) {+ return body.slice(0, 300);+ }+ if (!isRecord(body)) {+ return undefined;+ }+ const errors = body['errors'];+ if (isRecord(errors)) {+ const message = errors['message'];+ if (Array.isArray(message)) {+ return message.map((m) => String(m)).join('; ');+ }+ if (typeof message === 'string') {+ return message;+ }+ }+ if (typeof body['message'] === 'string') {+ return body['message'];+ }+ return undefined;+}++function describeError({+ status,+ body,+}: {+ status: number;+ body: unknown;+}): string {+ const vendorMessage = extractVendorMessage(body);+ if (status === 401 || status === 403) {+ return `Freshsales rejected the API key (HTTP ${status}). Check the API key and alias.${+ vendorMessage ? ` ${vendorMessage}` : ''+ }`;+ }+ if (status === 404) {+ return `Freshsales record or endpoint not found (HTTP 404).${+ vendorMessage ? ` ${vendorMessage}` : ''+ }`;+ }+ if (status === 429) {+ return 'Freshsales rate limit reached (1000 requests per hour). Try again later.';+ }+ if (status >= 300 && status < 400) {+ return `Freshsales redirected the request (HTTP ${status}). Check the account alias.`;+ }+ return `Freshsales request failed (HTTP ${status})${+ vendorMessage ? `: ${vendorMessage}` : '.'+ }`;+}++async function request<T>({+ auth,+ method,+ path,+ query,+ body,+}: RequestParams): Promise<T> {+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${getCrmRootUrl(auth.username)}${path}`,+ headers: getAuthHeaders(auth),+ queryParams: query,+ body,+ followRedirects: false,+ });+ if (response.status >= 300) {+ throw new FreshsalesApiError({+ status: response.status,+ message: describeError({ status: response.status, body: response.body }),+ });+ }+ return response.body;+ } catch (error) {+ if (error instanceof HttpError) {+ throw new FreshsalesApiError({+ status: error.response.status,+ message: describeError({ status: error.response.status, body: error.response.body }),+ });+ }+ throw error;+ }+}++function isNotFound(error: unknown): boolean {+ return error instanceof FreshsalesApiError && error.status === 404;+}++function pickDefined(+ input: Record<string, unknown>+): Record<string, unknown> {+ const output: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(input)) {+ if (value !== undefined && value !== null && value !== '') {+ output[key] = value;+ }+ }+ return output;+}++function toId({+ value,+ field,+}: {+ value: unknown;+ field: string;+}): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const text = String(value).trim();+ if (!/^\d+$/.test(text)) {+ throw new Error(`${field} must be a numeric Freshsales ID, got "${text}".`);+ }+ return Number(text);+}++function requireId({ value, field }: { value: unknown; field: string }): number {+ const id = toId({ value, field });+ if (id === undefined) {+ throw new Error(`${field} is required.`);+ }+ return id;+}++function toCustomFields(value: unknown): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (!isRecord(value)) {+ throw new Error('Custom Fields must be a JSON object, e.g. {"cf_plan": "Pro"}.');+ }+ return Object.keys(value).length > 0 ? value : undefined;+}++function toIsoDate(value: unknown): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const date = new Date(String(value));+ if (Number.isNaN(date.getTime())) {+ throw new Error(`Invalid date "${String(value)}". Use ISO 8601.`);+ }+ return date.toISOString();+}++function unwrap({+ body,+ key,+}: {+ body: unknown;+ key: string;+}): Record<string, unknown> {+ if (isRecord(body) && isRecord(body[key])) {+ return body[key];+ }+ throw new Error(`Unexpected Freshsales response: missing "${key}".`);+}++function readArray({ body, key }: { body: unknown; key: string }): unknown[] {+ if (isRecord(body) && Array.isArray(body[key])) {+ return body[key];+ }+ return [];+}++function readMeta(body: unknown): { total?: number; total_pages?: number } {+ if (isRecord(body) && isRecord(body['meta'])) {+ const meta = body['meta'];+ return {+ total: typeof meta['total'] === 'number' ? meta['total'] : undefined,+ total_pages:+ typeof meta['total_pages'] === 'number' ? meta['total_pages'] : undefined,+ };+ }+ return {};+}++export type FreshsalesAuthValue = {+ username: string;+ password: string;+};++type RequestParams = {+ auth: FreshsalesAuthValue;+ method: HttpMethod;+ path: string;+ query?: QueryParams;+ body?: unknown;+};diff --git a/packages/pieces/community/freshsales/src/lib/common/props.ts b/packages/pieces/community/freshsales/src/lib/common/props.tsnew file mode 100644index 00000000000..de082343286--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/common/props.ts@@ -0,0 +1,426 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient, FreshsalesAuthValue } from './client';++export const SELECTOR_TYPES = [+ { label: 'Territories', value: 'territories' },+ { label: 'Contact Statuses', value: 'contact_statuses' },+ { label: 'Lifecycle Stages', value: 'lifecycle_stages' },+ { label: 'Lead Sources', value: 'lead_sources' },+ { label: 'Campaigns', value: 'campaigns' },+ { label: 'Currencies', value: 'currencies' },+ { label: 'Deal Types', value: 'deal_types' },+ { label: 'Deal Reasons', value: 'deal_reasons' },+ { label: 'Industry Types', value: 'industry_types' },+ { label: 'Business Types', value: 'business_types' },+ { label: 'Sales Activity Types', value: 'sales_activity_types' },+];++export const TARGETABLE_TYPES = [+ { label: 'Contact', value: 'Contact' },+ { label: 'Account', value: 'SalesAccount' },+ { label: 'Deal', value: 'Deal' },+];++export const ENTITY_OPTIONS = [+ { label: 'Contacts', value: 'contacts' },+ { label: 'Accounts', value: 'sales_accounts' },+ { label: 'Deals', value: 'deals' },+];++export const FILTER_OPERATORS = [+ { label: 'Is any of', value: 'is_in' },+ { label: 'Is none of', value: 'is_not_in' },+ { label: 'Is after (date)', value: 'is_after' },+ { label: 'Is before (date)', value: 'is_before' },+];++export const freshsalesProps = {+ owner,+ territory,+ contactStatus,+ lifecycleStage,+ leadSource,+ campaign,+ currency,+ dealType,+ industryType,+ businessType,+ dealPipeline,+ dealStage,+ salesActivityType,+ salesActivityOutcome,+ view,+ targetableType,+ targetableId,+ customFields,+ marketingList,+ SELECTOR_TYPES,+ ENTITY_OPTIONS,+ TARGETABLE_TYPES,+ fetchSelector,+ findDefaultViewId,+};++const DEFAULT_VIEW_NAMES: Record<string, string> = {+ contacts: 'All Contacts',+ sales_accounts: 'All Accounts',+ deals: 'All Deals',+};++async function fetchSelector({+ auth,+ path,+}: {+ auth: FreshsalesAuthValue;+ path: string;+}): Promise<SelectorItem[]> {+ const body = await freshsalesClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path,+ });+ return toSelectorItems(body);+}++function toSelectorItems(body: unknown): SelectorItem[] {+ if (!freshsalesClient.isRecord(body)) {+ return [];+ }+ const list = Object.values(body).find((value) => Array.isArray(value));+ if (!Array.isArray(list)) {+ return [];+ }+ const items: SelectorItem[] = [];+ for (const entry of list) {+ if (!freshsalesClient.isRecord(entry) || entry['id'] === undefined) {+ continue;+ }+ const name =+ entry['display_name'] ?? entry['name'] ?? entry['currency_code'] ?? entry['email'];+ items.push({+ id: String(entry['id']),+ name: name === undefined || name === null ? String(entry['id']) : String(name),+ email: typeof entry['email'] === 'string' ? entry['email'] : undefined,+ position: typeof entry['position'] === 'number' ? entry['position'] : undefined,+ });+ }+ return items;+}++function selectorDropdown({+ displayName,+ description,+ path,+ required,+}: {+ displayName: string;+ description: string;+ path: string;+ required: boolean;+}) {+ return Property.Dropdown({+ auth: freshsalesAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };+ }+ try {+ const items = await fetchSelector({ auth, path });+ return {+ disabled: false,+ options: items.map((item) => ({ label: item.name, value: item.id })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message : 'Could not load options.',+ };+ }+ },+ });+}++function owner({ required, description }: { required: boolean; description?: string }) {+ return selectorDropdown({+ displayName: 'Owner',+ description: description ?? 'The Freshsales user who owns the record',+ path: '/api/selector/owners',+ required,+ });+}++function marketingList() {+ return selectorDropdown({+ displayName: 'Marketing List',+ description: 'The marketing list to change',+ path: '/api/lists',+ required: true,+ });+}++function territory() {+ return selectorDropdown({+ displayName: 'Territory',+ description: 'The territory the record belongs to',+ path: '/api/selector/territories',+ required: false,+ });+}++function contactStatus() {+ return selectorDropdown({+ displayName: 'Contact Status',+ description: 'The status of the contact',+ path: '/api/selector/contact_statuses',+ required: false,+ });+}++function lifecycleStage() {+ return selectorDropdown({+ displayName: 'Lifecycle Stage',+ description: 'The lifecycle stage of the contact',+ path: '/api/selector/lifecycle_stages',+ required: false,+ });+}++function leadSource() {+ return selectorDropdown({+ displayName: 'Lead Source',+ description: 'Where the record came from',+ path: '/api/selector/lead_sources',+ required: false,+ });+}++function campaign() {+ return selectorDropdown({+ displayName: 'Campaign',+ description: 'The campaign that brought the record',+ path: '/api/selector/campaigns',+ required: false,+ });+}++function currency() {+ return selectorDropdown({+ displayName: 'Currency',+ description: 'Deal currency (defaults to the account currency)',+ path: '/api/selector/currencies',+ required: false,+ });+}++function dealType() {+ return selectorDropdown({+ displayName: 'Deal Type',+ description: 'The type of the deal',+ path: '/api/selector/deal_types',+ required: false,+ });+}++function industryType() {+ return selectorDropdown({+ displayName: 'Industry Type',+ description: 'Industry of the account',+ path: '/api/selector/industry_types',+ required: false,+ });+}++function businessType() {+ return selectorDropdown({+ displayName: 'Business Type',+ description: 'Business type of the account',+ path: '/api/selector/business_types',+ required: false,+ });+}++function dealPipeline() {+ return selectorDropdown({+ displayName: 'Pipeline',+ description: 'The deal pipeline',+ path: '/api/selector/deal_pipelines',+ required: false,+ });+}++function dealStage() {+ return Property.Dropdown({+ auth: freshsalesAuth,+ displayName: 'Deal Stage',+ description: 'Stage of the deal; pick a pipeline first to narrow it',+ required: false,+ refreshers: ['deal_pipeline_id'],+ options: async ({ auth, deal_pipeline_id }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };+ }+ const pipelineId =+ typeof deal_pipeline_id === 'string' && deal_pipeline_id.length > 0+ ? deal_pipeline_id+ : undefined;+ try {+ const items = await fetchSelector({+ auth,+ path: pipelineId+ ? `/api/selector/deal_pipelines/${encodeURIComponent(pipelineId)}/deal_stages`+ : '/api/selector/deal_stages',+ });+ return {+ disabled: false,+ options: items.map((item) => ({ label: item.name, value: item.id })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message : 'Could not load stages.',+ };+ }+ },+ });+}++function salesActivityType() {+ return selectorDropdown({+ displayName: 'Activity Type',+ description: 'The sales activity type',+ path: '/api/selector/sales_activity_types',+ required: true,+ });+}++function salesActivityOutcome() {+ return Property.Dropdown({+ auth: freshsalesAuth,+ displayName: 'Outcome',+ description: 'Outcome of the activity (depends on the type)',+ required: false,+ refreshers: ['sales_activity_type_id'],+ options: async ({ auth, sales_activity_type_id }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };+ }+ if (typeof sales_activity_type_id !== 'string' || sales_activity_type_id.length === 0) {+ return { disabled: true, options: [], placeholder: 'Select an activity type first.' };+ }+ try {+ const items = await fetchSelector({+ auth,+ path: `/api/selector/sales_activity_types/${encodeURIComponent(+ sales_activity_type_id+ )}/sales_activity_outcomes`,+ });+ return {+ disabled: false,+ options: items.map((item) => ({ label: item.name, value: item.id })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message : 'Could not load outcomes.',+ };+ }+ },+ });+}++function view() {+ return Property.Dropdown({+ auth: freshsalesAuth,+ displayName: 'View',+ description: 'Saved view to list; leave empty for the "All" view',+ required: false,+ refreshers: ['entity'],+ options: async ({ auth, entity }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };+ }+ if (typeof entity !== 'string' || entity.length === 0) {+ return { disabled: true, options: [], placeholder: 'Select a record type first.' };+ }+ try {+ const items = await fetchSelector({+ auth,+ path: `/api/${encodeURIComponent(entity)}/filters`,+ });+ return {+ disabled: false,+ options: items.map((item) => ({ label: item.name, value: item.id })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: error instanceof Error ? error.message : 'Could not load views.',+ };+ }+ },+ });+}++function targetableType({ required }: { required: boolean }) {+ return Property.StaticDropdown({+ displayName: 'Related To',+ description: 'Type of the record this is linked to',+ required,+ options: { disabled: false, options: TARGETABLE_TYPES },+ });+}++function targetableId({ required }: { required: boolean }) {+ return Property.ShortText({+ displayName: 'Related Record ID',+ description: 'ID of the contact, account or deal',+ placeholder: '16000123456',+ required,+ });+}++function customFields() {+ return Property.Json({+ displayName: 'Custom Fields',+ description: 'Custom field values keyed by API name (cf_...)',+ required: false,+ defaultValue: {},+ });+}++async function findDefaultViewId({+ auth,+ entity,+}: {+ auth: FreshsalesAuthValue;+ entity: string;+}): Promise<string> {+ const items = await fetchSelector({ auth, path: `/api/${entity}/filters` });+ const systemName = DEFAULT_VIEW_NAMES[entity];+ const exact =+ systemName === undefined+ ? undefined+ : items.find((item) => item.name.trim().toLowerCase() === systemName.toLowerCase());+ const allView = exact ?? items.find((item) => /^all\b/i.test(item.name)) ?? items[0];+ if (!allView) {+ throw new Error(`No saved views found for ${entity}.`);+ }+ return allView.id;+}++export type SelectorItem = {+ id: string;+ name: string;+ email?: string;+ position?: number;+};diff --git a/packages/pieces/community/freshsales/src/lib/common/record-polling.ts b/packages/pieces/community/freshsales/src/lib/common/record-polling.tsnew file mode 100644index 00000000000..e5e25639859--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/common/record-polling.ts@@ -0,0 +1,192 @@+import {+ DedupeStrategy,+ HttpMethod,+ Polling,+} from '@activepieces/pieces-common';+import { AppConnectionValueForAuthProperty, Store } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesClient } from './client';+import { freshsalesProps } from './props';+import { freshsalesRecords, RecordEntity } from './records';++export const freshsalesPolling = {+ buildPolling,+};++const PER_PAGE = 100;+const MAX_PAGES = 10;+const TEST_PER_PAGE = 5;+const VIEW_ID_STORE_PREFIX = 'freshsales_default_view_';++function buildPolling({+ entity,+ timestampField,+}: {+ entity: RecordEntity;+ timestampField: 'created_at' | 'updated_at';+}): Polling<AppConnectionValueForAuthProperty<typeof freshsalesAuth>, Record<string, never>> {+ return {+ strategy: DedupeStrategy.TIMEBASED,+ items: async ({ auth, store, lastFetchEpochMS }) => {+ const isTest = lastFetchEpochMS === 0;+ const perPage = isTest ? TEST_PER_PAGE : PER_PAGE;+ const viewKey = `${VIEW_ID_STORE_PREFIX}${entity}`;+ const cachedViewId = await store.get<string>(viewKey);+ let viewId = cachedViewId ?? (await lookupViewId({ auth, store, entity, viewKey }));+ let viewRefreshed = cachedViewId === null || cachedViewId === undefined;+ const fetchPage = async (+ page: number+ ): Promise<{ records: Record<string, unknown>[]; totalPages: number | undefined }> => {+ try {+ return await fetchViewPage({ auth, entity, viewId, timestampField, page, perPage });+ } catch (error) {+ if (viewRefreshed || !freshsalesClient.isNotFound(error)) {+ throw error;+ }+ viewRefreshed = true;+ await store.delete(viewKey);+ viewId = await lookupViewId({ auth, store, entity, viewKey });+ return await fetchViewPage({ auth, entity, viewId, timestampField, page, perPage });+ }+ };+ const toItems = (records: Record<string, unknown>[]) =>+ records+ .map((record) => ({ record, epoch: readEpoch({ record, timestampField }) }))+ .filter(({ epoch }) => !Number.isNaN(epoch) && epoch > lastFetchEpochMS)+ .map(({ record, epoch }) => ({+ epochMilliSeconds: epoch,+ data: freshsalesRecords.shapeRecord({ entity, record }),+ }));++ if (isTest) {+ return toItems((await fetchPage(1)).records);+ }++ const collected: PolledItem[] = [];+ let totalPages = 1;+ for (let page = 1; page <= MAX_PAGES; page++) {+ const result = await fetchPage(page);+ totalPages = result.totalPages ?? totalPages;+ collected.push(...toItems(result.records));+ if (+ result.records.length < perPage ||+ reachesCheckpoint({ records: result.records, timestampField, lastFetchEpochMS })+ ) {+ return collected;+ }+ }++ let low = MAX_PAGES + 1;+ let high = Math.max(totalPages, low);+ const pages = new Map<number, Record<string, unknown>[]>();+ while (low < high) {+ const mid = Math.floor((low + high) / 2);+ const records = (await fetchPage(mid)).records;+ pages.set(mid, records);+ if (+ records.length < perPage ||+ reachesCheckpoint({ records, timestampField, lastFetchEpochMS })+ ) {+ high = mid;+ } else {+ low = mid + 1;+ }+ }++ const oldest: PolledItem[] = [];+ const firstPage = Math.max(1, low - MAX_PAGES + 1);+ for (let page = low; page >= firstPage; page--) {+ const records = pages.get(page) ?? (await fetchPage(page)).records;+ oldest.push(...toItems(records));+ }+ if (oldest.length === 0) {+ return collected;+ }+ const newestEpoch = oldest.reduce(+ (acc, item) => (item.epochMilliSeconds > acc ? item.epochMilliSeconds : acc),+ lastFetchEpochMS+ );+ const complete = oldest.filter((item) => item.epochMilliSeconds < newestEpoch);+ return complete.length > 0 ? complete : oldest;+ },+ };+}++async function lookupViewId({+ auth,+ store,+ entity,+ viewKey,+}: {+ auth: AppConnectionValueForAuthProperty<typeof freshsalesAuth>;+ store: Store;+ entity: RecordEntity;+ viewKey: string;+}): Promise<string> {+ const viewId = await freshsalesProps.findDefaultViewId({ auth, entity });+ await store.put(viewKey, viewId);+ return viewId;+}++async function fetchViewPage({+ auth,+ entity,+ viewId,+ timestampField,+ page,+ perPage,+}: {+ auth: AppConnectionValueForAuthProperty<typeof freshsalesAuth>;+ entity: RecordEntity;+ viewId: string;+ timestampField: 'created_at' | 'updated_at';+ page: number;+ perPage: number;+}): Promise<{ records: Record<string, unknown>[]; totalPages: number | undefined }> {+ const response = await freshsalesClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path: `/api/${entity}/view/${encodeURIComponent(viewId)}`,+ query: {+ page: String(page),+ per_page: String(perPage),+ sort: timestampField,+ sort_type: 'desc',+ include: freshsalesRecords.RECORD_INCLUDES[entity],+ },+ });+ const records = freshsalesClient+ .readArray({ body: response, key: entity })+ .filter((item) => freshsalesClient.isRecord(item));+ const meta = freshsalesClient.readMeta(response);+ const totalPages =+ meta.total_pages ?? (meta.total !== undefined ? Math.ceil(meta.total / perPage) : undefined);+ return { records, totalPages };+}++function readEpoch({+ record,+ timestampField,+}: {+ record: Record<string, unknown>;+ timestampField: 'created_at' | 'updated_at';+}): number {+ return new Date(String(record[timestampField] ?? '')).getTime();+}++function reachesCheckpoint({+ records,+ timestampField,+ lastFetchEpochMS,+}: {+ records: Record<string, unknown>[];+ timestampField: 'created_at' | 'updated_at';+ lastFetchEpochMS: number;+}): boolean {+ return records.some((record) => {+ const epoch = readEpoch({ record, timestampField });+ return !Number.isNaN(epoch) && epoch <= lastFetchEpochMS;+ });+}++type PolledItem = { epochMilliSeconds: number; data: Record<string, unknown> };diff --git a/packages/pieces/community/freshsales/src/lib/common/records.ts b/packages/pieces/community/freshsales/src/lib/common/records.tsnew file mode 100644index 00000000000..5cebeb05c0a--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/common/records.ts@@ -0,0 +1,311 @@+import { freshsalesClient } from './client';++export const SUBSCRIPTION_STATUS_OPTIONS = [+ { label: 'Unsubscribed', value: '0' },+ { label: 'Subscribed', value: '1' },+ { label: 'Reported as spam', value: '2' },+ { label: 'Not sure', value: '3' },+];++export const RECORD_INCLUDES: Record<RecordEntity, string> = {+ contacts: 'sales_accounts,owner,contact_status,lifecycle_stage,territory',+ sales_accounts: 'owner,industry_type',+ deals: 'owner,sales_account,currency,deal_type',+};++export const freshsalesRecords = {+ RECORD_INCLUDES,+ isRecordEntity,+ SUBSCRIPTION_STATUS_OPTIONS,+ buildContactBody,+ buildAccountBody,+ buildDealBody,+ shapeContact,+ shapeDeal,+ shapeRecord,+ shapeTargetable,+ toNumber,+ readSalesAccountIds,+ mergeSalesAccounts,+};++function toSubscriptionStatus(value: unknown): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const text = String(value).trim().toLowerCase();+ const match = SUBSCRIPTION_STATUS_OPTIONS.find(+ (option) => option.value === text || option.label.toLowerCase() === text+ );+ if (!match) {+ throw new Error(+ 'Subscription Status must be one of: Unsubscribed, Subscribed, Reported as spam, Not sure.'+ );+ }+ return Number(match.value);+}++function toNumber({ value, field }: { value: unknown; field: string }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed = Number(value);+ if (!Number.isFinite(parsed)) {+ throw new Error(`${field} must be a number.`);+ }+ return parsed;+}++function buildContactBody(input: ContactInput): Record<string, unknown> {+ const salesAccountId = freshsalesClient.toId({+ value: input.sales_account_id,+ field: 'Account ID',+ });+ const custom = freshsalesClient.toCustomFields(input.custom_fields);+ return freshsalesClient.pickDefined({+ first_name: input.first_name,+ last_name: input.last_name,+ job_title: input.job_title,+ email: input.email?.trim(),+ work_number: input.work_number,+ mobile_number: input.mobile_number,+ address: input.address,+ city: input.city,+ state: input.state,+ zipcode: input.zipcode,+ country: input.country,+ territory_id: freshsalesClient.toId({ value: input.territory_id, field: 'Territory' }),+ owner_id: freshsalesClient.toId({ value: input.owner_id, field: 'Owner' }),+ subscription_status: toSubscriptionStatus(input.subscription_status),+ medium: input.medium,+ campaign_id: freshsalesClient.toId({ value: input.campaign_id, field: 'Campaign' }),+ keyword: input.keyword,+ time_zone: input.time_zone,+ facebook: input.facebook,+ twitter: input.twitter,+ linkedin: input.linkedin,+ contact_status_id: freshsalesClient.toId({+ value: input.contact_status_id,+ field: 'Contact Status',+ }),+ lifecycle_stage_id: freshsalesClient.toId({+ value: input.lifecycle_stage_id,+ field: 'Lifecycle Stage',+ }),+ lead_source_id: freshsalesClient.toId({ value: input.lead_source_id, field: 'Lead Source' }),+ sales_accounts:+ salesAccountId === undefined ? undefined : [{ id: salesAccountId, is_primary: true }],+ custom_field: custom,+ });+}++function buildAccountBody(input: AccountInput): Record<string, unknown> {+ return freshsalesClient.pickDefined({+ name: input.name,+ website: input.website,+ phone: input.phone,+ address: input.address,+ city: input.city,+ state: input.state,+ zipcode: input.zipcode,+ country: input.country,+ industry_type_id: freshsalesClient.toId({ value: input.industry_type_id, field: 'Industry Type' }),+ business_type_id: freshsalesClient.toId({ value: input.business_type_id, field: 'Business Type' }),+ number_of_employees: toNumber({ value: input.number_of_employees, field: 'Number of Employees' }),+ annual_revenue: toNumber({ value: input.annual_revenue, field: 'Annual Revenue' }),+ owner_id: freshsalesClient.toId({ value: input.owner_id, field: 'Owner' }),+ territory_id: freshsalesClient.toId({ value: input.territory_id, field: 'Territory' }),+ parent_sales_account_id: freshsalesClient.toId({+ value: input.parent_sales_account_id,+ field: 'Parent Account ID',+ }),+ custom_field: freshsalesClient.toCustomFields(input.custom_fields),+ });+}++function buildDealBody(input: DealInput): Record<string, unknown> {+ const probability = toNumber({ value: input.probability, field: 'Probability' });+ if (probability !== undefined && (probability < 0 || probability > 100)) {+ throw new Error('Probability must be between 0 and 100.');+ }+ const expectedClose = freshsalesClient.toIsoDate(input.expected_close);+ return freshsalesClient.pickDefined({+ name: input.name,+ amount: toNumber({ value: input.amount, field: 'Amount' }),+ sales_account_id: freshsalesClient.toId({ value: input.sales_account_id, field: 'Account ID' }),+ currency_id: freshsalesClient.toId({ value: input.currency_id, field: 'Currency' }),+ deal_pipeline_id: freshsalesClient.toId({ value: input.deal_pipeline_id, field: 'Pipeline' }),+ deal_stage_id: freshsalesClient.toId({ value: input.deal_stage_id, field: 'Deal Stage' }),+ deal_type_id: freshsalesClient.toId({ value: input.deal_type_id, field: 'Deal Type' }),+ owner_id: freshsalesClient.toId({ value: input.owner_id, field: 'Owner' }),+ territory_id: freshsalesClient.toId({ value: input.territory_id, field: 'Territory' }),+ lead_source_id: freshsalesClient.toId({ value: input.lead_source_id, field: 'Lead Source' }),+ expected_close: expectedClose === undefined ? undefined : expectedClose.slice(0, 10),+ probability,+ custom_field: freshsalesClient.toCustomFields(input.custom_fields),+ });+}++function shapeContact(record: Record<string, unknown>): Record<string, unknown> {+ if (record['sales_account_id'] !== undefined) {+ return record;+ }+ const accounts = record['sales_accounts'];+ if (!Array.isArray(accounts)) {+ return record;+ }+ const primary =+ accounts.find((a) => freshsalesClient.isRecord(a) && a['is_primary'] === true) ?? accounts[0];+ return Object.assign({}, record, {+ sales_account_id: freshsalesClient.isRecord(primary) ? primary['id'] ?? null : null,+ });+}++function readSalesAccountIds(body: unknown): number[] {+ if (!freshsalesClient.isRecord(body)) {+ return [];+ }+ const contact = body['contact'];+ const nested = freshsalesClient.isRecord(contact) ? contact['sales_accounts'] : undefined;+ const accounts = Array.isArray(nested) ? nested : body['sales_accounts'];+ if (!Array.isArray(accounts)) {+ return [];+ }+ const ids: number[] = [];+ for (const account of accounts) {+ if (freshsalesClient.isRecord(account)) {+ const id = Number(account['id']);+ if (account['id'] !== null && Number.isSafeInteger(id) && id > 0 && !ids.includes(id)) {+ ids.push(id);+ }+ }+ }+ return ids;+}++function mergeSalesAccounts({+ existingIds,+ primaryId,+}: {+ existingIds: number[];+ primaryId: number;+}): { id: number; is_primary: boolean }[] {+ const others = existingIds.filter((id) => id !== primaryId);+ return [+ { id: primaryId, is_primary: true },+ ...others.map((id) => ({ id, is_primary: false })),+ ];+}++function isRecordEntity(value: unknown): value is RecordEntity {+ return value === 'contacts' || value === 'sales_accounts' || value === 'deals';+}++function shapeDeal(record: Record<string, unknown>): Record<string, unknown> {+ const amount = record['amount'];+ if (typeof amount !== 'string' || amount.trim().length === 0) {+ return record;+ }+ const parsed = Number(amount);+ return Number.isFinite(parsed) ? Object.assign({}, record, { amount: parsed }) : record;+}++function shapeRecord({+ entity,+ record,+}: {+ entity: RecordEntity;+ record: Record<string, unknown>;+}): Record<string, unknown> {+ if (entity === 'contacts') {+ return shapeContact(record);+ }+ if (entity === 'deals') {+ return shapeDeal(record);+ }+ return record;+}++function shapeTargetable(record: Record<string, unknown>): Record<string, unknown> {+ if (record['targetable_type'] !== undefined) {+ return record;+ }+ const targetables = record['targetables'];+ const first = Array.isArray(targetables) ? targetables[0] : undefined;+ if (!freshsalesClient.isRecord(first)) {+ return record;+ }+ return Object.assign({}, record, {+ targetable_type: first['type'] ?? null,+ targetable_id: first['id'] ?? null,+ });+}++export type RecordEntity = 'contacts' | 'sales_accounts' | 'deals';++type Text = string | undefined | null;+type Loose = unknown;++export type ContactInput = {+ first_name?: Text;+ last_name?: Text;+ job_title?: Text;+ email?: Text;+ work_number?: Text;+ mobile_number?: Text;+ address?: Text;+ city?: Text;+ state?: Text;+ zipcode?: Text;+ country?: Text;+ territory_id?: Loose;+ owner_id?: Loose;+ subscription_status?: Loose;+ medium?: Text;+ campaign_id?: Loose;+ keyword?: Text;+ time_zone?: Text;+ facebook?: Text;+ twitter?: Text;+ linkedin?: Text;+ contact_status_id?: Loose;+ lifecycle_stage_id?: Loose;+ lead_source_id?: Loose;+ sales_account_id?: Loose;+ custom_fields?: Loose;+};++export type AccountInput = {+ name?: Text;+ website?: Text;+ phone?: Text;+ address?: Text;+ city?: Text;+ state?: Text;+ zipcode?: Text;+ country?: Text;+ industry_type_id?: Loose;+ business_type_id?: Loose;+ number_of_employees?: Loose;+ annual_revenue?: Loose;+ owner_id?: Loose;+ territory_id?: Loose;+ parent_sales_account_id?: Loose;+ custom_fields?: Loose;+};++export type DealInput = {+ name?: Text;+ amount?: Loose;+ sales_account_id?: Loose;+ currency_id?: Loose;+ deal_pipeline_id?: Loose;+ deal_stage_id?: Loose;+ deal_type_id?: Loose;+ owner_id?: Loose;+ territory_id?: Loose;+ lead_source_id?: Loose;+ expected_close?: Loose;+ probability?: Loose;+ custom_fields?: Loose;+};diff --git a/packages/pieces/community/freshsales/src/lib/output-schemas.ts b/packages/pieces/community/freshsales/src/lib/output-schemas.tsnew file mode 100644index 00000000000..8fd90f6a10c--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/output-schemas.ts@@ -0,0 +1,264 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const contactFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Contact ID' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'emails', label: 'Emails', labelKey: 'value', listItems: [+ { key: 'value', label: 'Email', format: 'email' },+ { key: 'is_primary', label: 'Is Primary', format: 'boolean' },+ ] },+ { key: 'mobile_number', label: 'Mobile Number' },+ { key: 'work_number', label: 'Work Number' },+ { key: 'job_title', label: 'Job Title' },+ { key: 'city', label: 'City' },+ { key: 'country', label: 'Country' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'territory_id', label: 'Territory ID' },+ { key: 'contact_status_id', label: 'Contact Status ID' },+ { key: 'lifecycle_stage_id', label: 'Lifecycle Stage ID' },+ { key: 'sales_account_id', label: 'Primary Account ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'custom_field', label: 'Custom Fields', dynamicKey: true },+];++export const accountFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Account ID' },+ { key: 'name', label: 'Name' },+ { key: 'website', label: 'Website', format: 'url' },+ { key: 'phone', label: 'Phone' },+ { key: 'city', label: 'City' },+ { key: 'country', label: 'Country' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'industry_type_id', label: 'Industry Type ID' },+ { key: 'annual_revenue', label: 'Annual Revenue', format: 'number' },+ { key: 'number_of_employees', label: 'Number of Employees', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'custom_field', label: 'Custom Fields', dynamicKey: true },+];++export const dealFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Deal ID' },+ { key: 'name', label: 'Name' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'currency_id', label: 'Currency ID' },+ { key: 'deal_pipeline_id', label: 'Pipeline ID' },+ { key: 'deal_stage_id', label: 'Stage ID' },+ { key: 'sales_account_id', label: 'Account ID' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'expected_close', label: 'Expected Close', format: 'date' },+ { key: 'probability', label: 'Probability', format: 'number' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'custom_field', label: 'Custom Fields', dynamicKey: true },+];++export const taskFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Task ID' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'due_date', label: 'Due Date', format: 'datetime' },+ { key: 'status', label: 'Status (0 open, 1 done)', format: 'number' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'targetable_type', label: 'Related Type' },+ { key: 'targetable_id', label: 'Related Record ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+];++export const searchResultFields: OutputSchema['fields'] = [+ { key: 'id', label: 'ID' },+ { key: 'type', label: 'Type' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+];++export const deletedFields: OutputSchema['fields'] = [+ { key: 'id', label: 'ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+];++export const contactOutputSchema: OutputSchema = { fields: contactFields };++export const createContactOutputSchema: OutputSchema = {+ fields: [+ ...contactFields,+ { key: 'contact', label: 'Contact (legacy)', children: contactFields },+ ],+};++export const getContactOutputSchema: OutputSchema = {+ fields: [+ ...contactFields,+ { key: 'sales_accounts', label: 'Accounts', labelKey: 'name', listItems: [+ { key: 'id', label: 'Account ID' },+ { key: 'name', label: 'Name' },+ { key: 'is_primary', label: 'Is Primary', format: 'boolean' },+ ] },+ ],+};++export const findContactOutputSchema: OutputSchema = {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'contact', label: 'Contact', children: contactFields },+ ],+};++export const accountOutputSchema: OutputSchema = { fields: accountFields };++export const findAccountOutputSchema: OutputSchema = {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'accounts', label: 'Accounts', labelKey: 'name', listItems: accountFields },+ ],+};++export const dealOutputSchema: OutputSchema = { fields: dealFields };++export const deleteOutputSchema: OutputSchema = { fields: deletedFields };++export const searchRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'results', label: 'Results', labelKey: 'name', listItems: searchResultFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const listRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ ] },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'total', label: 'Total', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const taskOutputSchema: OutputSchema = { fields: taskFields };++export const listTasksOutputSchema: OutputSchema = {+ fields: [+ { key: 'tasks', label: 'Tasks', labelKey: 'title', listItems: taskFields },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const noteOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Note ID' },+ { key: 'description', label: 'Description' },+ { key: 'targetable_type', label: 'Related Type' },+ { key: 'targetable_id', label: 'Related Record ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ ],+};++export const appointmentOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Appointment ID' },+ { key: 'title', label: 'Title' },+ { key: 'from_date', label: 'Start', format: 'datetime' },+ { key: 'end_date', label: 'End', format: 'datetime' },+ { key: 'location', label: 'Location' },+ { key: 'is_allday', label: 'All Day', format: 'boolean' },+ { key: 'targetable_type', label: 'Related Type' },+ { key: 'targetable_id', label: 'Related Record ID' },+ ],+};++export const salesActivityOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Activity ID' },+ { key: 'title', label: 'Title' },+ { key: 'sales_activity_type_id', label: 'Activity Type ID' },+ { key: 'start_date', label: 'Start', format: 'datetime' },+ { key: 'end_date', label: 'End', format: 'datetime' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'targetable_type', label: 'Related Type' },+ { key: 'targetable_id', label: 'Related Record ID' },+ ],+};++export const listUsersOutputSchema: OutputSchema = {+ fields: [+ { key: 'users', label: 'Users', labelKey: 'name', listItems: [+ { key: 'id', label: 'User ID' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ ] },+ ],+};++export const listPipelinesOutputSchema: OutputSchema = {+ fields: [+ { key: 'pipelines', label: 'Pipelines', labelKey: 'name', listItems: [+ { key: 'id', label: 'Pipeline ID' },+ { key: 'name', label: 'Name' },+ { key: 'stages', label: 'Stages', labelKey: 'name', listItems: [+ { key: 'id', label: 'Stage ID' },+ { key: 'name', label: 'Name' },+ { key: 'position', label: 'Position', format: 'number' },+ ] },+ ] },+ ],+};++export const listFieldOptionsOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Options', labelKey: 'name', listItems: [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+ ] },+ ],+};++export const customFieldsOutputSchema: OutputSchema = {+ fields: [+ { key: 'fields', label: 'Fields', labelKey: 'label', listItems: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'required', label: 'Required', format: 'boolean' },+ { key: 'is_custom', label: 'Is Custom', format: 'boolean' },+ { key: 'choices', label: 'Choices', labelKey: 'value', listItems: [+ { key: 'id', label: 'Choice ID' },+ { key: 'value', label: 'Value' },+ ] },+ ] },+ ],+};++export const filteredSearchOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ ] },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'total', label: 'Total', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const marketingListUpdateOutputSchema: OutputSchema = {+ fields: [+ { key: 'list_id', label: 'List ID' },+ { key: 'contact_ids', label: 'Contact IDs' },+ { key: 'message', label: 'Message' },+ ],+};diff --git a/packages/pieces/community/freshsales/src/lib/triggers/new-account.ts b/packages/pieces/community/freshsales/src/lib/triggers/new-account.tsnew file mode 100644index 00000000000..e162b9c8dee--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/triggers/new-account.ts@@ -0,0 +1,52 @@+import { pollingHelper } from '@activepieces/pieces-common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesPolling } from '../common/record-polling';+import { accountOutputSchema } from '../output-schemas';++export const newAccount = createTrigger({+ auth: freshsalesAuth,+ name: 'new_account',+ displayName: 'New Account',+ description: 'Triggers when a new account is created',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a new account (company) is created in Freshsales. Polls the All accounts view sorted by creation time; each event is one new account record.',+ },+ outputSchema: accountOutputSchema,+ type: TriggerStrategy.POLLING,+ props: {},+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return await pollingHelper.poll(polling, context);+ },+ async test(context) {+ return await pollingHelper.test(polling, context);+ },+ sampleData: {+ id: 16000000100,+ name: 'Acme Inc',+ website: 'https://acme.com',+ phone: '+15550100',+ city: 'Austin',+ country: 'USA',+ owner_id: 16000000001,+ industry_type_id: 16000000400,+ annual_revenue: 5000000,+ number_of_employees: 120,+ created_at: '2026-10-22T10:00:00Z',+ updated_at: '2026-10-22T10:05:00Z',+ custom_field: {},+ },+});++const polling = freshsalesPolling.buildPolling({+ entity: 'sales_accounts',+ timestampField: 'created_at',+});diff --git a/packages/pieces/community/freshsales/src/lib/triggers/new-contact.ts b/packages/pieces/community/freshsales/src/lib/triggers/new-contact.tsnew file mode 100644index 00000000000..05aa6f20930--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/triggers/new-contact.ts@@ -0,0 +1,58 @@+import { pollingHelper } from '@activepieces/pieces-common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesPolling } from '../common/record-polling';+import { contactOutputSchema } from '../output-schemas';++export const newContact = createTrigger({+ auth: freshsalesAuth,+ name: 'new_contact',+ displayName: 'New Contact',+ description: 'Triggers when a new contact is created',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a new contact is created in Freshsales. Polls the All contacts view sorted by creation time; each event is one new contact record.',+ },+ outputSchema: contactOutputSchema,+ type: TriggerStrategy.POLLING,+ props: {},+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return await pollingHelper.poll(polling, context);+ },+ async test(context) {+ return await pollingHelper.test(polling, context);+ },+ sampleData: {+ id: 16000123456,+ first_name: 'Jane',+ last_name: 'Doe',+ display_name: 'Jane Doe',+ email: '[email protected]',+ emails: [{ id: 1, value: '[email protected]', is_primary: true }],+ mobile_number: '+15550100',+ work_number: null,+ job_title: 'CTO',+ city: 'Austin',+ country: 'USA',+ owner_id: 16000000001,+ territory_id: null,+ contact_status_id: 16000000010,+ lifecycle_stage_id: 16000000020,+ sales_account_id: 16000000100,+ created_at: '2026-10-22T10:00:00Z',+ updated_at: '2026-10-22T10:05:00Z',+ custom_field: { cf_plan: 'Pro' },+ },+});++const polling = freshsalesPolling.buildPolling({+ entity: 'contacts',+ timestampField: 'created_at',+});diff --git a/packages/pieces/community/freshsales/src/lib/triggers/new-deal.ts b/packages/pieces/community/freshsales/src/lib/triggers/new-deal.tsnew file mode 100644index 00000000000..596b4f12369--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/triggers/new-deal.ts@@ -0,0 +1,52 @@+import { pollingHelper } from '@activepieces/pieces-common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesPolling } from '../common/record-polling';+import { dealOutputSchema } from '../output-schemas';++export const newDeal = createTrigger({+ auth: freshsalesAuth,+ name: 'new_deal',+ displayName: 'New Deal',+ description: 'Triggers when a new deal is created',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a new deal is created in Freshsales. Polls the All deals view sorted by creation time; each event is one new deal record.',+ },+ outputSchema: dealOutputSchema,+ type: TriggerStrategy.POLLING,+ props: {},+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return await pollingHelper.poll(polling, context);+ },+ async test(context) {+ return await pollingHelper.test(polling, context);+ },+ sampleData: {+ id: 16000234567,+ name: 'Acme renewal 2026',+ amount: '12000.0',+ currency_id: 1,+ deal_pipeline_id: 16000000300,+ deal_stage_id: 16000000301,+ sales_account_id: 16000000100,+ owner_id: 16000000001,+ expected_close: '2026-12-31',+ probability: 60,+ created_at: '2026-10-22T10:00:00Z',+ updated_at: '2026-10-22T10:05:00Z',+ custom_field: {},+ },+});++const polling = freshsalesPolling.buildPolling({+ entity: 'deals',+ timestampField: 'created_at',+});diff --git a/packages/pieces/community/freshsales/src/lib/triggers/updated-contact.ts b/packages/pieces/community/freshsales/src/lib/triggers/updated-contact.tsnew file mode 100644index 00000000000..3b0151d6fe1--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/triggers/updated-contact.ts@@ -0,0 +1,58 @@+import { pollingHelper } from '@activepieces/pieces-common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesPolling } from '../common/record-polling';+import { contactOutputSchema } from '../output-schemas';++export const updatedContact = createTrigger({+ auth: freshsalesAuth,+ name: 'updated_contact',+ displayName: 'Updated Contact',+ description: 'Triggers when a contact is created or updated',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a Freshsales contact is updated (new contacts also count as an update). Polls the All contacts view sorted by update time; each event is the contact as it is now.',+ },+ outputSchema: contactOutputSchema,+ type: TriggerStrategy.POLLING,+ props: {},+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return await pollingHelper.poll(polling, context);+ },+ async test(context) {+ return await pollingHelper.test(polling, context);+ },+ sampleData: {+ id: 16000123456,+ first_name: 'Jane',+ last_name: 'Doe',+ display_name: 'Jane Doe',+ email: '[email protected]',+ emails: [{ id: 1, value: '[email protected]', is_primary: true }],+ mobile_number: '+15550100',+ work_number: null,+ job_title: 'CTO',+ city: 'Austin',+ country: 'USA',+ owner_id: 16000000001,+ territory_id: null,+ contact_status_id: 16000000010,+ lifecycle_stage_id: 16000000020,+ sales_account_id: 16000000100,+ created_at: '2026-10-22T10:00:00Z',+ updated_at: '2026-10-22T10:05:00Z',+ custom_field: { cf_plan: 'Pro' },+ },+});++const polling = freshsalesPolling.buildPolling({+ entity: 'contacts',+ timestampField: 'updated_at',+});diff --git a/packages/pieces/community/freshsales/src/lib/triggers/updated-deal.ts b/packages/pieces/community/freshsales/src/lib/triggers/updated-deal.tsnew file mode 100644index 00000000000..c6dd9c01b3a--- /dev/null+++ b/packages/pieces/community/freshsales/src/lib/triggers/updated-deal.ts@@ -0,0 +1,52 @@+import { pollingHelper } from '@activepieces/pieces-common';+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { freshsalesAuth } from '../auth';+import { freshsalesPolling } from '../common/record-polling';+import { dealOutputSchema } from '../output-schemas';++export const updatedDeal = createTrigger({+ auth: freshsalesAuth,+ name: 'updated_deal',+ displayName: 'Updated Deal',+ description: 'Triggers when a deal is created or updated (e.g. stage change)',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a Freshsales deal is updated, including stage changes (new deals also count). Polls the All deals view sorted by update time; each event is the deal as it is now.',+ },+ outputSchema: dealOutputSchema,+ type: TriggerStrategy.POLLING,+ props: {},+ async onEnable(context) {+ await pollingHelper.onEnable(polling, context);+ },+ async onDisable(context) {+ await pollingHelper.onDisable(polling, context);+ },+ async run(context) {+ return await pollingHelper.poll(polling, context);+ },+ async test(context) {+ return await pollingHelper.test(polling, context);+ },+ sampleData: {+ id: 16000234567,+ name: 'Acme renewal 2026',+ amount: '12000.0',+ currency_id: 1,+ deal_pipeline_id: 16000000300,+ deal_stage_id: 16000000301,+ sales_account_id: 16000000100,+ owner_id: 16000000001,+ expected_close: '2026-12-31',+ probability: 60,+ created_at: '2026-10-22T10:00:00Z',+ updated_at: '2026-10-22T10:05:00Z',+ custom_field: {},+ },+});++const polling = freshsalesPolling.buildPolling({+ entity: 'deals',+ timestampField: 'updated_at',+});diff --git a/packages/pieces/community/freshsales/test/record-polling.test.ts b/packages/pieces/community/freshsales/test/record-polling.test.tsnew file mode 100644index 00000000000..3c7d8a4464d--- /dev/null+++ b/packages/pieces/community/freshsales/test/record-polling.test.ts@@ -0,0 +1,260 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { pollingHelper } from '@activepieces/pieces-common';+import { FilesService, Store } from '@activepieces/pieces-framework';+import { FreshsalesApiError, freshsalesClient } from '../src/lib/common/client';+import { freshsalesPolling } from '../src/lib/common/record-polling';++const auth = { username: 'acme', password: 'key' };+const CHECKPOINT = Date.parse('2026-10-01T00:00:00Z');+const VIEW_KEY = 'freshsales_default_view_contacts';++describe('freshsales buildPolling', () => {+ let source: FakeSource;++ beforeEach(() => {+ source = createSource();+ vi.spyOn(freshsalesClient, 'request').mockImplementation(async ({ path, query }) =>+ source.handle({ path, query: query ?? {} })+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('emits every record of a backlog larger than 1,000 exactly once across polls', async () => {+ source.records.push(...makeRecords({ count: 2500, startId: 1, secondsPerRecord: 1 }));+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ const emitted = await pollUntilIdle({ store });++ expect(emitted.flat().length).toBe(2500);+ expect(new Set(emitted.flat()).size).toBe(2500);+ expect(emitted.length).toBeGreaterThan(2);+ });++ it('never splits records that share the same second between two polls', async () => {+ source.records.push(...makeRecords({ count: 2500, startId: 1, secondsPerRecord: 1, perSecond: 7 }));+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ const emitted = await pollUntilIdle({ store });++ expect(new Set(emitted.flat()).size).toBe(2500);+ expect(emitted.flat().length).toBe(2500);+ const pollBySecond = new Map<number, number>();+ emitted.forEach((ids, pollIndex) => {+ for (const id of ids) {+ const second = source.epochOf(id);+ const seenIn = pollBySecond.get(second);+ expect(seenIn === undefined || seenIn === pollIndex).toBe(true);+ pollBySecond.set(second, pollIndex);+ }+ });+ });++ it('keeps the checkpoint across polls and picks up records created while a backlog drains', async () => {+ source.records.push(...makeRecords({ count: 1500, startId: 1, secondsPerRecord: 1 }));+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ const first = await pollIds({ store });+ const checkpointAfterFirst = await store.get<number>('lastPoll');+ expect(checkpointAfterFirst).toBe(Math.max(...first.map((id) => source.epochOf(id))));++ source.records.push(...makeRecords({ count: 50, startId: 100000, secondsPerRecord: 1, offsetSeconds: 5000 }));+ const rest = await pollUntilIdle({ store });++ const all = [...first, ...rest.flat()];+ expect(all.length).toBe(1550);+ expect(new Set(all).size).toBe(1550);+ expect(await store.get<number>('lastPoll')).toBe(source.epochOf(100049));+ expect(await pollIds({ store })).toEqual([]);+ });++ it('known limitation: more than 1,000 records in the same second emits only the oldest 1,000 and skips the rest', async () => {+ source.records.push(...makeRecords({ count: 1200, startId: 1, secondsPerRecord: 1, perSecond: 1200 }));+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ const emitted = await pollUntilIdle({ store });++ expect(emitted.flat().length).toBe(1000);+ expect(new Set(emitted.flat()).size).toBe(1000);+ });++ it('uses the exact system view name over another view that starts with "All"', async () => {+ source.filters = [+ { id: 10, name: 'My Contacts' },+ { id: 11, name: 'All my open contacts' },+ { id: 12, name: 'All Contacts' },+ ];+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ await pollIds({ store });++ expect(source.viewIdsRequested).toEqual(['12']);+ expect(await store.get<string>(VIEW_KEY)).toBe('12');+ });++ it('falls back to the first view starting with "All" when the system name is missing', async () => {+ source.filters = [+ { id: 10, name: 'My Contacts' },+ { id: 11, name: 'All my open contacts' },+ ];+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ await pollIds({ store });++ expect(source.viewIdsRequested).toEqual(['11']);+ });++ it('caches the view id so later polls skip the filters request', async () => {+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);++ await pollIds({ store });+ await pollIds({ store });++ expect(source.filterRequests).toBe(1);+ expect(source.viewIdsRequested).toEqual(['12', '12']);+ });++ it('looks the view up again when the cached view id returns 404', async () => {+ source.records.push(...makeRecords({ count: 3, startId: 1, secondsPerRecord: 1 }));+ const store = createStore();+ await store.put('lastPoll', CHECKPOINT);+ await store.put(VIEW_KEY, '99');++ const ids = await pollIds({ store });++ expect(ids.length).toBe(3);+ expect(source.filterRequests).toBe(1);+ expect(source.viewIdsRequested).toEqual(['99', '12']);+ expect(await store.get<string>(VIEW_KEY)).toBe('12');+ });++ async function pollIds({ store }: { store: Store }): Promise<number[]> {+ const items = await pollingHelper.poll(polling, { store, auth, propsValue: {}, files });+ return items.map((item) => Number(readId(item)));+ }++ async function pollUntilIdle({ store }: { store: Store }): Promise<number[][]> {+ const polls: number[][] = [];+ for (let round = 0; round < 50; round++) {+ const ids = await pollIds({ store });+ if (ids.length === 0) {+ return polls;+ }+ polls.push(ids);+ }+ throw new Error('Polling did not settle.');+ }+});++const polling = freshsalesPolling.buildPolling({ entity: 'contacts', timestampField: 'created_at' });++const files: FilesService = {+ write: async () => '',+ upload: async () => '',+};++function createStore(): Store {+ const data = new Map<string, unknown>();+ return {+ put: async <T>(key: string, value: T) => {+ data.set(key, value);+ return value;+ },+ get: async <T>(key: string) => {+ const value: unknown = data.get(key);+ return value === undefined ? null : readStored<T>(value);+ },+ delete: async (key: string) => {+ data.delete(key);+ },+ };+}++function readStored<T>(value: unknown): T {+ return JSON.parse(JSON.stringify(value));+}++function readId(item: unknown): unknown {+ return typeof item === 'object' && item !== null && 'id' in item ? item.id : undefined;+}++function makeRecords({+ count,+ startId,+ secondsPerRecord,+ perSecond = 1,+ offsetSeconds = 0,+}: {+ count: number;+ startId: number;+ secondsPerRecord: number;+ perSecond?: number;+ offsetSeconds?: number;+}): FakeRecord[] {+ return Array.from({ length: count }, (_, index) => ({+ id: startId + index,+ created_at: new Date(+ CHECKPOINT + (offsetSeconds + 1 + Math.floor(index / perSecond) * secondsPerRecord) * 1000+ ).toISOString(),+ }));+}++function createSource(): FakeSource {+ const source: FakeSource = {+ records: [],+ filters: [+ { id: 10, name: 'My Contacts' },+ { id: 12, name: 'All Contacts' },+ ],+ filterRequests: 0,+ viewIdsRequested: [],+ epochOf: (id) => {+ const record = source.records.find((item) => item.id === id);+ return record === undefined ? Number.NaN : Date.parse(record.created_at);+ },+ handle: async ({ path, query }) => {+ if (path === '/api/contacts/filters') {+ source.filterRequests++;+ return { filters: source.filters };+ }+ const match = /^\/api\/contacts\/view\/(\d+)$/.exec(path);+ if (!match) {+ throw new Error(`Unexpected path ${path}`);+ }+ source.viewIdsRequested.push(match[1]);+ if (!source.filters.some((filter) => String(filter.id) === match[1])) {+ throw new FreshsalesApiError({ status: 404, message: 'not found' });+ }+ const page = Number(query['page']);+ const perPage = Number(query['per_page']);+ const sorted = [...source.records].sort(+ (a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) || b.id - a.id+ );+ return {+ contacts: sorted.slice((page - 1) * perPage, page * perPage),+ meta: { total_pages: Math.ceil(sorted.length / perPage), total: sorted.length },+ };+ },+ };+ return source;+}++type FakeRecord = { id: number; created_at: string };++type FakeSource = {+ records: FakeRecord[];+ filters: { id: number; name: string }[];+ filterRequests: number;+ viewIdsRequested: string[];+ epochOf: (id: number) => number;+ handle: (params: { path: string; query: Record<string, unknown> }) => Promise<unknown>;+};diff --git a/packages/pieces/community/freshsales/test/sales-accounts.test.ts b/packages/pieces/community/freshsales/test/sales-accounts.test.tsnew file mode 100644index 00000000000..4f55ed011a2--- /dev/null+++ b/packages/pieces/community/freshsales/test/sales-accounts.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { freshsalesRecords } from '../src/lib/common/records';++describe('freshsales contact sales accounts merge', () => {+ it('reads account ids from the contact when Freshsales nests them', () => {+ const body = {+ contact: {+ id: 1,+ sales_accounts: [+ { id: 101, is_primary: true },+ { id: 102, is_primary: false },+ ],+ },+ };++ expect(freshsalesRecords.readSalesAccountIds(body)).toEqual([101, 102]);+ });++ it('reads account ids from the top-level side-loaded list', () => {+ const body = { contact: { id: 1 }, sales_accounts: [{ id: '201' }, { id: 202 }, { id: 202 }] };++ expect(freshsalesRecords.readSalesAccountIds(body)).toEqual([201, 202]);+ });++ it('returns no ids when the contact has no accounts', () => {+ expect(freshsalesRecords.readSalesAccountIds({ contact: { id: 1 } })).toEqual([]);+ });++ it('keeps existing accounts as secondary and makes the chosen one primary', () => {+ expect(freshsalesRecords.mergeSalesAccounts({ existingIds: [101, 102], primaryId: 300 })).toEqual([+ { id: 300, is_primary: true },+ { id: 101, is_primary: false },+ { id: 102, is_primary: false },+ ]);+ });++ it('promotes an already linked account without duplicating it', () => {+ expect(freshsalesRecords.mergeSalesAccounts({ existingIds: [101, 102], primaryId: 102 })).toEqual([+ { id: 102, is_primary: true },+ { id: 101, is_primary: false },+ ]);+ });+});diff --git a/packages/pieces/community/freshsales/vitest.config.ts b/packages/pieces/community/freshsales/vitest.config.tsnew file mode 100644index 00000000000..1bd3d1e5fe7--- /dev/null+++ b/packages/pieces/community/freshsales/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ '@activepieces/core-piece-types': path.resolve(repoRoot, 'packages/core/piece-types/src/index.ts'),+ '@activepieces/core-utils': path.resolve(repoRoot, 'packages/core/utils/src/index.ts'),+ },+ },+})