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(salesforce): add AI actions and output schemas (#15768)
Kishan Parmarbf124d1d26c2
diff --git a/bun.lock b/bun.lockindex 6a5ddf09181..951bd746010 100644--- a/bun.lock+++ b/bun.lock@@ -7891,7 +7891,7 @@},"packages/pieces/community/salesforce": {"name": "@activepieces/piece-salesforce",- "version": "0.8.1",+ "version": "0.9.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/salesforce/package.json b/packages/pieces/community/salesforce/package.jsonindex 322b5ba04e8..b536707bf1a 100644--- a/packages/pieces/community/salesforce/package.json+++ b/packages/pieces/community/salesforce/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-salesforce",- "version": "0.8.1",+ "version": "0.9.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/salesforce/src/index.ts b/packages/pieces/community/salesforce/src/index.tsindex 10cf4ec8ad4..a0e11ea37cc 100644--- a/packages/pieces/community/salesforce/src/index.ts+++ b/packages/pieces/community/salesforce/src/index.ts@@ -43,6 +43,83 @@ import { newRecord } from './lib/trigger/new-record';import { newUpdatedFile } from './lib/trigger/new-updated-file';import { exportReport } from './lib/action/export-report';import { newCaseCreatedTrigger } from './lib/trigger/new-case-in-queue';+import { addContactToCampaignMember } from './lib/action/ai/add-contact-to-campaign-member';+import { addLeadToCampaignMember } from './lib/action/ai/add-lead-to-campaign-member';+import { addOpportunityProduct } from './lib/action/ai/add-opportunity-product';+import { applyLeadAssignmentRules } from './lib/action/ai/apply-lead-assignment-rules';+import { completeTask } from './lib/action/ai/complete-task';+import { createAccount } from './lib/action/ai/create-account';+import { createBulkQueryJob } from './lib/action/ai/create-bulk-query-job';+import { createCampaign } from './lib/action/ai/create-campaign';+import { createRecordTree } from './lib/action/ai/create-record-tree';+import { createRecordsBatch } from './lib/action/ai/create-records-batch';+import { createSfContact } from './lib/action/ai/create-sf-contact';+import { createSfLead } from './lib/action/ai/create-sf-lead';+import { createSfNote } from './lib/action/ai/create-sf-note';+import { createSfOpportunity } from './lib/action/ai/create-sf-opportunity';+import { createSfTask } from './lib/action/ai/create-sf-task';+import { createSobjectRecord } from './lib/action/ai/create-sobject-record';+import { deleteFile } from './lib/action/ai/delete-file';+import { deleteRecordsBatch } from './lib/action/ai/delete-records-batch';+import { deleteSobjectRecord } from './lib/action/ai/delete-sobject-record';+import { describeObject } from './lib/action/ai/describe-object';+import { downloadFile } from './lib/action/ai/download-file';+import { getBulkIngestJob } from './lib/action/ai/get-bulk-ingest-job';+import { getBulkIngestResults } from './lib/action/ai/get-bulk-ingest-results';+import { getBulkQueryJob } from './lib/action/ai/get-bulk-query-job';+import { getBulkQueryResults } from './lib/action/ai/get-bulk-query-results';+import { getChildRecords } from './lib/action/ai/get-child-records';+import { getCurrentUser } from './lib/action/ai/get-current-user';+import { getDashboard } from './lib/action/ai/get-dashboard';+import { getFileInfo } from './lib/action/ai/get-file-info';+import { getListViewMetadata } from './lib/action/ai/get-list-view-metadata';+import { getListViewRecords } from './lib/action/ai/get-list-view-records';+import { getNextQueryPage } from './lib/action/ai/get-next-query-page';+import { getOrgLimits } from './lib/action/ai/get-org-limits';+import { getQuickActionDefaults } from './lib/action/ai/get-quick-action-defaults';+import { getRecordByExternalId } from './lib/action/ai/get-record-by-external-id';+import { getRecordCounts } from './lib/action/ai/get-record-counts';+import { getRecord } from './lib/action/ai/get-record';+import { getRecordsBatch } from './lib/action/ai/get-records-batch';+import { getReportInstance } from './lib/action/ai/get-report-instance';+import { getReport } from './lib/action/ai/get-report';+import { getUpdatedRecordIds } from './lib/action/ai/get-updated-record-ids';+import { listDashboards } from './lib/action/ai/list-dashboards';+import { listEmailTemplates } from './lib/action/ai/list-email-templates';+import { listInvocableActions } from './lib/action/ai/list-invocable-actions';+import { listListViews } from './lib/action/ai/list-list-views';+import { listObjects } from './lib/action/ai/list-objects';+import { listPricebooks } from './lib/action/ai/list-pricebooks';+import { listQuickActions } from './lib/action/ai/list-quick-actions';+import { listReports } from './lib/action/ai/list-reports';+import { logCall } from './lib/action/ai/log-call';+import { logEmailActivity } from './lib/action/ai/log-email-activity';+import { removeCampaignMember } from './lib/action/ai/remove-campaign-member';+import { runBulkIngestJob } from './lib/action/ai/run-bulk-ingest-job';+import { runInvocableAction } from './lib/action/ai/run-invocable-action';+import { runQuickAction } from './lib/action/ai/run-quick-action';+import { runReportAsync } from './lib/action/ai/run-report-async';+import { runReportSync } from './lib/action/ai/run-report-sync';+import { runSoqlQueryAll } from './lib/action/ai/run-soql-query-all';+import { runSoqlQuery } from './lib/action/ai/run-soql-query';+import { runToolingQuery } from './lib/action/ai/run-tooling-query';+import { searchAccounts } from './lib/action/ai/search-accounts';+import { searchContacts } from './lib/action/ai/search-contacts';+import { searchKnowledgeArticles } from './lib/action/ai/search-knowledge-articles';+import { searchLeads } from './lib/action/ai/search-leads';+import { searchOpportunities } from './lib/action/ai/search-opportunities';+import { searchRecordsSosl } from './lib/action/ai/search-records-sosl';+import { sendEmailMessage } from './lib/action/ai/send-email-message';+import { updateAccount } from './lib/action/ai/update-account';+import { updateCampaign } from './lib/action/ai/update-campaign';+import { updateOpportunity } from './lib/action/ai/update-opportunity';+import { updateSfContact } from './lib/action/ai/update-sf-contact';+import { updateSfLead } from './lib/action/ai/update-sf-lead';+import { updateSobjectRecord } from './lib/action/ai/update-sobject-record';+import { updateTask } from './lib/action/ai/update-task';+import { uploadFile } from './lib/action/ai/upload-file';+import { upsertRecordByExternalId } from './lib/action/ai/upsert-record-by-external-id';+import { upsertRecordsBatch } from './lib/action/ai/upsert-records-batch';export const salesforceAuth = PieceAuth.OAuth2({props: {@@ -66,7 +143,7 @@ export const salesforceAuth = PieceAuth.OAuth2({export const salesforce = createPiece({displayName: 'Salesforce',description: 'CRM software solutions and enterprise cloud computing',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.87.0',logoUrl: 'https://cdn.activepieces.com/pieces/salesforce.png',authors: ['HKudria',@@ -107,6 +184,83 @@ export const salesforce = createPiece({updateRecord,upsertByExternalId,upsertByExternalIdBulk,+ addContactToCampaignMember,+ addLeadToCampaignMember,+ addOpportunityProduct,+ applyLeadAssignmentRules,+ completeTask,+ createAccount,+ createBulkQueryJob,+ createCampaign,+ createRecordTree,+ createRecordsBatch,+ createSfContact,+ createSfLead,+ createSfNote,+ createSfOpportunity,+ createSfTask,+ createSobjectRecord,+ deleteFile,+ deleteRecordsBatch,+ deleteSobjectRecord,+ describeObject,+ downloadFile,+ getBulkIngestJob,+ getBulkIngestResults,+ getBulkQueryJob,+ getBulkQueryResults,+ getChildRecords,+ getCurrentUser,+ getDashboard,+ getFileInfo,+ getListViewMetadata,+ getListViewRecords,+ getNextQueryPage,+ getOrgLimits,+ getQuickActionDefaults,+ getRecordByExternalId,+ getRecordCounts,+ getRecord,+ getRecordsBatch,+ getReportInstance,+ getReport,+ getUpdatedRecordIds,+ listDashboards,+ listEmailTemplates,+ listInvocableActions,+ listListViews,+ listObjects,+ listPricebooks,+ listQuickActions,+ listReports,+ logCall,+ logEmailActivity,+ removeCampaignMember,+ runBulkIngestJob,+ runInvocableAction,+ runQuickAction,+ runReportAsync,+ runReportSync,+ runSoqlQueryAll,+ runSoqlQuery,+ runToolingQuery,+ searchAccounts,+ searchContacts,+ searchKnowledgeArticles,+ searchLeads,+ searchOpportunities,+ searchRecordsSosl,+ sendEmailMessage,+ updateAccount,+ updateCampaign,+ updateOpportunity,+ updateSfContact,+ updateSfLead,+ updateSobjectRecord,+ updateTask,+ uploadFile,+ upsertRecordByExternalId,+ upsertRecordsBatch,createCustomApiCallAction({baseUrl: (auth) => (auth as OAuth2PropertyValue).data['instance_url'],auth: salesforceAuth,diff --git a/packages/pieces/community/salesforce/src/lib/action/add-contact-to-campaign.ts b/packages/pieces/community/salesforce/src/lib/action/add-contact-to-campaign.tsindex 604eca13f6c..7420086b7d9 100644--- a/packages/pieces/community/salesforce/src/lib/action/add-contact-to-campaign.ts+++ b/packages/pieces/community/salesforce/src/lib/action/add-contact-to-campaign.ts@@ -2,14 +2,16 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const addContactToCampaign = createAction({auth: salesforceAuth,name: 'add_contact_to_campaign',displayName: 'Add Contact to Campaign',description: 'Add a contact to a campaign.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Add a Contact to a Campaign by creating a CampaignMember linking the two, with an optional member status. Not idempotent — re-adding the same contact to the same campaign errors on the existing membership.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {campaign_id: salesforcesCommon.campaign,contact_id: salesforcesCommon.contact,diff --git a/packages/pieces/community/salesforce/src/lib/action/add-file-to-record.ts b/packages/pieces/community/salesforce/src/lib/action/add-file-to-record.tsindex 8c6319b8b50..994155510ff 100644--- a/packages/pieces/community/salesforce/src/lib/action/add-file-to-record.ts+++ b/packages/pieces/community/salesforce/src/lib/action/add-file-to-record.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const addFileToRecord = createAction({auth: salesforceAuth,name: 'add_file_to_record',displayName: 'Add File to Record',description: 'Uploads a file and attaches it to an existing record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Upload a file and attach it to an existing Salesforce record by creating a ContentVersion linked to the target record Id. Use when you need to attach a document, image, or other binary to a record. Not idempotent: each call creates a new file version, so re-running attaches a duplicate file.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {object: salesforcesCommon.object,record_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/add-lead-to-campaign.ts b/packages/pieces/community/salesforce/src/lib/action/add-lead-to-campaign.tsindex 0fdabb9e7b7..b2ce1672549 100644--- a/packages/pieces/community/salesforce/src/lib/action/add-lead-to-campaign.ts+++ b/packages/pieces/community/salesforce/src/lib/action/add-lead-to-campaign.ts@@ -2,14 +2,16 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const addLeadToCampaign = createAction({auth: salesforceAuth,name: 'add_lead_to_campaign',displayName: 'Add Lead to Campaign',description: 'Adds an existing lead to an existing campaign.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Link an existing Lead to an existing Campaign by creating a CampaignMember with the given member status. Use to enroll a known lead in a campaign. Not idempotent: re-running creates another CampaignMember, and Salesforce rejects a duplicate lead/campaign pairing with an error.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {campaign_id: salesforcesCommon.campaign,lead_id: salesforcesCommon.lead,diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/add-contact-to-campaign-member.ts b/packages/pieces/community/salesforce/src/lib/action/ai/add-contact-to-campaign-member.tsnew file mode 100644index 00000000000..0626ca66596--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/add-contact-to-campaign-member.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { addContactToCampaignMemberOutputSchema } from '../../output-schemas';++export const addContactToCampaignMember = createAction({+ auth: salesforceAuth,+ name: 'add_contact_to_campaign_member',+ classification: 'WRITE',+ displayName: 'Add Contact to Campaign',+ description: 'Add an existing contact to a campaign as a member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Enrolls an existing Contact in a Campaign by creating a CampaignMember, with an optional member status (e.g. Sent or Responded; defaults to the campaign default). Use Add Lead to Campaign for leads and Remove Campaign Member to take it out. Not idempotent: Salesforce rejects the call if the contact is already a member of that campaign.',+ idempotent: false,+ },+ outputSchema: addContactToCampaignMemberOutputSchema,+ props: {+ campaign_id: Property.ShortText({ displayName: 'Campaign ID', required: true }),+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),+ status: Property.ShortText({ displayName: 'Member Status', description: 'Campaign member status, e.g. Sent. Leave empty for the default.', required: false }),+ },+ async run(context) {+ const { campaign_id, contact_id, status } = context.propsValue;+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'CampaignMember',+ fields: { CampaignId: campaign_id, ContactId: contact_id, Status: status },+ additionalFields: undefined,+ });+ return { ...result, campaign_id, contact_id };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/add-lead-to-campaign-member.ts b/packages/pieces/community/salesforce/src/lib/action/ai/add-lead-to-campaign-member.tsnew file mode 100644index 00000000000..0a89b617b3c--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/add-lead-to-campaign-member.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { addLeadToCampaignMemberOutputSchema } from '../../output-schemas';++export const addLeadToCampaignMember = createAction({+ auth: salesforceAuth,+ name: 'add_lead_to_campaign_member',+ classification: 'WRITE',+ displayName: 'Add Lead to Campaign',+ description: 'Add an existing lead to a campaign as a member.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Enrolls an existing Lead in a Campaign by creating a CampaignMember, with an optional member status (e.g. Sent or Responded; defaults to the campaign default). Use Add Contact to Campaign for contacts and Remove Campaign Member to take it out. Not idempotent: Salesforce rejects the call if the lead is already a member of that campaign.',+ idempotent: false,+ },+ outputSchema: addLeadToCampaignMemberOutputSchema,+ props: {+ campaign_id: Property.ShortText({ displayName: 'Campaign ID', required: true }),+ lead_id: Property.ShortText({ displayName: 'Lead ID', required: true }),+ status: Property.ShortText({ displayName: 'Member Status', description: 'Campaign member status, e.g. Sent. Leave empty for the default.', required: false }),+ },+ async run(context) {+ const { campaign_id, lead_id, status } = context.propsValue;+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'CampaignMember',+ fields: { CampaignId: campaign_id, LeadId: lead_id, Status: status },+ additionalFields: undefined,+ });+ return { ...result, campaign_id, lead_id };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/add-opportunity-product.ts b/packages/pieces/community/salesforce/src/lib/action/ai/add-opportunity-product.tsnew file mode 100644index 00000000000..fd6be517bf0--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/add-opportunity-product.ts@@ -0,0 +1,47 @@+import { createAction, isNil, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { addOpportunityProductOutputSchema } from '../../output-schemas';++export const addOpportunityProduct = createAction({+ auth: salesforceAuth,+ name: 'add_opportunity_product',+ classification: 'WRITE',+ displayName: 'Add Opportunity Product',+ description: 'Add a product line item to an opportunity.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Adds a product line item (OpportunityLineItem) to an Opportunity from a price book entry, with a quantity and exactly one of unit price or total price. Get the entry id from List Price Books with entries included; the entry must belong to the opportunity's price book (set it with Update Opportunity first if empty). Not idempotent: each call adds another line.",+ idempotent: false,+ },+ outputSchema: addOpportunityProductOutputSchema,+ props: {+ opportunity_id: Property.ShortText({ displayName: 'Opportunity ID', required: true }),+ pricebook_entry_id: Property.ShortText({ displayName: 'Price Book Entry ID', required: true }),+ quantity: Property.Number({ displayName: 'Quantity', required: true }),+ unit_price: Property.Number({ displayName: 'Unit Price', description: 'Sales price per unit. Do not combine with Total Price.', required: false }),+ total_price: Property.Number({ displayName: 'Total Price', description: 'Quantity times price. Do not combine with Unit Price.', required: false }),+ description: Property.LongText({ displayName: 'Line Description', required: false }),+ },+ async run(context) {+ const { opportunity_id, pricebook_entry_id, quantity, unit_price, total_price, description } = context.propsValue;+ if (isNil(unit_price) === isNil(total_price)) {+ throw new Error('Provide exactly one of Unit Price or Total Price.');+ }+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'OpportunityLineItem',+ fields: {+ OpportunityId: opportunity_id,+ PricebookEntryId: pricebook_entry_id,+ Quantity: quantity,+ UnitPrice: unit_price,+ TotalPrice: total_price,+ Description: description,+ },+ additionalFields: undefined,+ });+ return { ...result, opportunity_id, pricebook_entry_id, quantity };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/apply-lead-assignment-rules.ts b/packages/pieces/community/salesforce/src/lib/action/ai/apply-lead-assignment-rules.tsnew file mode 100644index 00000000000..98db6f01c78--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/apply-lead-assignment-rules.ts@@ -0,0 +1,57 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { applyLeadAssignmentRulesOutputSchema } from '../../output-schemas';++export const applyLeadAssignmentRules = createAction({+ auth: salesforceAuth,+ name: 'apply_lead_assignment_rules',+ classification: 'WRITE',+ displayName: 'Apply Lead Assignment Rules',+ description: "Re-run the org's active lead assignment rule on a lead.",+ audience: 'ai',+ aiMetadata: {+ description:+ "Runs the org's active lead assignment rule on an existing Lead so it gets routed to the right owner or queue, and reports the owner before and after. Use it after Create Lead or Update Lead when ownership should follow the org's routing; to set an owner directly use Update Lead with Owner ID. Needs an active lead assignment rule in the org, otherwise the owner does not change. Safe to retry.",+ idempotent: true,+ },+ outputSchema: applyLeadAssignmentRulesOutputSchema,+ props: {+ lead_id: Property.ShortText({ displayName: 'Lead ID', required: true }),+ },+ async run(context) {+ const id = salesforceUtils.assertId({ value: context.propsValue.lead_id, fieldName: 'Lead ID' });+ const before = await getLead({ auth: context.auth, id });+ await callSalesforceApi(+ HttpMethod.PATCH,+ context.auth,+ `/services/data/v56.0/sobjects/Lead/${id}`,+ { Status: before.Status },+ { headers: { 'Sforce-Auto-Assign': 'TRUE' } }+ );+ const after = await getLead({ auth: context.auth, id });+ return {+ id,+ previous_owner_id: before.OwnerId,+ owner_id: after.OwnerId,+ reassigned: before.OwnerId !== after.OwnerId,+ };+ },+});++async function getLead({ auth, id }: { auth: OAuth2PropertyValue; id: string }) {+ const response = await callSalesforceApi<LeadOwnerRecord>(+ HttpMethod.GET,+ auth,+ `/services/data/v56.0/sobjects/Lead/${id}?fields=Status,OwnerId`,+ undefined+ );+ return response.body;+}++type LeadOwnerRecord = {+ Status: string;+ OwnerId: string;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/complete-task.ts b/packages/pieces/community/salesforce/src/lib/action/ai/complete-task.tsnew file mode 100644index 00000000000..aea2931cf67--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/complete-task.ts@@ -0,0 +1,50 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { crmUtils } from '../../common/crm';+import { salesforceUtils } from '../../common/utils';+import { completeTaskOutputSchema } from '../../output-schemas';++export const completeTask = createAction({+ auth: salesforceAuth,+ name: 'complete_task',+ classification: 'WRITE',+ displayName: 'Complete Task',+ description: 'Mark a task as completed.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Marks an existing Salesforce Task as done by setting its status to the org's first closed task status (usually Completed), optionally appending a closing note to its description. Use Update Task for other changes. Safe to retry, but a closing note is appended again on every call.",+ idempotent: true,+ },+ outputSchema: completeTaskOutputSchema,+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ closing_note: Property.LongText({ displayName: 'Closing Note', description: 'Text appended to the task description.', required: false }),+ },+ async run(context) {+ const id = salesforceUtils.assertId({ value: context.propsValue.task_id, fieldName: 'Task ID' });+ const note = context.propsValue.closing_note?.trim();+ const status = await crmUtils.getClosedTaskStatus({ auth: context.auth });+ const description = note ? await appendToDescription({ auth: context.auth, id, note }) : undefined;+ const body = salesforceUtils.compact({ Status: status, Description: description });+ await callSalesforceApi(HttpMethod.PATCH, context.auth, `/services/data/v56.0/sobjects/Task/${id}`, body);+ return { id, success: true, status, updated_fields: Object.keys(body) };+ },+});++async function appendToDescription({ auth, id, note }: { auth: OAuth2PropertyValue; id: string; note: string }): Promise<string> {+ const response = await callSalesforceApi<{ Description: string | null }>(+ HttpMethod.GET,+ auth,+ `/services/data/v56.0/sobjects/Task/${id}?fields=Description`,+ undefined+ );+ const current = response.body.Description;+ if (!current) {+ return note;+ }+ const appended = `${current}\n\n${note}`;+ return current === note || current.endsWith(`\n\n${note}`) ? current : appended;+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-account.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-account.tsnew file mode 100644index 00000000000..6c1ac3fef87--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-account.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createAccountOutputSchema } from '../../output-schemas';++export const createAccount = createAction({+ auth: salesforceAuth,+ name: 'create_account',+ classification: 'WRITE',+ displayName: 'Create Account',+ description: 'Create a new account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Account (company) with a required Name and optional phone, website, industry, billing address, owner and parent account; put custom fields in Additional Fields. Use Search Accounts first to avoid duplicates, and Update Account to change an existing one. Not idempotent: each call creates a new Account.',+ idempotent: false,+ },+ outputSchema: createAccountOutputSchema,+ props: {+ Name: Property.ShortText({ displayName: 'Account Name', required: true }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ Website: Property.ShortText({ displayName: 'Website', required: false }),+ Industry: Property.ShortText({ displayName: 'Industry', description: 'Industry picklist value, e.g. Technology.', required: false }),+ Type: Property.ShortText({ displayName: 'Type', description: 'Account type picklist value, e.g. Customer - Direct or Prospect.', required: false }),+ BillingStreet: Property.ShortText({ displayName: 'Billing Street', required: false }),+ BillingCity: Property.ShortText({ displayName: 'Billing City', required: false }),+ BillingState: Property.ShortText({ displayName: 'Billing State', required: false }),+ BillingPostalCode: Property.ShortText({ displayName: 'Billing Postal Code', required: false }),+ BillingCountry: Property.ShortText({ displayName: 'Billing Country', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', description: 'User id of the account owner.', required: false }),+ ParentId: Property.ShortText({ displayName: 'Parent Account ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const result = await crmUtils.createRecord({ auth: context.auth, object: 'Account', fields, additionalFields: additional_fields });+ return { ...result, name: fields.Name };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-bulk-query-job.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-bulk-query-job.tsnew file mode 100644index 00000000000..b48e23bb45d--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-bulk-query-job.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { bulkUtils } from '../../common/bulk';+import { bulkJobCreatedOutputSchema } from '../../output-schemas';++export const createBulkQueryJob = createAction({+ auth: salesforceAuth,+ name: 'create_bulk_query_job',+ classification: 'READ',+ displayName: 'Create Bulk Query Job',+ description: 'Start a Bulk API 2.0 query job for large SOQL exports.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Starts an asynchronous Bulk API 2.0 SOQL query and returns the job id immediately. Poll Get Bulk Query Job until JobComplete, then page through rows with Get Bulk Query Results. Use it for exports of many thousands of rows; for small result sets use the regular SOQL query action. queryAll also returns deleted and archived records. Starts a new job every call.',+ idempotent: false,+ },+ outputSchema: bulkJobCreatedOutputSchema,+ props: {+ query: Property.LongText({+ displayName: 'SOQL Query',+ description: 'e.g. SELECT Id, Name FROM Account. Bulk queries do not support GROUP BY, OFFSET or TYPEOF.',+ required: true,+ }),+ operation: Property.StaticDropdown({+ displayName: 'Operation',+ required: true,+ defaultValue: 'query',+ options: {+ options: [+ { label: 'Query', value: 'query' },+ { label: 'Query All (include deleted)', value: 'queryAll' },+ ],+ },+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (!query) {+ throw new Error('SOQL Query must not be empty.');+ }+ const response = await callSalesforceApi(HttpMethod.POST, context.auth, `${bulkUtils.BULK_API_PATH}/query`, {+ operation: context.propsValue.operation,+ query,+ });+ const job = bulkUtils.formatJob(response.body);+ return { job_id: job['id'], state: job['state'], operation: job['operation'], object: job['object'] };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-campaign.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-campaign.tsnew file mode 100644index 00000000000..ee6c4dcb60c--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-campaign.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createCampaignOutputSchema } from '../../output-schemas';++export const createCampaign = createAction({+ auth: salesforceAuth,+ name: 'create_campaign',+ classification: 'WRITE',+ displayName: 'Create Campaign',+ description: 'Create a new marketing campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Campaign with a required Name and optional type, status, start/end dates (YYYY-MM-DD), active flag, budget, expected revenue and parent campaign; custom fields go in Additional Fields. Use Update Campaign to change one, and Add Lead to Campaign / Add Contact to Campaign to enroll members. The user needs the Marketing User permission. Not idempotent: each call creates a new Campaign.',+ idempotent: false,+ },+ outputSchema: createCampaignOutputSchema,+ props: {+ Name: Property.ShortText({ displayName: 'Name', required: true }),+ Type: Property.ShortText({ displayName: 'Type', description: 'Campaign type picklist value, e.g. Webinar or Email.', required: false }),+ Status: Property.ShortText({ displayName: 'Status', description: 'Campaign status picklist value, e.g. Planned.', required: false }),+ StartDate: Property.ShortText({ displayName: 'Start Date', description: 'YYYY-MM-DD.', required: false }),+ EndDate: Property.ShortText({ displayName: 'End Date', description: 'YYYY-MM-DD.', required: false }),+ IsActive: Property.Checkbox({ displayName: 'Active', required: false }),+ BudgetedCost: Property.Number({ displayName: 'Budgeted Cost', required: false }),+ ExpectedRevenue: Property.Number({ displayName: 'Expected Revenue', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ ParentId: Property.ShortText({ displayName: 'Parent Campaign ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'Campaign',+ fields: {+ ...fields,+ StartDate: crmUtils.assertDate({ value: fields.StartDate, fieldName: 'Start Date' }),+ EndDate: crmUtils.assertDate({ value: fields.EndDate, fieldName: 'End Date' }),+ },+ additionalFields: additional_fields,+ });+ return { ...result, name: fields.Name };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-record-tree.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-record-tree.tsnew file mode 100644index 00000000000..817f665fbd8--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-record-tree.ts@@ -0,0 +1,90 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { recordsUtils } from '../../common/records';+import { createRecordTreeOutputSchema } from '../../output-schemas';++export const createRecordTree = createAction({+ auth: salesforceAuth,+ name: 'create_record_tree',+ classification: 'WRITE',+ displayName: 'Create Record Tree',+ description: 'Create parent records together with nested child records in one call.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates parent records of one object together with nested child records (e.g. an Account with its Contacts and Opportunities) in a single all-or-nothing call, returning the new id for each referenceId. Use it when children must be linked to parents created in the same step; for flat inserts use Create Records Batch. Limits: 200 records in total across all levels, up to 5 levels deep, insert only. Not idempotent: every call creates new records.',+ idempotent: false,+ },+ outputSchema: createRecordTreeOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Root Object',+ description: 'API name of the top-level records, e.g. Account.',+ required: true,+ }),+ records: Property.Json({+ displayName: 'Records',+ description:+ 'JSON array of top-level records. Nest children under their relationship name, e.g. [{"Name": "Acme", "Contacts": {"records": [{"attributes": {"type": "Contact", "referenceId": "c1"}, "LastName": "Doe"}]}}]. Top-level attributes are filled in when omitted.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Root Object' });+ const records = recordsUtils.parseRecordList({+ value: context.propsValue.records,+ fieldName: 'Records',+ max: recordsUtils.MAX_COMPOSITE_RECORDS,+ });+ const total = countTreeRecords(records);+ if (total > recordsUtils.MAX_COMPOSITE_RECORDS) {+ throw new Error(`A record tree can hold at most ${recordsUtils.MAX_COMPOSITE_RECORDS} records in total, including children; this one has ${total}.`);+ }+ const response = await callSalesforceApi<TreeResponse>(+ HttpMethod.POST,+ context.auth,+ `/services/data/v56.0/composite/tree/${object}`,+ { records: records.map((record, index) => withAttributes({ record, object, index })) }+ );+ return {+ has_errors: response.body.hasErrors,+ results: response.body.results.map((result) => ({+ reference_id: result.referenceId,+ id: result.id ?? null,+ errors: (result.errors ?? []).map((error) => `${error.statusCode}: ${error.message}`).join('; '),+ })),+ };+ },+});++function countTreeRecords(records: unknown[]): number {+ return records.reduce<number>((total, record) => {+ if (!salesforceUtils.isRecord(record)) {+ return total + 1;+ }+ const nested = Object.values(record)+ .filter((value): value is Record<string, unknown> => salesforceUtils.isRecord(value) && Array.isArray(value['records']))+ .reduce<number>((sum, value) => sum + countTreeRecords(Array.isArray(value['records']) ? value['records'] : []), 0);+ return total + 1 + nested;+ }, 0);+}++function withAttributes({ record, object, index }: { record: Record<string, unknown>; object: string; index: number }) {+ const attributes = salesforceUtils.isRecord(record['attributes']) ? record['attributes'] : {};+ return {+ ...record,+ attributes: { type: object, referenceId: `ref${index + 1}`, ...attributes },+ };+}++type TreeResponse = {+ hasErrors: boolean;+ results: {+ referenceId: string;+ id?: string;+ errors?: { statusCode: string; message: string; fields?: string[] }[];+ }[];+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-records-batch.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-records-batch.tsnew file mode 100644index 00000000000..baa0eeb92be--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-records-batch.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { CompositeResult, recordsUtils } from '../../common/records';+import { compositeBatchOutputSchema } from '../../output-schemas';++export const createRecordsBatch = createAction({+ auth: salesforceAuth,+ name: 'create_records_batch',+ classification: 'WRITE',+ displayName: 'Create Records Batch',+ description: 'Create up to 200 records of one object in one call.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates up to 200 records of one Salesforce object in a single call and returns a per-record result (id or error) in input order. Use it instead of repeated Create Record calls; to create parents with nested children use Create Record Tree, and to avoid duplicates on an external id use Upsert Records Batch. With All or None on, one failure rolls back the whole batch. Not idempotent: every call creates new records.',+ idempotent: false,+ },+ outputSchema: compositeBatchOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact or My_Object__c.',+ required: true,+ }),+ records: Property.Json({+ displayName: 'Records',+ description: 'JSON array of up to 200 objects of field API names to values, e.g. [{"Name": "Acme"}, {"Name": "Globex"}].',+ required: true,+ }),+ all_or_none: Property.Checkbox({+ displayName: 'All or None',+ description: 'Roll back every record if any record fails.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const records = recordsUtils.parseRecordList({+ value: context.propsValue.records,+ fieldName: 'Records',+ max: recordsUtils.MAX_COMPOSITE_RECORDS,+ });+ const response = await callSalesforceApi<CompositeResult[]>(+ HttpMethod.POST,+ context.auth,+ '/services/data/v56.0/composite/sobjects',+ {+ allOrNone: context.propsValue.all_or_none ?? false,+ records: records.map((record) => ({ ...record, attributes: { type: object } })),+ }+ );+ return recordsUtils.formatCompositeResults(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-contact.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-contact.tsnew file mode 100644index 00000000000..48b5dc98249--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-contact.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createSfContactOutputSchema } from '../../output-schemas';++export const createSfContact = createAction({+ auth: salesforceAuth,+ name: 'create_sf_contact',+ classification: 'WRITE',+ displayName: 'Create Contact',+ description: 'Create a new contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Contact with a required Last Name and optional name, email, phones, title, department, account link, mailing location, lead source and owner; custom fields go in Additional Fields. Use Search Contacts first to avoid duplicates and Update Contact to change an existing one; for unqualified prospects use Create Lead instead. Not idempotent: each call creates a new Contact.',+ idempotent: false,+ },+ outputSchema: createSfContactOutputSchema,+ props: {+ LastName: Property.ShortText({ displayName: 'Last Name', required: true }),+ FirstName: Property.ShortText({ displayName: 'First Name', required: false }),+ Email: Property.ShortText({ displayName: 'Email', required: false }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ MobilePhone: Property.ShortText({ displayName: 'Mobile Phone', required: false }),+ Title: Property.ShortText({ displayName: 'Title', required: false }),+ Department: Property.ShortText({ displayName: 'Department', required: false }),+ AccountId: Property.ShortText({ displayName: 'Account ID', required: false }),+ MailingCity: Property.ShortText({ displayName: 'Mailing City', required: false }),+ MailingCountry: Property.ShortText({ displayName: 'Mailing Country', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', description: 'Lead source picklist value, e.g. Web.', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const result = await crmUtils.createRecord({ auth: context.auth, object: 'Contact', fields, additionalFields: additional_fields });+ return { ...result, last_name: fields.LastName, email: fields.Email ?? null };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-lead.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-lead.tsnew file mode 100644index 00000000000..dadc2a410f6--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-lead.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createSfLeadOutputSchema } from '../../output-schemas';++export const createSfLead = createAction({+ auth: salesforceAuth,+ name: 'create_sf_lead',+ classification: 'WRITE',+ displayName: 'Create Lead',+ description: 'Create a new lead.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Lead with a required Last Name and Company plus optional contact details, status, lead source, industry, website, location and owner; custom fields go in Additional Fields. Use Search Leads first to avoid duplicates, Update Lead to change one, and Apply Lead Assignment Rules to route it to an owner. Not idempotent: each call creates a new Lead.',+ idempotent: false,+ },+ outputSchema: createSfLeadOutputSchema,+ props: {+ LastName: Property.ShortText({ displayName: 'Last Name', required: true }),+ Company: Property.ShortText({ displayName: 'Company', required: true }),+ FirstName: Property.ShortText({ displayName: 'First Name', required: false }),+ Email: Property.ShortText({ displayName: 'Email', required: false }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ Title: Property.ShortText({ displayName: 'Title', required: false }),+ Status: Property.ShortText({ displayName: 'Status', description: 'Lead status picklist value, e.g. Open - Not Contacted.', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', required: false }),+ Industry: Property.ShortText({ displayName: 'Industry', required: false }),+ Website: Property.ShortText({ displayName: 'Website', required: false }),+ City: Property.ShortText({ displayName: 'City', required: false }),+ Country: Property.ShortText({ displayName: 'Country', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', description: 'User or queue id.', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const result = await crmUtils.createRecord({ auth: context.auth, object: 'Lead', fields, additionalFields: additional_fields });+ return { ...result, last_name: fields.LastName, company: fields.Company };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-note.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-note.tsnew file mode 100644index 00000000000..c34290fa7db--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-note.ts@@ -0,0 +1,30 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createSfNoteOutputSchema } from '../../output-schemas';++export const createSfNote = createAction({+ auth: salesforceAuth,+ name: 'create_sf_note',+ classification: 'WRITE',+ displayName: 'Create Note',+ description: 'Attach a note to a record.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Attaches a classic Salesforce Note (title and plain-text body, up to 32 KB) to any record such as an Account, Contact, Lead, Opportunity or Case, optionally private to the owner. Use Create Task or Log Call for activities instead of free-text notes. Not idempotent: each call adds another note.',+ idempotent: false,+ },+ outputSchema: createSfNoteOutputSchema,+ props: {+ ParentId: Property.ShortText({ displayName: 'Parent Record ID', description: 'The record the note belongs to.', required: true }),+ Title: Property.ShortText({ displayName: 'Title', required: true }),+ Body: Property.LongText({ displayName: 'Body', required: false }),+ IsPrivate: Property.Checkbox({ displayName: 'Private', description: 'Only the owner and admins can see it.', required: false }),+ },+ async run(context) {+ const fields = context.propsValue;+ const result = await crmUtils.createRecord({ auth: context.auth, object: 'Note', fields, additionalFields: undefined });+ return { ...result, parent_id: fields.ParentId, title: fields.Title };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-opportunity.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-opportunity.tsnew file mode 100644index 00000000000..b71c1ef868f--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-opportunity.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createSfOpportunityOutputSchema } from '../../output-schemas';++export const createSfOpportunity = createAction({+ auth: salesforceAuth,+ name: 'create_sf_opportunity',+ classification: 'WRITE',+ displayName: 'Create Opportunity',+ description: 'Create a new opportunity.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Opportunity with a required Name, Stage and Close Date (YYYY-MM-DD) plus optional account, amount, probability, type, source, next step, owner and price book; custom fields go in Additional Fields. Use Update Opportunity to change one and Add Opportunity Product to add line items (set Price Book ID here or it must be set before adding products). Not idempotent: each call creates a new Opportunity.',+ idempotent: false,+ },+ outputSchema: createSfOpportunityOutputSchema,+ props: {+ Name: Property.ShortText({ displayName: 'Name', required: true }),+ StageName: Property.ShortText({ displayName: 'Stage', description: 'Stage picklist value, e.g. Prospecting.', required: true }),+ CloseDate: Property.ShortText({ displayName: 'Close Date', description: 'YYYY-MM-DD.', required: true }),+ AccountId: Property.ShortText({ displayName: 'Account ID', required: false }),+ Amount: Property.Number({ displayName: 'Amount', required: false }),+ Probability: Property.Number({ displayName: 'Probability (%)', required: false }),+ Type: Property.ShortText({ displayName: 'Type', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', required: false }),+ NextStep: Property.ShortText({ displayName: 'Next Step', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ Pricebook2Id: Property.ShortText({ displayName: 'Price Book ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const closeDate = crmUtils.assertDate({ value: fields.CloseDate, fieldName: 'Close Date' });+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'Opportunity',+ fields: { ...fields, CloseDate: closeDate },+ additionalFields: additional_fields,+ });+ return { ...result, name: fields.Name, stage: fields.StageName, close_date: closeDate };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-task.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-task.tsnew file mode 100644index 00000000000..9fdf8cce555--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sf-task.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { createSfTaskOutputSchema } from '../../output-schemas';++export const createSfTask = createAction({+ auth: salesforceAuth,+ name: 'create_sf_task',+ classification: 'WRITE',+ displayName: 'Create Task',+ description: 'Create a new task (to-do) in Salesforce.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Salesforce Task with a required Subject, optionally linked to a Contact or Lead (Who ID) and to an Account, Opportunity or other record (What ID), with owner, due date (YYYY-MM-DD), status, priority and description. Use Log Call to record a call that already happened, and Complete Task to close one. Not idempotent: each call creates a new Task.',+ idempotent: false,+ },+ outputSchema: createSfTaskOutputSchema,+ props: {+ Subject: Property.ShortText({ displayName: 'Subject', required: true }),+ WhoId: Property.ShortText({ displayName: 'Who ID', description: 'Contact or Lead id.', required: false }),+ WhatId: Property.ShortText({ displayName: 'What ID', description: 'Account, Opportunity, Case or other record id.', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Assigned To (User ID)', required: false }),+ ActivityDate: Property.ShortText({ displayName: 'Due Date', description: 'YYYY-MM-DD.', required: false }),+ Status: Property.ShortText({ displayName: 'Status', description: 'Task status picklist value, e.g. Not Started.', required: false }),+ Priority: Property.ShortText({ displayName: 'Priority', description: 'e.g. High, Normal or Low.', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { additional_fields, ...fields } = context.propsValue;+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'Task',+ fields: { ...fields, ActivityDate: crmUtils.assertDate({ value: fields.ActivityDate, fieldName: 'Due Date' }) },+ additionalFields: additional_fields,+ });+ return { ...result, subject: fields.Subject };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/create-sobject-record.ts b/packages/pieces/community/salesforce/src/lib/action/ai/create-sobject-record.tsnew file mode 100644index 00000000000..5a9d0a98799--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/create-sobject-record.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { createSobjectRecordOutputSchema } from '../../output-schemas';++export const createSobjectRecord = createAction({+ auth: salesforceAuth,+ name: 'create_sobject_record',+ classification: 'WRITE',+ displayName: 'Create Record',+ description: 'Create one record of any object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a single record of any Salesforce object (standard or custom) from a JSON object of field API names to values. Use it for one record; for up to 200 records in one call use Create Records Batch, and to create-or-update on an external id use Upsert Record by External ID. Required fields depend on the object (see Describe Object). Not idempotent: every call creates a new record.',+ idempotent: false,+ },+ outputSchema: createSobjectRecordOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact, Lead or My_Object__c.',+ required: true,+ }),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object of field API names to values, e.g. {"Name": "Acme", "Industry": "Technology"}.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const fields = salesforceUtils.parseJsonObject({ value: context.propsValue.fields, fieldName: 'Fields' }) ?? {};+ if (Object.keys(fields).length === 0) {+ throw new Error('Fields must contain at least one field.');+ }+ const response = await callSalesforceApi<{ id: string; success: boolean }>(+ HttpMethod.POST,+ context.auth,+ `/services/data/v56.0/sobjects/${object}`,+ fields+ );+ return { id: response.body.id, success: response.body.success, object };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/delete-file.ts b/packages/pieces/community/salesforce/src/lib/action/ai/delete-file.tsnew file mode 100644index 00000000000..1d832a0ecb3--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/delete-file.ts@@ -0,0 +1,36 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { deletedRecordOutputSchema } from '../../output-schemas';++export const deleteFile = createAction({+ auth: salesforceAuth,+ name: 'delete_file',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete File',+ description: 'Delete a Salesforce file and all its versions.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a Salesforce File, all of its versions and its links to records, by its content document id (starts with 069). Destructive: confirm the id with Get File Info first; the file goes to the Recycle Bin and disappears from every record it was shared on. Not idempotent: a second call fails because the file no longer exists.',+ idempotent: false,+ },+ outputSchema: deletedRecordOutputSchema,+ props: {+ content_document_id: Property.ShortText({+ displayName: 'Content Document ID',+ description: 'File id starting with 069.',+ required: true,+ }),+ },+ async run(context) {+ const id = salesforceUtils.assertId({+ value: context.propsValue.content_document_id,+ fieldName: 'Content Document ID',+ });+ await callSalesforceApi(HttpMethod.DELETE, context.auth, `/services/data/v56.0/connect/files/${id}`, undefined);+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/delete-records-batch.ts b/packages/pieces/community/salesforce/src/lib/action/ai/delete-records-batch.tsnew file mode 100644index 00000000000..8622aec61d8--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/delete-records-batch.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { CompositeResult, recordsUtils } from '../../common/records';+import { compositeBatchOutputSchema } from '../../output-schemas';++export const deleteRecordsBatch = createAction({+ auth: salesforceAuth,+ name: 'delete_records_batch',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Records Batch',+ description: 'Delete up to 200 records in one call.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Deletes up to 200 Salesforce records by id in a single call (ids may belong to different objects) and returns a per-record result in input order; deleted records go to the Recycle Bin. For a single record use Delete Record. With All or None on, one failure rolls back every delete. Not idempotent: already-deleted ids fail on a second call.',+ idempotent: false,+ },+ outputSchema: compositeBatchOutputSchema,+ props: {+ record_ids: Property.Array({+ displayName: 'Record IDs',+ description: 'Up to 200 record ids to delete.',+ required: true,+ }),+ all_or_none: Property.Checkbox({+ displayName: 'All or None',+ description: 'Roll back every delete if any delete fails.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const ids = recordsUtils.parseIdList({+ value: context.propsValue.record_ids,+ fieldName: 'Record IDs',+ max: recordsUtils.MAX_COMPOSITE_RECORDS,+ });+ const allOrNone = context.propsValue.all_or_none ?? false;+ const response = await callSalesforceApi<CompositeResult[]>(+ HttpMethod.DELETE,+ context.auth,+ `/services/data/v56.0/composite/sobjects?ids=${ids.join(',')}&allOrNone=${allOrNone}`,+ undefined+ );+ return recordsUtils.formatCompositeResults(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/delete-sobject-record.ts b/packages/pieces/community/salesforce/src/lib/action/ai/delete-sobject-record.tsnew file mode 100644index 00000000000..7c2d47b8075--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/delete-sobject-record.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { deletedRecordOutputSchema } from '../../output-schemas';++export const deleteSobjectRecord = createAction({+ auth: salesforceAuth,+ name: 'delete_sobject_record',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Record',+ description: 'Delete one record of any object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Deletes a single record of any Salesforce object by id; the record goes to the Recycle Bin (recoverable for about 15 days) and cascade-deletes master-detail children. For up to 200 ids in one call use Delete Records Batch. Not idempotent: a second call on the same id fails because the record is already deleted.',+ idempotent: false,+ },+ outputSchema: deletedRecordOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact or My_Object__c.',+ required: true,+ }),+ record_id: Property.ShortText({+ displayName: 'Record ID',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const recordId = salesforceUtils.assertId({ value: context.propsValue.record_id, fieldName: 'Record ID' });+ await callSalesforceApi(+ HttpMethod.DELETE,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${recordId}`,+ undefined+ );+ return { id: recordId, deleted: true };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/describe-object.ts b/packages/pieces/community/salesforce/src/lib/action/ai/describe-object.tsnew file mode 100644index 00000000000..d6fdd83619d--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/describe-object.ts@@ -0,0 +1,105 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { describeObjectOutputSchema } from '../../output-schemas';++export const describeObject = createAction({+ auth: salesforceAuth,+ name: 'describe_object',+ classification: 'READ',+ displayName: 'Describe Object',+ description: 'Get the fields, relationships and record types of one object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the schema of one Salesforce object: every field (API name, label, type, required-ness, create/update permission, external id flag, lookup targets, active picklist values), its child relationships and its record types. Call it before writing SOQL or creating/updating records to get exact field API names and valid picklist values; to find the object API name first use List Objects. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: describeObjectOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Opportunity or My_Object__c.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const response = await callSalesforceApi<DescribeResult>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/describe`,+ undefined+ );+ const body = response.body;+ return {+ name: body.name,+ label: body.label,+ custom: body.custom,+ key_prefix: body.keyPrefix,+ fields: body.fields.map((field) => ({+ name: field.name,+ label: field.label,+ type: field.type,+ length: field.length,+ nillable: field.nillable,+ createable: field.createable,+ updateable: field.updateable,+ custom: field.custom,+ external_id: field.externalId,+ reference_to: field.referenceTo,+ picklist_values: field.picklistValues+ .filter((value) => value.active)+ .map((value) => ({ value: value.value, label: value.label })),+ })),+ child_relationships: body.childRelationships+ .filter((relationship) => relationship.relationshipName !== null)+ .map((relationship) => ({+ relationship_name: relationship.relationshipName,+ child_object: relationship.childSObject,+ field: relationship.field,+ })),+ record_types: body.recordTypeInfos.map((recordType) => ({+ name: recordType.name,+ developer_name: recordType.developerName,+ record_type_id: recordType.recordTypeId,+ active: recordType.active,+ master: recordType.master,+ })),+ };+ },+});++type DescribeResult = {+ name: string;+ label: string;+ custom: boolean;+ keyPrefix: string | null;+ fields: {+ name: string;+ label: string;+ type: string;+ length: number;+ nillable: boolean;+ createable: boolean;+ updateable: boolean;+ custom: boolean;+ externalId: boolean;+ referenceTo: string[];+ picklistValues: { value: string; label: string; active: boolean }[];+ }[];+ childRelationships: {+ relationshipName: string | null;+ childSObject: string;+ field: string;+ }[];+ recordTypeInfos: {+ name: string;+ developerName: string;+ recordTypeId: string;+ active: boolean;+ master: boolean;+ }[];+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/download-file.ts b/packages/pieces/community/salesforce/src/lib/action/ai/download-file.tsnew file mode 100644index 00000000000..a5864682625--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/download-file.ts@@ -0,0 +1,62 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { downloadFileOutputSchema } from '../../output-schemas';++export const downloadFile = createAction({+ auth: salesforceAuth,+ name: 'download_file',+ classification: 'READ',+ displayName: 'Download File',+ description: 'Download the content of a Salesforce file.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Downloads the latest version of a Salesforce File by its content document id (starts with 069) and returns it as a file reference with its name, size and MIME type. Use Get File Info when you only need metadata. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: downloadFileOutputSchema,+ props: {+ content_document_id: Property.ShortText({+ displayName: 'Content Document ID',+ description: 'File id starting with 069.',+ required: true,+ }),+ },+ async run(context) {+ const id = salesforceUtils.assertId({+ value: context.propsValue.content_document_id,+ fieldName: 'Content Document ID',+ });+ const info = await callSalesforceApi<{ title: string; fileExtension?: string; mimeType?: string }>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/connect/files/${id}`,+ undefined,+ );+ const content = await callSalesforceApi<ArrayBuffer>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/connect/files/${id}/content`,+ undefined,+ { responseType: 'arraybuffer' },+ );+ const fileName = buildFileName({ title: info.body.title, extension: info.body.fileExtension });+ const data = Buffer.from(content.body);+ return {+ file: await context.files.write({ fileName, data }),+ file_name: fileName,+ size: data.length,+ mime_type: info.body.mimeType ?? null,+ };+ },+});++function buildFileName({ title, extension }: { title: string; extension: string | undefined }): string {+ if (!extension || title.toLowerCase().endsWith(`.${extension.toLowerCase()}`)) {+ return title;+ }+ return `${title}.${extension}`;+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-job.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-job.tsnew file mode 100644index 00000000000..9aaa2bc5adb--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-job.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { bulkUtils } from '../../common/bulk';+import { bulkJobOutputSchema } from '../../output-schemas';++export const getBulkIngestJob = createAction({+ auth: salesforceAuth,+ name: 'get_bulk_ingest_job',+ classification: 'READ',+ displayName: 'Get Bulk Ingest Job',+ description: 'Get the status and counters of a Bulk API 2.0 ingest job.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the state and processed/failed record counts of a Bulk API 2.0 ingest job started by Run Bulk Ingest Job. Poll it until the state is JobComplete, Failed or Aborted, then call Get Bulk Ingest Results. For query jobs use Get Bulk Query Job. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: bulkJobOutputSchema,+ props: {+ job_id: Property.ShortText({+ displayName: 'Job ID',+ required: true,+ }),+ },+ async run(context) {+ const jobId = salesforceUtils.assertId({ value: context.propsValue.job_id, fieldName: 'Job ID' });+ const response = await callSalesforceApi(HttpMethod.GET, context.auth, `${bulkUtils.BULK_API_PATH}/ingest/${jobId}`, undefined);+ return bulkUtils.formatJob(response.body);+ },+});+diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-results.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-results.tsnew file mode 100644index 00000000000..4255b6c7ef4--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-ingest-results.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { bulkUtils } from '../../common/bulk';+import { getBulkIngestResultsOutputSchema } from '../../output-schemas';++export const getBulkIngestResults = createAction({+ auth: salesforceAuth,+ name: 'get_bulk_ingest_results',+ classification: 'READ',+ displayName: 'Get Bulk Ingest Results',+ description: 'Get the successful, failed or unprocessed rows of a Bulk API 2.0 ingest job.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the per-row outcome of a Bulk API 2.0 ingest job as rows: successful rows carry sf__Id and sf__Created, failed rows carry sf__Error. Results only exist once Get Bulk Ingest Job reports JobComplete or Failed; unprocessed rows are those never attempted (e.g. after an abort). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getBulkIngestResultsOutputSchema,+ props: {+ job_id: Property.ShortText({+ displayName: 'Job ID',+ required: true,+ }),+ result_type: Property.StaticDropdown({+ displayName: 'Result Type',+ required: true,+ defaultValue: 'successfulResults',+ options: {+ options: [+ { label: 'Successful', value: 'successfulResults' },+ { label: 'Failed', value: 'failedResults' },+ { label: 'Unprocessed', value: 'unprocessedrecords' },+ ],+ },+ }),+ },+ async run(context) {+ const jobId = salesforceUtils.assertId({ value: context.propsValue.job_id, fieldName: 'Job ID' });+ const response = await callSalesforceApi<string>(+ HttpMethod.GET,+ context.auth,+ `${bulkUtils.BULK_API_PATH}/ingest/${jobId}/${context.propsValue.result_type}`,+ undefined,+ { responseType: 'text' }+ );+ const rows = bulkUtils.parseCsv(typeof response.body === 'string' ? response.body : '');+ return { rows, count: rows.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-job.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-job.tsnew file mode 100644index 00000000000..b92abe744eb--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-job.ts@@ -0,0 +1,33 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { bulkUtils } from '../../common/bulk';+import { bulkJobOutputSchema } from '../../output-schemas';++export const getBulkQueryJob = createAction({+ auth: salesforceAuth,+ name: 'get_bulk_query_job',+ classification: 'READ',+ displayName: 'Get Bulk Query Job',+ description: 'Get the status of a Bulk API 2.0 query job.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the state and processed record count of a Bulk API 2.0 query job started by Create Bulk Query Job. Poll it until the state is JobComplete (then call Get Bulk Query Results), Failed or Aborted. For ingest jobs use Get Bulk Ingest Job. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: bulkJobOutputSchema,+ props: {+ job_id: Property.ShortText({+ displayName: 'Job ID',+ required: true,+ }),+ },+ async run(context) {+ const jobId = salesforceUtils.assertId({ value: context.propsValue.job_id, fieldName: 'Job ID' });+ const response = await callSalesforceApi(HttpMethod.GET, context.auth, `${bulkUtils.BULK_API_PATH}/query/${jobId}`, undefined);+ return bulkUtils.formatJob(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-results.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-results.tsnew file mode 100644index 00000000000..9e613464d18--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-bulk-query-results.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { bulkUtils } from '../../common/bulk';+import { getBulkQueryResultsOutputSchema } from '../../output-schemas';++export const getBulkQueryResults = createAction({+ auth: salesforceAuth,+ name: 'get_bulk_query_results',+ classification: 'READ',+ displayName: 'Get Bulk Query Results',+ description: 'Get one page of rows from a completed Bulk API 2.0 query job.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one page of rows from a Bulk API 2.0 query job once Get Bulk Query Job reports JobComplete. Pass the returned next_locator to fetch the next page; next_locator is null when there are no more rows. Page size defaults to 1000 and is capped at 10000. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getBulkQueryResultsOutputSchema,+ props: {+ job_id: Property.ShortText({+ displayName: 'Job ID',+ required: true,+ }),+ locator: Property.ShortText({+ displayName: 'Locator',+ description: 'next_locator from the previous page. Leave empty for the first page.',+ required: false,+ }),+ max_records: Property.Number({+ displayName: 'Max Records',+ description: 'Rows per page (default 1000, max 10000).',+ required: false,+ defaultValue: 1000,+ }),+ },+ async run(context) {+ const jobId = salesforceUtils.assertId({ value: context.propsValue.job_id, fieldName: 'Job ID' });+ const maxRecords = Math.min(Math.max(Math.floor(context.propsValue.max_records ?? 1000), 1), 10000);+ const locator = context.propsValue.locator?.trim();+ const params = new URLSearchParams({ maxRecords: String(maxRecords), ...(locator ? { locator } : {}) });+ const response = await callSalesforceApi<string>(+ HttpMethod.GET,+ context.auth,+ `${bulkUtils.BULK_API_PATH}/query/${jobId}/results?${params.toString()}`,+ undefined,+ { responseType: 'text' }+ );+ const rows = bulkUtils.parseCsv(typeof response.body === 'string' ? response.body : '');+ const header = response.headers?.['sforce-locator'];+ const nextLocator = Array.isArray(header) ? header[0] : header;+ return {+ rows,+ count: rows.length,+ next_locator: !nextLocator || nextLocator === 'null' ? null : nextLocator,+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-child-records.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-child-records.tsnew file mode 100644index 00000000000..06a6f93f899--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-child-records.ts@@ -0,0 +1,61 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { soqlQueryOutputSchema } from '../../output-schemas';++export const getChildRecords = createAction({+ auth: salesforceAuth,+ name: 'get_child_records',+ classification: 'READ',+ displayName: 'Get Child Records',+ description: 'List the related child records of a parent record.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the child records under one parent record through a child relationship name, e.g. Contacts or Opportunities on an Account, or Cases on a Contact. Relationship names come from Describe Object (childRelationships); for filtered or sorted child lookups use Run SOQL Query instead. If next_records_url is not null, fetch more with Get Next Query Page. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: soqlQueryOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Parent Object',+ description: 'Parent object API name, e.g. Account.',+ required: true,+ }),+ record_id: Property.ShortText({+ displayName: 'Parent Record ID',+ required: true,+ }),+ relationship_name: Property.ShortText({+ displayName: 'Relationship Name',+ description: 'Child relationship name, e.g. Contacts, Opportunities or My_Children__r.',+ required: true,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Child field API names to return. Leave empty for all fields.',+ required: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Parent Object' });+ const recordId = salesforceUtils.assertId({ value: context.propsValue.record_id, fieldName: 'Parent Record ID' });+ const relationship = salesforceUtils.assertApiName({+ value: context.propsValue.relationship_name,+ fieldName: 'Relationship Name',+ });+ const fields = salesforceUtils+ .toStringArray(context.propsValue.fields)+ .map((field) => salesforceUtils.assertApiName({ value: field, fieldName: 'Fields' }));+ const query = fields.length > 0 ? `?fields=${fields.join(',')}` : '';+ const response = await callSalesforceApi<QueryResult<unknown>>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${recordId}/${relationship}${query}`,+ undefined+ );+ return salesforceUtils.formatQueryResult(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-current-user.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-current-user.tsnew file mode 100644index 00000000000..99def792195--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-current-user.ts@@ -0,0 +1,51 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { getCurrentUserOutputSchema } from '../../output-schemas';++export const getCurrentUser = createAction({+ auth: salesforceAuth,+ name: 'get_current_user',+ classification: 'READ',+ displayName: 'Get Current User',+ description: 'Get the connected Salesforce user and org.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the Salesforce user behind this connection (user id, username, name, email, locale, time zone, user type) and the org id. Use it to resolve "me" or "my" in a request, e.g. to filter by OwnerId in Run SOQL Query or to assign records to the current user. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getCurrentUserOutputSchema,+ props: {},+ async run(context) {+ const response = await callSalesforceApi<UserInfo>(+ HttpMethod.GET,+ context.auth,+ '/services/oauth2/userinfo',+ undefined+ );+ const user = response.body;+ return {+ user_id: user.user_id,+ organization_id: user.organization_id,+ username: user.preferred_username,+ name: user.name,+ email: user.email,+ locale: user.locale,+ zoneinfo: user.zoneinfo,+ user_type: user.user_type,+ };+ },+});++type UserInfo = {+ user_id: string;+ organization_id: string;+ preferred_username: string;+ name: string;+ email: string;+ locale: string;+ zoneinfo: string;+ user_type: string;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-dashboard.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-dashboard.tsnew file mode 100644index 00000000000..f3f26706fb3--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-dashboard.ts@@ -0,0 +1,83 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getDashboardOutputSchema } from '../../output-schemas';++export const getDashboard = createAction({+ auth: salesforceAuth,+ name: 'get_dashboard',+ classification: 'READ',+ displayName: 'Get Dashboard',+ description: 'Get a dashboard with its components and filters.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Describes a Salesforce dashboard by id: name, folder, filters and each component with its header, title, type and source report id. Use the report ids with Run Report Sync to get the underlying data; use List Dashboards to find the id. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getDashboardOutputSchema,+ props: {+ dashboard_id: Property.ShortText({+ displayName: 'Dashboard ID',+ description: 'Dashboard id starting with 01Z.',+ required: true,+ }),+ },+ async run(context) {+ const dashboardId = salesforceUtils.assertId({+ value: context.propsValue.dashboard_id,+ fieldName: 'Dashboard ID',+ });+ const response = await callSalesforceApi<DashboardDescribe>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/analytics/dashboards/${dashboardId}/describe`,+ undefined,+ );+ const dashboard = response.body;+ return {+ id: dashboard.id ?? dashboardId,+ name: dashboard.name ?? null,+ developer_name: dashboard.developerName ?? null,+ folder_id: dashboard.folderId ?? null,+ components: (dashboard.components ?? []).map((component) => ({+ id: component.id,+ header: component.header ?? null,+ title: component.title ?? null,+ type: component.type ?? null,+ visualization_type: component.properties?.visualizationType ?? null,+ report_id: component.reportId ?? null,+ })),+ filters: (dashboard.filters ?? []).map((filter) => ({+ name: filter.name,+ options: (filter.options ?? []).map((option) => ({+ id: option.id ?? null,+ alias: option.alias ?? null,+ operation: option.operation ?? null,+ value: option.value ?? null,+ })),+ })),+ };+ },+});++type DashboardDescribe = {+ id?: string;+ name?: string;+ developerName?: string;+ folderId?: string;+ components?: {+ id: string;+ header?: string | null;+ title?: string | null;+ type?: string;+ reportId?: string | null;+ properties?: { visualizationType?: string };+ }[];+ filters?: {+ name: string;+ options?: { id?: string; alias?: string | null; operation?: string; value?: string | null }[];+ }[];+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-file-info.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-file-info.tsnew file mode 100644index 00000000000..6ce58ff55f1--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-file-info.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getFileInfoOutputSchema } from '../../output-schemas';++export const getFileInfo = createAction({+ auth: salesforceAuth,+ name: 'get_file_info',+ classification: 'READ',+ displayName: 'Get File Info',+ description: 'Get the details of a Salesforce file.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the metadata of a Salesforce File (title, extension, type, size, MIME type, owner, dates, version) by its content document id (starts with 069). Use it to inspect a file; to get the bytes use Download File. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getFileInfoOutputSchema,+ props: {+ content_document_id: Property.ShortText({+ displayName: 'Content Document ID',+ description: 'File id starting with 069.',+ required: true,+ }),+ },+ async run(context) {+ const id = salesforceUtils.assertId({+ value: context.propsValue.content_document_id,+ fieldName: 'Content Document ID',+ });+ const response = await callSalesforceApi<ConnectFile>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/connect/files/${id}`,+ undefined,+ );+ const file = response.body;+ return {+ id: file.id,+ title: file.title,+ name: file.name ?? null,+ file_extension: file.fileExtension ?? null,+ file_type: file.fileType ?? null,+ content_size: file.contentSize ?? null,+ mime_type: file.mimeType ?? null,+ owner_id: file.owner?.id ?? null,+ owner_name: file.owner?.displayName ?? file.owner?.name ?? null,+ created_date: file.createdDate ?? null,+ modified_date: file.modifiedDate ?? null,+ version_number: file.versionNumber ?? null,+ download_url: file.downloadUrl ?? null,+ };+ },+});++type ConnectFile = {+ id: string;+ title: string;+ name?: string;+ fileExtension?: string;+ fileType?: string;+ contentSize?: number;+ mimeType?: string;+ owner?: { id?: string; displayName?: string; name?: string };+ createdDate?: string;+ modifiedDate?: string;+ versionNumber?: string;+ downloadUrl?: string;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-metadata.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-metadata.tsnew file mode 100644index 00000000000..0e111df17a1--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-metadata.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getListViewMetadataOutputSchema } from '../../output-schemas';++export const getListViewMetadata = createAction({+ auth: salesforceAuth,+ name: 'get_list_view_metadata',+ classification: 'READ',+ displayName: 'Get List View Metadata',+ description: 'Get the columns, filters and SOQL query behind a list view.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the columns, ordering, filter and underlying SOQL query of one list view (ids from List List Views). Use it to reuse or adapt the list view\'s query; to read its rows directly use Get List View Records. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getListViewMetadataOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account.',+ required: true,+ }),+ list_view_id: Property.ShortText({+ displayName: 'List View ID',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const listViewId = salesforceUtils.assertId({ value: context.propsValue.list_view_id, fieldName: 'List View ID' });+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/listviews/${listViewId}/describe`,+ undefined+ );+ const body: unknown = response.body;+ const result = salesforceUtils.isRecord(body) ? body : {};+ const columns = (Array.isArray(result['columns']) ? result['columns'] : []).filter(salesforceUtils.isRecord).map((column) => ({+ field_name_or_path: column['fieldNameOrPath'] ?? null,+ label: column['label'] ?? null,+ sortable: column['sortable'] ?? null,+ type: column['type'] ?? null,+ }));+ return {+ id: result['id'] ?? listViewId,+ sobject_type: result['sobjectType'] ?? object,+ query: result['query'] ?? null,+ columns,+ order_by: result['orderBy'] ?? null,+ where_condition: result['whereCondition'] ?? null,+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-records.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-records.tsnew file mode 100644index 00000000000..d43d9c0e4c5--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-list-view-records.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getListViewRecordsOutputSchema } from '../../output-schemas';++export const getListViewRecords = createAction({+ auth: salesforceAuth,+ name: 'get_list_view_records',+ classification: 'READ',+ displayName: 'Get List View Records',+ description: 'Get the rows a list view shows, with its columns.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the records of one list view (ids from List List Views) as flat rows keyed by the list view\'s columns, exactly as a user sees them. Use it to reuse a saved filter; for custom filtering write a SOQL query instead. Page with Offset; Limit defaults to 50, max 200. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getListViewRecordsOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account.',+ required: true,+ }),+ list_view_id: Property.ShortText({+ displayName: 'List View ID',+ required: true,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Rows to return (default 50, max 200).',+ required: false,+ defaultValue: 50,+ }),+ offset: Property.Number({+ displayName: 'Offset',+ description: 'Rows to skip, for paging.',+ required: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const listViewId = salesforceUtils.assertId({ value: context.propsValue.list_view_id, fieldName: 'List View ID' });+ const limit = Math.min(Math.max(Math.floor(context.propsValue.limit ?? 50), 1), 200);+ const offset = Math.max(Math.floor(context.propsValue.offset ?? 0), 0);+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/listviews/${listViewId}/results?limit=${limit}&offset=${offset}`,+ undefined+ );+ const body: unknown = response.body;+ const result = salesforceUtils.isRecord(body) ? body : {};+ const records = (Array.isArray(result['records']) ? result['records'] : []).filter(salesforceUtils.isRecord).map(flattenRow);+ return {+ records,+ count: records.length,+ size: result['size'] ?? null,+ done: result['done'] ?? null,+ };+ },+});++function flattenRow(row: Record<string, unknown>): Record<string, unknown> {+ const cells = Array.isArray(row['columns']) ? row['columns'] : [];+ return Object.fromEntries(+ cells.filter(salesforceUtils.isRecord).map((cell) => [String(cell['fieldNameOrPath']), cell['value'] ?? null])+ );+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-next-query-page.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-next-query-page.tsnew file mode 100644index 00000000000..e5ef3bbaa4b--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-next-query-page.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { soqlQueryOutputSchema } from '../../output-schemas';++export const getNextQueryPage = createAction({+ auth: salesforceAuth,+ name: 'get_next_query_page',+ classification: 'READ',+ displayName: 'Get Next Query Page',+ description: 'Fetch the next page of a query result.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetches the next batch of records for a query whose result had a non-null next_records_url, from Run SOQL Query, Run SOQL Query All, Run Tooling Query or Get Child Records. Pass that next_records_url exactly as returned (or just the query locator); keep calling until next_records_url is null. Read-only; safe to retry while the cursor is alive (about 15 minutes of inactivity).',+ idempotent: true,+ },+ outputSchema: soqlQueryOutputSchema,+ props: {+ next_records_url: Property.ShortText({+ displayName: 'Next Records URL',+ description: 'The next_records_url from a previous query result, e.g. /services/data/v56.0/query/01gD0000002HU6KIAW-2000.',+ required: true,+ }),+ },+ async run(context) {+ const path = toQueryPath(context.propsValue.next_records_url);+ const response = await callSalesforceApi<QueryResult<unknown>>(HttpMethod.GET, context.auth, path, undefined);+ return salesforceUtils.formatQueryResult(response.body);+ },+});++function toQueryPath(value: string): string {+ const trimmed = value.trim();+ if (NEXT_RECORDS_URL_PATTERN.test(trimmed)) {+ return trimmed;+ }+ if (LOCATOR_PATTERN.test(trimmed)) {+ return `/services/data/v56.0/query/${trimmed}`;+ }+ throw new Error('Next Records URL must be a next_records_url returned by a query, such as /services/data/v56.0/query/01g...-2000.');+}++const NEXT_RECORDS_URL_PATTERN = /^\/services\/data\/v\d+\.\d+\/(?:tooling\/)?(?:query|queryAll)\/[A-Za-z0-9-]+$/;+const LOCATOR_PATTERN = /^[A-Za-z0-9]+-\d+$/;diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-org-limits.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-org-limits.tsnew file mode 100644index 00000000000..5e1cc983086--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-org-limits.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { getOrgLimitsOutputSchema } from '../../output-schemas';++export const getOrgLimits = createAction({+ auth: salesforceAuth,+ name: 'get_org_limits',+ classification: 'READ',+ displayName: 'Get Org Limits',+ description: 'Get the org limits and how much of each is used.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the Salesforce org limits (e.g. DailyApiRequests, DataStorageMB, DailyBulkApiBatches) with max, remaining and used values. Use it to check API or storage headroom before heavy work; for per-object record totals use Get Record Counts. Filter with Name to return only matching limits. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getOrgLimitsOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Only return limits whose name contains this text (case-insensitive), e.g. Api or Storage.',+ required: false,+ }),+ },+ async run(context) {+ const response = await callSalesforceApi<Record<string, { Max: number; Remaining: number }>>(+ HttpMethod.GET,+ context.auth,+ '/services/data/v56.0/limits',+ undefined+ );+ const filter = (context.propsValue.name ?? '').trim().toLowerCase();+ const limits = Object.entries(response.body)+ .filter(([name]) => filter.length === 0 || name.toLowerCase().includes(filter))+ .map(([name, limit]) => ({+ name,+ max: limit.Max,+ remaining: limit.Remaining,+ used: limit.Max - limit.Remaining,+ }));+ return { limits, count: limits.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-quick-action-defaults.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-quick-action-defaults.tsnew file mode 100644index 00000000000..4de7906afe3--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-quick-action-defaults.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getQuickActionDefaultsOutputSchema } from '../../output-schemas';++export const getQuickActionDefaults = createAction({+ auth: salesforceAuth,+ name: 'get_quick_action_defaults',+ classification: 'READ',+ displayName: 'Get Quick Action Defaults',+ description: 'Get the default field values a quick action would pre-fill.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the field values a quick action pre-fills, optionally in the context of a parent record (e.g. an Account id for Account.NewContact). Call it before Run Quick Action to see which fields to send. Names come from List Quick Actions. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getQuickActionDefaultsOutputSchema,+ props: {+ action_name: Property.ShortText({+ displayName: 'Quick Action Name',+ description: 'Name exactly as returned by List Quick Actions: Object.Action for object-specific actions (e.g. Account.NewContact), a bare name for global ones (e.g. LogACall).',+ required: true,+ }),+ context_id: Property.ShortText({+ displayName: 'Context Record ID',+ description: 'Id of the record the action runs against. Optional.',+ required: false,+ }),+ },+ async run(context) {+ const actionName = assertQuickActionName(context.propsValue.action_name);+ const contextId = context.propsValue.context_id?.trim()+ ? `/${salesforceUtils.assertId({ value: context.propsValue.context_id, fieldName: 'Context Record ID' })}`+ : '';+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/${quickActionPath(actionName)}/defaultValues${contextId}`,+ undefined+ );+ return salesforceUtils.cleanRecord(response.body);+ },+});++function quickActionPath(actionName: string): string {+ const [objectName] = actionName.split('.');+ return actionName.includes('.') ? `sobjects/${objectName}/quickActions/${actionName}` : `quickActions/${actionName}`;+}++function assertQuickActionName(value: string): string {+ return value+ .trim()+ .split('.')+ .map((part) => salesforceUtils.assertApiName({ value: part, fieldName: 'Quick Action Name' }))+ .join('.');+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-record-by-external-id.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-record-by-external-id.tsnew file mode 100644index 00000000000..b0657276ade--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-record-by-external-id.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { recordOutputSchema } from '../../output-schemas';++export const getRecordByExternalId = createAction({+ auth: salesforceAuth,+ name: 'get_record_by_external_id',+ classification: 'READ',+ displayName: 'Get Record by External ID',+ description: 'Get one record by the value of an external id field.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns a single Salesforce record matched on an external id field (a field marked External ID or unique, e.g. My_Ext_Id__c) instead of the Salesforce id. Use it when you know an id from another system; if you have the Salesforce id use Get Record. Fails with 404 when nothing matches and 300 when several records match. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: recordOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or My_Object__c.',+ required: true,+ }),+ external_id_field: Property.ShortText({+ displayName: 'External ID Field',+ description: 'API name of the external id field, e.g. My_Ext_Id__c.',+ required: true,+ }),+ external_id_value: Property.ShortText({+ displayName: 'External ID Value',+ required: true,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Field API names to return. Leave empty for all fields.',+ required: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const externalField = salesforceUtils.assertApiName({+ value: context.propsValue.external_id_field,+ fieldName: 'External ID Field',+ });+ const value = context.propsValue.external_id_value.trim();+ if (value.length === 0) {+ throw new Error('External ID Value is required.');+ }+ const fields = salesforceUtils+ .toStringArray(context.propsValue.fields)+ .map((field) => salesforceUtils.assertApiName({ value: field, fieldName: 'Fields' }));+ const query = fields.length > 0 ? `?fields=${fields.join(',')}` : '';+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${externalField}/${encodeURIComponent(value)}${query}`,+ undefined+ );+ return salesforceUtils.cleanRecord(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-record-counts.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-record-counts.tsnew file mode 100644index 00000000000..31f98dccf97--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-record-counts.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getRecordCountsOutputSchema } from '../../output-schemas';++export const getRecordCounts = createAction({+ auth: salesforceAuth,+ name: 'get_record_counts',+ classification: 'READ',+ displayName: 'Get Record Counts',+ description: 'Get approximate record counts per object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the approximate number of records stored for each listed object (or every object when none are listed), as used for org storage. Use it for a quick size overview; counts are refreshed periodically and can lag, so for an exact filtered count use Run SOQL Query with SELECT COUNT(). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getRecordCountsOutputSchema,+ props: {+ objects: Property.Array({+ displayName: 'Objects',+ description: 'Object API names to count, e.g. Account, Contact. Leave empty for all objects.',+ required: false,+ }),+ },+ async run(context) {+ const objects = salesforceUtils+ .toStringArray(context.propsValue.objects)+ .map((object) => salesforceUtils.assertApiName({ value: object, fieldName: 'Objects' }));+ const query = objects.length > 0 ? `?sObjects=${objects.join(',')}` : '';+ const response = await callSalesforceApi<{ sObjects: { name: string; count: number }[] }>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/limits/recordCount${query}`,+ undefined+ );+ const counts = response.body.sObjects.map((item) => ({ name: item.name, count: item.count }));+ return { counts, count: counts.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-record.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-record.tsnew file mode 100644index 00000000000..746a2c6f5fc--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-record.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { recordOutputSchema } from '../../output-schemas';++export const getRecord = createAction({+ auth: salesforceAuth,+ name: 'get_record',+ classification: 'READ',+ displayName: 'Get Record',+ description: 'Get one record of any object by its id.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns a single Salesforce record of any object (Account, Contact, Lead, Opportunity, Case, custom objects…) by its 15- or 18-character id, with all fields or only the ones you list. Use it after a search or query returned an id; to fetch many records of one object at once use Get Records Batch. Field and object names are API names from Describe Object. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: recordOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact, Opportunity or My_Object__c.',+ required: true,+ }),+ record_id: Property.ShortText({+ displayName: 'Record ID',+ required: true,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Field API names to return. Leave empty for all fields.',+ required: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const recordId = salesforceUtils.assertId({ value: context.propsValue.record_id, fieldName: 'Record ID' });+ const fields = salesforceUtils+ .toStringArray(context.propsValue.fields)+ .map((field) => salesforceUtils.assertApiName({ value: field, fieldName: 'Fields' }));+ const query = fields.length > 0 ? `?fields=${fields.join(',')}` : '';+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${recordId}${query}`,+ undefined+ );+ return salesforceUtils.cleanRecord(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-records-batch.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-records-batch.tsnew file mode 100644index 00000000000..56f3e9181f0--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-records-batch.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { recordsUtils } from '../../common/records';+import { getRecordsBatchOutputSchema } from '../../output-schemas';++export const getRecordsBatch = createAction({+ auth: salesforceAuth,+ name: 'get_records_batch',+ classification: 'READ',+ displayName: 'Get Records Batch',+ description: 'Get up to 2000 records of one object by their ids.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns up to 2000 records of one Salesforce object by id in a single call, with the fields you list (at least one field is required). Use it instead of calling Get Record repeatedly; to find records by criteria use Run SOQL Query. Ids that do not exist come back as null entries in the same position, so the output stays aligned with the input. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getRecordsBatchOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact or My_Object__c.',+ required: true,+ }),+ record_ids: Property.Array({+ displayName: 'Record IDs',+ description: 'Up to 2000 record ids of this object.',+ required: true,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Field API names to return, e.g. Id, Name. At least one is required.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const ids = recordsUtils.parseIdList({ value: context.propsValue.record_ids, fieldName: 'Record IDs', max: MAX_IDS });+ const fields = salesforceUtils+ .toStringArray(context.propsValue.fields)+ .map((field) => salesforceUtils.assertApiName({ value: field, fieldName: 'Fields' }));+ if (fields.length === 0) {+ throw new Error('Fields must contain at least one field API name.');+ }+ const response = await callSalesforceApi<unknown[]>(+ HttpMethod.POST,+ context.auth,+ `/services/data/v56.0/composite/sobjects/${object}`,+ { ids, fields }+ );+ const records = response.body.map((record, index) => ({+ requested_id: ids[index],+ found: record !== null,+ record: salesforceUtils.cleanRecord(record),+ }));+ return {+ records,+ count: records.length,+ found_count: records.filter((record) => record.found).length,+ };+ },+});++const MAX_IDS = 2000;diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-report-instance.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-report-instance.tsnew file mode 100644index 00000000000..90a3e622ff2--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-report-instance.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { reportUtils, SalesforceReportResponse } from '../../common/report';+import { salesforceUtils } from '../../common/utils';+import { getReportInstanceOutputSchema } from '../../output-schemas';++export const getReportInstance = createAction({+ auth: salesforceAuth,+ name: 'get_report_instance',+ classification: 'READ',+ displayName: 'Get Report Instance',+ description: 'Check an async report run and get its rows when it is done.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the status of a report run started with Run Report Async (New, Running, Success or Error) and, once the status is Success, its flat rows keyed by column label. Call it again later while the status is New or Running. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getReportInstanceOutputSchema,+ props: {+ report_id: Property.ShortText({+ displayName: 'Report ID',+ description: 'Report id starting with 00O.',+ required: true,+ }),+ instance_id: Property.ShortText({+ displayName: 'Instance ID',+ description: 'Instance id returned by Run Report Async.',+ required: true,+ }),+ },+ async run(context) {+ const reportId = salesforceUtils.assertId({ value: context.propsValue.report_id, fieldName: 'Report ID' });+ const instanceId = salesforceUtils.assertId({ value: context.propsValue.instance_id, fieldName: 'Instance ID' });+ const response = await callSalesforceApi<SalesforceReportResponse>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/analytics/reports/${reportId}/instances/${instanceId}`,+ undefined,+ );+ const status = response.body.attributes?.status ?? 'Unknown';+ if (status !== 'Success') {+ return { instance_id: instanceId, status, reportId };+ }+ return {+ instance_id: instanceId,+ status,+ ...reportUtils.transformReportToRows(response.body),+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-report.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-report.tsnew file mode 100644index 00000000000..7cc7bf27aa2--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-report.ts@@ -0,0 +1,73 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getReportOutputSchema } from '../../output-schemas';++export const getReport = createAction({+ auth: salesforceAuth,+ name: 'get_report',+ classification: 'READ',+ displayName: 'Get Report',+ description: 'Get the definition of a report: columns, groupings and filters.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Describes a Salesforce report by id without running it: format, report type, detail columns with labels, groupings, saved filters and filter logic. Use it to learn the column API names before passing filters to Run Report Sync or Run Report Async; use List Reports to find the id. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getReportOutputSchema,+ props: {+ report_id: Property.ShortText({+ displayName: 'Report ID',+ description: 'Report id starting with 00O.',+ required: true,+ }),+ },+ async run(context) {+ const reportId = salesforceUtils.assertId({ value: context.propsValue.report_id, fieldName: 'Report ID' });+ const response = await callSalesforceApi<ReportDescribe>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/analytics/reports/${reportId}/describe`,+ undefined,+ );+ const metadata = response.body.reportMetadata;+ const columnInfo = response.body.reportExtendedMetadata?.detailColumnInfo ?? {};+ return {+ id: metadata.id,+ name: metadata.name,+ developer_name: metadata.developerName ?? null,+ format: metadata.reportFormat ?? null,+ report_type: metadata.reportType?.type ?? null,+ report_type_label: metadata.reportType?.label ?? null,+ detail_columns: metadata.detailColumns ?? [],+ groupings_down: (metadata.groupingsDown ?? []).map((grouping) => grouping.name),+ filters: metadata.reportFilters ?? [],+ filter_logic: metadata.reportBooleanFilter ?? null,+ columns: Object.entries(columnInfo).map(([apiName, info]) => ({+ api_name: apiName,+ label: info.label,+ data_type: info.dataType,+ })),+ };+ },+});++type ReportDescribe = {+ reportMetadata: {+ id: string;+ name: string;+ developerName?: string;+ reportFormat?: string;+ reportType?: { type: string; label: string };+ detailColumns?: string[];+ groupingsDown?: { name: string }[];+ reportFilters?: { column: string; operator: string; value: string }[];+ reportBooleanFilter?: string | null;+ };+ reportExtendedMetadata?: {+ detailColumnInfo?: Record<string, { label: string; dataType: string }>;+ };+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/get-updated-record-ids.ts b/packages/pieces/community/salesforce/src/lib/action/ai/get-updated-record-ids.tsnew file mode 100644index 00000000000..8e1d14f0e3e--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/get-updated-record-ids.ts@@ -0,0 +1,62 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { getUpdatedRecordIdsOutputSchema } from '../../output-schemas';++export const getUpdatedRecordIds = createAction({+ auth: salesforceAuth,+ name: 'get_updated_record_ids',+ classification: 'READ',+ displayName: 'Get Updated Record IDs',+ description: 'List ids of records of one object changed in a time window.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the ids of records of one Salesforce object that were created or updated between a start and end time, plus the latest time covered. Use it for incremental sync; to fetch the records afterwards use Get Records Batch, and to filter on other criteria use Run SOQL Query. The window must fall within the last 30 days; times are UTC at minute precision. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: getUpdatedRecordIdsOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or My_Object__c.',+ required: true,+ }),+ start: Property.DateTime({+ displayName: 'Start',+ description: 'ISO 8601 start time, within the last 30 days, e.g. 2026-09-01T00:00:00Z.',+ required: true,+ }),+ end: Property.DateTime({+ displayName: 'End',+ description: 'ISO 8601 end time. Defaults to now.',+ required: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const start = toSalesforceDate({ value: context.propsValue.start, fieldName: 'Start' });+ const end = toSalesforceDate({ value: context.propsValue.end ?? new Date().toISOString(), fieldName: 'End' });+ const response = await callSalesforceApi<{ ids: string[]; latestDateCovered: string }>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/updated/?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`,+ undefined+ );+ return {+ ids: response.body.ids,+ count: response.body.ids.length,+ latest_date_covered: response.body.latestDateCovered,+ };+ },+});++function toSalesforceDate({ value, fieldName }: { value: string; fieldName: string }): string {+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) {+ throw new Error(`${fieldName} must be an ISO 8601 date-time.`);+ }+ return date.toISOString().replace(/\.\d{3}Z$/, '+00:00');+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-dashboards.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-dashboards.tsnew file mode 100644index 00000000000..285c53d5383--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-dashboards.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { querySalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { listDashboardsOutputSchema } from '../../output-schemas';++export const listDashboards = createAction({+ auth: salesforceAuth,+ name: 'list_dashboards',+ classification: 'SEARCH',+ displayName: 'List Dashboards',+ description: 'List dashboards, optionally filtered by title.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists Salesforce dashboards (id, title, developer name, folder, description) filtered by title. Use it to find a dashboard id for Get Dashboard, which lists its components and their source reports. Returns at most 200 dashboards per call. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listDashboardsOutputSchema,+ props: {+ title_contains: Property.ShortText({+ displayName: 'Title Contains',+ description: 'Only dashboards whose title contains this text.',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum dashboards to return (1-200, default 50).',+ required: false,+ }),+ },+ async run(context) {+ const { title_contains, limit } = context.propsValue;+ const where = title_contains ? ` WHERE Title LIKE '%${salesforceUtils.escapeSoqlLike(title_contains)}%'` : '';+ const soql = `SELECT Id, Title, DeveloperName, FolderName, Description, LastModifiedDate FROM Dashboard${where} ORDER BY Title LIMIT ${clampLimit(limit)}`;+ const response = await querySalesforceApi<QueryResult<unknown>>(HttpMethod.GET, context.auth, soql);+ return salesforceUtils.formatQueryResult(response.body);+ },+});++function clampLimit(limit: number | undefined): number {+ return Math.min(Math.max(Math.floor(limit ?? 50), 1), 200);+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-email-templates.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-email-templates.tsnew file mode 100644index 00000000000..ca668e82f2f--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-email-templates.ts@@ -0,0 +1,61 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { querySalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { listEmailTemplatesOutputSchema } from '../../output-schemas';++export const listEmailTemplates = createAction({+ auth: salesforceAuth,+ name: 'list_email_templates',+ classification: 'SEARCH',+ displayName: 'List Email Templates',+ description: 'List email templates, optionally filtered by name or folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists Salesforce email templates (classic and Lightning) with their folder, type, subject and active flag, filtered by name, folder id or active only. Use it to look up a template id or developer name; it does not send anything, use Send Email Message for that. Returns at most 200 templates per call. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listEmailTemplatesOutputSchema,+ props: {+ name_contains: Property.ShortText({+ displayName: 'Name Contains',+ description: 'Only templates whose name contains this text.',+ required: false,+ }),+ folder_id: Property.ShortText({+ displayName: 'Folder ID',+ description: 'Only templates in this folder.',+ required: false,+ }),+ active_only: Property.Checkbox({+ displayName: 'Active Only',+ required: false,+ defaultValue: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum templates to return (1-200, default 50).',+ required: false,+ }),+ },+ async run(context) {+ const { name_contains, folder_id, active_only, limit } = context.propsValue;+ const conditions = [+ name_contains ? `Name LIKE '%${salesforceUtils.escapeSoqlLike(name_contains)}%'` : undefined,+ folder_id+ ? `FolderId = '${salesforceUtils.assertId({ value: folder_id, fieldName: 'Folder ID' })}'`+ : undefined,+ active_only ? 'IsActive = true' : undefined,+ ].filter((condition) => condition !== undefined);+ const where = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';+ const soql = `SELECT Id, Name, DeveloperName, Subject, FolderId, Folder.Name, TemplateType, IsActive, LastModifiedDate FROM EmailTemplate${where} ORDER BY Name LIMIT ${clampLimit(limit)}`;+ const response = await querySalesforceApi<QueryResult<unknown>>(HttpMethod.GET, context.auth, soql);+ return salesforceUtils.formatQueryResult(response.body);+ },+});++function clampLimit(limit: number | undefined): number {+ return Math.min(Math.max(Math.floor(limit ?? 50), 1), 200);+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-invocable-actions.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-invocable-actions.tsnew file mode 100644index 00000000000..70b94e942ff--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-invocable-actions.ts@@ -0,0 +1,61 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { listInvocableActionsOutputSchema } from '../../output-schemas';++export const listInvocableActions = createAction({+ auth: salesforceAuth,+ name: 'list_invocable_actions',+ classification: 'READ',+ displayName: 'List Invocable Actions',+ description: 'List the standard or custom invocable actions (flows, Apex, email alerts…) available in the org.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists invocable actions you can call with Run Invocable Action. Scope standard returns built-in actions (e.g. emailSimple, postToChatter); scope custom with no type returns the available custom action types (flow, apex, quickAction, emailAlert…), and with a type returns the actions of that type. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listInvocableActionsOutputSchema,+ props: {+ scope: Property.StaticDropdown({+ displayName: 'Scope',+ required: true,+ defaultValue: 'standard',+ options: {+ options: [+ { label: 'Standard', value: 'standard' },+ { label: 'Custom', value: 'custom' },+ ],+ },+ }),+ custom_type: Property.ShortText({+ displayName: 'Custom Action Type',+ description: 'For custom scope: flow, apex, quickAction, emailAlert… Leave empty to list the available types.',+ required: false,+ }),+ },+ async run(context) {+ const customType = context.propsValue.custom_type?.trim();+ const path =+ context.propsValue.scope === 'custom'+ ? `custom${customType ? `/${salesforceUtils.assertApiName({ value: customType, fieldName: 'Custom Action Type' })}` : ''}`+ : 'standard';+ const response = await callSalesforceApi(HttpMethod.GET, context.auth, `/services/data/v56.0/actions/${path}`, undefined);+ const body: unknown = response.body;+ if (salesforceUtils.isRecord(body) && Array.isArray(body['actions'])) {+ const actions = body['actions'].filter(salesforceUtils.isRecord).map((action) => ({+ name: action['name'] ?? null,+ label: action['label'] ?? null,+ type: action['type'] ?? null,+ url: action['url'] ?? null,+ }));+ return { actions, count: actions.length };+ }+ const types = salesforceUtils.isRecord(body)+ ? Object.entries(body).map(([type, url]) => ({ name: type, label: type, type: 'actionType', url }))+ : [];+ return { actions: types, count: types.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-list-views.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-list-views.tsnew file mode 100644index 00000000000..a83d4d52695--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-list-views.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { listListViewsOutputSchema } from '../../output-schemas';++export const listListViews = createAction({+ auth: salesforceAuth,+ name: 'list_list_views',+ classification: 'READ',+ displayName: 'List List Views',+ description: 'List the list views defined for an object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the list views of one object (e.g. "My Open Opportunities" on Opportunity) with their ids. Pass an id to Get List View Metadata to see its columns and SOQL, or to Get List View Records to read its rows. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listListViewsOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or Opportunity.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const response = await callSalesforceApi(HttpMethod.GET, context.auth, `/services/data/v56.0/sobjects/${object}/listviews`, undefined);+ const body: unknown = response.body;+ const listViews = (salesforceUtils.isRecord(body) && Array.isArray(body['listviews']) ? body['listviews'] : [])+ .filter(salesforceUtils.isRecord)+ .map((view) => ({+ id: view['id'] ?? null,+ label: view['label'] ?? null,+ developer_name: view['developerName'] ?? null,+ soql_compatible: view['soqlCompatible'] ?? null,+ results_url: view['resultsUrl'] ?? null,+ }));+ return { list_views: listViews, count: listViews.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-objects.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-objects.tsnew file mode 100644index 00000000000..08894560c8b--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-objects.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { listObjectsOutputSchema } from '../../output-schemas';++export const listObjects = createAction({+ auth: salesforceAuth,+ name: 'list_objects',+ classification: 'READ',+ displayName: 'List Objects',+ description: 'List the objects available in the org.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the standard and custom objects in the Salesforce org with their API name, label and what the current user may do with them (query, create, update, delete). Use it to discover the right object API name before calling other tools; for one object\'s fields and relationships use Describe Object. Narrow the list with Search or Custom Only, since orgs often have hundreds of objects. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listObjectsOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only return objects whose API name or label contains this text (case-insensitive).',+ required: false,+ }),+ custom_only: Property.Checkbox({+ displayName: 'Custom Only',+ description: 'Only return custom objects.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const response = await callSalesforceApi<{ sobjects: SObjectSummary[] }>(+ HttpMethod.GET,+ context.auth,+ '/services/data/v56.0/sobjects',+ undefined+ );+ const search = (context.propsValue.search ?? '').trim().toLowerCase();+ const objects = response.body.sobjects+ .filter((object) => !context.propsValue.custom_only || object.custom)+ .filter((object) => search.length === 0 || object.name.toLowerCase().includes(search) || object.label.toLowerCase().includes(search))+ .map((object) => ({+ name: object.name,+ label: object.label,+ custom: object.custom,+ queryable: object.queryable,+ createable: object.createable,+ updateable: object.updateable,+ deletable: object.deletable,+ key_prefix: object.keyPrefix,+ }));+ return { objects, count: objects.length };+ },+});++type SObjectSummary = {+ name: string;+ label: string;+ custom: boolean;+ queryable: boolean;+ createable: boolean;+ updateable: boolean;+ deletable: boolean;+ keyPrefix: string | null;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-pricebooks.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-pricebooks.tsnew file mode 100644index 00000000000..fd581b6dd4f--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-pricebooks.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { listPricebooksOutputSchema } from '../../output-schemas';++export const listPricebooks = createAction({+ auth: salesforceAuth,+ name: 'list_pricebooks',+ classification: 'READ',+ displayName: 'List Price Books',+ description: 'List price books and, optionally, their product entries.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists Salesforce price books (id, name, active, standard) and, when Include Entries is on, their price book entries with product name, code and list price, filtered by price book id and product name. Use it to find the Price Book ID for Create Opportunity and the Price Book Entry ID for Add Opportunity Product. Each list returns at most 200 rows (default 50). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listPricebooksOutputSchema,+ props: {+ pricebook_id: Property.ShortText({ displayName: 'Price Book ID', description: 'Only this price book.', required: false }),+ active_only: Property.Checkbox({ displayName: 'Active Only', required: false, defaultValue: false }),+ include_entries: Property.Checkbox({ displayName: 'Include Entries', description: 'Also return product entries.', required: false, defaultValue: false }),+ product_name: Property.ShortText({ displayName: 'Product Name Contains', description: 'Filters entries.', required: false }),+ limit: crmUtils.limitProp,+ },+ async run(context) {+ const { pricebook_id, active_only, include_entries, product_name, limit } = context.propsValue;+ const activeFilter = active_only ? true : undefined;+ const pricebooks = await crmUtils.searchRecords({+ auth: context.auth,+ object: 'Pricebook2',+ fields: ['Id', 'Name', 'IsActive', 'IsStandard', 'Description'],+ conditions: [crmUtils.idEquals({ field: 'Id', value: pricebook_id }), crmUtils.booleanEquals({ field: 'IsActive', value: activeFilter })],+ orderBy: 'Name ASC',+ limit,+ });+ if (!include_entries) {+ return { pricebooks, entries: null };+ }+ const entries = await crmUtils.searchRecords({+ auth: context.auth,+ object: 'PricebookEntry',+ fields: ['Id', 'Pricebook2Id', 'Product2Id', 'Product2.Name', 'ProductCode', 'UnitPrice', 'IsActive'],+ conditions: [+ crmUtils.idEquals({ field: 'Pricebook2Id', value: pricebook_id }),+ crmUtils.contains({ field: 'Product2.Name', value: product_name }),+ crmUtils.booleanEquals({ field: 'IsActive', value: activeFilter }),+ ],+ orderBy: 'Product2.Name ASC',+ limit,+ });+ return { pricebooks, entries };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-quick-actions.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-quick-actions.tsnew file mode 100644index 00000000000..79745088efb--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-quick-actions.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { listQuickActionsOutputSchema } from '../../output-schemas';++export const listQuickActions = createAction({+ auth: salesforceAuth,+ name: 'list_quick_actions',+ classification: 'READ',+ displayName: 'List Quick Actions',+ description: 'List global quick actions, or the quick actions of one object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists quick actions (e.g. LogACall, NewTask, custom create/update actions) either globally or for one object. Pass the returned names unchanged to Get Quick Action Defaults and Run Quick Action. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listQuickActionsOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account. Leave empty for global quick actions.',+ required: false,+ }),+ },+ async run(context) {+ const object = context.propsValue.object?.trim();+ const path = object+ ? `sobjects/${salesforceUtils.assertApiName({ value: object, fieldName: 'Object' })}/quickActions`+ : 'quickActions';+ const response = await callSalesforceApi(HttpMethod.GET, context.auth, `/services/data/v56.0/${path}`, undefined);+ const body: unknown = response.body;+ const actions = (Array.isArray(body) ? body : []).filter(salesforceUtils.isRecord).map((action) => ({+ name: action['name'] ?? null,+ label: action['label'] ?? null,+ type: action['type'] ?? null,+ }));+ return { actions, count: actions.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/list-reports.ts b/packages/pieces/community/salesforce/src/lib/action/ai/list-reports.tsnew file mode 100644index 00000000000..8e815db6fc7--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/list-reports.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { querySalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { listReportsOutputSchema } from '../../output-schemas';++export const listReports = createAction({+ auth: salesforceAuth,+ name: 'list_reports',+ classification: 'SEARCH',+ displayName: 'List Reports',+ description: 'List reports, optionally filtered by name or folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists Salesforce analytics reports (id, name, folder, format, last run) filtered by name or exact folder name. Use it to find a report id, then Get Report to see its columns or Run Report Sync / Run Report Async to get data. Returns at most 200 reports per call. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: listReportsOutputSchema,+ props: {+ name_contains: Property.ShortText({+ displayName: 'Name Contains',+ description: 'Only reports whose name contains this text.',+ required: false,+ }),+ folder_name: Property.ShortText({+ displayName: 'Folder Name',+ description: 'Only reports in the folder with exactly this name.',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum reports to return (1-200, default 50).',+ required: false,+ }),+ },+ async run(context) {+ const { name_contains, folder_name, limit } = context.propsValue;+ const conditions = [+ name_contains ? `Name LIKE '%${salesforceUtils.escapeSoqlLike(name_contains)}%'` : undefined,+ folder_name ? `FolderName = '${salesforceUtils.escapeSoqlValue(folder_name)}'` : undefined,+ ].filter((condition) => condition !== undefined);+ const where = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';+ const soql = `SELECT Id, Name, DeveloperName, FolderName, Format, Description, LastRunDate, LastModifiedDate FROM Report${where} ORDER BY Name LIMIT ${clampLimit(limit)}`;+ const response = await querySalesforceApi<QueryResult<unknown>>(HttpMethod.GET, context.auth, soql);+ return salesforceUtils.formatQueryResult(response.body);+ },+});++function clampLimit(limit: number | undefined): number {+ return Math.min(Math.max(Math.floor(limit ?? 50), 1), 200);+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/log-call.ts b/packages/pieces/community/salesforce/src/lib/action/ai/log-call.tsnew file mode 100644index 00000000000..b7b7adbc2c9--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/log-call.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { logCallOutputSchema } from '../../output-schemas';++export const logCall = createAction({+ auth: salesforceAuth,+ name: 'log_call',+ classification: 'WRITE',+ displayName: 'Log Call',+ description: 'Record a completed phone call as an activity.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Logs a phone call that already happened as a closed Call task on a Contact or Lead (Who ID) and/or an Account, Opportunity or other record (What ID), with duration, direction, outcome and notes; the date defaults to today (UTC). Use Create Task for a to-do that is still open. Not idempotent: each call logs another activity.",+ idempotent: false,+ },+ outputSchema: logCallOutputSchema,+ props: {+ subject: Property.ShortText({ displayName: 'Subject', description: 'e.g. Call with Jane about renewal.', required: true }),+ who_id: Property.ShortText({ displayName: 'Who ID', description: 'Contact or Lead id.', required: false }),+ what_id: Property.ShortText({ displayName: 'What ID', description: 'Account, Opportunity, Case or other record id.', required: false }),+ call_type: Property.StaticDropdown({+ displayName: 'Call Type',+ required: false,+ options: {+ options: [+ { label: 'Inbound', value: 'Inbound' },+ { label: 'Outbound', value: 'Outbound' },+ { label: 'Internal', value: 'Internal' },+ ],+ },+ }),+ duration_seconds: Property.Number({ displayName: 'Duration (Seconds)', required: false }),+ call_disposition: Property.ShortText({ displayName: 'Call Result', description: 'Outcome, e.g. Left voicemail.', required: false }),+ description: Property.LongText({ displayName: 'Notes', required: false }),+ activity_date: Property.ShortText({ displayName: 'Call Date', description: 'YYYY-MM-DD. Defaults to today.', required: false }),+ owner_id: Property.ShortText({ displayName: 'Owner ID', description: 'User who made the call. Defaults to you.', required: false }),+ },+ async run(context) {+ const { subject, who_id, what_id, call_type, duration_seconds, call_disposition, description, activity_date, owner_id } = context.propsValue;+ const activityDate = crmUtils.assertDate({ value: activity_date, fieldName: 'Call Date' }) ?? new Date().toISOString().slice(0, 10);+ const status = await crmUtils.getClosedTaskStatus({ auth: context.auth });+ const result = await crmUtils.createRecord({+ auth: context.auth,+ object: 'Task',+ fields: {+ TaskSubtype: 'Call',+ Status: status,+ Subject: subject,+ WhoId: who_id,+ WhatId: what_id,+ CallType: call_type,+ CallDurationInSeconds: duration_seconds,+ CallDisposition: call_disposition,+ Description: description,+ ActivityDate: activityDate,+ OwnerId: owner_id,+ },+ additionalFields: undefined,+ });+ return { ...result, subject, status, activity_date: activityDate };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/log-email-activity.ts b/packages/pieces/community/salesforce/src/lib/action/ai/log-email-activity.tsnew file mode 100644index 00000000000..942d5b03d5e--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/log-email-activity.ts@@ -0,0 +1,68 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { logEmailActivityOutputSchema } from '../../output-schemas';++export const logEmailActivity = createAction({+ auth: salesforceAuth,+ name: 'log_email_activity',+ classification: 'WRITE',+ displayName: 'Log Email Activity',+ description: 'Record an email on a Contact or Lead without sending it.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates an EmailMessage record marked as sent for a Contact or Lead, optionally related to another record, so the email shows in the activity history. It only records the email and does NOT deliver anything; to actually send an email use Send Email Message. Not idempotent: every call logs another email.',+ idempotent: false,+ },+ outputSchema: logEmailActivityOutputSchema,+ props: {+ recipient_id: Property.ShortText({+ displayName: 'Recipient ID',+ description: 'Id of the Contact or Lead the email was sent to.',+ required: true,+ }),+ subject: Property.ShortText({+ displayName: 'Subject',+ required: true,+ }),+ body: Property.LongText({+ displayName: 'Body',+ description: 'Email content, plain text or HTML.',+ required: true,+ }),+ related_record_id: Property.ShortText({+ displayName: 'Related Record ID',+ description: 'Id of a record (Account, Opportunity, Case…) to relate the email to.',+ required: false,+ }),+ },+ async run(context) {+ const { subject, body } = context.propsValue;+ const recipientId = salesforceUtils.assertId({ value: context.propsValue.recipient_id, fieldName: 'Recipient ID' });+ const relatedRecordId = context.propsValue.related_record_id+ ? salesforceUtils.assertId({ value: context.propsValue.related_record_id, fieldName: 'Related Record ID' })+ : undefined;+ const response = await callSalesforceApi<{ id: string; success: boolean }>(+ HttpMethod.POST,+ context.auth,+ '/services/data/v56.0/sobjects/EmailMessage',+ salesforceUtils.compact({+ ToIds: [recipientId],+ Subject: subject,+ HtmlBody: body,+ Status: '3',+ RelatedToId: relatedRecordId,+ }),+ );+ return {+ id: response.body.id,+ success: response.body.success,+ recipient_id: recipientId,+ related_record_id: relatedRecordId ?? null,+ subject,+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/remove-campaign-member.ts b/packages/pieces/community/salesforce/src/lib/action/ai/remove-campaign-member.tsnew file mode 100644index 00000000000..20465c88b64--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/remove-campaign-member.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { crmUtils } from '../../common/crm';+import { salesforceUtils } from '../../common/utils';+import { deletedRecordOutputSchema } from '../../output-schemas';++export const removeCampaignMember = createAction({+ auth: salesforceAuth,+ name: 'remove_campaign_member',+ classification: 'DESTRUCTIVE',+ displayName: 'Remove Campaign Member',+ description: 'Remove a lead or contact from a campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a Lead or Contact from a Campaign by deleting its CampaignMember record; give the campaign id and exactly one of lead id or contact id. The lead or contact itself is not deleted. Use Add Lead to Campaign / Add Contact to Campaign to enroll again. Reports deleted: false when it is not a member. Not idempotent: it deletes a record.',+ idempotent: false,+ },+ outputSchema: deletedRecordOutputSchema,+ props: {+ campaign_id: Property.ShortText({ displayName: 'Campaign ID', required: true }),+ lead_id: Property.ShortText({ displayName: 'Lead ID', description: 'Give this or Contact ID.', required: false }),+ contact_id: Property.ShortText({ displayName: 'Contact ID', description: 'Give this or Lead ID.', required: false }),+ },+ async run(context) {+ const { campaign_id, lead_id, contact_id } = context.propsValue;+ const memberIndex = crmUtils.exactlyOne({ values: [lead_id, contact_id], fieldNames: 'Lead ID or Contact ID' });+ const campaignId = salesforceUtils.assertId({ value: campaign_id, fieldName: 'Campaign ID' });+ const memberId = salesforceUtils.assertId({ value: (memberIndex === 0 ? lead_id : contact_id) ?? '', fieldName: memberIndex === 0 ? 'Lead ID' : 'Contact ID' });+ const memberField = memberIndex === 0 ? 'LeadId' : 'ContactId';+ const result = await crmUtils.query({+ auth: context.auth,+ soql: `SELECT Id FROM CampaignMember WHERE CampaignId = '${campaignId}' AND ${memberField} = '${memberId}' LIMIT 1`,+ });+ const member = result.records[0];+ if (!salesforceUtils.isRecord(member) || typeof member['Id'] !== 'string') {+ return { deleted: false, reason: 'Not a member of this campaign.' };+ }+ const id = salesforceUtils.assertId({ value: member['Id'], fieldName: 'Campaign Member ID' });+ await callSalesforceApi(HttpMethod.DELETE, context.auth, `/services/data/v56.0/sobjects/CampaignMember/${id}`, undefined);+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-bulk-ingest-job.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-bulk-ingest-job.tsnew file mode 100644index 00000000000..6b65944e21d--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-bulk-ingest-job.ts@@ -0,0 +1,90 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { bulkUtils } from '../../common/bulk';+import { bulkJobCreatedOutputSchema } from '../../output-schemas';++export const runBulkIngestJob = createAction({+ auth: salesforceAuth,+ name: 'run_bulk_ingest_job',+ classification: 'WRITE',+ displayName: 'Run Bulk Ingest Job',+ description: 'Start a Bulk API 2.0 job that inserts, updates, upserts or deletes records from CSV.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a Bulk API 2.0 ingest job, uploads the CSV and queues it for processing in one call, returning the job id right away while Salesforce works asynchronously. Poll Get Bulk Ingest Job until the state is JobComplete, Failed or Aborted, then read per-row outcomes with Get Bulk Ingest Results. Use it for thousands of rows; the CSV header must be field API names (Id for update/delete), and upsert needs an external id field. Not idempotent: rerunning inserts again.',+ idempotent: false,+ },+ outputSchema: bulkJobCreatedOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or My_Object__c.',+ required: true,+ }),+ operation: Property.StaticDropdown({+ displayName: 'Operation',+ required: true,+ options: {+ options: [+ { label: 'Insert', value: 'insert' },+ { label: 'Update', value: 'update' },+ { label: 'Upsert', value: 'upsert' },+ { label: 'Delete', value: 'delete' },+ ],+ },+ }),+ external_id_field: Property.ShortText({+ displayName: 'External ID Field',+ description: 'Field API name to match on. Required for upsert.',+ required: false,+ }),+ csv: Property.LongText({+ displayName: 'CSV',+ description: 'Records as CSV with a header row of field API names, lines separated by LF.',+ required: true,+ }),+ },+ async run(context) {+ const { operation, csv } = context.propsValue;+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const externalIdField = context.propsValue.external_id_field?.trim()+ ? salesforceUtils.assertApiName({ value: context.propsValue.external_id_field, fieldName: 'External ID Field' })+ : undefined;+ if (operation === 'upsert' && !externalIdField) {+ throw new Error('External ID Field is required for upsert.');+ }+ if (!csv.trim()) {+ throw new Error('CSV must not be empty.');+ }+ const created = await callSalesforceApi<{ id: string }>(HttpMethod.POST, context.auth, `${bulkUtils.BULK_API_PATH}/ingest`, {+ object,+ operation,+ contentType: 'CSV',+ lineEnding: 'LF',+ ...(externalIdField ? { externalIdFieldName: externalIdField } : {}),+ });+ const jobId = created.body.id;+ const jobPath = `${bulkUtils.BULK_API_PATH}/ingest/${jobId}`;+ try {+ await callSalesforceApi(HttpMethod.PUT, context.auth, `${jobPath}/batches`, csv.replace(/\r\n/g, '\n'), {+ headers: { 'Content-Type': 'text/csv' },+ });+ } catch (error) {+ await callSalesforceApi(HttpMethod.PATCH, context.auth, jobPath, { state: 'Aborted' }).catch(() => undefined);+ throw new Error(`CSV upload failed, job ${jobId} was aborted: ${error instanceof Error ? error.message : String(error)}`);+ }+ const closed = await callSalesforceApi<{ state?: string }>(HttpMethod.PATCH, context.auth, jobPath, {+ state: 'UploadComplete',+ });+ return {+ job_id: jobId,+ state: closed.body?.state ?? 'UploadComplete',+ object,+ operation,+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-invocable-action.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-invocable-action.tsnew file mode 100644index 00000000000..3e3f05c6491--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-invocable-action.ts@@ -0,0 +1,81 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { runInvocableActionOutputSchema } from '../../output-schemas';++export const runInvocableAction = createAction({+ auth: salesforceAuth,+ name: 'run_invocable_action',+ classification: 'WRITE',+ displayName: 'Run Invocable Action',+ description: 'Run a standard or custom invocable action, such as an autolaunched flow or Apex action.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Invokes a standard action (e.g. emailSimple) or a custom action (flow, apex, emailAlert…) with one or more input sets and returns each invocation\'s success, errors and output values. Find names and types with List Invocable Actions; flows must be active and autolaunched, and for Apex the name is the class name. Not idempotent: each call runs the action again.',+ idempotent: false,+ },+ outputSchema: runInvocableActionOutputSchema,+ props: {+ action_type: Property.ShortText({+ displayName: 'Custom Action Type',+ description: 'flow, apex, quickAction, emailAlert… Leave empty for a standard action.',+ required: false,+ }),+ action_name: Property.ShortText({+ displayName: 'Action Name',+ description: 'Action API name, e.g. emailSimple or My_Autolaunched_Flow.',+ required: true,+ }),+ inputs: Property.Json({+ displayName: 'Inputs',+ description: 'JSON array of input objects, one per invocation (a single object is also accepted), e.g. [{"recordId": "001..."}].',+ required: false,+ }),+ },+ async run(context) {+ const actionName = salesforceUtils.assertApiName({ value: context.propsValue.action_name, fieldName: 'Action Name' });+ const rawType = context.propsValue.action_type?.trim();+ const actionType = rawType && rawType.toLowerCase() !== 'standard' ? rawType : undefined;+ const path = actionType+ ? `custom/${salesforceUtils.assertApiName({ value: actionType, fieldName: 'Custom Action Type' })}/${actionName}`+ : `standard/${actionName}`;+ const inputs = parseInputs(context.propsValue.inputs);+ const response = await callSalesforceApi(HttpMethod.POST, context.auth, `/services/data/v56.0/actions/${path}`, { inputs });+ const body: unknown = response.body;+ const results = (Array.isArray(body) ? body : []).filter(salesforceUtils.isRecord).map((result) => ({+ action_name: result['actionName'] ?? actionName,+ is_success: result['isSuccess'] === true,+ errors: formatErrors(result['errors']),+ output_values: result['outputValues'] ?? null,+ }));+ const failures = results.filter((result) => !result.is_success);+ if (results.length > 0 && failures.length === results.length) {+ throw new Error(`Action ${actionName} failed: ${failures.map((failure) => failure.errors.join('; ')).join(' | ')}`);+ }+ return { results, count: results.length, failed_count: failures.length };+ },+});++function parseInputs(value: unknown): unknown[] {+ if (salesforceUtils.isRecord(value)) {+ return [value];+ }+ if (typeof value === 'string' && value.trim().startsWith('{')) {+ const single = salesforceUtils.parseJsonObject({ value, fieldName: 'Inputs' });+ return single ? [single] : [{}];+ }+ const list = salesforceUtils.parseJsonArray({ value, fieldName: 'Inputs' });+ return list && list.length > 0 ? list : [{}];+}++function formatErrors(errors: unknown): string[] {+ if (!Array.isArray(errors)) {+ return [];+ }+ return errors.map((error) =>+ salesforceUtils.isRecord(error) ? String(error['message'] ?? error['statusCode'] ?? JSON.stringify(error)) : String(error)+ );+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-quick-action.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-quick-action.tsnew file mode 100644index 00000000000..650a8e94d1f--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-quick-action.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { runQuickActionOutputSchema } from '../../output-schemas';++export const runQuickAction = createAction({+ auth: salesforceAuth,+ name: 'run_quick_action',+ classification: 'WRITE',+ displayName: 'Run Quick Action',+ description: 'Run a global or object-specific quick action with the given field values.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Executes a quick action (e.g. LogACall, NewContact) and returns the id of the record it created or updated. Find names with List Quick Actions and pre-filled fields with Get Quick Action Defaults; pass the name exactly as listed (Object.Action or a bare global name) and a Context Record ID when the action acts on a parent record. Not idempotent: each call creates again.',+ idempotent: false,+ },+ outputSchema: runQuickActionOutputSchema,+ props: {+ action_name: Property.ShortText({+ displayName: 'Quick Action Name',+ description: 'Name exactly as returned by List Quick Actions: Object.Action for object-specific actions (e.g. Account.NewContact), a bare name for global ones (e.g. LogACall).',+ required: true,+ }),+ context_id: Property.ShortText({+ displayName: 'Context Record ID',+ description: 'Id of the parent record the action runs against. Optional.',+ required: false,+ }),+ record: Property.Json({+ displayName: 'Fields',+ description: 'JSON object of field API names to values, e.g. {"Subject": "Call", "Description": "Notes"}.',+ required: true,+ }),+ },+ async run(context) {+ const actionName = context.propsValue.action_name+ .trim()+ .split('.')+ .map((part) => salesforceUtils.assertApiName({ value: part, fieldName: 'Quick Action Name' }))+ .join('.');+ const contextId = context.propsValue.context_id?.trim()+ ? salesforceUtils.assertId({ value: context.propsValue.context_id, fieldName: 'Context Record ID' })+ : undefined;+ const record = salesforceUtils.parseJsonObject({ value: context.propsValue.record, fieldName: 'Fields' }) ?? {};+ const [objectName] = actionName.split('.');+ const path = actionName.includes('.') ? `sobjects/${objectName}/quickActions/${actionName}` : `quickActions/${actionName}`;+ const response = await callSalesforceApi(HttpMethod.POST, context.auth, `/services/data/v56.0/${path}`, {+ ...(contextId ? { contextId } : {}),+ record,+ });+ const body: unknown = response.body;+ const result = salesforceUtils.isRecord(body) ? body : {};+ return {+ id: result['id'] ?? null,+ success: result['success'] ?? true,+ created: result['created'] ?? null,+ context_id: result['contextId'] ?? contextId ?? null,+ feed_item_ids: result['feedItemIds'] ?? null,+ errors: result['errors'] ?? [],+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-report-async.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-report-async.tsnew file mode 100644index 00000000000..27b1be5d47d--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-report-async.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { runReportAsyncOutputSchema } from '../../output-schemas';++export const runReportAsync = createAction({+ auth: salesforceAuth,+ name: 'run_report_async',+ classification: 'READ',+ displayName: 'Run Report Async',+ description: 'Start a report run in the background.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Starts an asynchronous run of a Salesforce report by id, optionally with filters overriding the saved ones, and returns the instance id right away. Poll Get Report Instance with the report id and instance id until the status is Success to get the rows; use it instead of Run Report Sync for reports over 2,000 detail rows. Results are kept for 24 hours. Not idempotent: every call starts another run.',+ idempotent: false,+ },+ outputSchema: runReportAsyncOutputSchema,+ props: {+ report_id: Property.ShortText({+ displayName: 'Report ID',+ description: 'Report id starting with 00O.',+ required: true,+ }),+ filters: Property.Json({+ displayName: 'Filters',+ description:+ 'Optional JSON array of {column, operator, value} using column API names from Get Report, e.g. [{"column":"ACCOUNT.NAME","operator":"equals","value":"Acme"}].',+ required: false,+ }),+ },+ async run(context) {+ const reportId = salesforceUtils.assertId({ value: context.propsValue.report_id, fieldName: 'Report ID' });+ const filters = salesforceUtils.parseJsonArray({ value: context.propsValue.filters, fieldName: 'Filters' });+ const response = await callSalesforceApi<ReportInstance>(+ HttpMethod.POST,+ context.auth,+ `/services/data/v56.0/analytics/reports/${reportId}/instances?includeDetails=true`,+ filters && filters.length > 0 ? { reportMetadata: { reportFilters: filters } } : undefined,+ );+ return {+ instance_id: response.body.id,+ status: response.body.status,+ report_id: reportId,+ request_date: response.body.requestDate ?? null,+ };+ },+});++type ReportInstance = {+ id: string;+ status: string;+ requestDate?: string;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-report-sync.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-report-sync.tsnew file mode 100644index 00000000000..004a4a60897--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-report-sync.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { reportUtils, SalesforceReportResponse } from '../../common/report';+import { salesforceUtils } from '../../common/utils';+import { runReportSyncOutputSchema } from '../../output-schemas';++export const runReportSync = createAction({+ auth: salesforceAuth,+ name: 'run_report_sync',+ classification: 'READ',+ displayName: 'Run Report Sync',+ description: 'Run a report now and return its rows.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Runs a Salesforce report by id and waits for the result, returning flat rows keyed by column label (grouping columns included), optionally with filters that override the saved ones for this run. Synchronous runs return at most 2,000 detail rows; for bigger reports use Run Report Async then Get Report Instance. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: runReportSyncOutputSchema,+ props: {+ report_id: Property.ShortText({+ displayName: 'Report ID',+ description: 'Report id starting with 00O.',+ required: true,+ }),+ filters: Property.Json({+ displayName: 'Filters',+ description:+ 'Optional JSON array of {column, operator, value} using column API names from Get Report, e.g. [{"column":"ACCOUNT.NAME","operator":"equals","value":"Acme"}].',+ required: false,+ }),+ },+ async run(context) {+ const reportId = salesforceUtils.assertId({ value: context.propsValue.report_id, fieldName: 'Report ID' });+ const filters = salesforceUtils.parseJsonArray({ value: context.propsValue.filters, fieldName: 'Filters' });+ const response = await callSalesforceApi<SalesforceReportResponse>(+ HttpMethod.POST,+ context.auth,+ `/services/data/v56.0/analytics/reports/${reportId}?includeDetails=true`,+ filters && filters.length > 0 ? { reportMetadata: { reportFilters: filters } } : undefined,+ );+ return reportUtils.transformReportToRows(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query-all.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query-all.tsnew file mode 100644index 00000000000..c5a09f606f3--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query-all.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { soqlQueryOutputSchema } from '../../output-schemas';++export const runSoqlQueryAll = createAction({+ auth: salesforceAuth,+ name: 'run_soql_query_all',+ classification: 'SEARCH',+ displayName: 'Run SOQL Query All',+ description: 'Run a SOQL query that also returns deleted and archived records.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Runs a SOQL query that also returns records in the Recycle Bin and archived records (e.g. old Tasks and Events); filter on IsDeleted = true to find only deleted ones. Use it for recovery or audit; for normal reads use Run SOQL Query. Always add a LIMIT; if next_records_url is not null, fetch more with Get Next Query Page. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: soqlQueryOutputSchema,+ props: {+ query: Property.LongText({+ displayName: 'SOQL Query',+ description: 'A complete SOQL statement with explicit fields and a LIMIT.',+ required: true,+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (query.length === 0) {+ throw new Error('SOQL Query is required.');+ }+ const response = await callSalesforceApi<QueryResult<unknown>>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/queryAll?q=${encodeURIComponent(query)}`,+ undefined+ );+ return salesforceUtils.formatQueryResult(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query.tsnew file mode 100644index 00000000000..beda66eb6e5--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-soql-query.ts@@ -0,0 +1,36 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { querySalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { soqlQueryOutputSchema } from '../../output-schemas';++export const runSoqlQuery = createAction({+ auth: salesforceAuth,+ name: 'run_soql_query',+ classification: 'SEARCH',+ displayName: 'Run SOQL Query',+ description: 'Run a SOQL query and return the matching records.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Runs a SOQL query (e.g. SELECT Id, Name FROM Account WHERE Industry = \'Technology\' LIMIT 50) and returns the matching records, excluding deleted and archived ones. Use it for filtered, sorted, related or aggregate reads; to include the Recycle Bin use Run SOQL Query All, for keyword search across objects use Search Records (SOSL), and for setup metadata use Run Tooling Query. Always add a LIMIT; if next_records_url is not null, fetch more with Get Next Query Page. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: soqlQueryOutputSchema,+ props: {+ query: Property.LongText({+ displayName: 'SOQL Query',+ description: 'A complete SOQL statement with explicit fields and a LIMIT.',+ required: true,+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (query.length === 0) {+ throw new Error('SOQL Query is required.');+ }+ const response = await querySalesforceApi<QueryResult<unknown>>(HttpMethod.GET, context.auth, query);+ return salesforceUtils.formatQueryResult(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/run-tooling-query.ts b/packages/pieces/community/salesforce/src/lib/action/ai/run-tooling-query.tsnew file mode 100644index 00000000000..7cb2462715b--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/run-tooling-query.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { soqlQueryOutputSchema } from '../../output-schemas';++export const runToolingQuery = createAction({+ auth: salesforceAuth,+ name: 'run_tooling_query',+ classification: 'SEARCH',+ displayName: 'Run Tooling Query',+ description: 'Run a SOQL query against the Tooling API for setup metadata.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Runs a SOQL query against the Tooling API to read setup metadata such as ApexClass, ApexTrigger, CustomField, Flow, ValidationRule or FieldDefinition. Use it for questions about org configuration and code; for business records use Run SOQL Query, and for a single object\'s fields Describe Object is simpler. Requires a user with View Setup permission; always add a LIMIT and page with Get Next Query Page. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: soqlQueryOutputSchema,+ props: {+ query: Property.LongText({+ displayName: 'SOQL Query',+ description: 'A Tooling API SOQL statement, e.g. SELECT Id, Name FROM ApexClass LIMIT 50.',+ required: true,+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (query.length === 0) {+ throw new Error('SOQL Query is required.');+ }+ const response = await callSalesforceApi<QueryResult<unknown>>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/tooling/query?q=${encodeURIComponent(query)}`,+ undefined+ );+ return salesforceUtils.formatQueryResult(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-accounts.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-accounts.tsnew file mode 100644index 00000000000..21fd2f747f5--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-accounts.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { searchAccountsOutputSchema } from '../../output-schemas';++export const searchAccounts = createAction({+ auth: salesforceAuth,+ name: 'search_accounts',+ classification: 'SEARCH',+ displayName: 'Search Accounts',+ description: 'Find accounts by name, industry, type, location or owner.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Finds Salesforce Accounts matching all the filters you give (name contains, exact industry, type, billing city/country, owner id), newest-modified first; with no filters it lists recent accounts. Use it to get an account id before Update Account or to link contacts and opportunities; for arbitrary conditions use a SOQL query action instead. Returns at most 200 rows (default 50). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchAccountsOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name Contains', required: false }),+ industry: Property.ShortText({ displayName: 'Industry', required: false }),+ type: Property.ShortText({ displayName: 'Type', required: false }),+ billing_city: Property.ShortText({ displayName: 'Billing City', required: false }),+ billing_country: Property.ShortText({ displayName: 'Billing Country', required: false }),+ owner_id: Property.ShortText({ displayName: 'Owner ID', required: false }),+ limit: crmUtils.limitProp,+ },+ async run(context) {+ const { name, industry, type, billing_city, billing_country, owner_id, limit } = context.propsValue;+ return crmUtils.searchRecords({+ auth: context.auth,+ object: 'Account',+ fields: ['Id', 'Name', 'Phone', 'Website', 'Industry', 'Type', 'BillingCity', 'BillingState', 'BillingCountry', 'OwnerId', 'ParentId', 'CreatedDate', 'LastModifiedDate'],+ conditions: [+ crmUtils.contains({ field: 'Name', value: name }),+ crmUtils.equals({ field: 'Industry', value: industry }),+ crmUtils.equals({ field: 'Type', value: type }),+ crmUtils.equals({ field: 'BillingCity', value: billing_city }),+ crmUtils.equals({ field: 'BillingCountry', value: billing_country }),+ crmUtils.idEquals({ field: 'OwnerId', value: owner_id }),+ ],+ orderBy: 'LastModifiedDate DESC',+ limit,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-contacts.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-contacts.tsnew file mode 100644index 00000000000..465edfec45c--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-contacts.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { searchContactsOutputSchema } from '../../output-schemas';++export const searchContacts = createAction({+ auth: salesforceAuth,+ name: 'search_contacts',+ classification: 'SEARCH',+ displayName: 'Search Contacts',+ description: 'Find contacts by name, email, account or title.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Finds Salesforce Contacts matching all the filters you give (name contains, exact email, account id, title contains), newest-modified first; with no filters it lists recent contacts. Use it to get a contact id before Update Contact, Add Contact to Campaign or Create Task; for leads use Search Leads. Returns at most 200 rows (default 50). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchContactsOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name Contains', required: false }),+ email: Property.ShortText({ displayName: 'Email', description: 'Exact email address.', required: false }),+ account_id: Property.ShortText({ displayName: 'Account ID', required: false }),+ title: Property.ShortText({ displayName: 'Title Contains', required: false }),+ limit: crmUtils.limitProp,+ },+ async run(context) {+ const { name, email, account_id, title, limit } = context.propsValue;+ return crmUtils.searchRecords({+ auth: context.auth,+ object: 'Contact',+ fields: ['Id', 'FirstName', 'LastName', 'Name', 'Email', 'Phone', 'MobilePhone', 'Title', 'Department', 'AccountId', 'Account.Name', 'OwnerId', 'CreatedDate', 'LastModifiedDate'],+ conditions: [+ crmUtils.contains({ field: 'Name', value: name }),+ crmUtils.equals({ field: 'Email', value: email }),+ crmUtils.idEquals({ field: 'AccountId', value: account_id }),+ crmUtils.contains({ field: 'Title', value: title }),+ ],+ orderBy: 'LastModifiedDate DESC',+ limit,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-knowledge-articles.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-knowledge-articles.tsnew file mode 100644index 00000000000..f74444d04a2--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-knowledge-articles.ts@@ -0,0 +1,87 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { searchKnowledgeArticlesOutputSchema } from '../../output-schemas';++export const searchKnowledgeArticles = createAction({+ auth: salesforceAuth,+ name: 'search_knowledge_articles',+ classification: 'SEARCH',+ displayName: 'Search Knowledge Articles',+ description: 'Search published Salesforce Knowledge articles by keyword.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches published Salesforce Knowledge articles by keyword in one language and returns titles, summaries and ids. Use it to answer support questions from the knowledge base; the id is the KnowledgeArticle id, not an article version id. Requires Knowledge enabled and a Knowledge User license on the connected user; page size defaults to 20, max 100. Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchKnowledgeArticlesOutputSchema,+ props: {+ query: Property.ShortText({+ displayName: 'Search Text',+ required: true,+ }),+ language: Property.ShortText({+ displayName: 'Language',+ description: 'Article language locale, e.g. en-US.',+ required: false,+ defaultValue: 'en-US',+ }),+ channel: Property.StaticDropdown({+ displayName: 'Channel',+ required: false,+ options: {+ options: [+ { label: 'Internal App', value: 'App' },+ { label: 'Public Knowledge Base', value: 'Pkb' },+ { label: 'Customer', value: 'Csp' },+ { label: 'Partner', value: 'Prm' },+ ],+ },+ }),+ page_size: Property.Number({+ displayName: 'Page Size',+ description: 'Articles to return (default 20, max 100).',+ required: false,+ defaultValue: 20,+ }),+ },+ async run(context) {+ const query = context.propsValue.query.trim();+ if (!query) {+ throw new Error('Search Text must not be empty.');+ }+ const language = context.propsValue.language?.trim() || 'en-US';+ if (!/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/.test(language)) {+ throw new Error('Language must be a locale such as en-US.');+ }+ const pageSize = Math.min(Math.max(Math.floor(context.propsValue.page_size ?? 20), 1), 100);+ const params = new URLSearchParams({+ q: query,+ pageSize: String(pageSize),+ ...(context.propsValue.channel ? { channel: context.propsValue.channel } : {}),+ });+ const response = await callSalesforceApi(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/support/knowledgeArticles?${params.toString()}`,+ undefined,+ { headers: { 'Accept-Language': language } }+ );+ const body: unknown = response.body;+ const articles = (salesforceUtils.isRecord(body) && Array.isArray(body['articles']) ? body['articles'] : [])+ .filter(salesforceUtils.isRecord)+ .map((article) => ({+ id: article['id'] ?? null,+ article_number: article['articleNumber'] ?? null,+ title: article['title'] ?? null,+ summary: article['summary'] ?? null,+ url_name: article['urlName'] ?? null,+ last_published_date: article['lastPublishedDate'] ?? null,+ view_count: article['viewCount'] ?? null,+ }));+ return { articles, count: articles.length };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-leads.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-leads.tsnew file mode 100644index 00000000000..9868f9855e7--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-leads.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { searchLeadsOutputSchema } from '../../output-schemas';++export const searchLeads = createAction({+ auth: salesforceAuth,+ name: 'search_leads',+ classification: 'SEARCH',+ displayName: 'Search Leads',+ description: 'Find leads by name, email, company, status, source or conversion.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Finds Salesforce Leads matching all the filters you give (name contains, exact email, company contains, status, lead source, converted yes/no), newest-modified first; with no filters it lists recent leads. Use it to get a lead id before Update Lead or Add Lead to Campaign; for contacts use Search Contacts. Returns at most 200 rows (default 50). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchLeadsOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name Contains', required: false }),+ email: Property.ShortText({ displayName: 'Email', description: 'Exact email address.', required: false }),+ company: Property.ShortText({ displayName: 'Company Contains', required: false }),+ status: Property.ShortText({ displayName: 'Status', required: false }),+ lead_source: Property.ShortText({ displayName: 'Lead Source', required: false }),+ is_converted: crmUtils.booleanFilterProp({ displayName: 'Converted', description: 'Leave empty for both converted and unconverted leads.' }),+ limit: crmUtils.limitProp,+ },+ async run(context) {+ const { name, email, company, status, lead_source, is_converted, limit } = context.propsValue;+ return crmUtils.searchRecords({+ auth: context.auth,+ object: 'Lead',+ fields: ['Id', 'FirstName', 'LastName', 'Name', 'Company', 'Email', 'Phone', 'Title', 'Status', 'LeadSource', 'Industry', 'IsConverted', 'ConvertedContactId', 'ConvertedAccountId', 'OwnerId', 'CreatedDate', 'LastModifiedDate'],+ conditions: [+ crmUtils.contains({ field: 'Name', value: name }),+ crmUtils.equals({ field: 'Email', value: email }),+ crmUtils.contains({ field: 'Company', value: company }),+ crmUtils.equals({ field: 'Status', value: status }),+ crmUtils.equals({ field: 'LeadSource', value: lead_source }),+ crmUtils.booleanEquals({ field: 'IsConverted', value: is_converted }),+ ],+ orderBy: 'LastModifiedDate DESC',+ limit,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-opportunities.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-opportunities.tsnew file mode 100644index 00000000000..16426770a00--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-opportunities.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { searchOpportunitiesOutputSchema } from '../../output-schemas';++export const searchOpportunities = createAction({+ auth: salesforceAuth,+ name: 'search_opportunities',+ classification: 'SEARCH',+ displayName: 'Search Opportunities',+ description: 'Find opportunities by name, account, stage, status, close date or amount.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Finds Salesforce Opportunities matching all the filters you give (name contains, account id, exact stage, closed / won yes-no, close date range in YYYY-MM-DD, minimum amount), newest-modified first; with no filters it lists recent opportunities. Use it to get an opportunity id before Update Opportunity or Add Opportunity Product, or to review a pipeline. Returns at most 200 rows (default 50). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchOpportunitiesOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name Contains', required: false }),+ account_id: Property.ShortText({ displayName: 'Account ID', required: false }),+ stage: Property.ShortText({ displayName: 'Stage', required: false }),+ is_closed: crmUtils.booleanFilterProp({ displayName: 'Closed', description: 'Leave empty for open and closed.' }),+ is_won: crmUtils.booleanFilterProp({ displayName: 'Won', description: 'Leave empty for won and not won.' }),+ close_date_from: Property.ShortText({ displayName: 'Close Date From', description: 'YYYY-MM-DD, inclusive.', required: false }),+ close_date_to: Property.ShortText({ displayName: 'Close Date To', description: 'YYYY-MM-DD, inclusive.', required: false }),+ min_amount: Property.Number({ displayName: 'Minimum Amount', required: false }),+ limit: crmUtils.limitProp,+ },+ async run(context) {+ const { name, account_id, stage, is_closed, is_won, close_date_from, close_date_to, min_amount, limit } = context.propsValue;+ return crmUtils.searchRecords({+ auth: context.auth,+ object: 'Opportunity',+ fields: ['Id', 'Name', 'AccountId', 'Account.Name', 'StageName', 'Amount', 'Probability', 'CloseDate', 'IsClosed', 'IsWon', 'Type', 'LeadSource', 'NextStep', 'Pricebook2Id', 'OwnerId', 'CreatedDate', 'LastModifiedDate'],+ conditions: [+ crmUtils.contains({ field: 'Name', value: name }),+ crmUtils.idEquals({ field: 'AccountId', value: account_id }),+ crmUtils.equals({ field: 'StageName', value: stage }),+ crmUtils.booleanEquals({ field: 'IsClosed', value: is_closed }),+ crmUtils.booleanEquals({ field: 'IsWon', value: is_won }),+ crmUtils.dateCompare({ field: 'CloseDate', operator: '>=', value: close_date_from }),+ crmUtils.dateCompare({ field: 'CloseDate', operator: '<=', value: close_date_to }),+ crmUtils.numberCompare({ field: 'Amount', operator: '>=', value: min_amount }),+ ],+ orderBy: 'LastModifiedDate DESC',+ limit,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/search-records-sosl.ts b/packages/pieces/community/salesforce/src/lib/action/ai/search-records-sosl.tsnew file mode 100644index 00000000000..2166fdec360--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/search-records-sosl.ts@@ -0,0 +1,88 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { searchRecordsSoslOutputSchema } from '../../output-schemas';++export const searchRecordsSosl = createAction({+ auth: salesforceAuth,+ name: 'search_records_sosl',+ classification: 'SEARCH',+ displayName: 'Search Records (SOSL)',+ description: 'Full-text search for a term across objects.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Full-text searches a word or phrase across all searchable fields of one or more objects (e.g. find "Acme" in Accounts, Contacts and Leads) and returns matches tagged with their object type. Use it when you only know a name, email or phrase and not which object or field holds it; for exact field filters use Run SOQL Query. The term needs at least 2 characters and results are capped by Limit (default 50, max 200). Read-only; safe to retry.',+ idempotent: true,+ },+ outputSchema: searchRecordsSoslOutputSchema,+ props: {+ search_term: Property.ShortText({+ displayName: 'Search Term',+ description: 'Word or phrase to search for, e.g. Acme or [email protected].',+ required: true,+ }),+ objects: Property.Array({+ displayName: 'Objects',+ description: 'Object API names to search, e.g. Account, Contact, Lead. Leave empty to search all searchable objects.',+ required: false,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Field API names to return for every object listed (Id is always returned), e.g. Name. Every field must exist on every listed object.',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of records to return (default 50, max 200).',+ required: false,+ defaultValue: 50,+ }),+ },+ async run(context) {+ const term = context.propsValue.search_term.trim();+ if (term.length < 2) {+ throw new Error('Search Term must contain at least 2 characters.');+ }+ const objects = salesforceUtils+ .toStringArray(context.propsValue.objects)+ .map((object) => salesforceUtils.assertApiName({ value: object, fieldName: 'Objects' }));+ const fields = salesforceUtils+ .toStringArray(context.propsValue.fields)+ .map((field) => salesforceUtils.assertApiName({ value: field, fieldName: 'Fields' }))+ .filter((field) => field.toLowerCase() !== 'id');+ const limit = Math.min(Math.max(Math.floor(context.propsValue.limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT);+ const selected = ['Id', ...fields].join(', ');+ const returning = objects.length > 0 ? ` RETURNING ${objects.map((object) => `${object}(${selected})`).join(', ')}` : '';+ const sosl = `FIND {${salesforceUtils.escapeSosl(term)}} IN ALL FIELDS${returning} LIMIT ${limit}`;+ const response = await callSalesforceApi<{ searchRecords?: unknown[] }>(+ HttpMethod.GET,+ context.auth,+ `/services/data/v56.0/search?q=${encodeURIComponent(sosl)}`,+ undefined+ );+ const records = (response.body.searchRecords ?? []).map((record) => ({+ object_type: getObjectType(record),+ ...toFlatRecord(record),+ }));+ return { records, count: records.length };+ },+});++function getObjectType(record: unknown): string | null {+ if (!salesforceUtils.isRecord(record) || !salesforceUtils.isRecord(record['attributes'])) {+ return null;+ }+ const type = record['attributes']['type'];+ return typeof type === 'string' ? type : null;+}++function toFlatRecord(record: unknown): Record<string, unknown> {+ const cleaned = salesforceUtils.cleanRecord(record);+ return salesforceUtils.isRecord(cleaned) ? cleaned : {};+}++const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 200;diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/send-email-message.ts b/packages/pieces/community/salesforce/src/lib/action/ai/send-email-message.tsnew file mode 100644index 00000000000..8379ee4a3c9--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/send-email-message.ts@@ -0,0 +1,120 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { sendEmailMessageOutputSchema } from '../../output-schemas';++export const sendEmailMessage = createAction({+ auth: salesforceAuth,+ name: 'send_email_message',+ classification: 'WRITE',+ displayName: 'Send Email Message',+ description: 'Send a real email through Salesforce.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Actually delivers an email from Salesforce (the standard Send Email action) to email addresses and/or a Contact, Lead or User id, optionally logged against a related record. Pick it when the email must reach the inbox; to only record an email that was sent elsewhere use Log Email Activity. Counts against the org daily external email limit, which is very small on Developer Edition orgs. Not idempotent: every call sends another email.',+ idempotent: false,+ },+ outputSchema: sendEmailMessageOutputSchema,+ props: {+ email_addresses: Property.Array({+ displayName: 'Email Addresses',+ description: 'Recipient email addresses. Required unless Recipient ID is set.',+ required: false,+ }),+ recipient_id: Property.ShortText({+ displayName: 'Recipient ID',+ description: 'Id of a Contact, Lead or User to send to.',+ required: false,+ }),+ subject: Property.ShortText({+ displayName: 'Subject',+ required: true,+ }),+ body: Property.LongText({+ displayName: 'Body',+ description: 'Plain-text email body.',+ required: true,+ }),+ sender_type: Property.StaticDropdown({+ displayName: 'Sender Type',+ description: 'Who the email is sent from. Defaults to the current user.',+ required: false,+ options: {+ options: [+ { label: 'Current User', value: 'CurrentUser' },+ { label: 'Default Workflow User', value: 'DefaultWorkflowUser' },+ { label: 'Org-Wide Email Address', value: 'OrgWideEmailAddress' },+ ],+ },+ }),+ sender_address: Property.ShortText({+ displayName: 'Sender Address',+ description: 'Verified org-wide email address. Required when Sender Type is Org-Wide Email Address.',+ required: false,+ }),+ related_record_id: Property.ShortText({+ displayName: 'Related Record ID',+ description: 'Id of a record (Account, Opportunity, Case…) to log the email against.',+ required: false,+ }),+ use_line_breaks: Property.Checkbox({+ displayName: 'Use Line Breaks',+ description: 'Keep the line breaks of the body in the sent email.',+ required: false,+ }),+ },+ async run(context) {+ const { subject, body, sender_type, sender_address, use_line_breaks } = context.propsValue;+ const emailAddresses = salesforceUtils.toStringArray(context.propsValue.email_addresses);+ const recipientId = context.propsValue.recipient_id+ ? salesforceUtils.assertId({ value: context.propsValue.recipient_id, fieldName: 'Recipient ID' })+ : undefined;+ const relatedRecordId = context.propsValue.related_record_id+ ? salesforceUtils.assertId({ value: context.propsValue.related_record_id, fieldName: 'Related Record ID' })+ : undefined;+ if (emailAddresses.length === 0 && !recipientId) {+ throw new Error('Provide at least one Email Address or a Recipient ID.');+ }+ if (sender_type === 'OrgWideEmailAddress' && !sender_address) {+ throw new Error('Sender Address is required when Sender Type is Org-Wide Email Address.');+ }+ const input = salesforceUtils.compact({+ emailAddressesArray: emailAddresses.length > 0 ? emailAddresses : undefined,+ recipientId,+ relatedRecordId,+ emailSubject: subject,+ emailBody: body,+ senderType: sender_type,+ senderAddress: sender_address,+ useLineBreaks: use_line_breaks ? true : undefined,+ });+ const response = await callSalesforceApi<EmailSimpleResult[]>(+ HttpMethod.POST,+ context.auth,+ '/services/data/v56.0/actions/standard/emailSimple',+ { inputs: [input] },+ );+ const result = response.body[0];+ if (!result || !result.isSuccess) {+ const messages = (result?.errors ?? []).map((error) => error.message).join('; ');+ throw new Error(`Salesforce did not send the email: ${messages || 'unknown error'}`);+ }+ return {+ success: true,+ email_addresses: emailAddresses,+ recipient_id: recipientId ?? null,+ related_record_id: relatedRecordId ?? null,+ subject,+ };+ },+});++type EmailSimpleResult = {+ actionName: string;+ errors: { statusCode?: string; message: string; fields?: string[] }[] | null;+ isSuccess: boolean;+ outputValues: Record<string, unknown> | null;+};diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-account.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-account.tsnew file mode 100644index 00000000000..6b7052c0e5d--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-account.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateAccount = createAction({+ auth: salesforceAuth,+ name: 'update_account',+ classification: 'WRITE',+ displayName: 'Update Account',+ description: 'Update fields on an existing account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Account by id; only the fields you supply are changed, everything else is left as is. Use Create Account for new accounts and Search Accounts to find the id. At least one field is required; custom fields go in Additional Fields (set a value to null there to clear it). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ account_id: Property.ShortText({ displayName: 'Account ID', required: true }),+ Name: Property.ShortText({ displayName: 'Account Name', required: false }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ Website: Property.ShortText({ displayName: 'Website', required: false }),+ Industry: Property.ShortText({ displayName: 'Industry', required: false }),+ Type: Property.ShortText({ displayName: 'Type', required: false }),+ BillingStreet: Property.ShortText({ displayName: 'Billing Street', required: false }),+ BillingCity: Property.ShortText({ displayName: 'Billing City', required: false }),+ BillingState: Property.ShortText({ displayName: 'Billing State', required: false }),+ BillingPostalCode: Property.ShortText({ displayName: 'Billing Postal Code', required: false }),+ BillingCountry: Property.ShortText({ displayName: 'Billing Country', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ ParentId: Property.ShortText({ displayName: 'Parent Account ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { account_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({ auth: context.auth, object: 'Account', recordId: account_id, fields, additionalFields: additional_fields });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-campaign.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-campaign.tsnew file mode 100644index 00000000000..52107150b9c--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-campaign.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateCampaign = createAction({+ auth: salesforceAuth,+ name: 'update_campaign',+ classification: 'WRITE',+ displayName: 'Update Campaign',+ description: 'Update fields on an existing campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Campaign by id, e.g. its status, dates (YYYY-MM-DD), active flag or budget; only the fields you supply change. Use Create Campaign for new campaigns. At least one field is required; custom fields go in Additional Fields (null clears a value). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ campaign_id: Property.ShortText({ displayName: 'Campaign ID', required: true }),+ Name: Property.ShortText({ displayName: 'Name', required: false }),+ Type: Property.ShortText({ displayName: 'Type', required: false }),+ Status: Property.ShortText({ displayName: 'Status', required: false }),+ StartDate: Property.ShortText({ displayName: 'Start Date', description: 'YYYY-MM-DD.', required: false }),+ EndDate: Property.ShortText({ displayName: 'End Date', description: 'YYYY-MM-DD.', required: false }),+ IsActive: crmUtils.booleanFilterProp({ displayName: 'Active', description: 'Leave empty to keep the current value.' }),+ BudgetedCost: Property.Number({ displayName: 'Budgeted Cost', required: false }),+ ExpectedRevenue: Property.Number({ displayName: 'Expected Revenue', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ ParentId: Property.ShortText({ displayName: 'Parent Campaign ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { campaign_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({+ auth: context.auth,+ object: 'Campaign',+ recordId: campaign_id,+ fields: {+ ...fields,+ StartDate: crmUtils.assertDate({ value: fields.StartDate, fieldName: 'Start Date' }),+ EndDate: crmUtils.assertDate({ value: fields.EndDate, fieldName: 'End Date' }),+ },+ additionalFields: additional_fields,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-opportunity.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-opportunity.tsnew file mode 100644index 00000000000..985574024cc--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-opportunity.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateOpportunity = createAction({+ auth: salesforceAuth,+ name: 'update_opportunity',+ classification: 'WRITE',+ displayName: 'Update Opportunity',+ description: 'Update fields on an existing opportunity.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Opportunity by id, e.g. to move its stage, change the amount or push the close date (YYYY-MM-DD); only the fields you supply change. Use Create Opportunity for new deals and Search Opportunities to find the id. At least one field is required; custom fields go in Additional Fields (null clears a value). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ opportunity_id: Property.ShortText({ displayName: 'Opportunity ID', required: true }),+ Name: Property.ShortText({ displayName: 'Name', required: false }),+ StageName: Property.ShortText({ displayName: 'Stage', required: false }),+ CloseDate: Property.ShortText({ displayName: 'Close Date', description: 'YYYY-MM-DD.', required: false }),+ AccountId: Property.ShortText({ displayName: 'Account ID', required: false }),+ Amount: Property.Number({ displayName: 'Amount', required: false }),+ Probability: Property.Number({ displayName: 'Probability (%)', required: false }),+ Type: Property.ShortText({ displayName: 'Type', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', required: false }),+ NextStep: Property.ShortText({ displayName: 'Next Step', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ Pricebook2Id: Property.ShortText({ displayName: 'Price Book ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { opportunity_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({+ auth: context.auth,+ object: 'Opportunity',+ recordId: opportunity_id,+ fields: { ...fields, CloseDate: crmUtils.assertDate({ value: fields.CloseDate, fieldName: 'Close Date' }) },+ additionalFields: additional_fields,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-contact.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-contact.tsnew file mode 100644index 00000000000..0c0adb8e9f5--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-contact.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateSfContact = createAction({+ auth: salesforceAuth,+ name: 'update_sf_contact',+ classification: 'WRITE',+ displayName: 'Update Contact',+ description: 'Update fields on an existing contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Contact by id; only the fields you supply change, the rest stay as they are. Set Account ID to move the contact to another account. Use Create Contact for new people and Search Contacts to find the id. At least one field is required; custom fields go in Additional Fields (null clears a value). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),+ LastName: Property.ShortText({ displayName: 'Last Name', required: false }),+ FirstName: Property.ShortText({ displayName: 'First Name', required: false }),+ Email: Property.ShortText({ displayName: 'Email', required: false }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ MobilePhone: Property.ShortText({ displayName: 'Mobile Phone', required: false }),+ Title: Property.ShortText({ displayName: 'Title', required: false }),+ Department: Property.ShortText({ displayName: 'Department', required: false }),+ AccountId: Property.ShortText({ displayName: 'Account ID', required: false }),+ MailingCity: Property.ShortText({ displayName: 'Mailing City', required: false }),+ MailingCountry: Property.ShortText({ displayName: 'Mailing Country', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { contact_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({ auth: context.auth, object: 'Contact', recordId: contact_id, fields, additionalFields: additional_fields });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-lead.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-lead.tsnew file mode 100644index 00000000000..73724ce1cf0--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-sf-lead.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateSfLead = createAction({+ auth: salesforceAuth,+ name: 'update_sf_lead',+ classification: 'WRITE',+ displayName: 'Update Lead',+ description: 'Update fields on an existing lead.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Lead by id; only the fields you supply change, the rest stay as they are. It does not convert the lead. Use Create Lead for new leads and Search Leads to find the id. At least one field is required; custom fields go in Additional Fields (null clears a value). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ lead_id: Property.ShortText({ displayName: 'Lead ID', required: true }),+ LastName: Property.ShortText({ displayName: 'Last Name', required: false }),+ Company: Property.ShortText({ displayName: 'Company', required: false }),+ FirstName: Property.ShortText({ displayName: 'First Name', required: false }),+ Email: Property.ShortText({ displayName: 'Email', required: false }),+ Phone: Property.ShortText({ displayName: 'Phone', required: false }),+ Title: Property.ShortText({ displayName: 'Title', required: false }),+ Status: Property.ShortText({ displayName: 'Status', required: false }),+ LeadSource: Property.ShortText({ displayName: 'Lead Source', required: false }),+ Industry: Property.ShortText({ displayName: 'Industry', required: false }),+ Website: Property.ShortText({ displayName: 'Website', required: false }),+ City: Property.ShortText({ displayName: 'City', required: false }),+ Country: Property.ShortText({ displayName: 'Country', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Owner ID', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { lead_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({ auth: context.auth, object: 'Lead', recordId: lead_id, fields, additionalFields: additional_fields });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-sobject-record.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-sobject-record.tsnew file mode 100644index 00000000000..6677cbfc7ea--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-sobject-record.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateSobjectRecord = createAction({+ auth: salesforceAuth,+ name: 'update_sobject_record',+ classification: 'WRITE',+ displayName: 'Update Record',+ description: 'Update fields on one record of any object.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates a single record of any Salesforce object by id; only the field API names you send change, every other field stays untouched (send null to clear a field). Use it when you have the record id; to match on an external id instead use Upsert Record by External ID, and for many records use Upsert Records Batch. Idempotent: resending the same values leaves the record in the same state.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account, Contact or My_Object__c.',+ required: true,+ }),+ record_id: Property.ShortText({+ displayName: 'Record ID',+ required: true,+ }),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object of field API names to new values. Only these fields change; use null to clear a field.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const recordId = salesforceUtils.assertId({ value: context.propsValue.record_id, fieldName: 'Record ID' });+ const fields = salesforceUtils.parseJsonObject({ value: context.propsValue.fields, fieldName: 'Fields' }) ?? {};+ const fieldNames = Object.keys(fields);+ if (fieldNames.length === 0) {+ throw new Error('Fields must contain at least one field to update.');+ }+ await callSalesforceApi(+ HttpMethod.PATCH,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${recordId}`,+ fields+ );+ return { id: recordId, success: true, updated_fields: fieldNames };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/update-task.ts b/packages/pieces/community/salesforce/src/lib/action/ai/update-task.tsnew file mode 100644index 00000000000..ffa0e32b302--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/update-task.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { salesforceAuth } from '../../..';+import { crmUtils } from '../../common/crm';+import { updateRecordOutputSchema } from '../../output-schemas';++export const updateTask = createAction({+ auth: salesforceAuth,+ name: 'update_task',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Update fields on an existing task.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Salesforce Task by id, e.g. its subject, due date (YYYY-MM-DD), status, priority, assignee or linked records; only the fields you supply change. To simply mark it done use Complete Task. At least one field is required; custom fields go in Additional Fields (null clears a value). Safe to retry with the same values.',+ idempotent: true,+ },+ outputSchema: updateRecordOutputSchema,+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ Subject: Property.ShortText({ displayName: 'Subject', required: false }),+ WhoId: Property.ShortText({ displayName: 'Who ID', description: 'Contact or Lead id.', required: false }),+ WhatId: Property.ShortText({ displayName: 'What ID', description: 'Account, Opportunity, Case or other record id.', required: false }),+ OwnerId: Property.ShortText({ displayName: 'Assigned To (User ID)', required: false }),+ ActivityDate: Property.ShortText({ displayName: 'Due Date', description: 'YYYY-MM-DD.', required: false }),+ Status: Property.ShortText({ displayName: 'Status', required: false }),+ Priority: Property.ShortText({ displayName: 'Priority', required: false }),+ Description: Property.LongText({ displayName: 'Description', required: false }),+ additional_fields: crmUtils.additionalFieldsProp,+ },+ async run(context) {+ const { task_id, additional_fields, ...fields } = context.propsValue;+ return crmUtils.updateRecord({+ auth: context.auth,+ object: 'Task',+ recordId: task_id,+ fields: { ...fields, ActivityDate: crmUtils.assertDate({ value: fields.ActivityDate, fieldName: 'Due Date' }) },+ additionalFields: additional_fields,+ });+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/upload-file.ts b/packages/pieces/community/salesforce/src/lib/action/ai/upload-file.tsnew file mode 100644index 00000000000..51deaf584c0--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/upload-file.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi, querySalesforceApi } from '../../common';+import { QueryResult, salesforceUtils } from '../../common/utils';+import { uploadFileOutputSchema } from '../../output-schemas';++export const uploadFile = createAction({+ auth: salesforceAuth,+ name: 'upload_file',+ classification: 'WRITE',+ displayName: 'Upload File',+ description: 'Upload a file to Salesforce Files, optionally linked to a record.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Uploads a file to Salesforce Files (creates a ContentVersion) and, when a record id is given, shares it on that record. Returns the content document id (starts with 069), which is what Get File Info, Download File and Delete File take. Not idempotent: every call uploads another file.',+ idempotent: false,+ },+ outputSchema: uploadFileOutputSchema,+ props: {+ file: Property.File({+ displayName: 'File',+ required: true,+ }),+ file_name: Property.ShortText({+ displayName: 'File Name',+ description: 'Name with extension, e.g. report.pdf. Defaults to the uploaded file name.',+ required: false,+ }),+ record_id: Property.ShortText({+ displayName: 'Record ID',+ description: 'Id of the record to attach the file to.',+ required: false,+ }),+ },+ async run(context) {+ const { file } = context.propsValue;+ const fileName = context.propsValue.file_name?.trim() || file.filename;+ const recordId = context.propsValue.record_id+ ? salesforceUtils.assertId({ value: context.propsValue.record_id, fieldName: 'Record ID' })+ : undefined;+ const created = await callSalesforceApi<{ id: string; success: boolean }>(+ HttpMethod.POST,+ context.auth,+ '/services/data/v56.0/sobjects/ContentVersion',+ salesforceUtils.compact({+ Title: fileName,+ PathOnClient: fileName,+ VersionData: file.base64,+ FirstPublishLocationId: recordId,+ }),+ );+ const versionId = salesforceUtils.assertId({ value: created.body.id, fieldName: 'ContentVersion id' });+ const version = await querySalesforceApi<QueryResult<{ ContentDocumentId: string }>>(+ HttpMethod.GET,+ context.auth,+ `SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${versionId}'`,+ );+ return {+ content_version_id: versionId,+ content_document_id: version.body.records[0]?.ContentDocumentId ?? null,+ title: fileName,+ record_id: recordId ?? null,+ };+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/upsert-record-by-external-id.ts b/packages/pieces/community/salesforce/src/lib/action/ai/upsert-record-by-external-id.tsnew file mode 100644index 00000000000..73c8a9bf6b8--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/upsert-record-by-external-id.ts@@ -0,0 +1,90 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { upsertRecordByExternalIdOutputSchema } from '../../output-schemas';++export const upsertRecordByExternalId = createAction({+ auth: salesforceAuth,+ name: 'upsert_record_by_external_id',+ classification: 'WRITE',+ displayName: 'Upsert Record by External ID',+ description: 'Create or update one record matched on an external id field.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates or updates a single Salesforce record matched on an external id field: updates the match if one exists, otherwise creates it, and reports which happened. Use it to sync from another system without duplicates; for up to 200 records use Upsert Records Batch, and to update by Salesforce id use Update Record. Do not include the external id field inside Fields. Idempotent on the external id: rerunning updates rather than duplicates.',+ idempotent: true,+ },+ outputSchema: upsertRecordByExternalIdOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or My_Object__c.',+ required: true,+ }),+ external_id_field: Property.ShortText({+ displayName: 'External ID Field',+ description: 'API name of the external id field, e.g. My_Ext_Id__c.',+ required: true,+ }),+ external_id_value: Property.ShortText({+ displayName: 'External ID Value',+ required: true,+ }),+ fields: Property.Json({+ displayName: 'Fields',+ description: 'JSON object of field API names to values to set on the record.',+ required: true,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const externalField = salesforceUtils.assertApiName({+ value: context.propsValue.external_id_field,+ fieldName: 'External ID Field',+ });+ const value = context.propsValue.external_id_value.trim();+ if (value.length === 0) {+ throw new Error('External ID Value is required.');+ }+ const fields = salesforceUtils.parseJsonObject({ value: context.propsValue.fields, fieldName: 'Fields' }) ?? {};+ const fieldNames = Object.keys(fields);+ if (fieldNames.length === 0) {+ throw new Error('Fields must contain at least one field.');+ }+ const response = await callSalesforceApi<{ id?: string; success?: boolean; created?: boolean } | string>(+ HttpMethod.PATCH,+ context.auth,+ `/services/data/v56.0/sobjects/${object}/${externalField}/${encodeURIComponent(value)}`,+ fields+ );+ const body = salesforceUtils.isRecord(response.body) ? response.body : {};+ const id =+ typeof body['id'] === 'string'+ ? body['id']+ : await resolveRecordId({ auth: context.auth, object, externalField, value });+ return {+ id,+ success: true,+ created: response.status === 201,+ external_id_field: externalField,+ external_id_value: value,+ updated_fields: fieldNames,+ };+ },+});++async function resolveRecordId({ auth, object, externalField, value }: { auth: OAuth2PropertyValue; object: string; externalField: string; value: string }): Promise<string | null> {+ if (externalField === 'Id') {+ return value;+ }+ const response = await callSalesforceApi<{ Id?: string }>(+ HttpMethod.GET,+ auth,+ `/services/data/v56.0/sobjects/${object}/${externalField}/${encodeURIComponent(value)}?fields=Id`,+ undefined+ );+ return response.body.Id ?? null;+}diff --git a/packages/pieces/community/salesforce/src/lib/action/ai/upsert-records-batch.ts b/packages/pieces/community/salesforce/src/lib/action/ai/upsert-records-batch.tsnew file mode 100644index 00000000000..2643eaf680b--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/action/ai/upsert-records-batch.ts@@ -0,0 +1,71 @@+import { createAction, isNil, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { salesforceAuth } from '../../..';+import { callSalesforceApi } from '../../common';+import { salesforceUtils } from '../../common/utils';+import { CompositeResult, recordsUtils } from '../../common/records';+import { upsertRecordsBatchOutputSchema } from '../../output-schemas';++export const upsertRecordsBatch = createAction({+ auth: salesforceAuth,+ name: 'upsert_records_batch',+ classification: 'WRITE',+ displayName: 'Upsert Records Batch',+ description: 'Create or update up to 200 records matched on an external id field.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates or updates up to 200 records of one Salesforce object in a single call, matching each on an external id field, and returns a per-record result with a created flag in input order. Use it to sync many records from another system; for one record use Upsert Record by External ID. Every record must include the external id field. Idempotent on the external id: rerunning updates rather than duplicates.',+ idempotent: true,+ },+ outputSchema: upsertRecordsBatchOutputSchema,+ props: {+ object: Property.ShortText({+ displayName: 'Object',+ description: 'Object API name, e.g. Account or My_Object__c.',+ required: true,+ }),+ external_id_field: Property.ShortText({+ displayName: 'External ID Field',+ description: 'API name of the external id field used to match, e.g. My_Ext_Id__c.',+ required: true,+ }),+ records: Property.Json({+ displayName: 'Records',+ description: 'JSON array of up to 200 objects; each must include the external id field, e.g. [{"My_Ext_Id__c": "A-1", "Name": "Acme"}].',+ required: true,+ }),+ all_or_none: Property.Checkbox({+ displayName: 'All or None',+ description: 'Roll back every record if any record fails.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const object = salesforceUtils.assertApiName({ value: context.propsValue.object, fieldName: 'Object' });+ const externalField = salesforceUtils.assertApiName({+ value: context.propsValue.external_id_field,+ fieldName: 'External ID Field',+ });+ const records = recordsUtils.parseRecordList({+ value: context.propsValue.records,+ fieldName: 'Records',+ max: recordsUtils.MAX_COMPOSITE_RECORDS,+ });+ const missing = records.findIndex((record) => isNil(record[externalField]) || record[externalField] === '');+ if (missing !== -1) {+ throw new Error(`Records[${missing}] is missing the external id field ${externalField}.`);+ }+ const response = await callSalesforceApi<CompositeResult[]>(+ HttpMethod.PATCH,+ context.auth,+ `/services/data/v56.0/composite/sobjects/${object}/${externalField}`,+ {+ allOrNone: context.propsValue.all_or_none ?? false,+ records: records.map((record) => ({ ...record, attributes: { type: object } })),+ }+ );+ return recordsUtils.formatCompositeResults(response.body);+ },+});diff --git a/packages/pieces/community/salesforce/src/lib/action/create-attachment.ts b/packages/pieces/community/salesforce/src/lib/action/create-attachment.tsindex 5798bade57a..7d18faac97f 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-attachment.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-attachment.ts@@ -2,6 +2,7 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createAttachment = createAction({auth: salesforceAuth,@@ -10,6 +11,7 @@ export const createAttachment = createAction({description: 'Creates a legacy Attachment record. Salesforce recommends using "Add File to Record" for modern apps.',audience: 'both',aiMetadata: { description: 'Attach a file to a record using the legacy Attachment object (single parent, no sharing). Prefer modern Files/ContentDocument when available; this is for older orgs or when a classic Attachment is specifically required. Not idempotent — repeated calls create duplicate attachments.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {object: salesforcesCommon.object,parent_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/create-case.ts b/packages/pieces/community/salesforce/src/lib/action/create-case.tsindex 744dd5fad9e..d704c5fc054 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-case.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-case.ts@@ -2,6 +2,7 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createCase = createAction({auth: salesforceAuth,@@ -10,6 +11,7 @@ export const createCase = createAction({description: 'Creates a Case, which represents a customer issue or problem.',audience: 'both',aiMetadata: { description: 'Create a new support Case (customer issue/problem) with a required Subject and optional status, priority, origin, and links to an Account or Contact. Not idempotent — each call opens a separate Case, so guard against duplicate submissions.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {Subject: Property.ShortText({displayName: 'Subject',diff --git a/packages/pieces/community/salesforce/src/lib/action/create-contact.ts b/packages/pieces/community/salesforce/src/lib/action/create-contact.tsindex 7338f02131a..d422315e048 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-contact.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-contact.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createContact = createAction({auth: salesforceAuth,name: 'create_contact',displayName: 'Create Contact',description: 'Creates a new contact record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a new Contact in Salesforce; Last Name is required and the contact can be linked to an existing Account. Not idempotent — calling it twice creates duplicate contacts, so check for an existing match (e.g. via Find Record) first if dedup matters.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {LastName: Property.ShortText({displayName: 'Last Name',diff --git a/packages/pieces/community/salesforce/src/lib/action/create-lead.ts b/packages/pieces/community/salesforce/src/lib/action/create-lead.tsindex ba4894e164c..467fe028752 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-lead.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-lead.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createLead = createAction({auth: salesforceAuth,name: 'create_lead',displayName: 'Create Lead',description: 'Creates a new lead.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a new Lead; Last Name and Company are required. Not idempotent — each call adds another Lead, so dedup beforehand if needed. Use Update Lead to modify an existing one.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {LastName: Property.ShortText({displayName: 'Last Name',diff --git a/packages/pieces/community/salesforce/src/lib/action/create-note.ts b/packages/pieces/community/salesforce/src/lib/action/create-note.tsindex 573e908bb11..3f113865aa1 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-note.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-note.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createNote = createAction({auth: salesforceAuth,name: 'create_note',displayName: 'Create Note',description: 'Creates a note and attaches it to a record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a classic Salesforce Note (title and body) and attach it to a parent record via its record Id. Use to add a free-text note to an existing record. Not idempotent: each call creates a new Note, so re-running adds a duplicate.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {object: salesforcesCommon.object,parent_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/create-opportunity.ts b/packages/pieces/community/salesforce/src/lib/action/create-opportunity.tsindex 90e0bd9482b..f475545a78f 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-opportunity.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-opportunity.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createOpportunity = createAction({auth: salesforceAuth,name: 'create_opportunity',displayName: 'Create Opportunity',description: 'Creates a new opportunity.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a new sales Opportunity; Name, Close Date (YYYY-MM-DD), and Stage are required, with an optional Account link and Amount. Not idempotent — each call creates another Opportunity.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {Name: Property.ShortText({displayName: 'Name',diff --git a/packages/pieces/community/salesforce/src/lib/action/create-record.ts b/packages/pieces/community/salesforce/src/lib/action/create-record.tsindex 682ede24577..190a1bb511e 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-record.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-record.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createRecord = createAction({auth: salesforceAuth,name: 'create_record',displayName: 'Create Record',description: 'Create a record of a given object.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a new Salesforce record of any standard or custom object (Account, Contact, Lead, etc.) by supplying the object API name plus a JSON map of field values. Pick this for the general "insert one record" case; use Create Object (Advanced) only when you need the raw API response envelope rather than the record body. Not idempotent: each call inserts a new record with a new Id, so re-running creates duplicates.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {object: salesforcesCommon.object,data: Property.Json({diff --git a/packages/pieces/community/salesforce/src/lib/action/create-task.ts b/packages/pieces/community/salesforce/src/lib/action/create-task.tsindex 527d799501a..5d82e425c19 100644--- a/packages/pieces/community/salesforce/src/lib/action/create-task.ts+++ b/packages/pieces/community/salesforce/src/lib/action/create-task.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const createTask = createAction({auth: salesforceAuth,name: 'create_task',displayName: 'Create Task',description: 'Creates a new task.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Create a new activity Task with a required Subject and optional owner, status, priority, and links to a Contact/Lead (WhoId) or other object (WhatId). Not idempotent — each call creates a separate task.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {Subject: Property.ShortText({displayName: 'Subject',diff --git a/packages/pieces/community/salesforce/src/lib/action/delete-opportunity.ts b/packages/pieces/community/salesforce/src/lib/action/delete-opportunity.tsindex 0f280fc7a10..6e4aea97104 100644--- a/packages/pieces/community/salesforce/src/lib/action/delete-opportunity.ts+++ b/packages/pieces/community/salesforce/src/lib/action/delete-opportunity.ts@@ -2,14 +2,16 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { successOutputSchema } from '../output-schemas';export const deleteOpportunity = createAction({auth: salesforceAuth,name: 'delete_opportunity',displayName: 'Delete Opportunity',description: 'Deletes an opportunity.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Delete a single Opportunity by its ID. Destructive and irreversible; not idempotent, since deleting an already-removed Opportunity errors. For other object types use the generic Delete Record.', idempotent: false },+ outputSchema: successOutputSchema,props: {opportunity_id: salesforcesCommon.opportunity,},diff --git a/packages/pieces/community/salesforce/src/lib/action/delete-record.ts b/packages/pieces/community/salesforce/src/lib/action/delete-record.tsindex 807156482e7..16b99a3d8c3 100644--- a/packages/pieces/community/salesforce/src/lib/action/delete-record.ts+++ b/packages/pieces/community/salesforce/src/lib/action/delete-record.ts@@ -2,14 +2,16 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { successOutputSchema } from '../output-schemas';export const deleteRecord = createAction({auth: salesforceAuth,name: 'delete_record',displayName: 'Delete Record',description: 'Deletes an existing record in an object.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Delete a single record of any object by its ID. Destructive and irreversible from here; not idempotent, since a repeat call on an already-deleted ID errors. Use this generic delete for objects without a dedicated one (Delete Opportunity exists separately).', idempotent: false },+ outputSchema: successOutputSchema,props: {object: salesforcesCommon.object,record_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/export-report.ts b/packages/pieces/community/salesforce/src/lib/action/export-report.tsindex 6e6d09a5f3d..2081d1e0de5 100644--- a/packages/pieces/community/salesforce/src/lib/action/export-report.ts+++ b/packages/pieces/community/salesforce/src/lib/action/export-report.ts@@ -6,6 +6,7 @@ import {} from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { exportReportOutputSchema } from '../output-schemas';export const exportReport = createAction({auth: salesforceAuth,@@ -14,6 +15,7 @@ export const exportReport = createAction({description: 'Export a Salesforce report as an Excel file.',audience: 'both',aiMetadata: { description: 'Run an existing Salesforce report by its ID and return its results as a downloadable Excel (.xlsx) file. Read-only — it does not change the report or any records, and the report definition must already exist.', idempotent: true },+ outputSchema: exportReportOutputSchema,props: {report_id: salesforcesCommon.report,},diff --git a/packages/pieces/community/salesforce/src/lib/action/find-child-records.ts b/packages/pieces/community/salesforce/src/lib/action/find-child-records.tsindex 9208bcfe30b..76786469a13 100644--- a/packages/pieces/community/salesforce/src/lib/action/find-child-records.ts+++ b/packages/pieces/community/salesforce/src/lib/action/find-child-records.ts@@ -2,14 +2,16 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { findChildRecordsOutputSchema } from '../output-schemas';export const findChildRecords = createAction({auth: salesforceAuth,name: 'find_child_records',displayName: 'Find Child Records',description: 'Finds child records related to a parent record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'List the child records on one side of a parent record relationship (e.g. the Contacts under an Account) by parent ID and child-relationship name (read-only). Use when you already have a parent record and want its related records via a defined relationship; for arbitrary filtered lookups use Run Query instead.', idempotent: true },+ outputSchema: findChildRecordsOutputSchema,props: {parent_object: salesforcesCommon.object,parent_id: salesforcesCommon.parentRecord,diff --git a/packages/pieces/community/salesforce/src/lib/action/find-record.ts b/packages/pieces/community/salesforce/src/lib/action/find-record.tsindex 9c8594de33c..b79492688df 100644--- a/packages/pieces/community/salesforce/src/lib/action/find-record.ts+++ b/packages/pieces/community/salesforce/src/lib/action/find-record.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { querySalesforceApi, salesforcesCommon } from '../common';+import { rawQueryOutputSchema } from '../output-schemas';export const findRecord = createAction({auth: salesforceAuth,name: 'find_record',displayName: 'Find Record',description: 'Finds a record by a field value.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Look up records of a chosen Salesforce object where a single field equals an exact value (read-only, returns up to 200 matches). Pick this for simple equality lookups by a known field such as Email or Name; for multi-condition filters, joins, or sorting use Run Query (SOQL) instead.', idempotent: true },+ outputSchema: rawQueryOutputSchema,props: {object: salesforcesCommon.object,field: salesforcesCommon.field,diff --git a/packages/pieces/community/salesforce/src/lib/action/find-records-by-query.ts b/packages/pieces/community/salesforce/src/lib/action/find-records-by-query.tsindex 5305a8b68ca..37e047cb21c 100644--- a/packages/pieces/community/salesforce/src/lib/action/find-records-by-query.ts+++ b/packages/pieces/community/salesforce/src/lib/action/find-records-by-query.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { querySalesforceApi, salesforcesCommon } from '../common';+import { rawQueryOutputSchema } from '../output-schemas';export const findRecordsByQuery = createAction({auth: salesforceAuth,name: 'find_records_by_query',displayName: 'Find Records by Query (Advanced)',description: 'Finds records in an object using a SOQL WHERE clause.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Search records of one Salesforce object by providing the object API name and a SOQL WHERE clause (no "WHERE" keyword); returns up to 200 matching records with all fields. Use this to look up or filter existing records by field conditions. Read-only and idempotent. Constraint: the WHERE clause is interpolated directly into the query, so it must be valid SOQL and properly escaped.', idempotent: true },+ outputSchema: rawQueryOutputSchema,props: {object: salesforcesCommon.object,where_clause: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/action/get-record-attachments.ts b/packages/pieces/community/salesforce/src/lib/action/get-record-attachments.tsindex 06757d3fbc0..c3c88c8a591 100644--- a/packages/pieces/community/salesforce/src/lib/action/get-record-attachments.ts+++ b/packages/pieces/community/salesforce/src/lib/action/get-record-attachments.ts@@ -2,6 +2,7 @@ import { createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { querySalesforceApi, salesforcesCommon } from '../common';+import { getRecordAttachmentsOutputSchema } from '../output-schemas';interface QueryResult {@@ -15,6 +16,7 @@ export const getRecordAttachments = createAction({description: 'Get all attachments (both classic and modern Files) for a record.',audience: 'both',aiMetadata: { description: 'List the files attached to a record, covering both legacy Attachment objects and modern Files (ContentDocument) in one read-only call. Use to discover what is attached to a record by its ID; it returns metadata only, not the file contents.', idempotent: true },+ outputSchema: getRecordAttachmentsOutputSchema,props: {object: salesforcesCommon.object,record_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/run-report.ts b/packages/pieces/community/salesforce/src/lib/action/run-report.tsindex 6c4070abbb9..3ddc799826f 100644--- a/packages/pieces/community/salesforce/src/lib/action/run-report.ts+++ b/packages/pieces/community/salesforce/src/lib/action/run-report.ts@@ -2,6 +2,8 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { reportUtils, SalesforceReportResponse } from '../common/report';+import { runReportSyncOutputSchema } from '../output-schemas';export const runReport = createAction({auth: salesforceAuth,@@ -9,8 +11,9 @@ export const runReport = createAction({displayName: 'Run Report',description:'Execute a Salesforce analytics report and return the results as easy-to-use rows.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Run an existing Salesforce analytics report by its report Id and get back flattened rows (detail and grouping columns) instead of raw factMap structures. Optionally pass dynamic filters to override the report\'s saved filters for this run. Use to read aggregated/reported data rather than to query raw records. Read-only and idempotent — it executes the report without changing it.', idempotent: true },+ outputSchema: runReportSyncOutputSchema,props: {report_id: salesforcesCommon.report,filters: Property.Json({@@ -50,161 +53,6 @@ export const runReport = createAction({const reportData = response.body;- return transformReportToRows(reportData);+ return reportUtils.transformReportToRows(reportData);},});--interface SalesforceReportResponse {- attributes: {- reportId: string;- reportName: string;- };- reportMetadata: {- detailColumns: string[];- name: string;- reportFormat: string;- aggregates: string[];- groupingsDown: {- name: string;- sortOrder: string;- dateGranularity: string;- column: string;- }[];- };- reportExtendedMetadata: {- detailColumnInfo: Record<string, { label: string; dataType: string }>;- groupingColumnInfo: Record<string, { label: string; dataType: string }>;- aggregateColumnInfo: Record<string, { label: string; dataType: string }>;- };- factMap: Record<- string,- {- rows: { dataCells: { label: string; value: unknown }[] }[];- aggregates: { label: string; value: unknown }[];- }- >;- groupingsDown: {- groupings: { key: string; label: string; value: unknown }[];- };-}--function transformReportToRows(report: SalesforceReportResponse): {- reportName: string;- reportId: string;- totalRows: number;- columns: string[];- rows: Record<string, unknown>[];-} {- const detailColumns = report.reportMetadata?.detailColumns ?? [];- const detailColumnInfo = report.reportExtendedMetadata?.detailColumnInfo ?? {};- const groupingsDown = report.reportMetadata?.groupingsDown ?? [];- const groupingColumnInfo = report.reportExtendedMetadata?.groupingColumnInfo ?? {};- const factMap = report.factMap ?? {};-- // Build ordered list of column labels for detail columns- const columnLabels = detailColumns.map((col) => detailColumnInfo[col]?.label ?? col);-- // Build grouping column labels- const groupingLabels = groupingsDown.map((g) => groupingColumnInfo[g.name]?.label ?? g.name);-- const allRows: Record<string, unknown>[] = [];-- // Collect grouping labels from groupingsDown for grouped/summary reports- const groupingValues = extractGroupingValues(report.groupingsDown?.groupings ?? []);-- // Iterate over all factMap entries to collect rows- // Keys: "T!T" (tabular/grand total), "0!T", "1!T" (summary groups), "0!0", "1!0" (matrix), etc.- for (const [factMapKey, factMapEntry] of Object.entries(factMap)) {- if (!factMapEntry?.rows) continue;-- // Determine grouping context from the factMap key- const groupContext = resolveGroupingContext(factMapKey, groupingValues, groupingLabels);-- for (const row of factMapEntry.rows) {- const rowObj: Record<string, unknown> = {};-- // Add grouping columns if present- for (const [key, value] of Object.entries(groupContext)) {- rowObj[key] = value;- }-- // Map each data cell to its column label- if (row.dataCells) {- for (let i = 0; i < row.dataCells.length; i++) {- const label = columnLabels[i] ?? `Column_${i}`;- const cell = row.dataCells[i];- let value = cell.label ?? cell.value;- if (value === '-' || value === '--') {- value = '';- }- rowObj[label] = value;- }- }-- allRows.push(rowObj);- }- }-- return {- reportName:- report.attributes?.reportName ?? report.reportMetadata?.name ?? 'Unknown Report',- reportId: report.attributes.reportId ?? 'Unknown Report',- totalRows: allRows.length,- columns: [...groupingLabels, ...columnLabels],- rows: allRows,- };-}--function extractGroupingValues(- groupings: {- key: string;- label: string;- value: unknown;- groupings?: { key: string; label: string; value: unknown }[];- }[],- depth = 0,- result: Record<string, { label: string; depth: number }> = {}-): Record<string, { label: string; depth: number }> {- for (const grouping of groupings) {- result[grouping.key] = { label: grouping.label, depth };- if (grouping.groupings && grouping.groupings.length > 0) {- extractGroupingValues(grouping.groupings, depth + 1, result);- }- }- return result;-}--function resolveGroupingContext(- factMapKey: string,- groupingValues: Record<string, { label: string; depth: number }>,- groupingLabels: string[]-): Record<string, string> {- const context: Record<string, string> = {};-- // factMap keys are like "0!T", "0_1!T", "T!T", etc.- // The part before "!" represents row groupings, after "!" represents column groupings- const [rowPart] = factMapKey.split('!');-- if (rowPart === 'T' || !rowPart) {- return context; // Grand total or no grouping- }-- // Row grouping keys can be like "0", "0_1" (nested groupings)- const rowKeys = rowPart.split('_');-- let currentKey = '';-- for (let depth = 0; depth < rowKeys.length; depth++) {- currentKey = depth === 0 ? rowKeys[depth] : `${currentKey}_${rowKeys[depth]}`;-- const groupInfo = groupingValues[currentKey];-- if (!groupInfo) continue;-- const columnLabel = groupingLabels[depth] ?? `Group_${depth}`;-- context[columnLabel] = groupInfo.label;- }-- return context;-}diff --git a/packages/pieces/community/salesforce/src/lib/action/run-sf-query.ts b/packages/pieces/community/salesforce/src/lib/action/run-sf-query.tsindex 504b3447eeb..f6e088fa2e3 100644--- a/packages/pieces/community/salesforce/src/lib/action/run-sf-query.ts+++ b/packages/pieces/community/salesforce/src/lib/action/run-sf-query.ts@@ -3,14 +3,16 @@ import { salesforcesCommon } from '../common';import { HttpMethod } from '@activepieces/pieces-common';import { querySalesforceApi } from '../common';import { salesforceAuth } from '../..';+import { runQueryOutputSchema } from '../output-schemas';export const runQuery = createAction({auth: salesforceAuth,name: 'run_query',displayName: 'Run Query (Advanced)',description: 'Run a salesforce query',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Run an arbitrary SOQL query string and return the matching records (read-only). Use this for any read needing multiple conditions, field selection, relationships, ordering, or aggregation that the simpler Find Record lookup cannot express; the caller must supply valid SOQL.', idempotent: true },+ outputSchema: runQueryOutputSchema,props: {query: Property.ShortText({displayName: 'Query',diff --git a/packages/pieces/community/salesforce/src/lib/action/send-email.ts b/packages/pieces/community/salesforce/src/lib/action/send-email.tsindex 3c479aa542b..ca5c4e08cec 100644--- a/packages/pieces/community/salesforce/src/lib/action/send-email.ts+++ b/packages/pieces/community/salesforce/src/lib/action/send-email.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi ,salesforcesCommon } from '../common';+import { sobjectCreateResponseOutputSchema } from '../output-schemas';export const sendEmail = createAction({auth: salesforceAuth,name: 'send_email',displayName: 'Send Email',description: 'Sends an email to a Contact or Lead by creating an EmailMessage record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Send an email to a Contact or Lead (body may be plain text or HTML) and log it as an EmailMessage, optionally related to another record. Not idempotent — each call sends and records another email.', idempotent: false },+ outputSchema: sobjectCreateResponseOutputSchema,props: {recipientId: salesforcesCommon.recipient,subject: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/action/update-contact.ts b/packages/pieces/community/salesforce/src/lib/action/update-contact.tsindex b9813273264..9183fd9a470 100644--- a/packages/pieces/community/salesforce/src/lib/action/update-contact.ts+++ b/packages/pieces/community/salesforce/src/lib/action/update-contact.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { successOutputSchema } from '../output-schemas';export const updateContact = createAction({auth: salesforceAuth,name: 'update_contact',displayName: 'Update Contact',description: 'Update an existing contact.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Update fields (name, email, phone, title, account, or arbitrary extra fields) on an existing Salesforce Contact identified by its record Id. Use when you already have the contact Id and want to modify it rather than create one. Idempotent: re-applying the same field values to the same Id yields the same result; omitted fields are left unchanged, and a call with no fields is a no-op.', idempotent: true },+ outputSchema: successOutputSchema,props: {contact_id: salesforcesCommon.contact,FirstName: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/action/update-lead.ts b/packages/pieces/community/salesforce/src/lib/action/update-lead.tsindex 33c3cc16aa6..ef3aeee78ac 100644--- a/packages/pieces/community/salesforce/src/lib/action/update-lead.ts+++ b/packages/pieces/community/salesforce/src/lib/action/update-lead.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { successOutputSchema } from '../output-schemas';export const updateLead = createAction({auth: salesforceAuth,name: 'update_lead',displayName: 'Update Lead',description: 'Update an existing lead.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Update fields on an existing Lead selected by its ID; only the fields you provide are changed and the Lead must already exist. Use Create Lead to add a new one; this does not convert the Lead.', idempotent: false },+ outputSchema: successOutputSchema,props: {lead_id: salesforcesCommon.lead,FirstName: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/action/update-record.ts b/packages/pieces/community/salesforce/src/lib/action/update-record.tsindex f2e0a7efb90..0b78c4f72d4 100644--- a/packages/pieces/community/salesforce/src/lib/action/update-record.ts+++ b/packages/pieces/community/salesforce/src/lib/action/update-record.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';import { callSalesforceApi, salesforcesCommon } from '../common';+import { successOutputSchema } from '../output-schemas';export const updateRecord = createAction({auth: salesforceAuth,name: 'update_record',displayName: 'Update Record',description: 'Updates an existing record.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Update an existing record of any object, selected by object type and record ID, with a JSON map of fields to change; only supplied fields are modified and the record must already exist. The standard update action — use a stable record ID, not an external ID (use Batch/Bulk Upsert for external-ID matching).', idempotent: false },+ outputSchema: successOutputSchema,props: {object: salesforcesCommon.object,record_id: salesforcesCommon.record,diff --git a/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id-bulk.ts b/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id-bulk.tsindex cd9197496c2..c7c4749729d 100644--- a/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id-bulk.ts+++ b/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id-bulk.ts@@ -9,6 +9,7 @@ import {import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';+import { upsertByExternalIdBulkOutputSchema } from '../output-schemas';export const upsertByExternalIdBulk = createAction({auth: salesforceAuth,@@ -17,6 +18,7 @@ export const upsertByExternalIdBulk = createAction({description: 'Bulk upsert a record by external id',audience: 'both',aiMetadata: { description: 'Insert-or-update many records at once via the Bulk API, matching on a stable external-ID field and accepting CSV input. Idempotent on the external ID — rerunning with the same data does not create duplicates. Pick this for large batches; use Batch Upsert for small JSON payloads.', idempotent: true },+ outputSchema: upsertByExternalIdBulkOutputSchema,props: {object: salesforcesCommon.object,external_field: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id.ts b/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id.tsindex ebb94de5722..0184049993a 100644--- a/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id.ts+++ b/packages/pieces/community/salesforce/src/lib/action/upsert-by-external-id.ts@@ -2,14 +2,16 @@ import { Property, createAction } from '@activepieces/pieces-framework';import { callSalesforceApi, salesforcesCommon } from '../common';import { HttpMethod } from '@activepieces/pieces-common';import { salesforceAuth } from '../..';+import { upsertByExternalIdOutputSchema } from '../output-schemas';export const upsertByExternalId = createAction({auth: salesforceAuth,name: 'upsert_by_external_id',displayName: 'Batch Upsert (Advanced)',description: 'Batch upsert a record by external id',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Insert-or-update a small batch of records via the composite API, matching on a stable external-ID field and accepting JSON input. Idempotent on the external ID — rerunning with the same data updates rather than duplicates. Use Bulk Upsert for large CSV loads.', idempotent: true },+ outputSchema: upsertByExternalIdOutputSchema,props: {object: salesforcesCommon.object,external_field: Property.ShortText({diff --git a/packages/pieces/community/salesforce/src/lib/common/bulk.ts b/packages/pieces/community/salesforce/src/lib/common/bulk.tsnew file mode 100644index 00000000000..7ca09bb93c1--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/common/bulk.ts@@ -0,0 +1,85 @@+import { salesforceUtils } from './utils';++function parseCsv(text: string): Record<string, string>[] {+ const rows = tokenizeCsv(text);+ if (rows.length === 0) {+ return [];+ }+ const [header, ...data] = rows;+ return data+ .filter((row) => !(row.length === 1 && row[0] === ''))+ .map((row) => Object.fromEntries(header.map((column, index) => [column, row[index] ?? ''])));+}++function formatJob(body: unknown): Record<string, unknown> {+ if (!salesforceUtils.isRecord(body)) {+ return {};+ }+ return Object.fromEntries(JOB_FIELDS.map((field) => [field, body[field] ?? null]));+}++export const bulkUtils = {+ parseCsv,+ formatJob,+ BULK_API_PATH: '/services/data/v58.0/jobs',+};++function tokenizeCsv(text: string): string[][] {+ const rows: string[][] = [];+ let row: string[] = [];+ let field = '';+ let inQuotes = false;+ let touched = false;+ for (let i = 0; i < text.length; i++) {+ const char = text[i];+ if (inQuotes) {+ if (char === '"' && text[i + 1] === '"') {+ field += '"';+ i++;+ } else if (char === '"') {+ inQuotes = false;+ } else {+ field += char;+ }+ continue;+ }+ if (char === '"') {+ inQuotes = true;+ touched = true;+ } else if (char === ',') {+ row.push(field);+ field = '';+ touched = true;+ } else if (char === '\n' || char === '\r') {+ if (char === '\r' && text[i + 1] === '\n') {+ i++;+ }+ row.push(field);+ rows.push(row);+ row = [];+ field = '';+ touched = false;+ } else {+ field += char;+ touched = true;+ }+ }+ if (touched || field !== '' || row.length > 0) {+ row.push(field);+ rows.push(row);+ }+ return rows;+}++const JOB_FIELDS = [+ 'id',+ 'state',+ 'object',+ 'operation',+ 'numberRecordsProcessed',+ 'numberRecordsFailed',+ 'errorMessage',+ 'createdDate',+ 'systemModstamp',+ 'totalProcessingTime',+];diff --git a/packages/pieces/community/salesforce/src/lib/common/crm.ts b/packages/pieces/community/salesforce/src/lib/common/crm.tsnew file mode 100644index 00000000000..9db20de90d2--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/common/crm.ts@@ -0,0 +1,186 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { isNil, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { callSalesforceApi, querySalesforceApi } from '.';+import { QueryResult, salesforceUtils } from './utils';++function buildBody({ fields, additionalFields }: { fields: Record<string, unknown>; additionalFields: unknown }): Record<string, unknown> {+ return {+ ...salesforceUtils.parseJsonObject({ value: additionalFields, fieldName: 'Additional Fields' }),+ ...salesforceUtils.compact(Object.fromEntries(Object.entries(fields).filter(([key]) => /^[A-Z]/.test(key)))),+ };+}++async function createRecord({ auth, object, fields, additionalFields }: RecordWriteParams & { object: string }) {+ const response = await callSalesforceApi<{ id: string; success: boolean }>(+ HttpMethod.POST,+ auth,+ `/services/data/v56.0/sobjects/${object}`,+ buildBody({ fields, additionalFields })+ );+ return { id: response.body.id, success: response.body.success };+}++async function updateRecord({ auth, object, recordId, fields, additionalFields }: RecordWriteParams & { object: string; recordId: string }) {+ const id = salesforceUtils.assertId({ value: recordId, fieldName: 'Record ID' });+ const body = buildBody({ fields, additionalFields });+ const updatedFields = Object.keys(body);+ if (updatedFields.length === 0) {+ throw new Error('Provide at least one field to update.');+ }+ await callSalesforceApi(HttpMethod.PATCH, auth, `/services/data/v56.0/sobjects/${object}/${id}`, body);+ return { id, success: true, updated_fields: updatedFields };+}++async function query({ auth, soql }: { auth: OAuth2PropertyValue; soql: string }) {+ const response = await querySalesforceApi<QueryResult<unknown>>(HttpMethod.GET, auth, soql);+ return response.body;+}++async function searchRecords({ auth, object, fields, conditions, orderBy, limit }: SearchParams) {+ const where = conditions.filter((condition): condition is string => typeof condition === 'string');+ const whereClause = where.length > 0 ? ` WHERE ${where.join(' AND ')}` : '';+ const soql = `SELECT ${fields.join(', ')} FROM ${object}${whereClause} ORDER BY ${orderBy} LIMIT ${clampLimit(limit)}`;+ return salesforceUtils.formatQueryResult(await query({ auth, soql }));+}++function equals({ field, value }: ConditionParams<string>): string | undefined {+ return isBlank(value) ? undefined : `${field} = '${salesforceUtils.escapeSoqlValue(value.trim())}'`;+}++function contains({ field, value }: ConditionParams<string>): string | undefined {+ return isBlank(value) ? undefined : `${field} LIKE '%${salesforceUtils.escapeSoqlLike(value.trim())}%'`;+}++function idEquals({ field, value }: ConditionParams<string>): string | undefined {+ return isBlank(value) ? undefined : `${field} = '${salesforceUtils.assertId({ value, fieldName: field })}'`;+}++function booleanEquals({ field, value }: ConditionParams<boolean>): string | undefined {+ if (isNil(value) || String(value) === '') {+ return undefined;+ }+ return `${field} = ${String(value).toLowerCase() === 'true' ? 'TRUE' : 'FALSE'}`;+}++function numberCompare({ field, operator, value }: ConditionParams<number> & { operator: '>=' | '<=' }): string | undefined {+ if (isNil(value)) {+ return undefined;+ }+ if (!Number.isFinite(value)) {+ throw new Error(`${field} must be a number.`);+ }+ return `${field} ${operator} ${value}`;+}++function dateCompare({ field, operator, value }: ConditionParams<string> & { operator: '>=' | '<=' }): string | undefined {+ const date = assertDate({ value, fieldName: field });+ return isNil(date) ? undefined : `${field} ${operator} ${date}`;+}++function assertDate({ value, fieldName }: { value: string | undefined | null; fieldName: string }): string | undefined {+ if (isBlank(value)) {+ return undefined;+ }+ const trimmed = value.trim();+ if (!DATE_PATTERN.test(trimmed) || Number.isNaN(Date.parse(trimmed))) {+ throw new Error(`${fieldName} must be a date in YYYY-MM-DD format.`);+ }+ return trimmed;+}++function exactlyOne({ values, fieldNames }: { values: (string | undefined | null)[]; fieldNames: string }): number {+ const provided = values.map((value, index) => (isBlank(value) ? -1 : index)).filter((index) => index >= 0);+ if (provided.length !== 1) {+ throw new Error(`Provide exactly one of ${fieldNames}.`);+ }+ return provided[0];+}++async function getClosedTaskStatus({ auth }: { auth: OAuth2PropertyValue }): Promise<string> {+ const result = await query({+ auth,+ soql: 'SELECT ApiName, MasterLabel FROM TaskStatus WHERE IsClosed = true ORDER BY SortOrder LIMIT 1',+ });+ const record = result.records[0];+ if (!salesforceUtils.isRecord(record)) {+ return 'Completed';+ }+ const status = record['ApiName'] ?? record['MasterLabel'];+ return typeof status === 'string' && status.length > 0 ? status : 'Completed';+}++function booleanFilterProp({ displayName, description }: { displayName: string; description: string }) {+ return Property.StaticDropdown<boolean>({+ displayName,+ description,+ required: false,+ options: {+ options: [+ { label: 'Yes', value: true },+ { label: 'No', value: false },+ ],+ },+ });+}++export const crmUtils = {+ createRecord,+ updateRecord,+ query,+ searchRecords,+ equals,+ contains,+ idEquals,+ booleanEquals,+ numberCompare,+ dateCompare,+ assertDate,+ exactlyOne,+ getClosedTaskStatus,+ booleanFilterProp,+ additionalFieldsProp: Property.Json({+ displayName: 'Additional Fields',+ description: 'Any other fields, including custom ones, as a JSON object of API name to value, e.g. {"My_Field__c": "x"}.',+ required: false,+ }),+ limitProp: Property.Number({+ displayName: 'Limit',+ description: 'Maximum records to return (default 50, max 200).',+ required: false,+ }),+};++function clampLimit(limit: number | undefined | null): number {+ if (isNil(limit) || !Number.isFinite(limit)) {+ return DEFAULT_LIMIT;+ }+ return Math.min(Math.max(Math.floor(limit), 1), MAX_LIMIT);+}++function isBlank(value: string | undefined | null): value is undefined | null {+ return isNil(value) || value.trim() === '';+}++const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 200;+const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;++type RecordWriteParams = {+ auth: OAuth2PropertyValue;+ fields: Record<string, unknown>;+ additionalFields: unknown;+};++type SearchParams = {+ auth: OAuth2PropertyValue;+ object: string;+ fields: string[];+ conditions: (string | undefined)[];+ orderBy: string;+ limit: number | undefined | null;+};++type ConditionParams<T> = {+ field: string;+ value: T | undefined | null;+};diff --git a/packages/pieces/community/salesforce/src/lib/common/index.ts b/packages/pieces/community/salesforce/src/lib/common/index.tsindex f9f9cf8cc17..3d22ecdd690 100644--- a/packages/pieces/community/salesforce/src/lib/common/index.ts+++ b/packages/pieces/community/salesforce/src/lib/common/index.ts@@ -726,12 +726,15 @@ export async function callSalesforceApi<T extends HttpMessageBody>(method: HttpMethod,authentication: OAuth2PropertyValue,url: string,- body: Record<string, unknown> | undefined+ body: Record<string, unknown> | unknown[] | string | undefined,+ options?: { headers?: Record<string, string>; responseType?: 'arraybuffer' | 'json' | 'text' }): Promise<HttpResponse<T>> {return await httpClient.sendRequest<T>({method: method,url: `${authentication.data['instance_url']}${url}`,body,+ headers: options?.headers,+ responseType: options?.responseType,authentication: {type: AuthenticationType.BEARER_TOKEN,token: authentication['access_token'],diff --git a/packages/pieces/community/salesforce/src/lib/common/records.ts b/packages/pieces/community/salesforce/src/lib/common/records.tsnew file mode 100644index 00000000000..278e2abe06b--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/common/records.ts@@ -0,0 +1,57 @@+import { salesforceUtils } from './utils';++function parseRecordList({ value, fieldName, max }: { value: unknown; fieldName: string; max: number }): Record<string, unknown>[] {+ const list = salesforceUtils.parseJsonArray({ value, fieldName }) ?? [];+ if (list.length === 0) {+ throw new Error(`${fieldName} must contain at least one record.`);+ }+ if (list.length > max) {+ throw new Error(`${fieldName} can contain at most ${max} records per call.`);+ }+ return list.map((item, index) => {+ if (!salesforceUtils.isRecord(item)) {+ throw new Error(`${fieldName}[${index}] must be a JSON object.`);+ }+ return item;+ });+}++function parseIdList({ value, fieldName, max }: { value: unknown; fieldName: string; max: number }): string[] {+ const ids = salesforceUtils.toStringArray(value).map((id) => salesforceUtils.assertId({ value: id, fieldName }));+ if (ids.length === 0) {+ throw new Error(`${fieldName} must contain at least one id.`);+ }+ if (ids.length > max) {+ throw new Error(`${fieldName} can contain at most ${max} ids per call.`);+ }+ return ids;+}++function formatCompositeResults(results: CompositeResult[]) {+ const rows = results.map((result, index) => ({+ index,+ id: result.id ?? null,+ success: result.success,+ ...(result.created === undefined ? {} : { created: result.created }),+ errors: (result.errors ?? []).map((error) => `${error.statusCode}: ${error.message}`).join('; '),+ }));+ return {+ results: rows,+ success_count: rows.filter((row) => row.success).length,+ failure_count: rows.filter((row) => !row.success).length,+ };+}++export const recordsUtils = {+ parseRecordList,+ parseIdList,+ formatCompositeResults,+ MAX_COMPOSITE_RECORDS: 200,+};++export type CompositeResult = {+ id?: string | null;+ success: boolean;+ created?: boolean;+ errors?: { statusCode: string; message: string; fields?: string[] }[];+};diff --git a/packages/pieces/community/salesforce/src/lib/common/report.ts b/packages/pieces/community/salesforce/src/lib/common/report.tsnew file mode 100644index 00000000000..8a5b6413734--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/common/report.ts@@ -0,0 +1,129 @@+function transformReportToRows(report: SalesforceReportResponse): {+ reportName: string;+ reportId: string;+ totalRows: number;+ columns: string[];+ rows: Record<string, unknown>[];+} {+ const detailColumns = report.reportMetadata?.detailColumns ?? [];+ const detailColumnInfo = report.reportExtendedMetadata?.detailColumnInfo ?? {};+ const groupingsDown = report.reportMetadata?.groupingsDown ?? [];+ const groupingColumnInfo = report.reportExtendedMetadata?.groupingColumnInfo ?? {};+ const factMap = report.factMap ?? {};++ const columnLabels = detailColumns.map((col) => detailColumnInfo[col]?.label ?? col);+ const groupingLabels = groupingsDown.map((g) => groupingColumnInfo[g.name]?.label ?? g.name);+ const groupingValues = extractGroupingValues({ groupings: report.groupingsDown?.groupings ?? [], depth: 0 });++ const allRows = Object.entries(factMap).flatMap(([factMapKey, factMapEntry]) => {+ if (!factMapEntry?.rows) {+ return [];+ }+ const groupContext = resolveGroupingContext({ factMapKey, groupingValues, groupingLabels });+ return factMapEntry.rows.map((row) => ({+ ...groupContext,+ ...Object.fromEntries(+ (row.dataCells ?? []).map((cell, i) => {+ const value = cell.label ?? cell.value;+ return [columnLabels[i] ?? `Column_${i}`, value === '-' || value === '--' ? '' : value];+ }),+ ),+ }));+ });++ return {+ reportName: report.attributes?.reportName ?? report.reportMetadata?.name ?? 'Unknown Report',+ reportId: report.attributes.reportId ?? 'Unknown Report',+ totalRows: allRows.length,+ columns: [...groupingLabels, ...columnLabels],+ rows: allRows,+ };+}++export const reportUtils = {+ transformReportToRows,+};++function extractGroupingValues({+ groupings,+ depth,+}: {+ groupings: ReportGrouping[];+ depth: number;+}): Record<string, { label: string; depth: number }> {+ return groupings.reduce<Record<string, { label: string; depth: number }>>(+ (acc, grouping) => ({+ ...acc,+ [grouping.key]: { label: grouping.label, depth },+ ...(grouping.groupings && grouping.groupings.length > 0+ ? extractGroupingValues({ groupings: grouping.groupings, depth: depth + 1 })+ : {}),+ }),+ {},+ );+}++function resolveGroupingContext({+ factMapKey,+ groupingValues,+ groupingLabels,+}: {+ factMapKey: string;+ groupingValues: Record<string, { label: string; depth: number }>;+ groupingLabels: string[];+}): Record<string, string> {+ const [rowPart] = factMapKey.split('!');+ if (rowPart === 'T' || !rowPart) {+ return {};+ }+ const rowKeys = rowPart.split('_');+ const cumulativeKeys = rowKeys.map((_, depth) => rowKeys.slice(0, depth + 1).join('_'));+ return Object.fromEntries(+ cumulativeKeys.flatMap((key, depth) => {+ const groupInfo = groupingValues[key];+ return groupInfo ? [[groupingLabels[depth] ?? `Group_${depth}`, groupInfo.label]] : [];+ }),+ );+}++type ReportGrouping = {+ key: string;+ label: string;+ value: unknown;+ groupings?: ReportGrouping[];+};++export type SalesforceReportResponse = {+ attributes: {+ reportId: string;+ reportName: string;+ status?: string;+ };+ reportMetadata: {+ detailColumns: string[];+ name: string;+ reportFormat: string;+ aggregates: string[];+ groupingsDown: {+ name: string;+ sortOrder: string;+ dateGranularity: string;+ column: string;+ }[];+ };+ reportExtendedMetadata: {+ detailColumnInfo: Record<string, { label: string; dataType: string }>;+ groupingColumnInfo: Record<string, { label: string; dataType: string }>;+ aggregateColumnInfo: Record<string, { label: string; dataType: string }>;+ };+ factMap: Record<+ string,+ {+ rows: { dataCells: { label: string; value: unknown }[] }[];+ aggregates: { label: string; value: unknown }[];+ }+ >;+ groupingsDown: {+ groupings: ReportGrouping[];+ };+};diff --git a/packages/pieces/community/salesforce/src/lib/common/utils.ts b/packages/pieces/community/salesforce/src/lib/common/utils.tsnew file mode 100644index 00000000000..ded6a998cc7--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/common/utils.ts@@ -0,0 +1,131 @@+import { isNil } from '@activepieces/pieces-framework';++function escapeSoqlValue(value: string): string {+ return value+ .replace(/\\/g, '\\\\')+ .replace(/'/g, "\\'")+ .replace(/"/g, '\\"')+ .replace(/\n/g, '\\n')+ .replace(/\r/g, '\\r')+ .replace(/\t/g, '\\t');+}++function escapeSoqlLike(value: string): string {+ return escapeSoqlValue(value).replace(/%/g, '\\%').replace(/_/g, '\\_');+}++function escapeSosl(value: string): string {+ return value.replace(/[?&|!{}[\]()^~*:\\"'+-]/g, (char) => `\\${char}`);+}++function assertApiName({ value, fieldName }: { value: string; fieldName: string }): string {+ const trimmed = value.trim();+ if (!API_NAME_PATTERN.test(trimmed)) {+ throw new Error(`${fieldName} must be a Salesforce API name such as Account or My_Field__c.`);+ }+ return trimmed;+}++function assertId({ value, fieldName }: { value: string; fieldName: string }): string {+ const trimmed = value.trim();+ if (!ID_PATTERN.test(trimmed)) {+ throw new Error(`${fieldName} must be a 15- or 18-character Salesforce record id.`);+ }+ return trimmed;+}++function parseJsonObject({ value, fieldName }: { value: unknown; fieldName: string }): Record<string, unknown> | undefined {+ if (isNil(value) || value === '') {+ return undefined;+ }+ const parsed = typeof value === 'string' ? parseJson({ value, fieldName }) : value;+ if (!isRecord(parsed)) {+ throw new Error(`${fieldName} must be a JSON object.`);+ }+ return parsed;+}++function parseJsonArray({ value, fieldName }: { value: unknown; fieldName: string }): unknown[] | undefined {+ if (isNil(value) || value === '') {+ return undefined;+ }+ const parsed = typeof value === 'string' ? parseJson({ value, fieldName }) : value;+ if (!Array.isArray(parsed)) {+ throw new Error(`${fieldName} must be a JSON array.`);+ }+ return parsed;+}++function toStringArray(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.map((item) => String(item).trim()).filter((item) => item.length > 0);+}++function compact(obj: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined && value !== null && value !== ''));+}++function cleanRecord(record: unknown): unknown {+ if (Array.isArray(record)) {+ return record.map(cleanRecord);+ }+ if (!isRecord(record)) {+ return record;+ }+ return Object.fromEntries(+ Object.entries(record)+ .filter(([key]) => key !== 'attributes')+ .map(([key, value]) => [key, cleanRecord(value)]),+ );+}++function formatQueryResult(result: QueryResult<unknown>) {+ return {+ records: result.records.map(cleanRecord),+ count: result.records.length,+ total_size: result.totalSize,+ done: result.done,+ next_records_url: result.nextRecordsUrl ?? null,+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export const salesforceUtils = {+ escapeSoqlValue,+ escapeSoqlLike,+ escapeSosl,+ assertApiName,+ assertId,+ parseJsonObject,+ parseJsonArray,+ toStringArray,+ compact,+ cleanRecord,+ formatQueryResult,+ isRecord,+};++function parseJson({ value, fieldName }: { value: string; fieldName: string }): unknown {+ try {+ return JSON.parse(value);+ } catch {+ throw new Error(`${fieldName} must be valid JSON.`);+ }+}++const API_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;+const ID_PATTERN = /^[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?$/;++export type SalesforceRecord = Record<string, unknown>;++export type QueryResult<T> = {+ totalSize: number;+ done: boolean;+ nextRecordsUrl?: string;+ records: T[];+};diff --git a/packages/pieces/community/salesforce/src/lib/output-schemas.ts b/packages/pieces/community/salesforce/src/lib/output-schemas.tsnew file mode 100644index 00000000000..d5a8af36dab--- /dev/null+++ b/packages/pieces/community/salesforce/src/lib/output-schemas.ts@@ -0,0 +1,1167 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const createResultFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+];++const updateResultFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'updated_fields', label: 'Updated Fields' },+];++const queryPageFields: OutputSchema['fields'] = [+ { key: 'count', label: 'Records Returned', format: 'number' },+ { key: 'total_size', label: 'Total Matching Records', format: 'number' },+ { key: 'done', label: 'All Records Returned', format: 'boolean' },+ { key: 'next_records_url', label: 'Next Records URL' },+];++const compositeResultItemFields: OutputSchema['fields'] = [+ { key: 'index', label: 'Index', format: 'number' },+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'errors', label: 'Errors' },+];++const compositeCountFields: OutputSchema['fields'] = [+ { key: 'success_count', label: 'Succeeded', format: 'number' },+ { key: 'failure_count', label: 'Failed', format: 'number' },+];++const bulkJobSummaryFields: OutputSchema['fields'] = [+ { key: 'job_id', label: 'Job ID' },+ { key: 'state', label: 'State' },+ { key: 'object', label: 'Object' },+ { key: 'operation', label: 'Operation' },+];++const reportRowsFields: OutputSchema['fields'] = [+ { key: 'reportName', label: 'Report Name' },+ { key: 'reportId', label: 'Report ID' },+ { key: 'totalRows', label: 'Total Rows', format: 'number' },+ { key: 'columns', label: 'Columns' },+ { key: 'rows', label: 'Rows' },+];++const accountNameFields: OutputSchema['fields'] = [{ key: 'Name', label: 'Account Name' }];++const accountRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Account ID' },+ { key: 'Name', label: 'Name' },+ { key: 'Phone', label: 'Phone' },+ { key: 'Website', label: 'Website', format: 'url' },+ { key: 'Industry', label: 'Industry' },+ { key: 'Type', label: 'Type' },+ { key: 'BillingCity', label: 'Billing City' },+ { key: 'BillingState', label: 'Billing State' },+ { key: 'BillingCountry', label: 'Billing Country' },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'ParentId', label: 'Parent Account ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+];++const contactRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Contact ID' },+ { key: 'FirstName', label: 'First Name' },+ { key: 'LastName', label: 'Last Name' },+ { key: 'Name', label: 'Full Name' },+ { key: 'Email', label: 'Email', format: 'email' },+ { key: 'Phone', label: 'Phone' },+ { key: 'MobilePhone', label: 'Mobile Phone' },+ { key: 'Title', label: 'Title' },+ { key: 'Department', label: 'Department' },+ { key: 'AccountId', label: 'Account ID' },+ { key: 'Account', label: 'Account', children: accountNameFields },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+];++const leadRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Lead ID' },+ { key: 'FirstName', label: 'First Name' },+ { key: 'LastName', label: 'Last Name' },+ { key: 'Name', label: 'Full Name' },+ { key: 'Company', label: 'Company' },+ { key: 'Email', label: 'Email', format: 'email' },+ { key: 'Phone', label: 'Phone' },+ { key: 'Title', label: 'Title' },+ { key: 'Status', label: 'Status' },+ { key: 'LeadSource', label: 'Lead Source' },+ { key: 'Industry', label: 'Industry' },+ { key: 'IsConverted', label: 'Converted', format: 'boolean' },+ { key: 'ConvertedContactId', label: 'Converted Contact ID' },+ { key: 'ConvertedAccountId', label: 'Converted Account ID' },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+];++const opportunityRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Opportunity ID' },+ { key: 'Name', label: 'Name' },+ { key: 'AccountId', label: 'Account ID' },+ { key: 'Account', label: 'Account', children: accountNameFields },+ { key: 'StageName', label: 'Stage' },+ { key: 'Amount', label: 'Amount', format: 'number' },+ { key: 'Probability', label: 'Probability (%)', format: 'number' },+ { key: 'CloseDate', label: 'Close Date', format: 'date' },+ { key: 'IsClosed', label: 'Closed', format: 'boolean' },+ { key: 'IsWon', label: 'Won', format: 'boolean' },+ { key: 'Type', label: 'Type' },+ { key: 'LeadSource', label: 'Lead Source' },+ { key: 'NextStep', label: 'Next Step' },+ { key: 'Pricebook2Id', label: 'Price Book ID' },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+];++const pricebookRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Price Book ID' },+ { key: 'Name', label: 'Name' },+ { key: 'IsActive', label: 'Active', format: 'boolean' },+ { key: 'IsStandard', label: 'Standard', format: 'boolean' },+ { key: 'Description', label: 'Description' },+];++const pricebookEntryRecordFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Price Book Entry ID' },+ { key: 'Pricebook2Id', label: 'Price Book ID' },+ { key: 'Product2Id', label: 'Product ID' },+ { key: 'Product2', label: 'Product', children: [{ key: 'Name', label: 'Product Name' }] },+ { key: 'ProductCode', label: 'Product Code' },+ { key: 'UnitPrice', label: 'Unit Price', format: 'number' },+ { key: 'IsActive', label: 'Active', format: 'boolean' },+];++const bulkJobFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Job ID' },+ { key: 'state', label: 'State' },+ { key: 'object', label: 'Object' },+ { key: 'operation', label: 'Operation' },+ { key: 'numberRecordsProcessed', label: 'Records Processed', format: 'number' },+ { key: 'numberRecordsFailed', label: 'Records Failed', format: 'number' },+ { key: 'errorMessage', label: 'Error Message' },+ { key: 'createdDate', label: 'Created Date', format: 'datetime' },+ { key: 'systemModstamp', label: 'Last Modified Date', format: 'datetime' },+ { key: 'totalProcessingTime', label: 'Total Processing Time (ms)', format: 'number' },+];++const sobjectEnvelopeFields: OutputSchema['fields'] = [+ { key: 'Id', label: 'Record ID' },+ { key: 'attributes', label: 'Record Info', children: [{ key: 'type', label: 'Object' }] },+];++const addressFields: OutputSchema['fields'] = [+ { key: 'street', label: 'Street' },+ { key: 'city', label: 'City' },+ { key: 'state', label: 'State' },+ { key: 'postalCode', label: 'Postal Code' },+ { key: 'country', label: 'Country' },+];++const rawQueryFields: OutputSchema['fields'] = [+ { key: 'totalSize', label: 'Total Matching Records', format: 'number' },+ { key: 'done', label: 'All Records Returned', format: 'boolean' },+ { key: 'records', label: 'Records' },+];++export const addContactToCampaignMemberOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Campaign Member ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID' },+ { key: 'contact_id', label: 'Contact ID' },+ ],+};++export const addLeadToCampaignMemberOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Campaign Member ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID' },+ { key: 'lead_id', label: 'Lead ID' },+ ],+};++export const addOpportunityProductOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Opportunity Product ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'opportunity_id', label: 'Opportunity ID' },+ { key: 'pricebook_entry_id', label: 'Price Book Entry ID' },+ { key: 'quantity', label: 'Quantity', format: 'number' },+ ],+};++export const applyLeadAssignmentRulesOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Lead ID' },+ { key: 'previous_owner_id', label: 'Previous Owner ID' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'reassigned', label: 'Reassigned', format: 'boolean' },+ ],+};++export const completeTaskOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Task ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'status', label: 'Status' },+ { key: 'updated_fields', label: 'Updated Fields' },+ ],+};++export const createAccountOutputSchema: OutputSchema = {+ fields: [...createResultFields, { key: 'name', label: 'Account Name' }],+};++export const createCampaignOutputSchema: OutputSchema = {+ fields: [...createResultFields, { key: 'name', label: 'Campaign Name' }],+};++export const createSfContactOutputSchema: OutputSchema = {+ fields: [+ ...createResultFields,+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ ],+};++export const createSfLeadOutputSchema: OutputSchema = {+ fields: [+ ...createResultFields,+ { key: 'last_name', label: 'Last Name' },+ { key: 'company', label: 'Company' },+ ],+};++export const createSfNoteOutputSchema: OutputSchema = {+ fields: [+ ...createResultFields,+ { key: 'parent_id', label: 'Parent Record ID' },+ { key: 'title', label: 'Title' },+ ],+};++export const createSfOpportunityOutputSchema: OutputSchema = {+ fields: [+ ...createResultFields,+ { key: 'name', label: 'Opportunity Name' },+ { key: 'stage', label: 'Stage' },+ { key: 'close_date', label: 'Close Date', format: 'date' },+ ],+};++export const createSfTaskOutputSchema: OutputSchema = {+ fields: [...createResultFields, { key: 'subject', label: 'Subject' }],+};++export const createSobjectRecordOutputSchema: OutputSchema = {+ fields: [...createResultFields, { key: 'object', label: 'Object' }],+};++export const logCallOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Task ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'subject', label: 'Subject' },+ { key: 'status', label: 'Status' },+ { key: 'activity_date', label: 'Call Date', format: 'date' },+ ],+};++export const logEmailActivityOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Email Message ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'recipient_id', label: 'Recipient ID' },+ { key: 'related_record_id', label: 'Related Record ID' },+ { key: 'subject', label: 'Subject' },+ ],+};++export const updateRecordOutputSchema: OutputSchema = { fields: updateResultFields };++export const upsertRecordByExternalIdOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'boolean' },+ { key: 'external_id_field', label: 'External ID Field' },+ { key: 'external_id_value', label: 'External ID Value' },+ { key: 'updated_fields', label: 'Updated Fields' },+ ],+};++export const deletedRecordOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Deleted ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+};++export const compositeBatchOutputSchema: OutputSchema = {+ fields: [+ { key: 'results', label: 'Results', labelKey: 'id', listItems: compositeResultItemFields },+ ...compositeCountFields,+ ],+};++export const upsertRecordsBatchOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'results',+ label: 'Results',+ labelKey: 'id',+ listItems: [...compositeResultItemFields, { key: 'created', label: 'Created', format: 'boolean' }],+ },+ ...compositeCountFields,+ ],+};++export const createRecordTreeOutputSchema: OutputSchema = {+ fields: [+ { key: 'has_errors', label: 'Has Errors', format: 'boolean' },+ {+ key: 'results',+ label: 'Results',+ labelKey: 'reference_id',+ listItems: [+ { key: 'reference_id', label: 'Reference ID' },+ { key: 'id', label: 'Record ID' },+ { key: 'errors', label: 'Errors' },+ ],+ },+ ],+};++export const recordOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Record ID' },+ { key: 'record', label: 'Record Fields', value: '', dynamicKey: true },+ ],+};++export const getRecordsBatchOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'records',+ label: 'Records',+ labelKey: 'requested_id',+ listItems: [+ { key: 'requested_id', label: 'Requested ID' },+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'record', label: 'Record', dynamicKey: true },+ ],+ },+ { key: 'count', label: 'Records Requested', format: 'number' },+ { key: 'found_count', label: 'Records Found', format: 'number' },+ ],+};++export const getQuickActionDefaultsOutputSchema: OutputSchema = {+ fields: [{ key: 'defaults', label: 'Default Field Values', value: '', dynamicKey: true }],+};++export const soqlQueryOutputSchema: OutputSchema = {+ fields: [{ key: 'records', label: 'Records' }, ...queryPageFields],+};++export const searchAccountsOutputSchema: OutputSchema = {+ fields: [{ key: 'records', label: 'Accounts', labelKey: 'Name', listItems: accountRecordFields }, ...queryPageFields],+};++export const searchContactsOutputSchema: OutputSchema = {+ fields: [{ key: 'records', label: 'Contacts', labelKey: 'Name', listItems: contactRecordFields }, ...queryPageFields],+};++export const searchLeadsOutputSchema: OutputSchema = {+ fields: [{ key: 'records', label: 'Leads', labelKey: 'Name', listItems: leadRecordFields }, ...queryPageFields],+};++export const searchOpportunitiesOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Opportunities', labelKey: 'Name', listItems: opportunityRecordFields },+ ...queryPageFields,+ ],+};++export const listDashboardsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'records',+ label: 'Dashboards',+ labelKey: 'Title',+ listItems: [+ { key: 'Id', label: 'Dashboard ID' },+ { key: 'Title', label: 'Title' },+ { key: 'DeveloperName', label: 'Developer Name' },+ { key: 'FolderName', label: 'Folder Name' },+ { key: 'Description', label: 'Description' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+ },+ ...queryPageFields,+ ],+};++export const listEmailTemplatesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'records',+ label: 'Email Templates',+ labelKey: 'Name',+ listItems: [+ { key: 'Id', label: 'Template ID' },+ { key: 'Name', label: 'Name' },+ { key: 'DeveloperName', label: 'Developer Name' },+ { key: 'Subject', label: 'Subject' },+ { key: 'FolderId', label: 'Folder ID' },+ { key: 'TemplateType', label: 'Template Type' },+ { key: 'IsActive', label: 'Active', format: 'boolean' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+ },+ ...queryPageFields,+ ],+};++export const listReportsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'records',+ label: 'Reports',+ labelKey: 'Name',+ listItems: [+ { key: 'Id', label: 'Report ID' },+ { key: 'Name', label: 'Name' },+ { key: 'DeveloperName', label: 'Developer Name' },+ { key: 'FolderName', label: 'Folder Name' },+ { key: 'Format', label: 'Format' },+ { key: 'Description', label: 'Description' },+ { key: 'LastRunDate', label: 'Last Run Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+ },+ ...queryPageFields,+ ],+};++export const listPricebooksOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'pricebooks',+ label: 'Price Books',+ children: [+ { key: 'records', label: 'Price Books', labelKey: 'Name', listItems: pricebookRecordFields },+ ...queryPageFields,+ ],+ },+ {+ key: 'entries',+ label: 'Price Book Entries',+ children: [+ { key: 'records', label: 'Entries', labelKey: 'ProductCode', listItems: pricebookEntryRecordFields },+ ...queryPageFields,+ ],+ },+ ],+};++export const searchRecordsSoslOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records' },+ { key: 'count', label: 'Records Returned', format: 'number' },+ ],+};++export const getListViewRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records' },+ { key: 'count', label: 'Records Returned', format: 'number' },+ { key: 'size', label: 'List View Size', format: 'number' },+ { key: 'done', label: 'All Records Returned', format: 'boolean' },+ ],+};++export const getListViewMetadataOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'List View ID' },+ { key: 'sobject_type', label: 'Object' },+ { key: 'query', label: 'SOQL Query' },+ {+ key: 'columns',+ label: 'Columns',+ labelKey: 'label',+ listItems: [+ { key: 'field_name_or_path', label: 'Field' },+ { key: 'label', label: 'Label' },+ { key: 'sortable', label: 'Sortable', format: 'boolean' },+ { key: 'type', label: 'Type' },+ ],+ },+ {+ key: 'order_by',+ label: 'Order By',+ labelKey: 'fieldNameOrPath',+ listItems: [+ { key: 'fieldNameOrPath', label: 'Field' },+ { key: 'sortDirection', label: 'Sort Direction' },+ { key: 'nullsPosition', label: 'Nulls Position' },+ ],+ },+ {+ key: 'where_condition',+ label: 'Filter',+ children: [+ { key: 'conjunction', label: 'Conjunction' },+ { key: 'conditions', label: 'Conditions' },+ ],+ },+ ],+};++export const listListViewsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'list_views',+ label: 'List Views',+ labelKey: 'label',+ listItems: [+ { key: 'id', label: 'List View ID' },+ { key: 'label', label: 'Label' },+ { key: 'developer_name', label: 'Developer Name' },+ { key: 'soql_compatible', label: 'SOQL Compatible', format: 'boolean' },+ { key: 'results_url', label: 'Results URL' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const describeObjectOutputSchema: OutputSchema = {+ fields: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'custom', label: 'Custom', format: 'boolean' },+ { key: 'key_prefix', label: 'Key Prefix' },+ {+ key: 'fields',+ label: 'Fields',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'length', label: 'Length', format: 'number' },+ { key: 'nillable', label: 'Nillable', format: 'boolean' },+ { key: 'createable', label: 'Createable', format: 'boolean' },+ { key: 'updateable', label: 'Updateable', format: 'boolean' },+ { key: 'custom', label: 'Custom', format: 'boolean' },+ { key: 'external_id', label: 'External ID', format: 'boolean' },+ { key: 'reference_to', label: 'References' },+ {+ key: 'picklist_values',+ label: 'Picklist Values',+ labelKey: 'label',+ listItems: [+ { key: 'value', label: 'Value' },+ { key: 'label', label: 'Label' },+ ],+ },+ ],+ },+ {+ key: 'child_relationships',+ label: 'Child Relationships',+ labelKey: 'relationship_name',+ listItems: [+ { key: 'relationship_name', label: 'Relationship Name' },+ { key: 'child_object', label: 'Child Object' },+ { key: 'field', label: 'Field' },+ ],+ },+ {+ key: 'record_types',+ label: 'Record Types',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'developer_name', label: 'Developer Name' },+ { key: 'record_type_id', label: 'Record Type ID' },+ { key: 'active', label: 'Active', format: 'boolean' },+ { key: 'master', label: 'Master', format: 'boolean' },+ ],+ },+ ],+};++export const listObjectsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'objects',+ label: 'Objects',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'custom', label: 'Custom', format: 'boolean' },+ { key: 'queryable', label: 'Queryable', format: 'boolean' },+ { key: 'createable', label: 'Createable', format: 'boolean' },+ { key: 'updateable', label: 'Updateable', format: 'boolean' },+ { key: 'deletable', label: 'Deletable', format: 'boolean' },+ { key: 'key_prefix', label: 'Key Prefix' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const downloadFileOutputSchema: OutputSchema = {+ fields: [+ { key: 'file', label: 'File', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'mime_type', label: 'MIME Type' },+ ],+};++export const getFileInfoOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Content Document ID' },+ { key: 'title', label: 'Title' },+ { key: 'name', label: 'Name' },+ { key: 'file_extension', label: 'File Extension' },+ { key: 'file_type', label: 'File Type' },+ { key: 'content_size', label: 'Size', format: 'filesize' },+ { key: 'mime_type', label: 'MIME Type' },+ { key: 'owner_id', label: 'Owner ID' },+ { key: 'owner_name', label: 'Owner Name' },+ { key: 'created_date', label: 'Created Date', format: 'datetime' },+ { key: 'modified_date', label: 'Modified Date', format: 'datetime' },+ { key: 'version_number', label: 'Version Number' },+ { key: 'download_url', label: 'Download Path' },+ ],+};++export const uploadFileOutputSchema: OutputSchema = {+ fields: [+ { key: 'content_version_id', label: 'Content Version ID' },+ { key: 'content_document_id', label: 'Content Document ID' },+ { key: 'title', label: 'Title' },+ { key: 'record_id', label: 'Linked Record ID' },+ ],+};++export const bulkJobCreatedOutputSchema: OutputSchema = { fields: bulkJobSummaryFields };++export const bulkJobOutputSchema: OutputSchema = { fields: bulkJobFields };++export const getBulkIngestResultsOutputSchema: OutputSchema = {+ fields: [+ { key: 'rows', label: 'Rows' },+ { key: 'count', label: 'Row Count', format: 'number' },+ ],+};++export const getBulkQueryResultsOutputSchema: OutputSchema = {+ fields: [+ { key: 'rows', label: 'Rows' },+ { key: 'count', label: 'Row Count', format: 'number' },+ { key: 'next_locator', label: 'Next Locator' },+ ],+};++export const getCurrentUserOutputSchema: OutputSchema = {+ fields: [+ { key: 'user_id', label: 'User ID' },+ { key: 'organization_id', label: 'Organization ID' },+ { key: 'username', label: 'Username' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'locale', label: 'Locale' },+ { key: 'zoneinfo', label: 'Time Zone' },+ { key: 'user_type', label: 'User Type' },+ ],+};++export const getDashboardOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Dashboard ID' },+ { key: 'name', label: 'Name' },+ { key: 'developer_name', label: 'Developer Name' },+ { key: 'folder_id', label: 'Folder ID' },+ {+ key: 'components',+ label: 'Components',+ labelKey: 'header',+ listItems: [+ { key: 'id', label: 'Component ID' },+ { key: 'header', label: 'Header' },+ { key: 'title', label: 'Title' },+ { key: 'type', label: 'Type' },+ { key: 'visualization_type', label: 'Visualization Type' },+ { key: 'report_id', label: 'Report ID' },+ ],+ },+ {+ key: 'filters',+ label: 'Filters',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ {+ key: 'options',+ label: 'Options',+ labelKey: 'alias',+ listItems: [+ { key: 'id', label: 'Option ID' },+ { key: 'alias', label: 'Alias' },+ { key: 'operation', label: 'Operation' },+ { key: 'value', label: 'Value' },+ ],+ },+ ],+ },+ ],+};++export const getOrgLimitsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'limits',+ label: 'Limits',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Limit' },+ { key: 'max', label: 'Max', format: 'number' },+ { key: 'remaining', label: 'Remaining', format: 'number' },+ { key: 'used', label: 'Used', format: 'number' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const getRecordCountsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'counts',+ label: 'Record Counts',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Object' },+ { key: 'count', label: 'Record Count', format: 'number' },+ ],+ },+ { key: 'count', label: 'Objects Counted', format: 'number' },+ ],+};++export const getReportOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Report ID' },+ { key: 'name', label: 'Name' },+ { key: 'developer_name', label: 'Developer Name' },+ { key: 'format', label: 'Format' },+ { key: 'report_type', label: 'Report Type' },+ { key: 'report_type_label', label: 'Report Type Label' },+ { key: 'detail_columns', label: 'Detail Columns' },+ { key: 'groupings_down', label: 'Row Groupings' },+ { key: 'filters', label: 'Filters' },+ { key: 'filter_logic', label: 'Filter Logic' },+ {+ key: 'columns',+ label: 'Columns',+ labelKey: 'label',+ listItems: [+ { key: 'api_name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'data_type', label: 'Data Type' },+ ],+ },+ ],+};++export const runReportSyncOutputSchema: OutputSchema = { fields: reportRowsFields };++export const getReportInstanceOutputSchema: OutputSchema = {+ fields: [+ { key: 'instance_id', label: 'Instance ID' },+ { key: 'status', label: 'Status' },+ ...reportRowsFields,+ ],+};++export const runReportAsyncOutputSchema: OutputSchema = {+ fields: [+ { key: 'instance_id', label: 'Instance ID' },+ { key: 'status', label: 'Status' },+ { key: 'report_id', label: 'Report ID' },+ { key: 'request_date', label: 'Request Date', format: 'datetime' },+ ],+};++export const getUpdatedRecordIdsOutputSchema: OutputSchema = {+ fields: [+ { key: 'ids', label: 'Record IDs' },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'latest_date_covered', label: 'Latest Date Covered', format: 'datetime' },+ ],+};++export const listInvocableActionsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'actions',+ label: 'Actions',+ labelKey: 'label',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'url', label: 'API Path' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const runInvocableActionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'results',+ label: 'Results',+ labelKey: 'action_name',+ listItems: [+ { key: 'action_name', label: 'Action Name' },+ { key: 'is_success', label: 'Success', format: 'boolean' },+ { key: 'errors', label: 'Errors' },+ { key: 'output_values', label: 'Output Values', dynamicKey: true },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'failed_count', label: 'Failed', format: 'number' },+ ],+};++export const listQuickActionsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'actions',+ label: 'Quick Actions',+ labelKey: 'label',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'sobject_type', label: 'Object' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const runQuickActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'boolean' },+ { key: 'context_id', label: 'Context Record ID' },+ { key: 'feed_item_ids', label: 'Feed Item IDs' },+ { key: 'errors', label: 'Errors' },+ ],+};++export const searchKnowledgeArticlesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'articles',+ label: 'Articles',+ labelKey: 'title',+ listItems: [+ { key: 'id', label: 'Article ID' },+ { key: 'article_number', label: 'Article Number' },+ { key: 'title', label: 'Title' },+ { key: 'summary', label: 'Summary' },+ { key: 'url_name', label: 'URL Name' },+ { key: 'last_published_date', label: 'Last Published Date', format: 'datetime' },+ { key: 'view_count', label: 'View Count', format: 'number' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const sendEmailMessageOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'email_addresses', label: 'Email Addresses' },+ { key: 'recipient_id', label: 'Recipient ID' },+ { key: 'related_record_id', label: 'Related Record ID' },+ { key: 'subject', label: 'Subject' },+ ],+};++export const sobjectCreateResponseOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'errors', label: 'Errors' },+ ],+};++export const successOutputSchema: OutputSchema = {+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],+};++export const exportReportOutputSchema: OutputSchema = {+ fields: [{ key: 'file', label: 'Report File', value: '', format: 'url' }],+};++export const findChildRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'count', label: 'Records Returned', format: 'number' },+ {+ key: 'records',+ label: 'Records',+ labelKey: 'id',+ listItems: [+ { key: 'id', label: 'Record ID' },+ { key: 'apiName', label: 'Object' },+ { key: 'fields', label: 'Fields', dynamicKey: true },+ { key: 'lastModifiedById', label: 'Last Modified By ID' },+ { key: 'lastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ { key: 'recordTypeId', label: 'Record Type ID' },+ ],+ },+ { key: 'nextPageToken', label: 'Next Page Token' },+ { key: 'nextPageUrl', label: 'Next Page URL' },+ ],+};++export const rawQueryOutputSchema: OutputSchema = { fields: rawQueryFields };++export const runQueryOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ { key: 'body', label: 'Result', children: rawQueryFields },+ ],+};++export const getRecordAttachmentsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'classic_attachments',+ label: 'Classic Attachments',+ labelKey: 'Name',+ listItems: [+ { key: 'Id', label: 'Attachment ID' },+ { key: 'Name', label: 'Name' },+ { key: 'BodyLength', label: 'Size', format: 'filesize' },+ { key: 'ContentType', label: 'Content Type' },+ ],+ },+ {+ key: 'files',+ label: 'Files',+ labelKey: 'Title',+ listItems: [+ { key: 'Id', label: 'Content Document ID' },+ { key: 'Title', label: 'Title' },+ ],+ },+ ],+};++export const upsertByExternalIdOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ {+ key: 'body',+ label: 'Results',+ labelKey: 'id',+ listItems: [+ { key: 'id', label: 'Record ID' },+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'boolean' },+ { key: 'errors', label: 'Errors' },+ ],+ },+ ],+};++export const upsertByExternalIdBulkOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ {+ key: 'body',+ label: 'Bulk Job',+ children: [+ { key: 'id', label: 'Job ID' },+ { key: 'state', label: 'State' },+ { key: 'object', label: 'Object' },+ { key: 'operation', label: 'Operation' },+ { key: 'externalIdFieldName', label: 'External ID Field' },+ { key: 'numberRecordsProcessed', label: 'Records Processed', format: 'number' },+ { key: 'numberRecordsFailed', label: 'Records Failed', format: 'number' },+ { key: 'createdById', label: 'Created By ID' },+ { key: 'createdDate', label: 'Created Date', format: 'datetime' },+ { key: 'systemModstamp', label: 'Last Modified Date', format: 'datetime' },+ ],+ },+ ],+};++export const newRecordTriggerOutputSchema: OutputSchema = {+ fields: [+ ...sobjectEnvelopeFields,+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ { key: 'record', label: 'Record Fields', value: '', dynamicKey: true },+ ],+};++export const newCaseTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Case ID' },+ { key: 'CaseNumber', label: 'Case Number' },+ { key: 'Subject', label: 'Subject' },+ { key: 'Description', label: 'Description' },+ { key: 'Status', label: 'Status' },+ { key: 'Priority', label: 'Priority' },+ { key: 'Origin', label: 'Origin' },+ { key: 'Type', label: 'Type' },+ { key: 'Reason', label: 'Reason' },+ { key: 'IsClosed', label: 'Is Closed', format: 'boolean' },+ { key: 'IsEscalated', label: 'Is Escalated', format: 'boolean' },+ { key: 'ClosedDate', label: 'Closed Date', format: 'datetime' },+ { key: 'AccountId', label: 'Account ID' },+ { key: 'ContactId', label: 'Contact ID' },+ { key: 'ContactEmail', label: 'Contact Email', format: 'email' },+ { key: 'ContactPhone', label: 'Contact Phone' },+ { key: 'ParentId', label: 'Parent Case ID' },+ { key: 'SuppliedName', label: 'Web Name' },+ { key: 'SuppliedEmail', label: 'Web Email', format: 'email' },+ { key: 'SuppliedPhone', label: 'Web Phone' },+ { key: 'SuppliedCompany', label: 'Web Company' },+ { key: 'OwnerId', label: 'Owner (Queue) ID' },+ { key: 'CreatedById', label: 'Created By ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+};++export const newContactTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Contact ID' },+ { key: 'Name', label: 'Full Name' },+ { key: 'Salutation', label: 'Salutation' },+ { key: 'FirstName', label: 'First Name' },+ { key: 'LastName', label: 'Last Name' },+ { key: 'Email', label: 'Email', format: 'email' },+ { key: 'Phone', label: 'Phone' },+ { key: 'MobilePhone', label: 'Mobile Phone' },+ { key: 'Title', label: 'Title' },+ { key: 'Department', label: 'Department' },+ { key: 'AccountId', label: 'Account ID' },+ { key: 'LeadSource', label: 'Lead Source' },+ { key: 'Description', label: 'Description' },+ { key: 'MailingAddress', label: 'Mailing Address', children: addressFields },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedById', label: 'Created By ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+};++export const newLeadTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Lead ID' },+ { key: 'Name', label: 'Full Name' },+ { key: 'Salutation', label: 'Salutation' },+ { key: 'FirstName', label: 'First Name' },+ { key: 'LastName', label: 'Last Name' },+ { key: 'Company', label: 'Company' },+ { key: 'Title', label: 'Title' },+ { key: 'Email', label: 'Email', format: 'email' },+ { key: 'Phone', label: 'Phone' },+ { key: 'MobilePhone', label: 'Mobile Phone' },+ { key: 'Website', label: 'Website', format: 'url' },+ { key: 'Status', label: 'Status' },+ { key: 'LeadSource', label: 'Lead Source' },+ { key: 'Industry', label: 'Industry' },+ { key: 'Rating', label: 'Rating' },+ { key: 'Description', label: 'Description' },+ { key: 'Address', label: 'Address', children: addressFields },+ { key: 'IsConverted', label: 'Converted', format: 'boolean' },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedById', label: 'Created By ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ ],+};++export const newUpdatedFileTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Content Document ID' },+ { key: 'Title', label: 'Title' },+ { key: 'FileType', label: 'File Type' },+ { key: 'FileExtension', label: 'File Extension' },+ { key: 'ContentSize', label: 'Size', format: 'filesize' },+ { key: 'Description', label: 'Description' },+ { key: 'LatestPublishedVersionId', label: 'Latest Version ID' },+ { key: 'PublishStatus', label: 'Publish Status' },+ { key: 'IsArchived', label: 'Archived', format: 'boolean' },+ { key: 'OwnerId', label: 'Owner ID' },+ { key: 'CreatedById', label: 'Created By ID' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ { key: 'LastModifiedDate', label: 'Last Modified Date', format: 'datetime' },+ { key: 'ContentModifiedDate', label: 'Content Modified Date', format: 'datetime' },+ { key: 'Type', label: 'Type' },+ ],+};++export const newCaseAttachmentTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'Attachment ID' },+ { key: 'attachment_type', label: 'Attachment Type' },+ { key: 'ParentId', label: 'Case ID' },+ { key: 'Name', label: 'Name' },+ { key: 'ContentType', label: 'Content Type' },+ { key: 'CreatedDate', label: 'Created Date', format: 'datetime' },+ ],+};++export const newFieldHistoryEventTriggerOutputSchema: OutputSchema = {+ fields: [+ { key: 'Id', label: 'History ID' },+ { key: 'ParentId', label: 'Record ID' },+ { key: 'Field', label: 'Field' },+ { key: 'OldValue', label: 'Old Value' },+ { key: 'NewValue', label: 'New Value' },+ { key: 'IsDeleted', label: 'Deleted', format: 'boolean' },+ { key: 'CreatedById', label: 'Changed By ID' },+ { key: 'CreatedDate', label: 'Changed Date', format: 'datetime' },+ ],+};++export const newOutboundMessageTriggerOutputSchema: OutputSchema = {+ itemLabel: 'Notification {Id}',+ fields: [+ {+ key: 'notifications',+ label: 'Notifications',+ value: '',+ listItems: [+ { key: 'Id', label: 'Notification ID' },+ { key: 'sObject', label: 'Record', dynamicKey: true },+ ],+ },+ ],+};diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-case-attachment.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-case-attachment.tsindex c9f1bb5dff9..10ab4168e2d 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-case-attachment.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-case-attachment.ts@@ -14,6 +14,7 @@ import { querySalesforceApi } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newCaseAttachmentTriggerOutputSchema } from '../output-schemas';export const newCaseAttachment = createTrigger({auth: salesforceAuth,@@ -23,6 +24,7 @@ export const newCaseAttachment = createTrigger({aiMetadata: {description: 'Fires when an attachment is added to any Case in Salesforce, covering both classic Attachments and modern Files (ContentDocumentLink) linked to recently modified Cases. Each event represents one attachment and includes an attachment_type field of either "Classic" or "File". Detected by polling for records modified since the last poll.',},+ outputSchema: newCaseAttachmentTriggerOutputSchema,props: {},sampleData: {"Id": "00P7Q000002XyA4UAK",diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-case-in-queue.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-case-in-queue.tsindex 1e8ad475b69..a6a4e43997b 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-case-in-queue.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-case-in-queue.ts@@ -8,6 +8,7 @@ import { querySalesforceApi, salesforcesCommon } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newCaseTriggerOutputSchema } from '../output-schemas';// https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_fields.htm// Hard Salesforce limit: FIELDS(ALL) returns at most 200 records per query@@ -21,6 +22,7 @@ export const newCaseCreatedTrigger = createTrigger({aiMetadata: {description: 'Fires when a Case becomes owned by the selected Salesforce queue, whether assigned at creation by an Assignment Rule or moved into the queue later via an owner change. Each event emits all fields of the Case. Detected by polling CaseHistory owner changes and newly created Cases owned by the queue since the last poll.',},+ outputSchema: newCaseTriggerOutputSchema,props: {caseQueueId: salesforcesCommon.caseQueueId,},diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-contact.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-contact.tsindex 52765971391..7e93cfc059f 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-contact.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-contact.ts@@ -14,6 +14,7 @@ import { querySalesforceApi } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newContactTriggerOutputSchema } from '../output-schemas';export const newContact = createTrigger({auth: salesforceAuth,@@ -23,6 +24,7 @@ export const newContact = createTrigger({aiMetadata: {description: 'Fires once for each new Contact record created in Salesforce, emitting all fields of the created Contact. Detected by polling for records whose CreatedDate is later than the last poll. Does not fire on updates to existing Contacts.',},+ outputSchema: newContactTriggerOutputSchema,props: {},sampleData: {"Id": "0037Q000005x4aXUAQ",diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-field-history-event.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-field-history-event.tsindex 0d7794f863f..aed194a50e6 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-field-history-event.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-field-history-event.ts@@ -13,6 +13,7 @@ import { querySalesforceApi, salesforcesCommon } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newFieldHistoryEventTriggerOutputSchema } from '../output-schemas';export const newFieldHistoryEvent = createTrigger({auth: salesforceAuth,@@ -22,6 +23,7 @@ export const newFieldHistoryEvent = createTrigger({aiMetadata: {description: 'Fires once for each field-history entry recorded when a history-tracked field changes on the selected Salesforce object (for example Account, Contact, or a custom object). Each event represents a single field change and includes the field name, old value, and new value. Requires field history tracking to be enabled for that object and field in Salesforce; standard objects use the <Object>History table and custom objects use the <Object>__History table.',},+ outputSchema: newFieldHistoryEventTriggerOutputSchema,props: {object: salesforcesCommon.object,},diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-lead.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-lead.tsindex 9abeeff182f..8b4b945f559 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-lead.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-lead.ts@@ -13,6 +13,7 @@ import { querySalesforceApi } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newLeadTriggerOutputSchema } from '../output-schemas';export const newLead = createTrigger({auth: salesforceAuth,@@ -22,6 +23,7 @@ export const newLead = createTrigger({aiMetadata: {description: 'Fires once for each new Lead record created in Salesforce, emitting all fields of the created Lead. Detected by polling for records whose CreatedDate is later than the last poll. Does not fire on updates to existing Leads or when a Lead is converted.',},+ outputSchema: newLeadTriggerOutputSchema,props: {},sampleData: {"Id": "00Q7Q000003x4aXUAQ",diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-outbound-message.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-outbound-message.tsindex 11adac9576b..60b65dfcca9 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-outbound-message.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-outbound-message.ts@@ -4,6 +4,7 @@ import {} from '@activepieces/pieces-framework';import { XMLParser } from 'fast-xml-parser';import { salesforceAuth } from '../..';+import { newOutboundMessageTriggerOutputSchema } from '../output-schemas';export const newOutboundMessage = createTrigger({auth: salesforceAuth,@@ -13,6 +14,7 @@ export const newOutboundMessage = createTrigger({aiMetadata: {description: 'Fires when Salesforce pushes an Outbound Message notification to this webhook, typically configured via a Workflow Rule or Flow action in Salesforce. The incoming SOAP XML payload is parsed and the event represents one or more notification objects, each carrying the affected sObject and its fields. Requires the Salesforce Outbound Message endpoint to point at this trigger\'s webhook URL.',},+ outputSchema: newOutboundMessageTriggerOutputSchema,props: {},// See https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_om_outboundmessaging_notification.htmsampleData: {diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-record.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-record.tsindex 3df49061b16..d91e661af88 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-record.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-record.ts@@ -14,6 +14,7 @@ import { querySalesforceApi, salesforcesCommon } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newRecordTriggerOutputSchema } from '../output-schemas';export const newRecord = createTrigger({auth: salesforceAuth,@@ -23,6 +24,7 @@ export const newRecord = createTrigger({aiMetadata: {description: 'Fires once for each new record created for the selected Salesforce object, detected by polling for records whose CreatedDate is later than the last poll. Each event emits all fields of the created record. An optional SOQL where-clause condition can further filter which records trigger the event. Does not fire on updates to existing records.',},+ outputSchema: newRecordTriggerOutputSchema,props: {object: salesforcesCommon.object,conditions: Property.LongText({diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-updated-file.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-updated-file.tsindex b5965e835c4..14406b777cb 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-updated-file.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-updated-file.ts@@ -13,6 +13,7 @@ import { querySalesforceApi } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newUpdatedFileTriggerOutputSchema } from '../output-schemas';export const newUpdatedFile = createTrigger({auth: salesforceAuth,@@ -22,6 +23,7 @@ export const newUpdatedFile = createTrigger({aiMetadata: {description: 'Fires whenever a Salesforce Files ContentDocument is created or modified, detected by polling for records whose SystemModstamp is later than the last poll. Each event represents the current state of one file and includes its fields plus a Type of ContentDocument. Does not fire for classic Attachments or Notes.',},+ outputSchema: newUpdatedFileTriggerOutputSchema,props: {},sampleData: {"Id": "0697Q000002qB9iQAE",diff --git a/packages/pieces/community/salesforce/src/lib/trigger/new-updated-record.ts b/packages/pieces/community/salesforce/src/lib/trigger/new-updated-record.tsindex 04a74b17f90..17d13d3460c 100644--- a/packages/pieces/community/salesforce/src/lib/trigger/new-updated-record.ts+++ b/packages/pieces/community/salesforce/src/lib/trigger/new-updated-record.ts@@ -14,6 +14,7 @@ import { querySalesforceApi, salesforcesCommon } from '../common';import dayjs from 'dayjs';import { salesforceAuth } from '../..';+import { newRecordTriggerOutputSchema } from '../output-schemas';export const newOrUpdatedRecord = createTrigger({auth: salesforceAuth,@@ -23,6 +24,7 @@ export const newOrUpdatedRecord = createTrigger({aiMetadata: {description: 'Fires whenever a record of the selected Salesforce object is created or updated, detected by polling for records whose LastModifiedDate is later than the last poll. Each event emits all fields of the changed record. An optional SOQL where-clause condition can further filter which records trigger the event.',},+ outputSchema: newRecordTriggerOutputSchema,props: {object: salesforcesCommon.object,conditions: Property.LongText({