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(vtiger): manage records, relations, tags and leads from flows and AI agents (#16399)
Odai Ahmad4705ebaf48ba
diff --git a/bun.lock b/bun.lockindex e6eee0aba9c..c78f3e836ac 100644--- a/bun.lock+++ b/bun.lock@@ -9745,7 +9745,7 @@},"packages/pieces/community/vtiger": {"name": "@activepieces/piece-vtiger",- "version": "1.4.1",+ "version": "1.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9753,10 +9753,12 @@"@activepieces/pieces-framework": "workspace:*","crypto-js": "4.2.0","dayjs": "1.11.9",+ "undici": "7.29.1",},"devDependencies": {"@types/crypto-js": "4.2.2","tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/wafeq": {diff --git a/packages/pieces/community/vtiger/package.json b/packages/pieces/community/vtiger/package.jsonindex 14fe5121d84..ba92bf3aa6a 100644--- a/packages/pieces/community/vtiger/package.json+++ b/packages/pieces/community/vtiger/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-vtiger",- "version": "1.4.1",+ "version": "1.5.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -9,15 +9,18 @@"crypto-js": "4.2.0","dayjs": "1.11.9","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"devDependencies": {"@types/crypto-js": "4.2.2",- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/vtiger/src/i18n/translation.json b/packages/pieces/community/vtiger/src/i18n/translation.jsonindex 2ea0a02e890..26ce57d8fe8 100644--- a/packages/pieces/community/vtiger/src/i18n/translation.json+++ b/packages/pieces/community/vtiger/src/i18n/translation.json@@ -14,6 +14,30 @@"Query Records": "Query Records","Search Records": "Search Records","Custom API Call (Deprecated)": "Custom API Call (Deprecated)",+ "Get Current User": "Get Current User",+ "List Modules": "List Modules",+ "Describe Module": "Describe Module",+ "Create Module Record": "Create Module Record",+ "Get Record by ID": "Get Record by ID",+ "Update Record Fields": "Update Record Fields",+ "List Changed Records": "List Changed Records",+ "Delete Record by ID": "Delete Record by ID",+ "List Relation Types": "List Relation Types",+ "Reopen Record": "Reopen Record",+ "Unlink Records": "Unlink Records",+ "Add Tags to Record": "Add Tags to Record",+ "Get Record Tags": "Get Record Tags",+ "Remove Tags from Record": "Remove Tags from Record",+ "Get Account Hierarchy": "Get Account Hierarchy",+ "Find Records by Email or Phone": "Find Records by Email or Phone",+ "Get Picklist Dependency": "Get Picklist Dependency",+ "Convert Lead": "Convert Lead",+ "Link Records": "Link Records",+ "List Related Records": "List Related Records",+ "Query Related Records": "Query Related Records",+ "Download Attachment": "Download Attachment",+ "Search Module Records": "Search Module Records",+ "Find or Create Record": "Find or Create Record","Custom API Call": "Custom API Call","Create a Record": "Create a Record","Get a Record by value": "Get a Record by value",@@ -22,6 +46,30 @@"Query records by SQL statement.": "Query records by SQL statement.","Search for a record.": "Search for a record.","Performs an arbitrary authorized API call. (Deprecated)": "Performs an arbitrary authorized API call. (Deprecated)",+ "Returns the Vtiger user the connection authenticates as.": "Returns the Vtiger user the connection authenticates as.",+ "Lists the Vtiger modules the connected user can access.": "Lists the Vtiger modules the connected user can access.",+ "Lists the fields of a Vtiger module with their types and allowed values.": "Lists the fields of a Vtiger module with their types and allowed values.",+ "Creates a record in any Vtiger module from a JSON object of field values.": "Creates a record in any Vtiger module from a JSON object of field values.",+ "Retrieves one Vtiger record by its webservice ID.": "Retrieves one Vtiger record by its webservice ID.",+ "Changes only the given fields of a Vtiger record.": "Changes only the given fields of a Vtiger record.",+ "Lists record IDs created, updated or deleted in a module since a point in time.": "Lists record IDs created, updated or deleted in a module since a point in time.",+ "Deletes a Vtiger record (moves it to the Recycle Bin).": "Deletes a Vtiger record (moves it to the Recycle Bin).",+ "Lists the related lists (relations) a Vtiger module has.": "Lists the related lists (relations) a Vtiger module has.",+ "Reopens a closed Vtiger record such as a won or lost deal.": "Reopens a closed Vtiger record such as a won or lost deal.",+ "Removes a record from a related list of another record. Both records stay.": "Removes a record from a related list of another record. Both records stay.",+ "Adds tags to a Vtiger record.": "Adds tags to a Vtiger record.",+ "Lists the tags on a Vtiger record.": "Lists the tags on a Vtiger record.",+ "Removes tags from one Vtiger record.": "Removes tags from one Vtiger record.",+ "Returns the parent and child accounts of an Organization.": "Returns the parent and child accounts of an Organization.",+ "Finds Contacts, Leads or Accounts that have a given email address or phone number.": "Finds Contacts, Leads or Accounts that have a given email address or phone number.",+ "Returns which target picklist values are allowed for each source picklist value.": "Returns which target picklist values are allowed for each source picklist value.",+ "Converts a Lead into a Contact, and optionally an Organization and a Deal.": "Converts a Lead into a Contact, and optionally an Organization and a Deal.",+ "Adds a record to a related list of another record.": "Adds a record to a related list of another record.",+ "Lists the records in one related list of a Vtiger record.": "Lists the records in one related list of a Vtiger record.",+ "Pages through the related records of one module linked to a Vtiger record.": "Pages through the related records of one module linked to a Vtiger record.",+ "Downloads an image attachment of a Vtiger record as a file.": "Downloads an image attachment of a Vtiger record as a file.",+ "Finds records in a Vtiger module whose fields match the given values.": "Finds records in a Vtiger module whose fields match the given values.",+ "Returns the record whose field equals a value, or creates it when none exists.": "Returns the record whose field equals a value, or creates it when none exists.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Module Type": "Module Type","Record Fields": "Record Fields",@@ -34,6 +82,35 @@"URL Path (deprecated)": "URL Path (deprecated)","Headers": "Headers","Data": "Data",+ "Module": "Module",+ "Fields": "Fields",+ "Record ID": "Record ID",+ "Modified Since": "Modified Since",+ "Scope": "Scope",+ "Source Record ID": "Source Record ID",+ "Related Record ID": "Related Record ID",+ "Tags": "Tags",+ "Account ID": "Account ID",+ "Lookup Type": "Lookup Type",+ "Value": "Value",+ "Modules": "Modules",+ "Source Field": "Source Field",+ "Target Field": "Target Field",+ "Lead ID": "Lead ID",+ "Assigned To": "Assigned To",+ "Contact Fields": "Contact Fields",+ "Create Organization": "Create Organization",+ "Organization Fields": "Organization Fields",+ "Create Deal": "Create Deal",+ "Deal Fields": "Deal Fields",+ "Relation Label": "Relation Label",+ "Related Module": "Related Module",+ "Offset": "Offset",+ "Attachment ID": "Attachment ID",+ "Filters": "Filters",+ "Match": "Match",+ "Match Field": "Match Field",+ "Match Value": "Match Value","Method": "Method","Query Parameters": "Query Parameters","Body Type": "Body Type",@@ -44,15 +121,50 @@"Follow redirects": "Follow redirects","The module / element type": "The module / element type","Add new fields to be created in the new record": "Add new fields to be created in the new record",- "The record's id": "The record's id",- "Enter the query statement, e.g. SELECT count(*) FROM Contacts;": "Enter the query statement, e.g. SELECT count(*) FROM Contacts;",- "Enter your filter criteria": "Enter your filter criteria",- "Enter the maximum number of records to return.": "Enter the maximum number of records to return.",+ "The record's id. Only the first 100 records of the module are listed; use an expression to pass another id.": "The record's id. Only the first 100 records of the module are listed; use an expression to pass another id.",+ "Fields to update. Values shown are the record values when the step was configured.": "Fields to update. Values shown are the record values when the step was configured.",+ "Enter the query statement, e.g. SELECT count(*) FROM Contacts; Add LIMIT offset, count to page through large results.": "Enter the query statement, e.g. SELECT count(*) FROM Contacts; Add LIMIT offset, count to page through large results.",+ "Enter your filter criteria. Unchecked checkboxes are ignored.": "Enter your filter criteria. Unchecked checkboxes are ignored.",+ "Enter the maximum number of records to return (default and maximum 1000).": "Enter the maximum number of records to return (default and maximum 1000).","Select the HTTP method you want to use": "Select the HTTP method you want to use",- "Absolute URL or path. If a relative path is provided (e.g., /me, /listtypes, /describe), it will be called against the REST base.": "Absolute URL or path. If a relative path is provided (e.g., /me, /listtypes, /describe), it will be called against the REST base.",+ "Path (e.g. /me, /listtypes, /describe) called against the REST base, or an absolute URL on the connected instance.": "Path (e.g. /me, /listtypes, /describe) called against the REST base, or an absolute URL on the connected instance.","Deprecated. Use 'URL' instead. API endpoint's URL path (example: /me, /listtypes, /describe)": "Deprecated. Use 'URL' instead. API endpoint's URL path (example: /me, /listtypes, /describe)","Enter the desired request headers. Skip the authorization headers": "Enter the desired request headers. Skip the authorization headers","Enter the data to pass. if its POST, it will be sent as body data, and if GET, as query string": "Enter the data to pass. if its POST, it will be sent as body data, and if GET, as query string",+ "API name of the Vtiger module, for example Contacts, Leads, Accounts, Potentials or Cases. Get the exact names from List Modules.": "API name of the Vtiger module, for example Contacts, Leads, Accounts, Potentials or Cases. Get the exact names from List Modules.",+ "JSON object of field API name to value, for example {\"lastname\": \"Smith\", \"email\": \"[email protected]\"}.": "JSON object of field API name to value, for example {\"lastname\": \"Smith\", \"email\": \"[email protected]\"}.",+ "Vtiger webservice ID of the record, for example 12x345. Get it from Search Module Records, Query Records or a previous create.": "Vtiger webservice ID of the record, for example 12x345. Get it from Search Module Records, Query Records or a previous create.",+ "JSON object of only the fields to change, for example {\"leadstatus\": \"Contacted\"}.": "JSON object of only the fields to change, for example {\"leadstatus\": \"Contacted\"}.",+ "Unix seconds (e.g. 1735689600) or an ISO 8601 date such as 2026-01-01T00:00:00Z.": "Unix seconds (e.g. 1735689600) or an ISO 8601 date such as 2026-01-01T00:00:00Z.",+ "Which records to include.": "Which records to include.",+ "API name of the source module, for example Accounts.": "API name of the source module, for example Accounts.",+ "Webservice ID of the parent record.": "Webservice ID of the parent record.",+ "Webservice ID of the linked record.": "Webservice ID of the linked record.",+ "Tag names to add.": "Tag names to add.",+ "Tag names to remove from this record.": "Tag names to remove from this record.",+ "Webservice ID of an Accounts (Organizations) record, for example 11x42.": "Webservice ID of an Accounts (Organizations) record, for example 11x42.",+ "The email address or phone number to look for.": "The email address or phone number to look for.",+ "Module API names to search in. Defaults to Contacts, Leads and Accounts.": "Module API names to search in. Defaults to Contacts, Leads and Accounts.",+ "API name of the controlling picklist field (from Describe Module).": "API name of the controlling picklist field (from Describe Module).",+ "API name of the dependent picklist field (from Describe Module).": "API name of the dependent picklist field (from Describe Module).",+ "Webservice ID of the Leads record, for example 10x123.": "Webservice ID of the Leads record, for example 10x123.",+ "Webservice ID of the user who will own the new records. Defaults to the connected user.": "Webservice ID of the user who will own the new records. Defaults to the connected user.",+ "Optional JSON of extra Contacts fields. Lead values are mapped automatically.": "Optional JSON of extra Contacts fields. Lead values are mapped automatically.",+ "Optional JSON of Accounts fields, for example {\"accountname\": \"Acme\"}.": "Optional JSON of Accounts fields, for example {\"accountname\": \"Acme\"}.",+ "JSON of Potentials fields; required when Create Deal is on, for example {\"potentialname\": \"Acme deal\", \"closingdate\": \"2026-12-31\", \"sales_stage\": \"Prospecting\"}.": "JSON of Potentials fields; required when Create Deal is on, for example {\"potentialname\": \"Acme deal\", \"closingdate\": \"2026-12-31\", \"sales_stage\": \"Prospecting\"}.",+ "Webservice ID of the record to add.": "Webservice ID of the record to add.",+ "Relation label from List Relation Types, for example Contacts.": "Relation label from List Relation Types, for example Contacts.",+ "Webservice ID of the parent record, for example 11x42.": "Webservice ID of the parent record, for example 11x42.",+ "The relation label from List Relation Types (its label, not the translated label), for example Contacts or Activities.": "The relation label from List Relation Types (its label, not the translated label), for example Contacts or Activities.",+ "API name of the related module, for example Contacts.": "API name of the related module, for example Contacts.",+ "Records per page, 1 to 100 (default 100).": "Records per page, 1 to 100 (default 100).",+ "Number of records to skip (default 0).": "Number of records to skip (default 0).",+ "Value from the record's imageattachmentids field.": "Value from the record's imageattachmentids field.",+ "JSON object of field API name to value, for example {\"lastname\": \"Smith\", \"leadsource\": \"Web Site\"}.": "JSON object of field API name to value, for example {\"lastname\": \"Smith\", \"leadsource\": \"Web Site\"}.",+ "Maximum records to return, 1 to 1000 (default 100).": "Maximum records to return, 1 to 1000 (default 100).",+ "Field API name to match on, for example email.": "Field API name to match on, for example email.",+ "Value the field must equal exactly.": "Value the field must equal exactly.",+ "JSON of fields used only when a record is created; include the mandatory fields, for example {\"lastname\": \"Smith\"}.": "JSON of fields used only when a record is created; include the mandatory fields, for example {\"lastname\": \"Smith\"}.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",@@ -64,13 +176,21 @@"PUT": "PUT","PATCH": "PATCH","DELETE": "DELETE",+ "All records": "All records",+ "User's and user's groups' records": "User's and user's groups' records",+ "User's records only": "User's records only",+ "Email": "Email",+ "Phone": "Phone",+ "Exact": "Exact",+ "Contains (text values)": "Contains (text values)","HEAD": "HEAD","New or Updated Record": "New or Updated Record",- "Triggers when a new record is introduced or a record is updated.": "Triggers when a new record is introduced or a record is updated.",+ "Triggers when a new record is introduced or a record is updated. Deleted records are not emitted.": "Triggers when a new record is introduced or a record is updated. Deleted records are not emitted.","Watch By": "Watch By","Sync Scope": "Sync Scope","Column to watch for trigger": "Column to watch for trigger","Records visibility scope for sync": "Records visibility scope for sync",+ "Enter the maximum number of records to return per poll (1 to 1000).": "Enter the maximum number of records to return per poll (1 to 1000).","Created Time": "Created Time","Modified Time": "Modified Time","Application (all records)": "Application (all records)",diff --git a/packages/pieces/community/vtiger/src/index.ts b/packages/pieces/community/vtiger/src/index.tsindex cc2ceb85b31..6065d4bc0ac 100644--- a/packages/pieces/community/vtiger/src/index.ts+++ b/packages/pieces/community/vtiger/src/index.ts@@ -1,113 +1,48 @@-import {- createPiece,- PieceAuth,- Property,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { createRecord } from './lib/actions/create-record';import { deleteRecord } from './lib/actions/delete-record';import { getRecord } from './lib/actions/get-record';-import { makeAPICall } from './lib/actions/make-api-call';+import { customApiCallAuthHeaders, makeAPICall } from './lib/actions/make-api-call';+import { queryRecords } from './lib/actions/query-records';import { searchRecords } from './lib/actions/search-record';import { updateRecord } from './lib/actions/update-record';-import { instanceLogin, isBaseUrl } from './lib/common';+import { addTagsToRecordAction } from './lib/actions/ai/add-tags-to-record';+import { convertLeadAction } from './lib/actions/ai/convert-lead';+import { createModuleRecordAction } from './lib/actions/ai/create-module-record';+import { deleteRecordByIdAction } from './lib/actions/ai/delete-record-by-id';+import { describeModuleAction } from './lib/actions/ai/describe-module';+import { downloadAttachmentAction } from './lib/actions/ai/download-attachment';+import { findOrCreateRecordAction } from './lib/actions/ai/find-or-create-record';+import { findRecordsByEmailOrPhoneAction } from './lib/actions/ai/find-records-by-email-or-phone';+import { getAccountHierarchyAction } from './lib/actions/ai/get-account-hierarchy';+import { getCurrentUserAction } from './lib/actions/ai/get-current-user';+import { getPicklistDependencyAction } from './lib/actions/ai/get-picklist-dependency';+import { getRecordByIdAction } from './lib/actions/ai/get-record-by-id';+import { getRecordTagsAction } from './lib/actions/ai/get-record-tags';+import { linkRecordsAction } from './lib/actions/ai/link-records';+import { listChangedRecordsAction } from './lib/actions/ai/list-changed-records';+import { listModulesAction } from './lib/actions/ai/list-modules';+import { listRelatedRecordsAction } from './lib/actions/ai/list-related-records';+import { listRelationTypesAction } from './lib/actions/ai/list-relation-types';+import { queryRelatedRecordsAction } from './lib/actions/ai/query-related-records';+import { removeTagsFromRecordAction } from './lib/actions/ai/remove-tags-from-record';+import { reopenRecordAction } from './lib/actions/ai/reopen-record';+import { searchModuleRecordsAction } from './lib/actions/ai/search-module-records';+import { unlinkRecordsAction } from './lib/actions/ai/unlink-records';+import { updateRecordFieldsAction } from './lib/actions/ai/update-record-fields';+import { vtigerAuth } from './lib/auth';+import { isRecord, restBaseUrl } from './lib/rest-client';import { newOrUpdatedRecord } from './lib/triggers/new-or-updated-record';-import { queryRecords } from './lib/actions/query-records';-import { createCustomApiCallAction } from '@activepieces/pieces-common';--const markdownProperty = `-To obtain your Access Key, follow these steps:--1. Login to Vtiger CRM:-Open a web browser and log in to your Vtiger CRM instance.--2. Navigate to User Profile:-In the top right corner, click on your profile name.-Select "My Preferences."--3. The system will generate an access key for you.-Copy and securely store the access key. This key will be used for authentication when making API requests.-Note:--Access keys are sensitive information, and they should be kept secure.-Treat the access key like a password. Do not share it publicly or expose it in an insecure manner.-`;--export const vtigerAuth = PieceAuth.CustomAuth({- description: markdownProperty,- props: {- instance_url: Property.ShortText({- displayName: 'VTiger Instance URL',- description:- 'For the instance URL, add the url without the endpoint. For example enter https://<instance>.od2.vtiger.com instead of https://<instance>.od2.vtiger.com/restapi/v1/vtiger/default',- required: true,- }),- username: Property.ShortText({- displayName: 'Username',- description: 'Enter your username/email',- required: true,- }),- password: PieceAuth.SecretText({- displayName: 'Access Key',- description: 'Enter your access Key',- required: true,- }),- },- validate: async ({ auth }) => {- const { instance_url, username, password } = auth;-- try {- if (!isBaseUrl(instance_url)) {- return {- valid: false,- error:- 'Please ensure that the website is valid and does not contain any paths, for example, https://<instance>.od2.vtiger.com ',- };- }- if (instance_url.endsWith('/')) {- return {- valid: false,- error:- 'Please enter the URL without a trailing slash. E.g. https://<instance>.od2.vtiger.com instead of https://<instance>.od2.vtiger.com/',- };- }- if (instance_url.includes('restapi/')) {- return {- valid: false,- error:- 'Add the url without the endpoint. For example add https://<instance>.od2.vtiger.com instead of https://<instance>.od2.vtiger.com/restapi/v1/vtiger/default',- };- }-- const instance = await instanceLogin(instance_url, username, password);- if (!instance) {- return {- valid: false,- error: 'Invalid credentials, check and try again.',- };- }-- return {- valid: true,- };- } catch (err) {- return {- valid: false,- error: 'Unexpected error. Please check your credentials and try again.',- };- }- },- required: true,-});export const vtiger = createPiece({displayName: 'Vtiger',description: 'CRM software for sales, marketing, and support teams',auth: vtigerAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/vtiger.png',categories: [PieceCategory.SALES_AND_CRM],- authors: ["kanarelo","kishanprmr","abuaboud", "privatestefans"],+ authors: ['kanarelo', 'kishanprmr', 'abuaboud', 'privatestefans'],actions: [createRecord,getRecord,@@ -115,19 +50,39 @@ export const vtiger = createPiece({deleteRecord,queryRecords,searchRecords,- makeAPICall, // deprecated+ makeAPICall,+ getCurrentUserAction,+ listModulesAction,+ describeModuleAction,+ createModuleRecordAction,+ getRecordByIdAction,+ updateRecordFieldsAction,+ listChangedRecordsAction,+ deleteRecordByIdAction,+ listRelationTypesAction,+ reopenRecordAction,+ unlinkRecordsAction,+ addTagsToRecordAction,+ getRecordTagsAction,+ removeTagsFromRecordAction,+ getAccountHierarchyAction,+ findRecordsByEmailOrPhoneAction,+ getPicklistDependencyAction,+ convertLeadAction,+ linkRecordsAction,+ listRelatedRecordsAction,+ queryRelatedRecordsAction,+ downloadAttachmentAction,+ searchModuleRecordsAction,+ findOrCreateRecordAction,createCustomApiCallAction({auth: vtigerAuth,- baseUrl: (auth: any) => `${auth.instance_url}/restapi/v1/vtiger/default`,- authMapping: async (auth: any) => {- const { username, password } = auth;- return {- Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString(- 'base64'- )}`,- };- },+ baseUrl: (auth) => (auth ? restBaseUrl(auth.props) : ''),+ authMapping: async (auth, propsValue) =>+ customApiCallAuthHeaders({ creds: auth.props, url: isRecord(propsValue['url']) ? propsValue['url']['url'] : undefined }),}),],triggers: [newOrUpdatedRecord],});++export { vtigerAuth };diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/add-tags-to-record.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/add-tags-to-record.tsnew file mode 100644index 00000000000..f7f70456964--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/add-tags-to-record.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, stringList } from '../../ai-common';+import { tagChangeSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const addTagsToRecordAction = createAction({+ auth: vtigerAuth,+ name: 'add_tags_to_record',+ displayName: 'Add Tags to Record',+ description: 'Adds tags to a Vtiger record.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds one or more tags to a record; tags that do not exist yet are created. Adding a tag the record already has changes nothing.',+ idempotent: true,+ },+ outputSchema: tagChangeSchema,+ props: {+ recordId: recordIdProp(),+ tags: Property.Array({+ displayName: 'Tags',+ description: 'Tag names to add.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.recordId });+ const tags = stringList({ value: propsValue.tags, label: 'Tags' });+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.POST,+ path: 'tags_add',+ form: { id, tags: JSON.stringify(tags) },+ });+ return { recordId: id, tags, message: isRecord(result) && typeof result['message'] === 'string' ? result['message'] : '' };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/convert-lead.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/convert-lead.tsnew file mode 100644index 00000000000..2fcbe69a067--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/convert-lead.ts@@ -0,0 +1,137 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { fieldsJsonProp } from '../../ai-common';+import { recordFromJson } from '../../common';+import { convertLeadSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export function convertLeadElement({+ leadId,+ assignedTo,+ contactFields,+ createAccount,+ accountFields,+ createPotential,+ potentialFields,+}: {+ leadId: unknown;+ assignedTo: string;+ contactFields: unknown;+ createAccount: unknown;+ accountFields: unknown;+ createPotential: unknown;+ potentialFields: unknown;+}): string {+ const potential = recordFromJson({ value: potentialFields, label: 'Deal Fields' });+ if (createPotential === true) {+ const missing = ['potentialname', 'closingdate', 'sales_stage'].filter(+ (field) => potential[field] === undefined || potential[field] === ''+ );+ if (missing.length > 0) {+ throw new Error(`Deal Fields must include ${missing.join(', ')} when Create Deal is on`);+ }+ }+ const entities: Record<string, Record<string, unknown>> = {+ Contacts: { ...recordFromJson({ value: contactFields, label: 'Contact Fields' }), create: true, name: 'Contacts' },+ };+ if (createAccount === true) {+ entities['Accounts'] = {+ ...recordFromJson({ value: accountFields, label: 'Organization Fields' }),+ create: true,+ name: 'Accounts',+ };+ }+ if (createPotential === true) {+ entities['Potentials'] = { ...potential, create: true, name: 'Potentials' };+ }+ return JSON.stringify({+ leadId: assertRecordId({ value: leadId, label: 'Lead ID' }),+ assignedTo: assertRecordId({ value: assignedTo, label: 'Assigned To' }),+ entities,+ });+}++export const convertLeadAction = createAction({+ auth: vtigerAuth,+ name: 'convert_lead',+ displayName: 'Convert Lead',+ description: 'Converts a Lead into a Contact, and optionally an Organization and a Deal.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Converts one Lead into a new Contact, optionally also creating an Organization and a Deal. Cannot be undone: the Lead is marked converted and leaves lead lists, and a second call fails or creates duplicates. A Deal needs potentialname, closingdate and sales_stage.',+ idempotent: false,+ },+ outputSchema: convertLeadSchema,+ props: {+ leadId: Property.ShortText({+ displayName: 'Lead ID',+ description: 'Webservice ID of the Leads record, for example 10x123.',+ required: true,+ }),+ assignedTo: Property.ShortText({+ displayName: 'Assigned To',+ description: 'Webservice ID of the user who will own the new records. Defaults to the connected user.',+ required: false,+ }),+ contactFields: fieldsJsonProp({+ displayName: 'Contact Fields',+ description: 'Optional JSON of extra Contacts fields. Lead values are mapped automatically.',+ required: false,+ }),+ createAccount: Property.Checkbox({+ displayName: 'Create Organization',+ required: false,+ defaultValue: false,+ }),+ accountFields: fieldsJsonProp({+ displayName: 'Organization Fields',+ description: 'Optional JSON of Accounts fields, for example {"accountname": "Acme"}.',+ required: false,+ }),+ createPotential: Property.Checkbox({+ displayName: 'Create Deal',+ required: false,+ defaultValue: false,+ }),+ potentialFields: fieldsJsonProp({+ displayName: 'Deal Fields',+ description:+ 'JSON of Potentials fields; required when Create Deal is on, for example {"potentialname": "Acme deal", "closingdate": "2026-12-31", "sales_stage": "Prospecting"}.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const assignedTo =+ typeof propsValue.assignedTo === 'string' && propsValue.assignedTo.trim() !== ''+ ? propsValue.assignedTo.trim()+ : await currentUserId(auth.props);+ const element = convertLeadElement({ ...propsValue, assignedTo });+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.POST,+ path: 'convertlead',+ form: { element },+ });+ const created = isRecord(result) ? result : {};+ return {+ leadId: propsValue.leadId.trim(),+ contactId: typeof created['Contacts'] === 'string' ? created['Contacts'] : '',+ accountId: typeof created['Accounts'] === 'string' ? created['Accounts'] : '',+ potentialId: typeof created['Potentials'] === 'string' ? created['Potentials'] : '',+ result,+ };+ },+});++async function currentUserId(creds: { instance_url: string; username: string; password: string }): Promise<string> {+ const me = await vtigerRest<unknown>({ creds, method: HttpMethod.GET, path: 'me' });+ const id = isRecord(me) ? me['id'] : undefined;+ if (typeof id !== 'string') {+ throw new Error('Could not read the connected user ID; set Assigned To');+ }+ return id;+}diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/create-module-record.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/create-module-record.tsnew file mode 100644index 00000000000..eb5a8d46254--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/create-module-record.ts@@ -0,0 +1,61 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { fieldsJsonProp, moduleProp, recordOutput } from '../../ai-common';+import { recordFromJson } from '../../common';+import { aiRecordSchema } from '../../output-schemas';+import { VtigerCredentials, vtigerRest } from '../../rest-client';+import { assertModuleName } from '../../vtql';++export async function createModuleRecord({+ creds,+ module,+ fields,+}: {+ creds: VtigerCredentials;+ module: string;+ fields: Record<string, unknown>;+}): Promise<Record<string, unknown>> {+ if (Object.keys(fields).length === 0) {+ throw new Error('Fields must contain at least one field value');+ }+ if ('id' in fields) {+ throw new Error('Fields must not contain id when creating a record');+ }+ return vtigerRest<Record<string, unknown>>({+ creds,+ method: HttpMethod.POST,+ path: 'create',+ form: { elementType: assertModuleName(module), element: JSON.stringify(fields) },+ });+}++export const createModuleRecordAction = createAction({+ auth: vtigerAuth,+ name: 'create_module_record',+ displayName: 'Create Module Record',+ description: 'Creates a record in any Vtiger module from a JSON object of field values.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one record in a Vtiger module (e.g. Contacts, Leads, Cases) from field API names and values; mandatory fields (see Describe Module) must be included, and assigned_user_id defaults to the connected user when omitted. Each call creates a new record, so use Find or Create Record to avoid duplicates.',+ idempotent: false,+ },+ outputSchema: aiRecordSchema,+ props: {+ module: moduleProp(),+ fields: fieldsJsonProp({+ description: 'JSON object of field API name to value, for example {"lastname": "Smith", "email": "[email protected]"}.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const record = await createModuleRecord({+ creds: auth.props,+ module: propsValue.module,+ fields: recordFromJson({ value: propsValue.fields, label: 'Fields' }),+ });+ return recordOutput(record);+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/delete-record-by-id.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/delete-record-by-id.tsnew file mode 100644index 00000000000..09f178d6c34--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/delete-record-by-id.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp } from '../../ai-common';+import { deleteResultSchema } from '../../output-schemas';+import { deleteRestRecord } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const deleteRecordByIdAction = createAction({+ auth: vtigerAuth,+ name: 'delete_record_by_id',+ displayName: 'Delete Record by ID',+ description: 'Deletes a Vtiger record (moves it to the Recycle Bin).',+ classification: 'DESTRUCTIVE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Deletes one record by webservice ID. Vtiger moves it to the Recycle Bin, where only an admin can restore it from the web UI. Deleting an ID that is already gone fails with HTTP 400.',+ idempotent: false,+ },+ outputSchema: deleteResultSchema,+ props: {+ recordId: recordIdProp(),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.recordId });+ await deleteRestRecord({ creds: auth.props, id });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/describe-module.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/describe-module.tsnew file mode 100644index 00000000000..91dc4b8305b--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/describe-module.ts@@ -0,0 +1,73 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { moduleProp } from '../../ai-common';+import { describeModuleSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertModuleName } from '../../vtql';++export function shapeDescribe(result: unknown) {+ const value = isRecord(result) ? result : {};+ const fields = Array.isArray(value['fields']) ? value['fields'].filter(isRecord) : [];+ const shaped = fields.map((field) => {+ const type = isRecord(field['type']) ? field['type'] : {};+ const picklist = Array.isArray(type['picklistValues']) ? type['picklistValues'].filter(isRecord) : [];+ return {+ name: textOf(field['name']),+ label: textOf(field['label']),+ type: textOf(type['name']),+ mandatory: field['mandatory'] === true,+ editable: field['editable'] !== false,+ picklistValues: picklist.map((p) => textOf(p['value'])),+ refersTo: Array.isArray(type['refersTo']) ? type['refersTo'].map(textOf) : [],+ };+ });+ return {+ name: textOf(value['name']),+ label: textOf(value['label']),+ idPrefix: textOf(value['idPrefix']),+ createable: value['createable'] === true,+ updateable: value['updateable'] === true,+ deleteable: value['deleteable'] === true,+ labelFields: textOf(value['labelFields']),+ fields: shaped,+ fieldCount: shaped.length,+ };+}++function textOf(value: unknown): string {+ if (typeof value === 'string') {+ return value;+ }+ if (Array.isArray(value)) {+ return value.map(textOf).join(',');+ }+ return typeof value === 'number' || typeof value === 'boolean' ? String(value) : '';+}++export const describeModuleAction = createAction({+ auth: vtigerAuth,+ name: 'describe_module',+ displayName: 'Describe Module',+ description: 'Lists the fields of a Vtiger module with their types and allowed values.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the fields of one Vtiger module: API name, label, type, whether it is mandatory, picklist values and the modules a reference field points to. Call it before creating, updating or filtering records so you use real field names (e.g. lastname, cf_853) and valid picklist values.',+ idempotent: true,+ },+ outputSchema: describeModuleSchema,+ props: {+ module: moduleProp(),+ },+ async run({ auth, propsValue }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'describe',+ query: { elementType: assertModuleName(propsValue.module) },+ });+ return shapeDescribe(result);+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/download-attachment.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/download-attachment.tsnew file mode 100644index 00000000000..d053c647045--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/download-attachment.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { downloadAttachmentSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';++export function assertAttachmentId(value: unknown): string {+ const id = typeof value === 'string' ? value.trim() : '';+ if (!/^[0-9]+(x[0-9]+)?(_[0-9]+)?$/.test(id)) {+ throw new Error(+ `Attachment ID "${String(value ?? '')}" is not valid. Use a value from the record's imageattachmentids field.`+ );+ }+ return id;+}++export function pickAttachment(result: unknown): Record<string, unknown> {+ const item = Array.isArray(result) ? result.find(isRecord) : result;+ if (!isRecord(item) || typeof item['filecontents'] !== 'string') {+ throw new Error('Vtiger returned no file contents for this attachment ID');+ }+ return item;+}++export const downloadAttachmentAction = createAction({+ auth: vtigerAuth,+ name: 'download_attachment',+ displayName: 'Download Attachment',+ description: 'Downloads an image attachment of a Vtiger record as a file.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ "Downloads one attachment (e.g. a contact photo or product image) and returns it as a file. The input is an attachment ID taken from a record's imageattachmentids field (Get Record by ID), not the record ID.",+ idempotent: true,+ },+ outputSchema: downloadAttachmentSchema,+ props: {+ attachmentId: Property.ShortText({+ displayName: 'Attachment ID',+ description: "Value from the record's imageattachmentids field.",+ required: true,+ }),+ },+ async run({ auth, propsValue, files }) {+ const id = assertAttachmentId(propsValue.attachmentId);+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'files_retrieve',+ query: { id },+ });+ const item = pickAttachment(result);+ const contents = String(item['filecontents']);+ if (contents.length > MAX_BASE64_LENGTH) {+ throw new Error('The attachment is larger than 25 MB and cannot be downloaded by this action');+ }+ const data = Buffer.from(contents, 'base64');+ const fileName = typeof item['filename'] === 'string' && item['filename'] !== '' ? item['filename'] : `attachment-${id}`;+ const file = await files.write({ fileName, data });+ return {+ attachmentId: id,+ fileName,+ fileType: typeof item['filetype'] === 'string' ? item['filetype'] : '',+ fileSize: data.length,+ file,+ };+ },+});++const MAX_BASE64_LENGTH = Math.ceil((25 * 1024 * 1024 * 4) / 3);diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/find-or-create-record.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/find-or-create-record.tsnew file mode 100644index 00000000000..cf5b70ee891--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/find-or-create-record.ts@@ -0,0 +1,74 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { fieldsJsonProp, moduleProp, recordOutput, requiredText } from '../../ai-common';+import { recordFromJson } from '../../common';+import { findOrCreateSchema } from '../../output-schemas';+import { VtigerCredentials } from '../../rest-client';+import { assertFieldName, assertModuleName } from '../../vtql';+import { createModuleRecord } from './create-module-record';+import { searchModule } from './search-module-records';++export async function findOrCreate({+ creds,+ module,+ matchField,+ matchValue,+ fields,+}: {+ creds: VtigerCredentials;+ module: unknown;+ matchField: unknown;+ matchValue: unknown;+ fields: unknown;+}) {+ const name = assertModuleName(module);+ const field = assertFieldName(matchField);+ const value = requiredText({ value: matchValue, label: 'Match Value' });+ const extra = recordFromJson({ value: fields, label: 'Fields' });+ const { records } = await searchModule({+ creds,+ module: name,+ filters: [{ field, value, operator: '=' }],+ limit: 2,+ });+ if (records.length > 0) {+ return { created: false, matchCount: records.length, ...recordOutput(records[0]) };+ }+ const record = await createModuleRecord({ creds, module: name, fields: { ...extra, [field]: value } });+ return { created: true, matchCount: 0, ...recordOutput(record) };+}++export const findOrCreateRecordAction = createAction({+ auth: vtigerAuth,+ name: 'find_or_create_record',+ displayName: 'Find or Create Record',+ description: 'Returns the record whose field equals a value, or creates it when none exists.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Looks up a record in a module by one field (exact match, e.g. email) and returns the first match; only when nothing matches it creates a record with that value plus the given fields. Safe to retry only when the match field is unique in Vtiger; two concurrent calls can both create.',+ idempotent: false,+ },+ outputSchema: findOrCreateSchema,+ props: {+ module: moduleProp(),+ matchField: Property.ShortText({+ displayName: 'Match Field',+ description: 'Field API name to match on, for example email.',+ required: true,+ }),+ matchValue: Property.ShortText({+ displayName: 'Match Value',+ description: 'Value the field must equal exactly.',+ required: true,+ }),+ fields: fieldsJsonProp({+ description: 'JSON of fields used only when a record is created; include the mandatory fields, for example {"lastname": "Smith"}.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return findOrCreate({ creds: auth.props, ...propsValue });+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/find-records-by-email-or-phone.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/find-records-by-email-or-phone.tsnew file mode 100644index 00000000000..e317218a7a5--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/find-records-by-email-or-phone.ts@@ -0,0 +1,79 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordList, requiredText } from '../../ai-common';+import { recordListSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertModuleName } from '../../vtql';++export function lookupQuery({+ type,+ value,+ modules,+}: {+ type: unknown;+ value: unknown;+ modules: unknown;+}): Record<string, string> {+ if (type !== 'email' && type !== 'phone') {+ throw new Error('Lookup Type must be email or phone');+ }+ const names = Array.isArray(modules)+ ? modules.filter((m) => typeof m === 'string' && m.trim() !== '').map((m) => assertModuleName(m))+ : [];+ return {+ type,+ value: requiredText({ value, label: 'Value' }),+ searchIn: JSON.stringify(names.length > 0 ? names : DEFAULT_LOOKUP_MODULES),+ };+}++export const findRecordsByEmailOrPhoneAction = createAction({+ auth: vtigerAuth,+ name: 'find_records_by_email_or_phone',+ displayName: 'Find Records by Email or Phone',+ description: 'Finds Contacts, Leads or Accounts that have a given email address or phone number.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Looks up records by an email address or phone number across every email or phone field of the chosen modules (default Contacts, Leads, Accounts). Prefer it over Search Module Records when you only have an email or phone and do not know which field or module holds it.',+ idempotent: true,+ },+ outputSchema: recordListSchema,+ props: {+ type: Property.StaticDropdown({+ displayName: 'Lookup Type',+ required: true,+ defaultValue: 'email',+ options: {+ options: [+ { label: 'Email', value: 'email' },+ { label: 'Phone', value: 'phone' },+ ],+ },+ }),+ value: Property.ShortText({+ displayName: 'Value',+ description: 'The email address or phone number to look for.',+ required: true,+ }),+ modules: Property.Array({+ displayName: 'Modules',+ description: 'Module API names to search in. Defaults to Contacts, Leads and Accounts.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'lookup',+ query: lookupQuery({ type: propsValue.type, value: propsValue.value, modules: propsValue.modules }),+ });+ const records = recordList(result);+ return { records, count: records.length };+ },+});++const DEFAULT_LOOKUP_MODULES = ['Contacts', 'Leads', 'Accounts'];diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/get-account-hierarchy.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/get-account-hierarchy.tsnew file mode 100644index 00000000000..c49d4d236af--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/get-account-hierarchy.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp } from '../../ai-common';+import { accountHierarchySchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const getAccountHierarchyAction = createAction({+ auth: vtigerAuth,+ name: 'get_account_hierarchy',+ displayName: 'Get Account Hierarchy',+ description: 'Returns the parent and child accounts of an Organization.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the account hierarchy (parent and member organizations) around one Accounts (Organizations) record. Only works with Accounts IDs.',+ idempotent: true,+ },+ outputSchema: accountHierarchySchema,+ props: {+ accountId: recordIdProp({+ displayName: 'Account ID',+ description: 'Webservice ID of an Accounts (Organizations) record, for example 11x42.',+ }),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.accountId, label: 'Account ID' });+ const hierarchy = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'get_account_hierarchy',+ query: { id },+ });+ return { accountId: id, hierarchy };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/get-current-user.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/get-current-user.tsnew file mode 100644index 00000000000..a99e717a840--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/get-current-user.ts@@ -0,0 +1,24 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { currentUserSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';++export const getCurrentUserAction = createAction({+ auth: vtigerAuth,+ name: 'get_current_user',+ displayName: 'Get Current User',+ description: 'Returns the Vtiger user the connection authenticates as.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the profile of the connected Vtiger user (webservice user ID, name, email, role, time zone, date format). Use it to get your own user ID for assigned_user_id fields or to read the user time zone before interpreting record timestamps.',+ idempotent: true,+ },+ outputSchema: currentUserSchema,+ props: {},+ async run({ auth }) {+ return vtigerRest<Record<string, unknown>>({ creds: auth.props, method: HttpMethod.GET, path: 'me' });+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/get-picklist-dependency.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/get-picklist-dependency.tsnew file mode 100644index 00000000000..663440db744--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/get-picklist-dependency.ts@@ -0,0 +1,50 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { moduleProp } from '../../ai-common';+import { picklistDependencySchema } from '../../output-schemas';+import { fetchPicklistDependency, isRecord } from '../../rest-client';+import { assertFieldName, assertModuleName } from '../../vtql';++export function toMappings(result: unknown): { sourceValue: string; targetValues: string[] }[] {+ const rows = isRecord(result) && Array.isArray(result['valuemapping']) ? result['valuemapping'] : [];+ return rows.filter(isRecord).map((row) => ({+ sourceValue: String(row['sourcevalue'] ?? ''),+ targetValues: Array.isArray(row['targetvalues']) ? row['targetvalues'].map((v) => String(v)) : [],+ }));+}++export const getPicklistDependencyAction = createAction({+ auth: vtigerAuth,+ name: 'get_picklist_dependency',+ displayName: 'Get Picklist Dependency',+ description: 'Returns which target picklist values are allowed for each source picklist value.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the picklist dependency between two picklist fields of a module: for each source value, the target values Vtiger allows. Use it before setting dependent picklists so the update is accepted. hasDependency is false and mappings is empty when no dependency is configured for the pair.',+ idempotent: true,+ },+ outputSchema: picklistDependencySchema,+ props: {+ module: moduleProp(),+ sourceField: Property.ShortText({+ displayName: 'Source Field',+ description: 'API name of the controlling picklist field (from Describe Module).',+ required: true,+ }),+ targetField: Property.ShortText({+ displayName: 'Target Field',+ description: 'API name of the dependent picklist field (from Describe Module).',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const module = assertModuleName(propsValue.module);+ const sourceField = assertFieldName(propsValue.sourceField);+ const targetField = assertFieldName(propsValue.targetField);+ const dependency = await fetchPicklistDependency({ creds: auth.props, module, sourceField, targetField });+ const mappings = toMappings(dependency);+ return { module, sourceField, targetField, hasDependency: mappings.length > 0, mappings };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-by-id.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-by-id.tsnew file mode 100644index 00000000000..fbce126cd75--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-by-id.ts@@ -0,0 +1,34 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, recordOutput } from '../../ai-common';+import { aiRecordSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const getRecordByIdAction = createAction({+ auth: vtigerAuth,+ name: 'get_record_by_id',+ displayName: 'Get Record by ID',+ description: 'Retrieves one Vtiger record by its webservice ID.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetches every field of one Vtiger record from its webservice ID (e.g. 12x345); the module is implied by the ID prefix. Use it when you already have the ID; to find a record by field values use Search Module Records.',+ idempotent: true,+ },+ outputSchema: aiRecordSchema,+ props: {+ recordId: recordIdProp(),+ },+ async run({ auth, propsValue }) {+ const record = await vtigerRest<Record<string, unknown>>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'retrieve',+ query: { id: assertRecordId({ value: propsValue.recordId }) },+ });+ return recordOutput(record);+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-tags.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-tags.tsnew file mode 100644index 00000000000..84a234435de--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/get-record-tags.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp } from '../../ai-common';+import { recordTagsSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export function tagNames(result: unknown): string[] {+ const list = Array.isArray(result)+ ? result+ : isRecord(result) && Array.isArray(result['tags'])+ ? result['tags']+ : [];+ return list.flatMap((tag): string[] => {+ if (typeof tag === 'string') {+ return [tag];+ }+ if (isRecord(tag)) {+ const name = tag['tag'] ?? tag['name'];+ return typeof name === 'string' ? [name] : [];+ }+ return [];+ });+}++export const getRecordTagsAction = createAction({+ auth: vtigerAuth,+ name: 'get_record_tags',+ displayName: 'Get Record Tags',+ description: 'Lists the tags on a Vtiger record.',+ classification: 'READ',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the tags attached to one Vtiger record. Use it to check tags before adding or removing them.',+ idempotent: true,+ },+ outputSchema: recordTagsSchema,+ props: {+ recordId: recordIdProp(),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.recordId });+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'tags_retrieve',+ query: { id },+ });+ const tags = tagNames(result);+ return { recordId: id, tags, count: tags.length };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/link-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/link-records.tsnew file mode 100644index 00000000000..15814abed74--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/link-records.ts@@ -0,0 +1,58 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, requiredText } from '../../ai-common';+import { linkResultSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export function linkForm({+ sourceRecordId,+ relatedRecordId,+ relationLabel,+}: {+ sourceRecordId: unknown;+ relatedRecordId: unknown;+ relationLabel: unknown;+}): Record<string, string> {+ return {+ sourceRecordId: assertRecordId({ value: sourceRecordId, label: 'Source Record ID' }),+ relatedRecordId: assertRecordId({ value: relatedRecordId, label: 'Related Record ID' }),+ relationIdLabel: requiredText({ value: relationLabel, label: 'Relation Label' }),+ };+}++export const linkRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'link_records',+ displayName: 'Link Records',+ description: 'Adds a record to a related list of another record.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Links two existing records through a relation, e.g. adds a Contact to an Account or a Document to a Ticket. Take the relation label from List Relation Types for the source module. Linking a pair that is already linked succeeds and changes nothing.',+ idempotent: true,+ },+ outputSchema: linkResultSchema,+ props: {+ sourceRecordId: recordIdProp({ displayName: 'Source Record ID', description: 'Webservice ID of the parent record.' }),+ relatedRecordId: recordIdProp({ displayName: 'Related Record ID', description: 'Webservice ID of the record to add.' }),+ relationLabel: Property.ShortText({+ displayName: 'Relation Label',+ description: 'Relation label from List Relation Types, for example Contacts.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const form = linkForm(propsValue);+ const result = await vtigerRest<unknown>({ creds: auth.props, method: HttpMethod.POST, path: 'add_related', form });+ return {+ sourceRecordId: form['sourceRecordId'],+ relatedRecordId: form['relatedRecordId'],+ relationLabel: form['relationIdLabel'],+ linked: true,+ result,+ };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/list-changed-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/list-changed-records.tsnew file mode 100644index 00000000000..8db76220fe2--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/list-changed-records.ts@@ -0,0 +1,80 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { moduleProp, toUnixSeconds } from '../../ai-common';+import { changedRecordsSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertModuleName } from '../../vtql';++export function shapeSync(result: unknown) {+ const value = isRecord(result) ? result : {};+ const ids = (list: unknown): string[] =>+ Array.isArray(list)+ ? list.flatMap((item): string[] =>+ typeof item === 'string'+ ? [item]+ : isRecord(item) && typeof item['id'] === 'string'+ ? [item['id']]+ : []+ )+ : [];+ const updated = ids(value['updated']);+ const deleted = ids(value['deleted']);+ return {+ updatedIds: updated,+ deletedIds: deleted,+ updatedCount: updated.length,+ deletedCount: deleted.length,+ more: value['more'] === true,+ lastModifiedTime: Number(value['lastModifiedTime'] ?? 0) || 0,+ };+}++export const listChangedRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'list_changed_records',+ displayName: 'List Changed Records',+ description: 'Lists record IDs created, updated or deleted in a module since a point in time.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the IDs of records in one module that changed or were deleted since a timestamp, using the Vtiger sync API. When more is true, call again with lastModifiedTime as Modified Since to continue. Fetch full records with Get Record by ID.',+ idempotent: true,+ },+ outputSchema: changedRecordsSchema,+ props: {+ module: moduleProp(),+ modifiedSince: Property.ShortText({+ displayName: 'Modified Since',+ description: 'Unix seconds (e.g. 1735689600) or an ISO 8601 date such as 2026-01-01T00:00:00Z.',+ required: true,+ }),+ syncType: Property.StaticDropdown({+ displayName: 'Scope',+ description: 'Which records to include.',+ required: false,+ defaultValue: 'application',+ options: {+ options: [+ { value: 'application', label: 'All records' },+ { value: 'userandgroup', label: "User's and user's groups' records" },+ { value: 'user', label: "User's records only" },+ ],+ },+ }),+ },+ async run({ auth, propsValue }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'sync',+ query: {+ modifiedTime: String(toUnixSeconds(propsValue.modifiedSince)),+ elementType: assertModuleName(propsValue.module),+ syncType: propsValue.syncType || 'application',+ },+ });+ return shapeSync(result);+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/list-modules.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/list-modules.tsnew file mode 100644index 00000000000..74c994d11ee--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/list-modules.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { listModulesSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';++export function shapeModules(result: unknown): { modules: ModuleSummary[]; count: number } {+ const types = isRecord(result) && Array.isArray(result['types']) ? result['types'] : [];+ const information = isRecord(result) && isRecord(result['information']) ? result['information'] : {};+ const modules = types+ .filter((name): name is string => typeof name === 'string')+ .map((name) => {+ const info = isRecord(information[name]) ? information[name] : {};+ return {+ name,+ label: typeof info['label'] === 'string' ? info['label'] : name,+ singular: typeof info['singular'] === 'string' ? info['singular'] : '',+ isEntity: info['isEntity'] === true || info['isEntity'] === '1' || info['isEntity'] === 1,+ };+ });+ return { modules, count: modules.length };+}++export const listModulesAction = createAction({+ auth: vtigerAuth,+ name: 'list_modules',+ displayName: 'List Modules',+ description: 'Lists the Vtiger modules the connected user can access.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists every Vtiger module (element type) visible to the connected user with its API name and label. Call this first to find the exact module name (e.g. Accounts for Organizations, Potentials for Deals) that the other actions take.',+ idempotent: true,+ },+ outputSchema: listModulesSchema,+ props: {},+ async run({ auth }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'listtypes',+ query: { fieldTypeList: 'null' },+ });+ return shapeModules(result);+ },+});++type ModuleSummary = { name: string; label: string; singular: string; isEntity: boolean };diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/list-related-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/list-related-records.tsnew file mode 100644index 00000000000..bdc9b68c169--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/list-related-records.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, recordList, requiredText } from '../../ai-common';+import { recordListSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertModuleName, assertRecordId } from '../../vtql';++export const listRelatedRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'list_related_records',+ displayName: 'List Related Records',+ description: 'Lists the records in one related list of a Vtiger record.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the records in one related list of a record, e.g. the Contacts of an Account. Take the relation label and related module from List Relation Types for the record's module. Use Query Related Records when you need paging.",+ idempotent: true,+ },+ outputSchema: recordListSchema,+ props: {+ recordId: recordIdProp({ description: 'Webservice ID of the parent record, for example 11x42.' }),+ relatedLabel: Property.ShortText({+ displayName: 'Relation Label',+ description: 'The relation label from List Relation Types (its label, not the translated label), for example Contacts or Activities.',+ required: true,+ }),+ relatedModule: Property.ShortText({+ displayName: 'Related Module',+ description: 'API name of the related module, for example Contacts.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'retrieve_related',+ query: {+ id: assertRecordId({ value: propsValue.recordId }),+ relatedLabel: requiredText({ value: propsValue.relatedLabel, label: 'Relation Label' }),+ relatedType: assertModuleName(propsValue.relatedModule),+ },+ });+ const records = recordList(result);+ return { records, count: records.length };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/list-relation-types.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/list-relation-types.tsnew file mode 100644index 00000000000..8d5c6ca17d7--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/list-relation-types.ts@@ -0,0 +1,65 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { moduleProp } from '../../ai-common';+import { relationTypesSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertModuleName } from '../../vtql';++export function shapeRelations(result: unknown): { relations: RelationSummary[]; count: number } {+ const information = isRecord(result) && isRecord(result['information']) ? result['information'] : {};+ const relations = Object.entries(information).flatMap(([key, info]): RelationSummary[] => {+ if (!isRecord(info)) {+ return [];+ }+ return [+ {+ relationId: text(info['relation_id']) || key,+ relatedModule: text(info['name']),+ relationLabel: text(info['label']),+ translatedLabel: text(info['translated_label']),+ actions: text(info['actions']).toLowerCase(),+ },+ ];+ });+ return { relations, count: relations.length };+}++function text(value: unknown): string {+ return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '';+}++export const listRelationTypesAction = createAction({+ auth: vtigerAuth,+ name: 'list_relation_types',+ displayName: 'List Relation Types',+ description: 'Lists the related lists (relations) a Vtiger module has.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the relations of a Vtiger module (e.g. Accounts to Contacts, Potentials, Documents) with their labels and related modules. Call it to get the relation label (relationLabel, not translatedLabel) and related module that Link Records, List Related Records and Query Related Records need.',+ idempotent: true,+ },+ outputSchema: relationTypesSchema,+ props: {+ module: moduleProp({ description: 'API name of the source module, for example Accounts.' }),+ },+ async run({ auth, propsValue }) {+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'relatedtypes',+ query: { elementType: assertModuleName(propsValue.module) },+ });+ return shapeRelations(result);+ },+});++type RelationSummary = {+ relationId: string;+ relatedModule: string;+ relationLabel: string;+ translatedLabel: string;+ actions: string;+};diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/query-related-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/query-related-records.tsnew file mode 100644index 00000000000..5327f8f243b--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/query-related-records.ts@@ -0,0 +1,92 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, recordList, requiredText } from '../../ai-common';+import { pagedRecordListSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertModuleName, assertRecordId, clampLimit, VTQL_PAGE_SIZE } from '../../vtql';++export function relatedQueryParams({+ recordId,+ relatedModule,+ relatedLabel,+ limit,+ offset,+}: {+ recordId: unknown;+ relatedModule: unknown;+ relatedLabel: unknown;+ limit: unknown;+ offset: unknown;+}): { query: Record<string, string>; limit: number; offset: number } {+ const module = assertModuleName(relatedModule);+ const size = clampLimit({ value: limit, fallback: VTQL_PAGE_SIZE, max: VTQL_PAGE_SIZE });+ const start = offset === undefined || offset === null || offset === '' ? 0 : Number(offset);+ if (!Number.isInteger(start) || start < 0) {+ throw new Error('Offset must be a whole number of 0 or more');+ }+ const label = requiredText({ value: relatedLabel, label: 'Relation Label' });+ return {+ query: {+ query: `SELECT * FROM ${module} LIMIT ${start}, ${size}`,+ id: assertRecordId({ value: recordId }),+ relatedLabel: label,+ },+ limit: size,+ offset: start,+ };+}++export const queryRelatedRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'query_related_records',+ displayName: 'Query Related Records',+ description: 'Pages through the related records of one module linked to a Vtiger record.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one page (up to 100) of the records of a related module linked to a record, e.g. Potentials of an Account. When hasMore is true, call again with offset + limit. Take the relation label and related module from List Relation Types; they differ for some relations (Calendar is labelled Activities).',+ idempotent: true,+ },+ outputSchema: pagedRecordListSchema,+ props: {+ recordId: recordIdProp({ description: 'Webservice ID of the parent record, for example 11x42.' }),+ relatedModule: Property.ShortText({+ displayName: 'Related Module',+ description: 'API name of the related module, for example Contacts.',+ required: true,+ }),+ relatedLabel: Property.ShortText({+ displayName: 'Relation Label',+ description: 'The relation label from List Relation Types (its label, not the translated label), for example Contacts or Activities.',+ required: true,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Records per page, 1 to 100 (default 100).',+ required: false,+ }),+ offset: Property.Number({+ displayName: 'Offset',+ description: 'Number of records to skip (default 0).',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const params = relatedQueryParams(propsValue);+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.GET,+ path: 'query_related',+ query: params.query,+ });+ const records = recordList(result);+ return {+ records,+ count: records.length,+ offset: params.offset,+ hasMore: records.length >= params.limit,+ };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/remove-tags-from-record.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/remove-tags-from-record.tsnew file mode 100644index 00000000000..a3955d497e6--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/remove-tags-from-record.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp, stringList } from '../../ai-common';+import { tagChangeSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const removeTagsFromRecordAction = createAction({+ auth: vtigerAuth,+ name: 'remove_tags_from_record',+ displayName: 'Remove Tags from Record',+ description: 'Removes tags from one Vtiger record.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes one or more tags from a single record only; the tags stay on other records and can be re-added with Add Tags to Record. Removing a tag the record does not have changes nothing.',+ idempotent: true,+ },+ outputSchema: tagChangeSchema,+ props: {+ recordId: recordIdProp(),+ tags: Property.Array({+ displayName: 'Tags',+ description: 'Tag names to remove from this record.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.recordId });+ const tags = stringList({ value: propsValue.tags, label: 'Tags' });+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.POST,+ path: 'tags_delete',+ form: { id, tags: JSON.stringify(tags), delete_all: 'false' },+ });+ return { recordId: id, tags, message: isRecord(result) && typeof result['message'] === 'string' ? result['message'] : '' };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/reopen-record.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/reopen-record.tsnew file mode 100644index 00000000000..e957e5e95f7--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/reopen-record.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp } from '../../ai-common';+import { reopenRecordSchema } from '../../output-schemas';+import { isRecord, vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const reopenRecordAction = createAction({+ auth: vtigerAuth,+ name: 'reopen_record',+ displayName: 'Reopen Record',+ description: 'Reopens a closed Vtiger record such as a won or lost deal.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Reopens a closed record by webservice ID, for example a deal in Closed Won or Closed Lost (its isclosed field is 1). Vtiger returns HTTP 400 when the record is not closed, including a Case whose status was only set to Closed. Requires permission to edit the record.',+ idempotent: false,+ },+ outputSchema: reopenRecordSchema,+ props: {+ recordId: recordIdProp(),+ },+ async run({ auth, propsValue }) {+ const id = assertRecordId({ value: propsValue.recordId });+ const result = await vtigerRest<unknown>({ creds: auth.props, method: HttpMethod.POST, path: 'reopen', form: { id } });+ const message = isRecord(result) && typeof result['message'] === 'string' ? result['message'] : '';+ return { id, reopened: true, message };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/search-module-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/search-module-records.tsnew file mode 100644index 00000000000..3ba1e50422c--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/search-module-records.ts@@ -0,0 +1,96 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { fieldsJsonProp, moduleProp, recordList } from '../../ai-common';+import { recordFromJson } from '../../common';+import { searchRecordListSchema } from '../../output-schemas';+import { VtigerCredentials, vtigerRest } from '../../rest-client';+import {+ assertModuleName,+ buildWhere,+ clampLimit,+ filterValueToString,+ pagedQuery,+ VtqlFilter,+} from '../../vtql';++const SEARCH_MAX = 1000;++export function filtersFromJson({ value, match }: { value: unknown; match: unknown }): VtqlFilter[] {+ const fields = recordFromJson({ value, label: 'Filters' });+ return Object.entries(fields).flatMap(([field, raw]): VtqlFilter[] => {+ const text = filterValueToString(raw);+ if (text === undefined) {+ return [];+ }+ return [{ field, value: text, operator: match === 'contains' && typeof raw === 'string' ? 'LIKE' : '=' }];+ });+}++export async function searchModule({+ creds,+ module,+ filters,+ limit,+}: {+ creds: VtigerCredentials;+ module: string;+ filters: VtqlFilter[];+ limit: number;+}) {+ return pagedQuery<Record<string, unknown>>({+ module: assertModuleName(module),+ where: buildWhere({ filters }),+ limit,+ fetchPage: async (query) =>+ recordList(await vtigerRest<unknown>({ creds, method: HttpMethod.GET, path: 'query', query: { query } })),+ });+}++export const searchModuleRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'search_module_records',+ displayName: 'Search Module Records',+ description: 'Finds records in a Vtiger module whose fields match the given values.',+ classification: 'SEARCH',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Finds records in one module whose fields match all given values, filtered server-side. Exact match by default; contains does a substring match on text values. With no filters it lists records. Use Describe Module for field names and Query Records for OR conditions or sorting.',+ idempotent: true,+ },+ outputSchema: searchRecordListSchema,+ props: {+ module: moduleProp(),+ filters: fieldsJsonProp({+ displayName: 'Filters',+ description: 'JSON object of field API name to value, for example {"lastname": "Smith", "leadsource": "Web Site"}.',+ required: false,+ }),+ match: Property.StaticDropdown({+ displayName: 'Match',+ required: false,+ defaultValue: 'exact',+ options: {+ options: [+ { label: 'Exact', value: 'exact' },+ { label: 'Contains (text values)', value: 'contains' },+ ],+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: `Maximum records to return, 1 to ${SEARCH_MAX} (default 100).`,+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const { records, hasMore } = await searchModule({+ creds: auth.props,+ module: propsValue.module,+ filters: filtersFromJson({ value: propsValue.filters, match: propsValue.match }),+ limit: clampLimit({ value: propsValue.limit, fallback: 100, max: SEARCH_MAX }),+ });+ return { records, count: records.length, hasMore };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/unlink-records.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/unlink-records.tsnew file mode 100644index 00000000000..674905fca82--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/unlink-records.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { recordIdProp } from '../../ai-common';+import { unlinkResultSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export const unlinkRecordsAction = createAction({+ auth: vtigerAuth,+ name: 'unlink_records',+ displayName: 'Unlink Records',+ description: 'Removes a record from a related list of another record. Both records stay.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes the link between two records (e.g. takes a Contact off an Account) without deleting either record; Link Records restores it. Unlinking a pair that is not linked succeeds and changes nothing.',+ idempotent: true,+ },+ outputSchema: unlinkResultSchema,+ props: {+ sourceRecordId: recordIdProp({ displayName: 'Source Record ID', description: 'Webservice ID of the parent record.' }),+ relatedRecordId: recordIdProp({ displayName: 'Related Record ID', description: 'Webservice ID of the linked record.' }),+ },+ async run({ auth, propsValue }) {+ const sourceRecordId = assertRecordId({ value: propsValue.sourceRecordId, label: 'Source Record ID' });+ const relatedRecordId = assertRecordId({ value: propsValue.relatedRecordId, label: 'Related Record ID' });+ const result = await vtigerRest<unknown>({+ creds: auth.props,+ method: HttpMethod.POST,+ path: 'delete_related',+ form: { sourceRecordId, relatedRecordId },+ });+ return { sourceRecordId, relatedRecordId, unlinked: true, result };+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/ai/update-record-fields.ts b/packages/pieces/community/vtiger/src/lib/actions/ai/update-record-fields.tsnew file mode 100644index 00000000000..ce3598dd880--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/actions/ai/update-record-fields.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../../auth';+import { fieldsJsonProp, recordIdProp, recordOutput } from '../../ai-common';+import { recordFromJson } from '../../common';+import { aiRecordSchema } from '../../output-schemas';+import { vtigerRest } from '../../rest-client';+import { assertRecordId } from '../../vtql';++export function reviseElement({ recordId, fields }: { recordId: unknown; fields: unknown }): string {+ const id = assertRecordId({ value: recordId });+ const values = recordFromJson({ value: fields, label: 'Fields' });+ const { id: givenId, ...rest } = values;+ if (givenId !== undefined && givenId !== id) {+ throw new Error('Fields contains an id different from Record ID');+ }+ if (Object.keys(rest).length === 0) {+ throw new Error('Fields must contain at least one field to change');+ }+ return JSON.stringify({ ...rest, id });+}++export const updateRecordFieldsAction = createAction({+ auth: vtigerAuth,+ name: 'update_record_fields',+ displayName: 'Update Record Fields',+ description: 'Changes only the given fields of a Vtiger record.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the fields you pass on one record (Vtiger revise); every other field keeps its value and mandatory fields need not be restated. Send an empty string to clear a field. Re-running with the same values leaves the record unchanged.',+ idempotent: true,+ },+ outputSchema: aiRecordSchema,+ props: {+ recordId: recordIdProp(),+ fields: fieldsJsonProp({+ description: 'JSON object of only the fields to change, for example {"leadstatus": "Contacted"}.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const record = await vtigerRest<Record<string, unknown>>({+ creds: auth.props,+ method: HttpMethod.POST,+ path: 'revise',+ form: { element: reviseElement({ recordId: propsValue.recordId, fields: propsValue.fields }) },+ });+ return recordOutput(record);+ },+});diff --git a/packages/pieces/community/vtiger/src/lib/actions/create-record.ts b/packages/pieces/community/vtiger/src/lib/actions/create-record.tsindex 202a29339ae..0ad1e83cc2b 100644--- a/packages/pieces/community/vtiger/src/lib/actions/create-record.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/create-record.ts@@ -1,11 +1,9 @@-import { HttpMethod, httpClient } from '@activepieces/pieces-common';import { createAction } from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import { instanceLogin, recordProperty } from '../common';-import { elementTypeProperty } from '../common';--//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+import { vtigerAuth } from '../auth';+import { elementTypeProperty, propText, recordProperty } from '../common';+import { originalRecordEnvelopeSchema } from '../output-schemas';+import { assertModuleName } from '../vtql';+import { vtwsCall, vtwsLogin } from '../vtws';export const createRecord = createAction({name: 'create_record',@@ -13,37 +11,25 @@ export const createRecord = createAction({auth: vtigerAuth,displayName: 'Create Record',description: 'Create a Record',- audience: 'both',- aiMetadata: { description: 'Creates a new record of a given Vtiger module (element type, e.g. Contacts, Leads, Accounts) with the supplied field values. Choose this to add a new CRM entity. Each call inserts a new record, so repeated calls create duplicates.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new record of a given Vtiger module (element type, e.g. Contacts, Leads, Accounts) with the supplied field values. Choose this to add a new CRM entity. Each call inserts a new record, so repeated calls create duplicates.',+ idempotent: false,+ },+ outputSchema: originalRecordEnvelopeSchema,props: {elementType: elementTypeProperty,record: recordProperty(),},async run({ propsValue: { elementType, record }, auth }) {- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );-- if (instance !== null) {- const response = await httpClient.sendRequest<Record<string, unknown>[]>({- method: HttpMethod.POST,- url: `${auth.props.instance_url}/webservice.php`,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: {- operation: 'create',- sessionName: instance.sessionId ?? instance.sessionName,- elementType: elementType,- element: JSON.stringify(record),- },- });-- return response.body;- }-- return null;+ const module = assertModuleName(propText(elementType));+ const session = await vtwsLogin(auth.props);+ return vtwsCall<Record<string, unknown>>({+ creds: auth.props,+ session,+ operation: 'create',+ params: { elementType: module, element: JSON.stringify(record ?? {}) },+ });},});diff --git a/packages/pieces/community/vtiger/src/lib/actions/delete-record.ts b/packages/pieces/community/vtiger/src/lib/actions/delete-record.tsindex fdaff247cae..9ae4bc9df95 100644--- a/packages/pieces/community/vtiger/src/lib/actions/delete-record.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/delete-record.ts@@ -1,11 +1,9 @@-import { HttpMethod, httpClient } from '@activepieces/pieces-common';import { createAction } from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import { instanceLogin, recordIdProperty } from '../common';-import { elementTypeProperty } from '../common';--//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+import { vtigerAuth } from '../auth';+import { elementTypeProperty, propText, recordIdProperty } from '../common';+import { originalDeleteEnvelopeSchema } from '../output-schemas';+import { assertModuleName, assertRecordId } from '../vtql';+import { vtwsCall, vtwsLogin } from '../vtws';export const deleteRecord = createAction({name: 'delete_record',@@ -13,36 +11,26 @@ export const deleteRecord = createAction({auth: vtigerAuth,displayName: 'Delete Record',description: 'Delete a Record',- audience: 'both',- aiMetadata: { description: 'Deletes a Vtiger record by its id within a given module (element type). Choose this to remove a known record. Idempotent in effect: once deleted, repeating the call leaves the record absent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Deletes a Vtiger record by its id within a given module (element type). Choose this to remove a known record. Deleting an id that no longer exists fails the step.',+ idempotent: false,+ },+ outputSchema: originalDeleteEnvelopeSchema,props: {elementType: elementTypeProperty,record: recordIdProperty(),},- async run({- propsValue: { elementType, record },- auth- }) {- const instance = await instanceLogin(auth.props.instance_url, auth.props.username, auth.props.password);-- if (instance !== null) {- const response = await httpClient.sendRequest<Record<string, unknown>[]>({- method: HttpMethod.POST,- url: `${auth.props.instance_url}/webservice.php`,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: {- operation: 'delete',- sessionName: instance.sessionId ?? instance.sessionName,- elementType,- id: record['id'],- },- });-- return response.body;- }-- return null;+ async run({ propsValue: { elementType, record }, auth }) {+ const module = assertModuleName(propText(elementType));+ const id = assertRecordId({ value: record?.['id'] });+ const session = await vtwsLogin(auth.props);+ return vtwsCall<Record<string, unknown>>({+ creds: auth.props,+ session,+ operation: 'delete',+ params: { elementType: module, id },+ });},});diff --git a/packages/pieces/community/vtiger/src/lib/actions/get-record.ts b/packages/pieces/community/vtiger/src/lib/actions/get-record.tsindex 182707b9436..436257988a6 100644--- a/packages/pieces/community/vtiger/src/lib/actions/get-record.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/get-record.ts@@ -1,11 +1,9 @@-import { HttpMethod, httpClient } from '@activepieces/pieces-common';import { createAction } from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import { instanceLogin, recordIdProperty } from '../common';-import { elementTypeProperty } from '../common';--//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+import { vtigerAuth } from '../auth';+import { elementTypeProperty, propText, recordIdProperty } from '../common';+import { originalRecordEnvelopeSchema } from '../output-schemas';+import { assertModuleName, assertRecordId } from '../vtql';+import { vtwsCall, vtwsLogin } from '../vtws';export const getRecord = createAction({name: 'get_record',@@ -13,33 +11,26 @@ export const getRecord = createAction({auth: vtigerAuth,displayName: 'Get Record',description: 'Get a Record by value',- audience: 'both',- aiMetadata: { description: 'Retrieves a single Vtiger record by its id within a given module (element type). Choose this when you already have the record id and need its current field values. Read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Retrieves a single Vtiger record by its id within a given module (element type). Choose this when you already have the record id and need its current field values. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: originalRecordEnvelopeSchema,props: {elementType: elementTypeProperty,record: recordIdProperty(),},- async run({- propsValue: { elementType, record },- auth- }) {- const instance = await instanceLogin(auth.props.instance_url, auth.props.username, auth.props.password);-- if (instance !== null) {- const response = await httpClient.sendRequest<Record<string, unknown>[]>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- operation: 'retrieve',- sessionName: instance.sessionId ?? instance.sessionName,- elementType: elementType as unknown as string,- ...record,- },- });-- return response.body;- }-- return null;+ async run({ propsValue: { elementType, record }, auth }) {+ const module = assertModuleName(propText(elementType));+ const id = assertRecordId({ value: record?.['id'] });+ const session = await vtwsLogin(auth.props);+ return vtwsCall<Record<string, unknown>>({+ creds: auth.props,+ session,+ operation: 'retrieve',+ params: { elementType: module, id },+ });},});diff --git a/packages/pieces/community/vtiger/src/lib/actions/make-api-call.ts b/packages/pieces/community/vtiger/src/lib/actions/make-api-call.tsindex ad4a576b7d9..fb6a4993920 100644--- a/packages/pieces/community/vtiger/src/lib/actions/make-api-call.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/make-api-call.ts@@ -1,17 +1,81 @@import { Property, createAction } from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import { instanceLogin } from '../common';import {- AuthenticationType,HttpHeaders,HttpMessageBody,HttpMethod,HttpRequest,httpClient,} from '@activepieces/pieces-common';--//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+import { vtigerAuth } from '../auth';+import {+ basicAuthorization,+ isRecord,+ normalizeInstanceUrl,+ restBaseUrl,+ verifiedTlsDispatcher,+ VtigerCredentials,+} from '../rest-client';+import { vtwsLogin } from '../vtws';++export function resolveCustomCallTarget({+ creds,+ url,+ urlPath,+}: {+ creds: VtigerCredentials;+ url?: string;+ urlPath?: string;+}): { url: string; useRestAuth: boolean } {+ const origin = normalizeInstanceUrl(creds.instance_url);+ const restBase = restBaseUrl(creds);+ if (urlPath && !urlPath.startsWith('/')) {+ throw new Error('URL path must start with a slash, example: /me, /listtypes, /describe');+ }+ if (url) {+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {+ const parsed = parseAbsolute(url);+ if (parsed.origin !== origin || parsed.username !== '' || parsed.password !== '') {+ throw new Error(+ `Absolute URLs must point to the connected instance (${origin}). Use a path such as /me instead.`+ );+ }+ return {+ url: parsed.toString(),+ useRestAuth: parsed.pathname.startsWith('/restapi/'),+ };+ }+ return { url: `${restBase}${url.startsWith('/') ? url : `/${url}`}`, useRestAuth: true };+ }+ if (urlPath) {+ return { url: `${restBase}${urlPath}`, useRestAuth: true };+ }+ return { url: `${origin}/webservice.php`, useRestAuth: false };+}++export function customApiCallAuthHeaders({+ creds,+ url,+}: {+ creds: VtigerCredentials;+ url: unknown;+}): { Authorization: string } {+ const value = typeof url === 'string' ? url.trim() : '';+ if (/^https?:\/\//i.test(value)) {+ const parsed = parseAbsolute(value);+ const restBase = new URL(restBaseUrl(creds));+ if (+ parsed.origin !== restBase.origin ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ !`${parsed.pathname}/`.startsWith(`${restBase.pathname}/`)+ ) {+ throw new Error(+ `Absolute URLs must point to the connected instance's REST API (${restBase.toString()}). Use a relative path such as /me instead.`+ );+ }+ }+ return { Authorization: basicAuthorization(creds) };+}export const makeAPICall = createAction({name: 'make_api_call',@@ -19,8 +83,12 @@ export const makeAPICall = createAction({auth: vtigerAuth,displayName: 'Custom API Call (Deprecated)',description: 'Performs an arbitrary authorized API call. (Deprecated)',- audience: 'both',- aiMetadata: { description: 'Deprecated. Makes an arbitrary authenticated HTTP call to the Vtiger API, routing to either the legacy webservice.php endpoint or the REST base depending on the URL given. Prefer the dedicated record/query actions; reach for this only for endpoints they do not cover. Idempotency depends on the method and operation invoked, so treat write calls as non-idempotent.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Deprecated. Makes an arbitrary authenticated HTTP call to the connected Vtiger instance, routing to the legacy webservice.php endpoint or the REST base depending on the URL given. Prefer the dedicated actions. Treat write calls as non-idempotent.',+ idempotent: false,+ },props: {method: Property.StaticDropdown<HttpMethod>({displayName: 'Http Method',@@ -39,7 +107,7 @@ export const makeAPICall = createAction({url: Property.ShortText({displayName: 'URL',description:- 'Absolute URL or path. If a relative path is provided (e.g., /me, /listtypes, /describe), it will be called against the REST base.',+ 'Path (e.g. /me, /listtypes, /describe) called against the REST base, or an absolute URL on the connected instance.',required: false,}),urlPath: Property.ShortText({@@ -63,136 +131,67 @@ export const makeAPICall = createAction({},async run({ propsValue, auth }) {const method = propsValue.method ?? HttpMethod.GET;- const urlPath = propsValue.urlPath;- const url = propsValue.url;-- if (urlPath && !urlPath.startsWith('/')) {- return {- error:- 'URL path must start with a slash, example: /me, /listtypes, /describe',- };+ const target = resolveCustomCallTarget({+ creds: auth.props,+ url: propsValue.url,+ urlPath: propsValue.urlPath,+ });+ const headers = normalizeHeaders(propsValue.headers);+ const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === 'content-type');+ if (method !== HttpMethod.GET && !hasContentType) {+ headers['Content-Type'] = target.useRestAuth ? 'application/json' : 'application/x-www-form-urlencoded';}-- let finalUrl = `${auth.props.instance_url}/webservice.php`;- let useRestAuth = false;-- if (url) {- if (url.startsWith('http://') || url.startsWith('https://')) {- finalUrl = url;- } else if (url.startsWith('/')) {- finalUrl = `${auth.props.instance_url}/restapi/v1/vtiger/default${url}`;- useRestAuth = true;- } else {- finalUrl = `${auth.props.instance_url}/restapi/v1/vtiger/default/${url}`;- useRestAuth = true;- }- } else if (urlPath) {- finalUrl = `${auth.props.instance_url}/restapi/v1/vtiger/default${urlPath}`;- useRestAuth = true;+ const userData = isRecord(propsValue.data) ? propsValue.data : {};+ const data: Record<string, unknown> = target.useRestAuth+ ? userData+ : { ...userData, sessionName: (await vtwsLogin(auth.props)).sessionName };+ if (target.useRestAuth) {+ headers['Authorization'] = basicAuthorization(auth.props);}-- const normalizeHeaders = (h: unknown): HttpHeaders => {- const out: HttpHeaders = {};- if (h && typeof h === 'object' && !Array.isArray(h)) {- for (const [k, v] of Object.entries(h as Record<string, unknown>)) {- if (v === undefined || v === null) {- out[k] = undefined;- } else if (Array.isArray(v)) {- out[k] = (v as unknown[]).map((x) => String(x));- } else if (typeof v === 'string') {- out[k] = v;- } else {- out[k] = String(v);- }- }- }- return out;- };-- const headers: HttpHeaders = normalizeHeaders(propsValue.headers);-- if (useRestAuth) {- // Default JSON for REST when not GET and no explicit content-type provided- if (- method !== HttpMethod.GET &&- !Object.keys(headers).some(- (k) => k.toLowerCase() === 'content-type'- )- ) {- headers['Content-Type'] = 'application/json';- }- } else {- // webservice.php defaults to urlencoded for POST operations- if (- method !== HttpMethod.GET &&- !Object.keys(headers).some(- (k) => k.toLowerCase() === 'content-type'- )- ) {- headers['Content-Type'] = 'application/x-www-form-urlencoded';- }- }-- const httpRequest: HttpRequest<HttpMessageBody> = {- url: finalUrl,- method,- headers,- };-- let data: Record<string, unknown> = propsValue.data ?? {};-- const toQueryParams = (obj: Record<string, unknown>): Record<string, string> => {- const qp: Record<string, string> = {};- for (const [k, v] of Object.entries(obj ?? {})) {- if (v === undefined || v === null) continue;- qp[k] = typeof v === 'string' ? v : JSON.stringify(v);- }- return qp;- };-- if (useRestAuth) {- httpRequest.authentication = {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,- };- } else {- const vtigerInstance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (vtigerInstance === null) return;-- data = {- sessionName: vtigerInstance.sessionId ?? vtigerInstance.sessionName,- ...(propsValue.data ?? {}),- };- }-+ const request: HttpRequest<HttpMessageBody> = { url: target.url, method, headers };if (method === HttpMethod.GET) {- httpRequest['queryParams'] = toQueryParams(data);+ request.queryParams = toQueryParams(data);} else {- // For REST with JSON default, send raw object; else url-encodeconst contentType = Object.entries(headers).find(([k]) => k.toLowerCase() === 'content-type')?.[1];const ct = Array.isArray(contentType) ? contentType[0] : contentType;- if (useRestAuth && ct === 'application/json') {- httpRequest['body'] = data;- } else {- httpRequest['body'] = toQueryParams(data);- }+ request.body = target.useRestAuth && ct === 'application/json' ? data : toQueryParams(data);}-- const response = await httpClient.sendRequest<Record<string, unknown>[]>(- httpRequest- );-- if ([200, 201].includes(response.status)) {- return response.body;- }-- return {- error: 'Unexpected outcome!',- };+ const dispatcher = await verifiedTlsDispatcher();+ const response = await httpClient.sendRequest<HttpMessageBody>(request, { dispatcher });+ return response.body;},});++function parseAbsolute(url: string): URL {+ try {+ return new URL(url);+ } catch {+ throw new Error(`"${url}" is not a valid URL`);+ }+}++function normalizeHeaders(h: unknown): HttpHeaders {+ if (!isRecord(h)) {+ return {};+ }+ return Object.fromEntries(+ Object.entries(h)+ .filter(([k]) => k.toLowerCase() !== 'authorization')+ .map(([k, v]): [string, string | string[] | undefined] => [+ k,+ v === undefined || v === null+ ? undefined+ : Array.isArray(v)+ ? v.map((x) => String(x))+ : String(v),+ ])+ );+}++function toQueryParams(obj: Record<string, unknown>): Record<string, string> {+ return Object.fromEntries(+ Object.entries(obj)+ .filter(([, v]) => v !== undefined && v !== null)+ .map(([k, v]) => [k, typeof v === 'string' ? v : JSON.stringify(v)])+ );+}diff --git a/packages/pieces/community/vtiger/src/lib/actions/query-records.ts b/packages/pieces/community/vtiger/src/lib/actions/query-records.tsindex 9e0219f1cbf..47fcb58c6f0 100644--- a/packages/pieces/community/vtiger/src/lib/actions/query-records.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/query-records.ts@@ -1,15 +1,7 @@import { Property, createAction } from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import {- Operation,- elementTypeProperty,- instanceLogin,- prepareHttpRequest,-} from '../common';-import { httpClient } from '@activepieces/pieces-common';--//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+import { vtigerAuth } from '../auth';+import { queryRecordsSchema } from '../output-schemas';+import { vtwsLogin, vtwsQuery } from '../vtws';export const queryRecords = createAction({name: 'query_records',@@ -18,41 +10,26 @@ export const queryRecords = createAction({displayName: 'Query Records',description: 'Query records by SQL statement.',audience: 'both',- aiMetadata: { description: 'Runs a Vtiger VTQL/SQL-style read query (e.g. SELECT ... FROM Contacts) and returns matching records or aggregates such as count(*). Choose this when you need a custom filtered read with full control over columns, conditions, and limit rather than the simpler field-match Search. Read-only and idempotent.', idempotent: true },+ aiMetadata: {+ description:+ 'Runs a Vtiger VTQL read query (e.g. SELECT * FROM Contacts WHERE lastname = \'Smith\' LIMIT 0, 100;) and returns the matching rows or aggregates such as count(*). Choose this for custom conditions or columns that Search Module Records cannot express. Add LIMIT offset, count to page through large result sets. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: queryRecordsSchema,props: {query: Property.LongText({displayName: 'Query',description:- 'Enter the query statement, e.g. SELECT count(*) FROM Contacts;',+ 'Enter the query statement, e.g. SELECT count(*) FROM Contacts; Add LIMIT offset, count to page through large results.',required: true,}),},async run({ propsValue, auth }) {- const vtigerInstance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (vtigerInstance === null) return;-- const response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, unknown>[];- }>(- prepareHttpRequest(- auth.props.instance_url,- vtigerInstance.sessionId ?? vtigerInstance.sessionName,- 'query' as Operation,- { query: propsValue.query }- )- );-- if (response.body.success) {- return response.body.result;- } else {- return {- error: 'Unexpected outcome!',- };+ const query = propsValue.query.trim();+ if (query === '') {+ throw new Error('Query must not be empty');}+ const session = await vtwsLogin(auth.props);+ return vtwsQuery<Record<string, unknown>>({ creds: auth.props, session, query });},});diff --git a/packages/pieces/community/vtiger/src/lib/actions/search-record.ts b/packages/pieces/community/vtiger/src/lib/actions/search-record.tsindex 18d960ee38d..705bb5d025d 100644--- a/packages/pieces/community/vtiger/src/lib/actions/search-record.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/search-record.ts@@ -1,20 +1,31 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../auth';+import { elementTypeProperty, generateElementFields, propText } from '../common';+import { queryRecordsSchema } from '../output-schemas';import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import {- VTigerAuthValue,- queryRecords,- countRecords,- elementTypeProperty,- generateElementFields,- instanceLogin,-} from '../common';+ assertModuleName,+ buildWhere,+ clampLimit,+ filterValueToString,+ pagedQuery,+ VtqlFilter,+} from '../vtql';+import { vtwsLogin, vtwsQuery } from '../vtws';-//Docs: https://code.vtiger.com/vtiger/vtigercrm-manual/-/wikis/Webservice-Docs-//Extra: https://help.vtiger.com/article/147111249-Rest-API-Manual+const SEARCH_MAX = 1000;++export function searchFiltersFromFields(fields: Record<string, unknown>): VtqlFilter[] {+ return Object.entries(fields).flatMap(([field, value]): VtqlFilter[] => {+ if (value === false || value === '') {+ return [];+ }+ const text = filterValueToString(value);+ if (text === undefined) {+ return [];+ }+ return [{ field, value: text, operator: typeof value === 'string' ? 'LIKE' : '=' }];+ });+}export const searchRecords = createAction({name: 'search_records',@@ -22,76 +33,46 @@ export const searchRecords = createAction({auth: vtigerAuth,displayName: 'Search Records',description: 'Search for a record.',- audience: 'both',- aiMetadata: { description: 'Searches a Vtiger module (element type) by filtering its records against field-value criteria; string fields match case-insensitive substrings and other fields match exactly. Leaving the criteria empty returns all records (optionally capped by limit). Choose this for simple field-based lookups; use Query Records for custom SQL-style conditions. Read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Searches a Vtiger module (element type) by field-value criteria; text fields match case-insensitive substrings and other fields match exactly. Leaving the criteria empty returns all records up to the limit. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: queryRecordsSchema,props: {elementType: elementTypeProperty,fields: Property.DynamicProperties({auth: vtigerAuth,displayName: 'Search Fields',- description: 'Enter your filter criteria',+ description: 'Enter your filter criteria. Unchecked checkboxes are ignored.',required: true,refreshers: ['elementType'],props: async ({ auth, elementType }) => {- if (!auth || !elementType) {+ const module = propText(elementType);+ if (!auth || module === '') {return {};}-- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );-- if (instance === null) {- return {};- }-- return generateElementFields(- auth,- elementType as unknown as string,- {},- true- );+ return generateElementFields({ auth, elementType: module, defaultValue: {}, skipMandatory: true });},}),limit: Property.Number({displayName: 'Limit',- description: 'Enter the maximum number of records to return.',+ description: `Enter the maximum number of records to return (default and maximum ${SEARCH_MAX}).`,required: false,}),},async run({ propsValue, auth }) {- const vtigerInstance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (vtigerInstance === null) return;-- const count = await countRecords(auth, propsValue.elementType as string);- if (count > 0) {- const records: Record<string, unknown>[] = await queryRecords(- auth,- propsValue.elementType as string,- 0,- count- );-- const filtered = records.filter((record) => {- return Object.entries(propsValue['fields']).every(([key, value]) => {- const recordValue = record[key];- if (typeof value === 'string') {- const rv = typeof recordValue === 'string' ? recordValue : String(recordValue ?? '');- return rv.toLowerCase().includes(value.toLowerCase());- }- return recordValue === value;- });- });-- return propsValue.limit ? filtered.slice(0, propsValue.limit) : filtered;- } else {- return [];- }+ const module = assertModuleName(propText(propsValue.elementType));+ const limit = clampLimit({ value: propsValue.limit, fallback: SEARCH_MAX, max: SEARCH_MAX });+ const where = buildWhere({ filters: searchFiltersFromFields(propsValue.fields ?? {}) });+ const session = await vtwsLogin(auth.props);+ const { records } = await pagedQuery<Record<string, unknown>>({+ module,+ where,+ limit,+ fetchPage: (query) => vtwsQuery<Record<string, unknown>>({ creds: auth.props, session, query }),+ });+ return records;},});diff --git a/packages/pieces/community/vtiger/src/lib/actions/update-record.ts b/packages/pieces/community/vtiger/src/lib/actions/update-record.tsindex 3e9f3aa961f..763db272370 100644--- a/packages/pieces/community/vtiger/src/lib/actions/update-record.ts+++ b/packages/pieces/community/vtiger/src/lib/actions/update-record.ts@@ -1,24 +1,16 @@-import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { vtigerAuth } from '../auth';import {- DropdownState,- DynamicPropsValue,- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import {- instanceLogin,- VTigerAuthValue,- Modules,- Field,- getRecordReference,+ DROPDOWN_RECORD_CAP,+ elementTypeProperty,+ errorText,+ generateElementFields,+ moduleLabeler,+ propText,} from '../common';-import { elementTypeProperty } from '../common';--function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}+import { originalRecordEnvelopeSchema } from '../output-schemas';+import { assertModuleName, assertRecordId } from '../vtql';+import { vtwsCall, vtwsLogin, vtwsQuery } from '../vtws';export const updateRecord = createAction({name: 'update_record',@@ -26,284 +18,103 @@ export const updateRecord = createAction({auth: vtigerAuth,displayName: 'Update Record',description: 'Update a Record',- audience: 'both',- aiMetadata: { description: 'Updates an existing Vtiger record, identified by its id within a given module (element type), with the supplied field values. Choose this to modify a known record. Idempotent: re-running with the same fields leaves the record in the same state.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates an existing Vtiger record, identified by its id within a given module (element type), with the supplied field values using Vtiger revise (only the sent fields change). Idempotent: re-running with the same fields leaves the record in the same state.',+ idempotent: true,+ },+ outputSchema: originalRecordEnvelopeSchema,props: {elementType: elementTypeProperty,id: Property.Dropdown({auth: vtigerAuth,displayName: 'Id',- description: "The record's id",+ description: `The record's id. Only the first ${DROPDOWN_RECORD_CAP} records of the module are listed; use an expression to pass another id.`,required: true,refreshers: ['elementType'],options: async ({ auth, elementType }) => {- if (!auth || !elementType) {+ const module = propText(elementType);+ if (!auth || module === '') {return {disabled: true,options: [],- placeholder:- 'Please select the element type and setup authentication to continue.',+ placeholder: 'Please select the element type and setup authentication to continue.',};}-- let c = 0;- let instance = null;- while (!instance && c < 3) {- instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- await sleep(1500);- c++;- }-- if (!instance) {+ try {+ const name = assertModuleName(module);+ const session = await vtwsLogin(auth.props);+ const records = await vtwsQuery<Record<string, unknown>>({+ creds: auth.props,+ session,+ query: `SELECT * FROM ${name} LIMIT ${DROPDOWN_RECORD_CAP};`,+ });+ const label = moduleLabeler({ creds: auth.props, module: name });return {- disabled: true,- options: [],- placeholder: 'Authentication failed.',+ disabled: false,+ options: await Promise.all(+ records.map(async (record) => {+ const id = typeof record['id'] === 'string' ? record['id'] : '';+ return { label: (await label(record)) || id, value: id };+ })+ ),};- }-- const response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, string>[];- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- sessionName: instance.sessionId ?? instance.sessionName,- operation: 'query',- elementType: elementType as unknown as string,- query: `SELECT * FROM ${elementType} LIMIT 100;`,- },- });-- if (!response.body.success)+ } catch (error) {return {disabled: true,options: [],- placeholder: 'Request unsuccessful.',+ placeholder: `Could not load records: ${errorText(error)}`,};-- const element: string = elementType as unknown as string;-- return {- options: await Promise.all(response.body.result.map(async (record) => {- return {- label: await Modules[element]?.(record) || record['id'],- value: record['id'] as string,- };- })),- disabled: false,- };+ }},}),record: Property.DynamicProperties({auth: vtigerAuth,displayName: 'Record Fields',- description: 'Add new fields to be created in the new record',+ description: 'Fields to update. Values shown are the record values when the step was configured.',required: true,refreshers: ['id', 'elementType'],props: async ({ auth, id, elementType }) => {- if (!auth || !elementType) {+ const module = propText(elementType);+ if (!auth || module === '') {return {};}-- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (!instance) return {};-- let defaultValue: Record<string, unknown>;- if (id && 'id') {- const retrieve_response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, unknown>;- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- operation: 'retrieve',- sessionName: instance.sessionId ?? instance.sessionName,- elementType: elementType as unknown as string,- id: id as unknown as string,- },- });- if (retrieve_response.body.result) {- defaultValue = retrieve_response.body.result;- } else {- defaultValue = {};- }- } else {- defaultValue = {};- }-- const describe_response = await httpClient.sendRequest<{- success: boolean;- result: { fields: Field[] };- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- sessionName: instance.sessionId ?? instance.sessionName,- operation: 'describe',- elementType: elementType as unknown as string,- },+ const recordId = propText(id);+ const defaultValue =+ recordId === ''+ ? {}+ : await vtwsLogin(auth.props).then(async (session) =>+ (+ await vtwsCall<Record<string, unknown>>({+ creds: auth.props,+ session,+ operation: 'retrieve',+ params: { elementType: assertModuleName(module), id: assertRecordId({ value: recordId }) },+ })+ ).result+ );+ return generateElementFields({+ auth,+ elementType: module,+ defaultValue,+ skipFields: ['id'],});-- const fields: DynamicPropsValue = {};-- if (describe_response.body.success) {- let limit = 30; // Limit to show 30 input property, more than this will cause frontend unresponsive-- const generateField = async (field: Field) => {- const params = {- displayName: field.label,- description: `Field ${field.name} of object type ${elementType}`,- required: field.mandatory,- };-- if (- [- 'string',- 'text',- 'mediumtext',- 'phone',- 'url',- 'email',- ].includes(field.type.name)- ) {- if (['mediumtext', 'url'].includes(field.type.name)) {- fields[field.name] = Property.LongText({- ...params,- defaultValue: defaultValue?.[field.name] as string,- });- } else {- fields[field.name] = Property.ShortText({- ...params,- defaultValue: defaultValue?.[field.name] as string,- });- }- } else if (- ['picklist', 'reference', 'owner'].includes(field.type.name)- ) {- let options: DropdownState<string>;- if (field.type.name === 'picklist') {- options = {- disabled: false,- options: field.type.picklistValues ?? [],- };- } else if (field.type.name === 'owner') {- options = await getRecordReference(- auth,- ['Users']- );- } else if (field.type.refersTo) {- options = await getRecordReference(- auth,- field.type.refersTo ?? []- );- } else {- options = { disabled: false, options: [] };- }-- fields[field.name] = Property.StaticDropdown({- ...params,- defaultValue: defaultValue?.[field.name] as string,- options,- });- } else if (- ['double', 'integer', 'currency'].includes(field.type.name)- ) {- fields[field.name] = Property.Number({- ...params,- defaultValue: defaultValue?.[field.name] as number,- });- } else if (['boolean'].includes(field.type.name)) {- fields[field.name] = Property.Checkbox({- displayName: field.label,- description: `The fields to fill in the object type ${elementType}`,- required: field.mandatory,- defaultValue: defaultValue?.[field.name] ? true : false,- });- } else if (['date', 'datetime', 'time'].includes(field.type.name)) {- fields[field.name] = Property.DateTime({- displayName: field.label,- description: `The fields to fill in the object type ${elementType}`,- defaultValue: defaultValue?.[field.name] as string,- required: field.mandatory,- });- }- };-- const skipFields = [- 'id',- ];-- // Prioritize mandatory fields- for (const field of describe_response.body.result.fields) {- if (skipFields.includes(field.name)) {- continue;- }-- if (field.mandatory) {- await generateField(field);- limit--;- }- }-- // Let's add the rest...- for (const field of describe_response.body.result.fields) {- if (skipFields.includes(field.name)) {- continue;- }-- // Skip the rest of field to avoid unresponsive frontend- if (limit < 0) break;-- if (!field.mandatory) {- await generateField(field);- limit--;- }- }- }-- return fields;},}),},async run({ propsValue: { elementType, id, record }, auth }) {- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );-- if (instance !== null) {- const response = await httpClient.sendRequest<Record<string, unknown>[]>({- method: HttpMethod.POST,- url: `${auth.props.instance_url}/webservice.php`,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: {- operation: 'update',- sessionName: instance.sessionId ?? instance.sessionName,- elementType: elementType,- element: JSON.stringify({- id: id,- ...record,- }),- },- });-- return response.body;- }-- return null;+ const module = assertModuleName(propText(elementType));+ const recordId = assertRecordId({ value: id });+ const session = await vtwsLogin(auth.props);+ return vtwsCall<Record<string, unknown>>({+ creds: auth.props,+ session,+ operation: 'revise',+ params: {+ elementType: module,+ element: JSON.stringify({ ...(record ?? {}), id: recordId }),+ },+ });},});diff --git a/packages/pieces/community/vtiger/src/lib/ai-common.ts b/packages/pieces/community/vtiger/src/lib/ai-common.tsnew file mode 100644index 00000000000..73b5c7a719d--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/ai-common.ts@@ -0,0 +1,94 @@+import { Property } from '@activepieces/pieces-framework';+import { isRecord } from './rest-client';++export function moduleProp({ description }: { description?: string } = {}) {+ return Property.ShortText({+ displayName: 'Module',+ description:+ description ??+ 'API name of the Vtiger module, for example Contacts, Leads, Accounts, Potentials or Cases. Get the exact names from List Modules.',+ required: true,+ });+}++export function recordIdProp({+ displayName = 'Record ID',+ description,+}: {+ displayName?: string;+ description?: string;+} = {}) {+ return Property.ShortText({+ displayName,+ description:+ description ??+ 'Vtiger webservice ID of the record, for example 12x345. Get it from Search Module Records, Query Records or a previous create.',+ required: true,+ });+}++export function fieldsJsonProp({+ displayName = 'Fields',+ description,+ required,+}: {+ displayName?: string;+ description: string;+ required: boolean;+}) {+ return Property.Json({ displayName, description, required });+}++export function recordOutput(record: unknown): { id: string; record: Record<string, unknown> } {+ const value = isRecord(record) ? record : {};+ return { id: typeof value['id'] === 'string' ? value['id'] : '', record: value };+}++export function recordList(result: unknown): Record<string, unknown>[] {+ if (Array.isArray(result)) {+ return result.filter(isRecord);+ }+ if (isRecord(result) && Array.isArray(result['records'])) {+ return result['records'].filter(isRecord);+ }+ return [];+}++export function stringList({ value, label }: { value: unknown; label: string }): string[] {+ const raw = Array.isArray(value)+ ? value+ : typeof value === 'string'+ ? value.split(',')+ : [];+ const items = raw+ .map((item) => (typeof item === 'string' || typeof item === 'number' ? String(item).trim() : ''))+ .filter((item) => item !== '');+ if (items.length === 0) {+ throw new Error(`${label} must contain at least one value`);+ }+ return [...new Set(items)];+}++export function requiredText({ value, label }: { value: unknown; label: string }): string {+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';+ if (text === '') {+ throw new Error(`${label} is required`);+ }+ return text;+}++export function toUnixSeconds(value: unknown): number {+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';+ if (text === '') {+ throw new Error('Modified Since is required: Unix seconds (e.g. 1735689600) or an ISO 8601 date');+ }+ if (/^\d+$/.test(text)) {+ const n = Number(text);+ return n > 100000000000 ? Math.floor(n / 1000) : n;+ }+ const ms = Date.parse(text);+ if (Number.isNaN(ms)) {+ throw new Error(`Modified Since "${text}" is neither Unix seconds nor an ISO 8601 date`);+ }+ return Math.floor(ms / 1000);+}diff --git a/packages/pieces/community/vtiger/src/lib/auth.ts b/packages/pieces/community/vtiger/src/lib/auth.tsnew file mode 100644index 00000000000..ddf6413f1be--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/auth.ts@@ -0,0 +1,66 @@+import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { assertPublicInstanceUrl, VtigerApiError } from './rest-client';+import { vtwsLogin } from './vtws';++const markdownProperty = `+To obtain your Access Key, follow these steps:++1. Login to Vtiger CRM:+Open a web browser and log in to your Vtiger CRM instance.++2. Navigate to User Profile:+In the top right corner, click on your profile name.+Select "My Preferences."++3. The system will generate an access key for you.+Copy and securely store the access key. This key will be used for authentication when making API requests.+Note:++Access keys are sensitive information, and they should be kept secure.+Treat the access key like a password. Do not share it publicly or expose it in an insecure manner.+`;++export const vtigerAuth = PieceAuth.CustomAuth({+ description: markdownProperty,+ props: {+ instance_url: Property.ShortText({+ displayName: 'VTiger Instance URL',+ description:+ 'For the instance URL, add the url without the endpoint. For example enter https://<instance>.od2.vtiger.com instead of https://<instance>.od2.vtiger.com/restapi/v1/vtiger/default',+ required: true,+ }),+ username: Property.ShortText({+ displayName: 'Username',+ description: 'Enter your username/email',+ required: true,+ }),+ password: PieceAuth.SecretText({+ displayName: 'Access Key',+ description: 'Enter your access Key',+ required: true,+ }),+ },+ validate: async ({ auth }) => {+ try {+ assertPublicInstanceUrl(auth.instance_url);+ } catch (error) {+ return { valid: false, error: error instanceof Error ? error.message : String(error) };+ }+ try {+ await vtwsLogin(auth);+ return { valid: true };+ } catch (error) {+ if (error instanceof VtigerApiError) {+ return {+ valid: false,+ error: `Vtiger rejected the login (${error.message}). Check the username and access key.`,+ };+ }+ return {+ valid: false,+ error: `Could not reach the Vtiger instance: ${error instanceof Error ? error.message : String(error)}`,+ };+ }+ },+ required: true,+});diff --git a/packages/pieces/community/vtiger/src/lib/common.ts b/packages/pieces/community/vtiger/src/lib/common.tsindex ca83df6f12e..e07d59980b8 100644--- a/packages/pieces/community/vtiger/src/lib/common.ts+++ b/packages/pieces/community/vtiger/src/lib/common.ts@@ -1,236 +1,57 @@-import {- AuthenticationType,- HttpHeaders,- HttpMessageBody,- HttpMethod,- HttpRequest,- httpClient,-} from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';import {AppConnectionValueForAuthProperty,DropdownState,DynamicPropsValue,- PiecePropValueSchema,Property,} from '@activepieces/pieces-framework';-import * as crypto from 'crypto-js';-import { Challenge, Instance } from './models';-import { vtigerAuth } from '..';--export const isBaseUrl = (urlString: string): boolean => {- try {- const url = new URL(urlString);- return !url.pathname || url.pathname === '/';- } catch (error) {- // Handle invalid URLs here, e.g., return false or throw an error- return false;- }-};--export const md5 = (contents: string) => crypto.MD5(contents).toString();-export const calculateAuthKey = (- challengeToken: string,- accessKey: string-): string => crypto.MD5(challengeToken + accessKey).toString(crypto.enc.Hex);+import { vtigerAuth } from './auth';+import { isRecord, vtigerRest, VtigerCredentials } from './rest-client';+import { assertModuleName } from './vtql';+import { restOrVtws, vtwsCall, vtwsLogin, vtwsQuery, VtwsSession } from './vtws';-export const instanceLogin = async (- instance_url: string,- username: string,- password: string,- debug = false-) => {- const endpoint = `${instance_url}/webservice.php`;- const challenge = await httpClient.sendRequest<{- success: boolean;- result: Challenge;- }>({- method: HttpMethod.GET,- url: `${endpoint}?operation=getchallenge&username=${username}`,- });-- const accessKey = calculateAuthKey(challenge.body.result.token, password);- const response = await httpClient.sendRequest<{- success: boolean;- result: Instance;- }>({- method: HttpMethod.POST,- url: `${endpoint}`,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: {- operation: 'login',- username,- accessKey,- },- });+export function propText(value: unknown): string {+ return typeof value === 'string' ? value : '';+}- if (debug) {- console.debug('>>>>>>>>>>>> LOGIN', response.body, {- method: HttpMethod.POST,- url: `${endpoint}`,- headers: {- 'Content-Type': 'multipart/form-data',- },- body: {- operation: 'login',- username,- accessKey,- },- });- }- if (response.body.success) {- return response.body.result;+export function moduleLabeler({+ creds,+ module,+}: {+ creds: VtigerCredentials;+ module: string;+}): (record: Record<string, unknown>) => Promise<string> {+ const fixed = STATIC_LABELS[module];+ if (fixed) {+ return async (record) => fixed(record);}-- return null;-};--export type Operation =- | 'create'- | 'retrieve'- | 'delete'- | 'update'- | 'query'- | 'listtypes';--export const Operations: Record<Operation, BodyParams> = {- listtypes: {- method: HttpMethod.GET,- },- create: {- method: HttpMethod.POST,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- },- retrieve: {- method: HttpMethod.GET,- },- delete: {- method: HttpMethod.POST,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- },- update: {- method: HttpMethod.POST,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- },- query: {- method: HttpMethod.GET,- },-};--export const prepareHttpRequest = (- instanceUrl: string,- sessionName: string,- operation: Operation,- record: Record<string, string>-) => {- const data: Record<string, string> = {- operation,- sessionName,- ...record,+ let labelField: Promise<string> | undefined;+ return async (record) => {+ labelField ??= describeLabelField({ creds, module });+ const field = await labelField;+ return field === '' ? '' : textOf(record[field]);};- if ('element' in record) data['element'] = JSON.stringify(record['element']);-- const httpRequest: HttpRequest<HttpMessageBody> = {- url: `${instanceUrl}/webservice.php`,- method: Operations[operation].method,- headers: Operations[operation].headers,- };-- if (Operations[operation].method === HttpMethod.GET) {- httpRequest['queryParams'] = data;- } else if (Operations[operation].method === HttpMethod.POST) {- httpRequest['body'] = data;- }-- return httpRequest;-};--interface BodyParams {- method: HttpMethod;- headers?: HttpHeaders;}-export const Modules: Record<string, (record: Record<string, string>) => Promise<string>> = {- Contacts: async (record) => `${record['email']}`, // firstname,lastname- Documents: async (record) => `${record['notes_title']}`, // title- Faq: async (record) => `${record['faq_no']}`, // question- // HelpDesk: async (record) => `${record['ticket_no']}`, // this module not exist- Invoice: async (record) => `${record['invoice_no']}`, // subject- Leads: async (record) => `${record['lead_no']}: ${record['firstname']} ${record['lastname']}`, // firstname,lastname- LineItem: async (record) => `${record['productid']}`, // no label field- ProductTaxes: async (record) => `#${record['taxid']} pid: ${record['productid']}`, // no label field- // ProjectTask: async (record) => `${record['projecttaskname']}`, // this module not exist- SalesOrder: async (record) => `${record['salesorder_no']}`, // subject- Tax: async (record) => `${record['taxname']}`, // taxlabel- Users: async (record) => `${record['user_name']}`, // first_name,last_name-};--export async function refreshModules(auth: VTigerAuthValue){- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/restapi/v1/vtiger/default/listtypes?fieldTypeList=null`,- authentication: {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,+export async function listModuleNames(creds: VtigerCredentials): Promise<string[]> {+ const result = await restOrVtws<{ types?: unknown }>({+ rest: () =>+ vtigerRest<{ types?: unknown }>({+ creds,+ method: HttpMethod.GET,+ path: 'listtypes',+ query: { fieldTypeList: 'null' },+ }),+ vtws: async () => {+ const session = await vtwsLogin(creds);+ return (await vtwsCall<{ types?: unknown }>({ creds, session, operation: 'listtypes', params: {} })).result;},});-- if(response.body.success !== true){- throw new Error('Failed to retrieve module types');- }-- const types = response.body.result.types;- for (let i = 0; i < types.length; i++) {- const element = types[i];-- let labelFields = '';- let isModuleLabelUnknown = false;- Modules[element] ??= async (record) => {- if(labelFields !== '') return labelFields;- if(isModuleLabelUnknown) return '';-- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/restapi/v1/vtiger/default/describe?elementType=${element}`,- authentication: {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,- },- });-- if (!response.body.success) return '';-- const result = response.body.result;- const lf = result.labelFields;- if (Array.isArray(lf)) {- labelFields = (lf[0] ?? '') as string;- } else if (typeof lf === 'string') {- labelFields = lf.includes(',') ? lf.split(',')[0] : lf;- } else {- labelFields = '';- }-- if(labelFields === '') {- if(!result.fields?.length){- isModuleLabelUnknown = true;- return '';- }-- labelFields = result.fields[0].name;- }-- return record[labelFields];- };- }+ const types = Array.isArray(result.types)+ ? result.types.filter((t): t is string => typeof t === 'string')+ : [];+ const names = new Set([...Object.keys(STATIC_LABELS), ...types]);+ return [...names].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));}export const elementTypeProperty = Property.Dropdown({@@ -239,8 +60,7 @@ export const elementTypeProperty = Property.Dropdown({description: 'The module / element type',required: true,refreshers: [],- options: async (props) => {- const { auth } = props;+ options: async ({ auth }) => {if (!auth) {return {disabled: true,@@ -248,39 +68,22 @@ export const elementTypeProperty = Property.Dropdown({placeholder: 'Please setup authentication to continue',};}-- await refreshModules(auth);-- const modules = Object.keys(Modules).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));- return {- disabled: false,- options: modules.map((module) => ({- label: module,- value: module,- }))- };- }+ try {+ const modules = await listModuleNames(auth.props);+ return {+ disabled: false,+ options: modules.map((module) => ({ label: module, value: module })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: `Could not load modules: ${errorText(error)}`,+ };+ }+ },});-export interface Field {- name: string;- dblabel: string;- label: string;- default: string;- mandatory: boolean;- type: {- name: string;- length?: string;- refersTo?: string[];- picklistValues?: {- label: string;- value: string;- }[];- };-}--export type VTigerAuthValue = AppConnectionValueForAuthProperty<typeof vtigerAuth>;-export const recordIdProperty = () =>Property.DynamicProperties({auth: vtigerAuth,@@ -289,118 +92,71 @@ export const recordIdProperty = () =>required: true,refreshers: ['elementType'],props: async ({ auth, elementType }) => {- if (!auth || !elementType) {+ const module = propText(elementType);+ if (!auth || module === '') {return {};}-- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (!instance) return {};-- const response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, string>[];- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- sessionName: instance.sessionId ?? instance.sessionName,- operation: 'query',- elementType: elementType as unknown as string,- query: `SELECT * FROM ${elementType} LIMIT 100;`,- },- });-- if (!response.body.success) return {};-- const fields: DynamicPropsValue = {};- const _type: string = elementType as unknown as string;- const _module: CallableFunction = Modules[_type];-- fields['id'] = Property.StaticDropdown<string>({- displayName: 'Id',- description: "The record's id",- required: true,- options: {- options: response.body.result.map((r) => ({- label: _module?.(r) || r['id'],- value: r['id'],- })),- },+ const name = assertModuleName(module);+ const session = await vtwsLogin(auth.props);+ const records = await vtwsQuery<Record<string, unknown>>({+ creds: auth.props,+ session,+ query: `SELECT * FROM ${name} LIMIT ${DROPDOWN_RECORD_CAP};`,});-+ const label = moduleLabeler({ creds: auth.props, module: name });+ const options = await Promise.all(+ records.map(async (r) => ({+ label: (await label(r)) || textOf(r['id']),+ value: textOf(r['id']),+ }))+ );+ const fields: DynamicPropsValue = {+ id: Property.StaticDropdown<string>({+ displayName: 'Id',+ description: `The record's id. Only the first ${DROPDOWN_RECORD_CAP} records of the module are listed; use an expression to pass another id.`,+ required: true,+ options: { options },+ }),+ };return fields;},});-export const FieldMapping = {- autogenerated: Property.ShortText,- string: Property.ShortText,- text: Property.ShortText,- double: Property.Number,- integer: Property.Number,- mediumtext: Property.LongText,- phone: Property.LongText,- url: Property.LongText,- email: Property.LongText,- picklist: Property.StaticDropdown,- reference: Property.StaticDropdown,- currency: Property.Number,- boolean: Property.Checkbox,- owner: Property.StaticDropdown,- date: Property.DateTime,- datetime: Property.DateTime,- file: Property.File,- time: Property.DateTime,-};--export async function getRecordReference(- auth: AppConnectionValueForAuthProperty<typeof vtigerAuth>,- modules: string[]-): Promise<DropdownState<string>> {- const module = modules[0]; //Limit to the first reference for now- const vtigerInstance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (vtigerInstance === null)+export async function getRecordReference({+ auth,+ modules,+ session,+}: {+ auth: VTigerAuthValue;+ modules: string[];+ session?: VtwsSession;+}): Promise<DropdownState<string>> {+ const module = modules[0];+ try {+ const name = assertModuleName(module);+ const activeSession = session ?? (await vtwsLogin(auth.props));+ const records = await vtwsQuery<Record<string, unknown>>({+ creds: auth.props,+ session: activeSession,+ query: `SELECT * FROM ${name} LIMIT ${DROPDOWN_RECORD_CAP};`,+ });+ const label = moduleLabeler({ creds: auth.props, module: name });return {- disabled: true,- options: [],+ disabled: false,+ options: await Promise.all(+ records.map(async (record) => ({+ label: (await label(record)) || textOf(record['id']),+ value: textOf(record['id']),+ }))+ ),};-- const httpRequest = prepareHttpRequest(- auth.props.instance_url,- vtigerInstance.sessionId ?? vtigerInstance.sessionName,- 'query' as Operation,- { query: `SELECT * FROM ${module};` }- );-- const response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, any>[];- }>(httpRequest);-- if (response.body.success) {+ } catch (error) {return {- disabled: false,- options: await Promise.all(response.body.result.map(async (record) => {- return {- label: await Modules[module]?.(record) || record['id'],- value: record['id'] as string,- };- })),+ disabled: true,+ options: [],+ placeholder: `Could not load ${String(module)} records: ${errorText(error)}`,};}-- return {- disabled: true,- options: [],- };}export const recordProperty = () =>@@ -410,226 +166,277 @@ export const recordProperty = () =>description: 'Add new fields to be created in the new record',required: true,refreshers: ['elementType'],- props: async ({ auth, id, elementType }) => {- if (!auth || !elementType) {+ props: async ({ auth, elementType }) => {+ const module = propText(elementType);+ if (!auth || module === '') {return {};}--- return generateElementFields(- auth,- elementType as unknown as string,- {}- );+ return generateElementFields({ auth, elementType: module, defaultValue: {} });},});-export const queryRecords = async (- auth: AppConnectionValueForAuthProperty<typeof vtigerAuth>,- elementType: string,- page = 0,- limit = 100-) => {- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password- );- if (!instance) return [];-- const response = await httpClient.sendRequest<{- success: boolean;- result: Record<string, unknown>[];- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- sessionName: instance.sessionId ?? instance.sessionName,- operation: 'query',- elementType: elementType as unknown as string,- query: `SELECT * FROM ${elementType} LIMIT ${page}, ${limit};`,+export async function describeFields({+ creds,+ module,+}: {+ creds: VtigerCredentials;+ module: string;+}): Promise<Field[]> {+ const elementType = assertModuleName(module);+ const result = await restOrVtws<{ fields?: Field[] }>({+ rest: () =>+ vtigerRest<{ fields?: Field[] }>({ creds, method: HttpMethod.GET, path: 'describe', query: { elementType } }),+ vtws: async () => {+ const session = await vtwsLogin(creds);+ return (await vtwsCall<{ fields?: Field[] }>({ creds, session, operation: 'describe', params: { elementType } })).result;},});+ return Array.isArray(result.fields) ? result.fields : [];+}- if (response.body.success) {- return response.body.result;- }+export function buildFieldProps({+ fields,+ elementType,+ defaultValue,+ skipMandatory,+ skipFields,+ references,+}: {+ fields: Field[];+ elementType: string;+ defaultValue: Record<string, unknown>;+ skipMandatory: boolean;+ skipFields: string[];+ references: Record<string, DropdownState<string>>;+}): DynamicPropsValue {+ const usable = fields.filter((field) => !skipFields.includes(field.name));+ const mandatory = usable.filter((field) => field.mandatory);+ const optional = usable.filter((field) => !field.mandatory);+ const selected = [...mandatory, ...optional.slice(0, Math.max(0, FIELD_PROP_CAP - mandatory.length + 1))];+ return selected.reduce<DynamicPropsValue>((acc, field) => {+ const prop = fieldProp({ field, elementType, defaultValue, skipMandatory, references });+ return prop === undefined ? acc : { ...acc, [field.name]: prop };+ }, {});+}- return [];+export const generateElementFields = async ({+ auth,+ elementType,+ defaultValue,+ skipMandatory = false,+ skipFields = ['id', 'modifiedtime', 'createdtime', 'modifiedby', 'created_user_id'],+}: {+ auth: VTigerAuthValue;+ elementType: string;+ defaultValue: Record<string, unknown>;+ skipMandatory?: boolean;+ skipFields?: string[];+}): Promise<DynamicPropsValue> => {+ const fields = await describeFields({ creds: auth.props, module: elementType });+ const references = await loadReferences({ auth, fields, skipFields });+ return buildFieldProps({ fields, elementType, defaultValue, skipMandatory, skipFields, references });};-export const countRecords = async (- auth: VTigerAuthValue,- elementType: string-) => {- const instance = await instanceLogin(- auth.props.instance_url,- auth.props.username,- auth.props.password+async function loadReferences({+ auth,+ fields,+ skipFields,+}: {+ auth: VTigerAuthValue;+ fields: Field[];+ skipFields: string[];+}): Promise<Record<string, DropdownState<string>>> {+ const wanted = fields.filter(+ (field) =>+ !skipFields.includes(field.name) &&+ (field.type.name === 'owner' || (field.type.name === 'reference' && (field.type.refersTo ?? []).length > 0)));- if (!instance) return 0;-- const response = await httpClient.sendRequest<{- success: boolean;- result: { count: string }[];- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/webservice.php`,- queryParams: {- sessionName: instance.sessionId ?? instance.sessionName,- operation: 'query',- elementType: elementType as unknown as string,- query: `SELECT count(*) FROM ${elementType};`,- },- });-- if (response.body.success) {- return Number.parseInt(response.body.result[0].count);+ if (wanted.length === 0) {+ return {};}+ const session = await vtwsLogin(auth.props);+ const references: Record<string, DropdownState<string>> = {};+ for (const field of wanted) {+ const modules = field.type.name === 'owner' ? ['Users'] : field.type.refersTo ?? [];+ references[field.name] = await getRecordReference({ auth, modules, session });+ }+ return references;+}- return 0;-};--export const generateElementFields = async (- auth: VTigerAuthValue,- elementType: string,- defaultValue: Record<string, unknown>,- skipMandatory = false-): Promise<DynamicPropsValue> => {- const describe_response = await httpClient.sendRequest<{- success: boolean;- result: { fields: Field[] };- }>({- method: HttpMethod.GET,- url: `${auth.props.instance_url}/restapi/v1/vtiger/default/describe`,- authentication: {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,- },- queryParams: {- elementType: elementType,- },- });-- const fields: DynamicPropsValue = {};+function fieldProp({+ field,+ elementType,+ defaultValue,+ skipMandatory,+ references,+}: {+ field: Field;+ elementType: string;+ defaultValue: Record<string, unknown>;+ skipMandatory: boolean;+ references: Record<string, DropdownState<string>>;+}) {+ const required = skipMandatory ? false : field.mandatory;+ const params = {+ displayName: field.label,+ description: `Field ${field.name} of object type ${elementType}`,+ required,+ };+ const current = defaultValue[field.name];+ const typeName = field.type.name;+ if (['mediumtext', 'url'].includes(typeName)) {+ return Property.LongText({ ...params, defaultValue: textDefault(current) });+ }+ if (['string', 'text', 'phone', 'email'].includes(typeName)) {+ return Property.ShortText({ ...params, defaultValue: textDefault(current) });+ }+ if (typeName === 'picklist') {+ return Property.StaticDropdown({+ ...params,+ defaultValue: textDefault(current),+ options: { disabled: false, options: field.type.picklistValues ?? [] },+ });+ }+ if (typeName === 'reference' || typeName === 'owner') {+ return Property.StaticDropdown({+ ...params,+ defaultValue: textDefault(current),+ options: references[field.name] ?? { disabled: false, options: [] },+ });+ }+ if (['double', 'integer', 'currency'].includes(typeName)) {+ return Property.Number({ ...params, defaultValue: numberDefault(current) });+ }+ if (typeName === 'boolean') {+ return Property.Checkbox({+ displayName: field.label,+ description: `The fields to fill in the object type ${elementType}`,+ required,+ defaultValue: current === true || current === '1' || current === 1,+ });+ }+ if (['date', 'datetime', 'time'].includes(typeName)) {+ return Property.DateTime({+ displayName: field.label,+ description: `The fields to fill in the object type ${elementType}`,+ defaultValue: textDefault(current),+ required,+ });+ }+ if (required) {+ return Property.ShortText({ ...params, defaultValue: textDefault(current) });+ }+ return undefined;+}- if (describe_response.body.success) {- let limit = 30; // Limit to show 30 input property, more than this will cause frontend unresponsive+async function describeLabelField({+ creds,+ module,+}: {+ creds: VtigerCredentials;+ module: string;+}): Promise<string> {+ try {+ const result = await vtigerRest<{ labelFields?: unknown; fields?: Field[] }>({+ creds,+ method: HttpMethod.GET,+ path: 'describe',+ query: { elementType: assertModuleName(module) },+ });+ const lf = result.labelFields;+ const fromLabel = Array.isArray(lf)+ ? textOf(lf[0])+ : typeof lf === 'string'+ ? lf.split(',')[0]+ : '';+ if (fromLabel !== '') {+ return fromLabel;+ }+ return result.fields?.[0]?.name ?? '';+ } catch {+ return '';+ }+}- const generateField = async (field: Field) => {- const params = {- displayName: field.label,- description: `Field ${field.name} of object type ${elementType}`,- required: !skipMandatory ? field.mandatory : false,- };+function textOf(value: unknown): string {+ if (typeof value === 'string') {+ return value;+ }+ if (typeof value === 'number' || typeof value === 'boolean') {+ return String(value);+ }+ return '';+}- if (- ['string', 'text', 'mediumtext', 'phone', 'url', 'email'].includes(- field.type.name- )- ) {- if (['mediumtext', 'url'].includes(field.type.name)) {- fields[field.name] = Property.LongText({- ...params,- defaultValue: defaultValue?.[field.name] as string,- });- } else {- fields[field.name] = Property.ShortText({- ...params,- defaultValue: defaultValue?.[field.name] as string,- });- }- } else if (['picklist', 'reference', 'owner'].includes(field.type.name)) {- let options: DropdownState<string>;- if (field.type.name === 'picklist') {- options = {- disabled: false,- options: field.type.picklistValues ?? [],- };- } else if (field.type.name === 'owner') {- options = await getRecordReference(- auth,- ['Users']- );- } else if (field.type.refersTo) {- options = await getRecordReference(- auth,- field.type.refersTo ?? []- );- } else {- options = { disabled: false, options: [] };- }+function textDefault(value: unknown): string | undefined {+ return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : undefined;+}- fields[field.name] = Property.StaticDropdown({- ...params,- defaultValue: defaultValue?.[field.name] as string,- options,- });- } else if (['double', 'integer', 'currency'].includes(field.type.name)) {- fields[field.name] = Property.Number({- ...params,- defaultValue: defaultValue?.[field.name] as number,- });- } else if (['boolean'].includes(field.type.name)) {- fields[field.name] = Property.Checkbox({- displayName: field.label,- description: `The fields to fill in the object type ${elementType}`,- required: !skipMandatory ? field.mandatory : false,- defaultValue: defaultValue?.[field.name] ? true : false,- });- } else if (['date', 'datetime', 'time'].includes(field.type.name)) {- fields[field.name] = Property.DateTime({- displayName: field.label,- description: `The fields to fill in the object type ${elementType}`,- defaultValue: defaultValue?.[field.name] as string,- required: !skipMandatory ? field.mandatory : false,- });- } else if(params.required) {- // Add the mandatory field for unknown input type, but with text input- fields[field.name] = Property.ShortText({- ...params,- defaultValue: defaultValue?.[field.name] as string,- });- }- };+function numberDefault(value: unknown): number | undefined {+ if (typeof value === 'number') {+ return value;+ }+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {+ return Number(value);+ }+ return undefined;+}- const skipFields = [- 'id',- 'modifiedtime',- 'createdtime',- 'modifiedby',- 'created_user_id',- ];+export function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}- // Prioritize mandatory fields- for (const field of describe_response.body.result.fields) {- if (skipFields.includes(field.name)) {- continue;- }+export function recordFromJson({ value, label }: { value: unknown; label: string }): Record<string, unknown> {+ if (value === undefined || value === null || value === '') {+ return {};+ }+ const parsed = typeof value === 'string' ? parseJson({ text: value, label }) : value;+ if (!isRecord(parsed)) {+ throw new Error(`${label} must be a JSON object of field name to value, for example {"lastname": "Smith"}`);+ }+ return parsed;+}- if (field.mandatory) {- await generateField(field);- limit--;- }- }+function parseJson({ text, label }: { text: string; label: string }): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} is not valid JSON`);+ }+}- // Let's add the rest...- for (const field of describe_response.body.result.fields) {- if (skipFields.includes(field.name)) {- continue;- }+const STATIC_LABELS: Record<string, (record: Record<string, unknown>) => string> = {+ Contacts: (record) => textOf(record['email']),+ Documents: (record) => textOf(record['notes_title']),+ Faq: (record) => textOf(record['faq_no']),+ Invoice: (record) => textOf(record['invoice_no']),+ Leads: (record) =>+ `${textOf(record['lead_no'])}: ${textOf(record['firstname'])} ${textOf(record['lastname'])}`,+ LineItem: (record) => textOf(record['productid']),+ ProductTaxes: (record) => `#${textOf(record['taxid'])} pid: ${textOf(record['productid'])}`,+ SalesOrder: (record) => textOf(record['salesorder_no']),+ Tax: (record) => textOf(record['taxname']),+ Users: (record) => textOf(record['user_name']),+};- // Skip the rest of field to avoid unresponsive frontend- if (limit < 0) break;+export const DROPDOWN_RECORD_CAP = 100;+export const FIELD_PROP_CAP = 30;- if (!field.mandatory) {- await generateField(field);- limit--;- }- }- }- else throw new Error("Failed to get module description");+export type VTigerAuthValue = AppConnectionValueForAuthProperty<typeof vtigerAuth>;- return fields;-};+export interface Field {+ name: string;+ dblabel: string;+ label: string;+ default: string;+ mandatory: boolean;+ type: {+ name: string;+ length?: string;+ refersTo?: string[];+ picklistValues?: {+ label: string;+ value: string;+ }[];+ };+}diff --git a/packages/pieces/community/vtiger/src/lib/models.ts b/packages/pieces/community/vtiger/src/lib/models.tsindex aca2dcecc30..3ee53412423 100644--- a/packages/pieces/community/vtiger/src/lib/models.ts+++ b/packages/pieces/community/vtiger/src/lib/models.ts@@ -1,6 +1,6 @@export interface Challenge {- token: string; // Challenge token to be used for login.- serverTime: string; // Current Server time+ token: string;+ serverTime: string;expireTime: string;}diff --git a/packages/pieces/community/vtiger/src/lib/output-schemas.ts b/packages/pieces/community/vtiger/src/lib/output-schemas.tsnew file mode 100644index 00000000000..c4855fd1e8a--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/output-schemas.ts@@ -0,0 +1,258 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const WS_ID = 'Vtiger webservice ID, for example 12x345.';+const RECORD_FIELDS = 'All fields of the record, keyed by field API name.';++export const originalRecordEnvelopeSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'result', label: 'Record', description: RECORD_FIELDS },+ ],+};++export const originalDeleteEnvelopeSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'result', label: 'Result', children: [{ key: 'status', label: 'Status' }] },+ ],+};++export const queryRecordsSchema: OutputSchema = {+ fields: [{ key: 'records', value: '', label: 'Rows', description: 'Each row holds the selected columns.' }],+ itemLabel: '{id}',+};++export const currentUserSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'User ID', description: WS_ID },+ { key: 'user_name', label: 'Username' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email1', label: 'Email', format: 'email' },+ { key: 'userlabel', label: 'Display Name' },+ { key: 'user_type', label: 'User Type' },+ { key: 'status', label: 'Status' },+ { key: 'is_admin', label: 'Is Admin', description: 'on for administrators.' },+ { key: 'roleid', label: 'Role ID' },+ { key: 'time_zone', label: 'Time Zone' },+ { key: 'date_format', label: 'Date Format' },+ { key: 'hour_format', label: 'Hour Format' },+ { key: 'language', label: 'Language' },+ ],+};++export const listModulesSchema: OutputSchema = {+ fields: [+ {+ key: 'modules',+ label: 'Modules',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'singular', label: 'Singular Label' },+ { key: 'isEntity', label: 'Is Entity', format: 'boolean' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const describeModuleSchema: OutputSchema = {+ fields: [+ { key: 'name', label: 'Module' },+ { key: 'label', label: 'Label' },+ { key: 'idPrefix', label: 'ID Prefix' },+ { key: 'createable', label: 'Createable', format: 'boolean' },+ { key: 'updateable', label: 'Updateable', format: 'boolean' },+ { key: 'deleteable', label: 'Deleteable', format: 'boolean' },+ { key: 'labelFields', label: 'Label Fields' },+ {+ key: 'fields',+ label: 'Fields',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'API Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'mandatory', label: 'Mandatory', format: 'boolean' },+ { key: 'editable', label: 'Editable', format: 'boolean' },+ { key: 'picklistValues', label: 'Picklist Values' },+ { key: 'refersTo', label: 'Refers To' },+ ],+ },+ { key: 'fieldCount', label: 'Field Count', format: 'number' },+ ],+};++export const aiRecordSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID', description: WS_ID },+ { key: 'record', label: 'Record', description: RECORD_FIELDS },+ ],+};++export const relationTypesSchema: OutputSchema = {+ fields: [+ {+ key: 'relations',+ label: 'Relations',+ labelKey: 'relationLabel',+ listItems: [+ { key: 'relationId', label: 'Relation ID' },+ { key: 'relatedModule', label: 'Related Module' },+ { key: 'relationLabel', label: 'Relation Label', description: 'Pass this as Relation Label.' },+ { key: 'translatedLabel', label: 'Display Label' },+ { key: 'actions', label: 'Allowed Actions', description: 'add and/or select.' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const recordTagsSchema: OutputSchema = {+ fields: [+ { key: 'recordId', label: 'Record ID', description: WS_ID },+ { key: 'tags', label: 'Tags' },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const tagChangeSchema: OutputSchema = {+ fields: [+ { key: 'recordId', label: 'Record ID', description: WS_ID },+ { key: 'tags', label: 'Requested Tags' },+ { key: 'message', label: 'Vtiger Message' },+ ],+};++export const accountHierarchySchema: OutputSchema = {+ fields: [+ { key: 'accountId', label: 'Account ID', description: WS_ID },+ {+ key: 'hierarchy',+ label: 'Hierarchy',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Account ID', description: WS_ID },+ { key: 'name', label: 'Name' },+ { key: 'level', label: 'Level', format: 'number' },+ { key: 'label', label: 'Level Label', description: 'Org, Child Org, and so on.' },+ { key: 'current', label: 'Is Requested Account' },+ ],+ },+ ],+};++export const picklistDependencySchema: OutputSchema = {+ fields: [+ { key: 'module', label: 'Module' },+ { key: 'sourceField', label: 'Source Field' },+ { key: 'targetField', label: 'Target Field' },+ { key: 'hasDependency', label: 'Has Dependency', format: 'boolean' },+ {+ key: 'mappings',+ label: 'Mappings',+ labelKey: 'sourceValue',+ listItems: [+ { key: 'sourceValue', label: 'Source Value' },+ { key: 'targetValues', label: 'Allowed Target Values' },+ ],+ },+ ],+};++export const reopenRecordSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID', description: WS_ID },+ { key: 'reopened', label: 'Reopened', format: 'boolean' },+ { key: 'message', label: 'Message' },+ ],+};++export const changedRecordsSchema: OutputSchema = {+ fields: [+ { key: 'updatedIds', label: 'Created or Updated IDs' },+ { key: 'deletedIds', label: 'Deleted IDs' },+ { key: 'updatedCount', label: 'Updated Count', format: 'number' },+ { key: 'deletedCount', label: 'Deleted Count', format: 'number' },+ { key: 'more', label: 'More', format: 'boolean' },+ { key: 'lastModifiedTime', label: 'Last Modified Time', description: 'Unix seconds; pass as Modified Since to continue.' },+ ],+};++export const downloadAttachmentSchema: OutputSchema = {+ fields: [+ { key: 'attachmentId', label: 'Attachment ID' },+ { key: 'fileName', label: 'File Name' },+ { key: 'fileType', label: 'File Type' },+ { key: 'fileSize', label: 'File Size', format: 'filesize' },+ { key: 'file', label: 'File', format: 'url' },+ ],+};++export const recordListSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', description: RECORD_FIELDS },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const searchRecordListSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', description: RECORD_FIELDS },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ ],+};++export const pagedRecordListSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', description: RECORD_FIELDS },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ ],+};++export const deleteResultSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Record ID', description: WS_ID },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+};++export const linkResultSchema: OutputSchema = {+ fields: [+ { key: 'sourceRecordId', label: 'Source Record ID', description: WS_ID },+ { key: 'relatedRecordId', label: 'Related Record ID', description: WS_ID },+ { key: 'relationLabel', label: 'Relation Label' },+ { key: 'linked', label: 'Linked', format: 'boolean' },+ ],+};++export const unlinkResultSchema: OutputSchema = {+ fields: [+ { key: 'sourceRecordId', label: 'Source Record ID', description: WS_ID },+ { key: 'relatedRecordId', label: 'Related Record ID', description: WS_ID },+ { key: 'unlinked', label: 'Unlinked', format: 'boolean' },+ ],+};++export const convertLeadSchema: OutputSchema = {+ fields: [+ { key: 'leadId', label: 'Lead ID', description: WS_ID },+ { key: 'contactId', label: 'Contact ID', description: WS_ID },+ { key: 'accountId', label: 'Organization ID', description: WS_ID },+ { key: 'potentialId', label: 'Deal ID', description: WS_ID },+ ],+};++export const findOrCreateSchema: OutputSchema = {+ fields: [+ { key: 'created', label: 'Created', format: 'boolean' },+ { key: 'matchCount', label: 'Match Count', format: 'number', description: 'Matches found (capped at 2).' },+ { key: 'id', label: 'Record ID', description: WS_ID },+ { key: 'record', label: 'Record', description: RECORD_FIELDS },+ ],+};diff --git a/packages/pieces/community/vtiger/src/lib/rest-client.ts b/packages/pieces/community/vtiger/src/lib/rest-client.tsnew file mode 100644index 00000000000..64089425eff--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/rest-client.ts@@ -0,0 +1,334 @@+import { HttpMethod, httpClient } from '@activepieces/pieces-common';++export class VtigerApiError extends Error {+ readonly code: string;+ readonly status: number | undefined;++ constructor({+ code,+ message,+ status,+ }: {+ code: string;+ message: string;+ status?: number;+ }) {+ super(`${code}: ${message}`);+ this.name = 'VtigerApiError';+ this.code = code;+ this.status = status;+ }+}++let verifiedTlsAgent: Promise<unknown> | undefined;++export function verifiedTlsDispatcher(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } })+ );+ return verifiedTlsAgent;+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export function normalizeInstanceUrl(raw: string): string {+ const trimmed = (raw ?? '').trim().replace(/\/+$/, '');+ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ throw new Error(+ 'The instance URL is not a valid URL. Use the form https://<instance>.od2.vtiger.com'+ );+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ throw new Error('The instance URL must start with https:// or http://');+ }+ if (url.username !== '' || url.password !== '') {+ throw new Error('The instance URL must not contain a username or password');+ }+ if (url.pathname.includes('restapi')) {+ throw new Error(+ 'Enter the URL without the endpoint. For example https://<instance>.od2.vtiger.com instead of https://<instance>.od2.vtiger.com/restapi/v1/vtiger/default'+ );+ }+ if ((url.pathname !== '' && url.pathname !== '/') || url.search !== '' || url.hash !== '') {+ throw new Error(+ 'The instance URL must not contain a path, query or fragment, for example https://<instance>.od2.vtiger.com'+ );+ }+ return url.origin;+}++const BLOCKED_HOSTNAMES = new Set([+ 'localhost',+ 'metadata',+ 'metadata.google.internal',+ 'instance-data',+]);++function ipv4Octets(host: string): number[] | undefined {+ if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) {+ return undefined;+ }+ const octets = host.split('.').map((part) => Number(part));+ return octets.every((octet) => octet >= 0 && octet <= 255) ? octets : undefined;+}++function isBlockedIpv4(octets: number[]): boolean {+ const [a, b] = octets;+ return (+ a === 0 ||+ a === 10 ||+ a === 127 ||+ (a === 169 && b === 254) ||+ (a === 172 && b >= 16 && b <= 31) ||+ (a === 192 && b === 168) ||+ (a === 100 && b >= 64 && b <= 127)+ );+}++function mappedIpv4(host: string): number[] | undefined {+ const rest = host.slice('::ffff:'.length);+ const dotted = ipv4Octets(rest);+ if (dotted) {+ return dotted;+ }+ const groups = rest.split(':');+ if (groups.length !== 2 || !groups.every((g) => /^[0-9a-f]{1,4}$/.test(g))) {+ return undefined;+ }+ const high = parseInt(groups[0], 16);+ const low = parseInt(groups[1], 16);+ return [high >> 8, high & 255, low >> 8, low & 255];+}++export function isBlockedHost(hostname: string): boolean {+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');+ if (BLOCKED_HOSTNAMES.has(host) || host.endsWith('.localhost')) {+ return true;+ }+ const v4 = ipv4Octets(host);+ if (v4) {+ return isBlockedIpv4(v4);+ }+ if (!host.includes(':')) {+ return false;+ }+ if (host === '::' || host === '::1') {+ return true;+ }+ if (host.startsWith('::ffff:')) {+ const mapped = mappedIpv4(host);+ return mapped === undefined ? true : isBlockedIpv4(mapped);+ }+ return /^f[cd]/.test(host) || /^fe[89ab]/.test(host);+}++export function assertPublicInstanceUrl(raw: string): string {+ const origin = normalizeInstanceUrl(raw);+ if (isBlockedHost(new URL(origin).hostname)) {+ throw new Error(+ 'The instance URL points to a private, loopback, link-local or metadata address, which is not allowed'+ );+ }+ return origin;+}++export function restBaseUrl(creds: VtigerCredentials): string {+ return `${normalizeInstanceUrl(creds.instance_url)}${REST_PATH}`;+}++export function basicAuthorization(creds: VtigerCredentials): string {+ return `Basic ${Buffer.from(`${creds.username}:${creds.password}`).toString('base64')}`;+}++function statusMessage(status: number): string {+ if (status === 401 || status === 403) {+ return 'Vtiger rejected the username or access key, or the user lacks permission for this operation';+ }+ if (status === 404) {+ return 'The Vtiger endpoint or record was not found';+ }+ if (status === 400) {+ return 'Vtiger rejected the request (HTTP 400). The record may not exist or may be deleted, or a module, relation label, field name or query is invalid';+ }+ if (status === 429) {+ return 'Vtiger rate limit reached; retry later';+ }+ return `Vtiger returned HTTP ${status}`;+}++export function envelopeError({+ body,+ status,+}: {+ body: unknown;+ status?: number;+}): VtigerApiError {+ const error = isRecord(body) && isRecord(body['error']) ? body['error'] : undefined;+ const code = error && typeof error['code'] === 'string' && error['code'] !== '' ? error['code'] : undefined;+ const message =+ error && typeof error['message'] === 'string' && error['message'] !== ''+ ? error['message']+ : undefined;+ return new VtigerApiError({+ code: code ?? (status ? `HTTP_${status}` : 'UNEXPECTED_RESPONSE'),+ message:+ message !== undefined && message !== code+ ? message+ : status+ ? statusMessage(status)+ : message ?? 'Vtiger returned a response without a success flag',+ status,+ });+}++export function unwrapEnvelope<T>({+ body,+ status,+}: {+ body: VtigerEnvelope<T> | undefined;+ status?: number;+}): T {+ if (isRecord(body) && body.success === true && body.result !== undefined) {+ return body.result;+ }+ throw envelopeError({+ body,+ status: isRecord(body) && body.success === false ? undefined : status,+ });+}++function readHttpFailure(error: unknown): { status: number; body: unknown } | undefined {+ if (typeof error !== 'object' || error === null || !('response' in error)) {+ return undefined;+ }+ const response = error.response;+ if (!isRecord(response) || typeof response['status'] !== 'number') {+ return undefined;+ }+ return { status: response['status'], body: response['body'] };+}++export async function sendVtiger<T>({+ url,+ method,+ headers,+ query,+ form,+}: {+ url: string;+ method: HttpMethod;+ headers?: Record<string, string>;+ query?: Record<string, string>;+ form?: Record<string, string>;+}): Promise<VtigerEnvelope<T>> {+ const dispatcher = await verifiedTlsDispatcher();+ try {+ const response = await httpClient.sendRequest<VtigerEnvelope<T>>(+ {+ method,+ url,+ headers: {+ Accept: 'application/json',+ ...(form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),+ ...headers,+ },+ queryParams: query,+ body: form ? new URLSearchParams(form).toString() : undefined,+ followRedirects: false,+ },+ { dispatcher }+ );+ if (response.status >= 300) {+ throw new VtigerApiError({+ code: `HTTP_${response.status}`,+ message:+ 'The Vtiger instance redirected the request. Check that the instance URL uses the final address (for example https instead of http).',+ status: response.status,+ });+ }+ if (!isRecord(response.body) || response.body.success !== true) {+ throw envelopeError({+ body: response.body,+ status: isRecord(response.body) && response.body.success === false ? undefined : response.status,+ });+ }+ return response.body;+ } catch (error) {+ const failure = readHttpFailure(error);+ if (failure && failure.status === 404 && url.includes(REST_PATH)) {+ throw new VtigerApiError({ code: REST_UNAVAILABLE, message: REST_UNAVAILABLE_MESSAGE, status: 404 });+ }+ if (failure) {+ throw envelopeError({ body: failure.body, status: failure.status });+ }+ throw error;+ }+}++export async function deleteRestRecord({ creds, id }: { creds: VtigerCredentials; id: string }): Promise<void> {+ await vtigerRest<unknown>({ creds, method: HttpMethod.POST, path: 'delete', form: { id } });+}++export async function fetchPicklistDependency({+ creds,+ module,+ sourceField,+ targetField,+}: {+ creds: VtigerCredentials;+ module: string;+ sourceField: string;+ targetField: string;+}): Promise<unknown> {+ return vtigerRest<unknown>({+ creds,+ method: HttpMethod.GET,+ path: 'picklist_dependency',+ query: { module, sourcefield: sourceField, targetfield: targetField },+ });+}++export async function vtigerRest<T = unknown>({+ creds,+ method,+ path,+ query,+ form,+}: {+ creds: VtigerCredentials;+ method: HttpMethod;+ path: string;+ query?: Record<string, string>;+ form?: Record<string, string>;+}): Promise<T> {+ const envelope = await sendVtiger<T>({+ url: `${restBaseUrl(creds)}/${path}`,+ method,+ headers: { Authorization: basicAuthorization(creds) },+ query,+ form,+ });+ return unwrapEnvelope<T>({ body: envelope });+}++export type VtigerCredentials = {+ instance_url: string;+ username: string;+ password: string;+};++export type VtigerEnvelope<T> = {+ success?: boolean;+ result?: T;+ error?: { code?: string; message?: string };+};++export const REST_PATH = '/restapi/v1/vtiger/default';+export const REST_UNAVAILABLE = 'REST_API_UNAVAILABLE';+export const REST_UNAVAILABLE_MESSAGE =+ 'This action needs the Vtiger Cloud REST API (/restapi/v1), which self-hosted/open-source Vtiger does not provide. Use the Create/Get/Update/Delete/Query/Search Record actions instead.';diff --git a/packages/pieces/community/vtiger/src/lib/triggers/new-or-updated-record.ts b/packages/pieces/community/vtiger/src/lib/triggers/new-or-updated-record.tsindex 334665b960e..d485da5190c 100644--- a/packages/pieces/community/vtiger/src/lib/triggers/new-or-updated-record.ts+++ b/packages/pieces/community/vtiger/src/lib/triggers/new-or-updated-record.ts@@ -1,25 +1,158 @@-import {- AuthenticationType,- DedupeStrategy,- HttpMethod,- Polling,- httpClient,- pollingHelper,-} from '@activepieces/pieces-common';+import { DedupeStrategy, HttpMethod, Polling, pollingHelper } from '@activepieces/pieces-common';import {AppConnectionValueForAuthProperty,createTrigger,- PiecePropValueSchema,Property,TriggerStrategy,} from '@activepieces/pieces-framework';-import { vtigerAuth } from '../..';-import {- elementTypeProperty,- instanceLogin,- prepareHttpRequest,-} from '../common';import dayjs from 'dayjs';+import utc from 'dayjs/plugin/utc';+import { vtigerAuth } from '../auth';+import { elementTypeProperty, propText } from '../common';+import { isRecord, VtigerApiError, VtigerCredentials, vtigerRest } from '../rest-client';+import { restOrVtws, vtwsCall, vtwsLogin, vtwsQuery, VtwsSession } from '../vtws';+import { assertModuleName, clampLimit } from '../vtql';++dayjs.extend(utc);++export function vtigerTimeToEpochMs(value: unknown): number {+ if (typeof value !== 'string' || value.trim() === '') {+ return 0;+ }+ const parsed = dayjs.utc(value.trim(), 'YYYY-MM-DD HH:mm:ss');+ return parsed.isValid() ? parsed.valueOf() : 0;+}++export async function fetchChangedRecords({+ creds,+ module,+ syncType,+ limit,+ lastFetchEpochMS,+}: {+ creds: VtigerCredentials;+ module: string;+ syncType: string;+ limit: number;+ lastFetchEpochMS: number;+}): Promise<Record<string, unknown>[]> {+ const transport = changeTransport(creds);+ let modifiedTimeSec = Math.floor(lastFetchEpochMS / 1000);+ let changed: SyncItem[] = [];+ let more = true;+ let pages = 0;+ while (more && changed.length < limit && pages < MAX_SYNC_PAGES) {+ const res = await transport.sync({ modifiedTime: String(modifiedTimeSec), elementType: module, syncType });+ const deleted = new Set(syncIds(res.deleted));+ const seen = new Set(changed.map((item) => item.id));+ const fresh = syncItems(res.updated).filter((item) => !deleted.has(item.id) && !seen.has(item.id));+ changed = [...changed, ...fresh].slice(0, limit);+ more = res.more === true;+ const next = Number(res.lastModifiedTime);+ if (!Number.isFinite(next) || next <= modifiedTimeSec) {+ break;+ }+ modifiedTimeSec = next;+ pages++;+ }+ const records: Record<string, unknown>[] = [];+ for (const item of changed) {+ const record = item.record ?? (await retrieveUnlessDeleted({ retrieve: transport.retrieve, id: item.id }));+ if (record !== undefined) {+ records.push(record);+ }+ }+ return records;+}++export function isMissingRecordError(error: unknown): boolean {+ return (+ error instanceof VtigerApiError &&+ (error.status === 400 || error.status === 404 || MISSING_RECORD_CODES.has(error.code))+ );+}++async function retrieveUnlessDeleted({+ retrieve,+ id,+}: {+ retrieve: (id: string) => Promise<Record<string, unknown>>;+ id: string;+}): Promise<Record<string, unknown> | undefined> {+ try {+ return await retrieve(id);+ } catch (error) {+ if (isMissingRecordError(error)) {+ return undefined;+ }+ throw error;+ }+}++export async function fetchNewestRecords({+ creds,+ module,+ watchBy,+}: {+ creds: VtigerCredentials;+ module: string;+ watchBy: string;+}): Promise<Record<string, unknown>[]> {+ const column = watchBy === 'createdtime' ? 'createdtime' : 'modifiedtime';+ const query = `SELECT * FROM ${assertModuleName(module)} ORDER BY ${column} DESC LIMIT ${TEST_SAMPLE_SIZE};`;+ const rows = await restOrVtws<unknown>({+ rest: () => vtigerRest<unknown>({ creds, method: HttpMethod.GET, path: 'query', query: { query } }),+ vtws: async () => vtwsQuery<unknown>({ creds, session: await vtwsLogin(creds), query }),+ });+ return Array.isArray(rows) ? rows.filter(isRecord) : [];+}++function changeTransport(creds: VtigerCredentials) {+ let mode: 'rest' | 'vtws' = 'rest';+ let session: Promise<VtwsSession> | undefined;+ const vtwsSession = () => {+ session ??= vtwsLogin(creds);+ return session;+ };+ const vtwsSync = async (params: Record<string, string>) =>+ (await vtwsCall<SyncResult>({ creds, session: await vtwsSession(), operation: 'sync', params })).result;+ const vtwsRetrieve = async (id: string) =>+ (await vtwsCall<Record<string, unknown>>({ creds, session: await vtwsSession(), operation: 'retrieve', params: { id } }))+ .result;+ return {+ sync: async (params: Record<string, string>): Promise<SyncResult> => {+ if (mode === 'vtws') {+ return vtwsSync(params);+ }+ return restOrVtws<SyncResult>({+ rest: () => vtigerRest<SyncResult>({ creds, method: HttpMethod.GET, path: 'sync', query: params }),+ vtws: () => {+ mode = 'vtws';+ return vtwsSync(params);+ },+ });+ },+ retrieve: async (id: string): Promise<Record<string, unknown>> =>+ mode === 'vtws'+ ? vtwsRetrieve(id)+ : vtigerRest<Record<string, unknown>>({ creds, method: HttpMethod.GET, path: 'retrieve', query: { id } }),+ };+}++function syncItems(value: unknown): SyncItem[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.flatMap((item): SyncItem[] => {+ if (typeof item === 'string') {+ return [{ id: item }];+ }+ if (isRecord(item) && typeof item['id'] === 'string') {+ return [{ id: item['id'], record: Object.keys(item).length > 1 ? item : undefined }];+ }+ return [];+ });+}export const newOrUpdatedRecord = createTrigger({auth: vtigerAuth,@@ -27,9 +160,10 @@ export const newOrUpdatedRecord = createTrigger({classification: 'READ',displayName: 'New or Updated Record',description:- 'Triggers when a new record is introduced or a record is updated.',+ 'Triggers when a new record is introduced or a record is updated. Deleted records are not emitted.',aiMetadata: {- description: 'Fires when a record in the selected Vtiger module (element type) is created or modified, polling the sync API. Whether new records, updated records, or both fire is governed by the watched timestamp column (created time vs. modified time); the sync scope can be limited to the user, their groups, or the whole application.',+ description:+ 'Fires when a record in the selected Vtiger module (element type) is created or modified, polling the sync API. Whether new records, updated records, or both fire is governed by the watched timestamp column (created time vs. modified time); the sync scope can be limited to the user, their groups, or the whole application. Deletions are not emitted.',},props: {elementType: elementTypeProperty,@@ -59,137 +193,82 @@ export const newOrUpdatedRecord = createTrigger({}),limit: Property.Number({displayName: 'Limit',- description: 'Enter the maximum number of records to return.',+ description: 'Enter the maximum number of records to return per poll (1 to 1000).',defaultValue: 100,required: true,}),},sampleData: {- success: true,- result: [- {- id: '3x291',- createdtime: '2020-07-22 12:46:55',- modifiedtime: '2020-07-22 12:46:55',- },- ],+ id: '3x291',+ createdtime: '2020-07-22 12:46:55',+ modifiedtime: '2020-07-22 12:46:55',},type: TriggerStrategy.POLLING,async test(ctx) {- return await pollingHelper.test(polling, { ...ctx });+ const records = await fetchNewestRecords({+ creds: ctx.auth.props,+ module: propText(ctx.propsValue.elementType),+ watchBy: propText(ctx.propsValue.watchBy),+ });+ return records;},async onEnable(ctx) {- await pollingHelper.onEnable(polling, { ...ctx });+ await pollingHelper.onEnable(polling, ctx);},async onDisable(ctx) {- await pollingHelper.onDisable(polling, { ...ctx });+ await pollingHelper.onDisable(polling, ctx);},async run(ctx) {- return await pollingHelper.poll(polling, { ...ctx });+ return await pollingHelper.poll(polling, ctx);},});+function syncIds(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.flatMap((item): string[] => {+ if (typeof item === 'string') {+ return [item];+ }+ if (typeof item === 'object' && item !== null && 'id' in item && typeof item.id === 'string') {+ return [item.id];+ }+ return [];+ });+}+const polling: Polling<AppConnectionValueForAuthProperty<typeof vtigerAuth>,{ elementType?: string; watchBy?: string; limit?: number; syncType?: string }> = {strategy: DedupeStrategy.TIMEBASED,items: async ({ auth, propsValue, lastFetchEpochMS }) => {- const items = await fetchRecords({ auth, propsValue, lastFetchEpochMS });-- return (items ?? []).map((item) => {- return {- epochMilliSeconds: dayjs(- propsValue.watchBy === 'createdtime'- ? item['createdtime']- : item['modifiedtime']- ).valueOf(),- data: item,- };+ const items = await fetchChangedRecords({+ creds: auth.props,+ module: assertModuleName(propsValue.elementType),+ syncType: propsValue.syncType || 'application',+ limit: clampLimit({ value: propsValue.limit, fallback: 100, max: 1000 }),+ lastFetchEpochMS: lastFetchEpochMS || 0,});+ return items.map((item) => ({+ epochMilliSeconds: vtigerTimeToEpochMs(+ propsValue.watchBy === 'createdtime' ? item['createdtime'] : item['modifiedtime']+ ),+ data: item,+ }));},};-const fetchRecords = async ({- auth,- propsValue,- lastFetchEpochMS,-}: {- auth: AppConnectionValueForAuthProperty<typeof vtigerAuth>;- propsValue: Record<string, unknown>;- lastFetchEpochMS: number;-}) => {- const elementType = propsValue['elementType'] as string;- const limit = (propsValue['limit'] as number) ?? 100;- const syncType = (propsValue['syncType'] as string) ?? 'application';-- const baseUrl = `${auth.props.instance_url}/restapi/v1/vtiger/default`;-- // Vtiger expects UNIX timestamp (seconds)- let modifiedTimeSec = Math.floor((lastFetchEpochMS || 0) / 1000);+const MAX_SYNC_PAGES = 10;+const MISSING_RECORD_CODES = new Set(['RECORD_NOT_FOUND']);+const TEST_SAMPLE_SIZE = 5;- const updatedIds: string[] = [];- let more = true;- let safety = 0;-- while (more && updatedIds.length < limit && safety < 10) {- const syncResp = await httpClient.sendRequest<{- success: boolean;- result: { updated: string[]; deleted: string[]; more: boolean; lastModifiedTime: number };- }>({- method: HttpMethod.GET,- url: `${baseUrl}/sync`,- authentication: {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,- },- queryParams: {- modifiedTime: String(modifiedTimeSec),- elementType,- syncType,- },- });-- if (!syncResp.body?.success) break;-- const res = syncResp.body.result;- more = res.more === true;- modifiedTimeSec = res.lastModifiedTime || modifiedTimeSec;-- for (const id of res.updated ?? []) {- if (updatedIds.length < limit) updatedIds.push(id);- }-- safety++;- }-- if (updatedIds.length === 0) return [];-- const idsToFetch = updatedIds.slice(0, limit);-- const results: Record<string, any>[] = [];- for (const id of idsToFetch) {- const retrieveResp = await httpClient.sendRequest<{- success: boolean;- result: Record<string, any>;- }>({- method: HttpMethod.GET,- url: `${baseUrl}/retrieve`,- authentication: {- type: AuthenticationType.BASIC,- username: auth.props.username,- password: auth.props.password,- },- queryParams: {- id,- },- });-- if (retrieveResp.body?.success && retrieveResp.body.result) {- results.push(retrieveResp.body.result);- }- }-- return results;+type SyncResult = {+ updated?: unknown;+ deleted?: unknown;+ more?: boolean;+ lastModifiedTime?: number | string;};++type SyncItem = { id: string; record?: Record<string, unknown> };diff --git a/packages/pieces/community/vtiger/src/lib/vtql.ts b/packages/pieces/community/vtiger/src/lib/vtql.tsnew file mode 100644index 00000000000..4afb9671753--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/vtql.ts@@ -0,0 +1,139 @@+export function assertModuleName(value: unknown): string {+ const name = typeof value === 'string' ? value.trim() : '';+ if (!MODULE_NAME.test(name)) {+ throw new Error(+ `Invalid module name "${String(value ?? '')}". Use the API name of the module, for example Contacts, Leads or Accounts (see List Modules).`+ );+ }+ return name;+}++export function assertRecordId({+ value,+ label = 'Record ID',+}: {+ value: unknown;+ label?: string;+}): string {+ const id = typeof value === 'string' ? value.trim() : '';+ if (!RECORD_ID.test(id)) {+ throw new Error(+ `${label} "${String(value ?? '')}" is not a Vtiger webservice ID. IDs look like 12x345 (module prefix, "x", record number).`+ );+ }+ return id;+}++export function assertFieldName(value: unknown): string {+ const name = typeof value === 'string' ? value.trim() : '';+ if (!FIELD_NAME.test(name)) {+ throw new Error(+ `Invalid field name "${String(value ?? '')}". Use the field's API name from Describe Module, for example lastname or cf_853.`+ );+ }+ return name;+}++export function vtqlQuote(value: string): string {+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;+}++export function escapeLikePattern(value: string): string {+ return value.replace(/[\\%_]/g, (char) => `\\${char}`);+}++export function filterValueToString(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ if (typeof value === 'boolean') {+ return value ? '1' : '0';+ }+ if (typeof value === 'number') {+ if (!Number.isFinite(value)) {+ throw new Error(`Filter value ${value} is not a finite number`);+ }+ return String(value);+ }+ if (typeof value === 'string') {+ return value;+ }+ throw new Error('Filter values must be text, numbers or booleans');+}++export function buildWhere({ filters }: { filters: VtqlFilter[] }): string {+ if (filters.length === 0) {+ return '';+ }+ const clauses = filters.map(({ field, value, operator }) => {+ const name = assertFieldName(field);+ return operator === 'LIKE'+ ? `${name} LIKE ${vtqlQuote(`%${escapeLikePattern(value)}%`)}`+ : `${name} = ${vtqlQuote(value)}`;+ });+ return ` WHERE ${clauses.join(' AND ')}`;+}++export function clampLimit({+ value,+ fallback,+ max,+}: {+ value: unknown;+ fallback: number;+ max: number;+}): number {+ if (value === undefined || value === null || value === '') {+ return fallback;+ }+ const n = typeof value === 'number' ? value : Number(value);+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1) {+ throw new Error(`Limit must be a whole number between 1 and ${max}`);+ }+ return Math.min(n, max);+}++export async function pagedQuery<R>({+ module,+ where,+ orderBy,+ limit,+ fetchPage,+}: {+ module: string;+ where: string;+ orderBy?: string;+ limit: number;+ fetchPage: (query: string) => Promise<R[]>;+}): Promise<{ records: R[]; hasMore: boolean }> {+ const name = assertModuleName(module);+ const order = orderBy ? ` ORDER BY ${assertFieldName(orderBy)}` : '';+ let records: R[] = [];+ let offset = 0;+ let lastPageFull = false;+ while (records.length < limit) {+ const size = Math.min(VTQL_PAGE_SIZE, limit - records.length);+ const page = await fetchPage(+ `SELECT * FROM ${name}${where}${order} LIMIT ${offset}, ${size};`+ );+ records = [...records, ...page.slice(0, size)];+ lastPageFull = page.length >= size;+ if (!lastPageFull) {+ break;+ }+ offset += size;+ }+ return { records, hasMore: lastPageFull && records.length >= limit };+}++const MODULE_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;+const RECORD_ID = /^\d+x\d+$/;+const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;++export const VTQL_PAGE_SIZE = 100;++export type VtqlFilter = {+ field: string;+ value: string;+ operator: '=' | 'LIKE';+};diff --git a/packages/pieces/community/vtiger/src/lib/vtws.ts b/packages/pieces/community/vtiger/src/lib/vtws.tsnew file mode 100644index 00000000000..953e0330f86--- /dev/null+++ b/packages/pieces/community/vtiger/src/lib/vtws.ts@@ -0,0 +1,137 @@+import { HttpMethod } from '@activepieces/pieces-common';+import * as crypto from 'crypto-js';+import { Instance } from './models';+import {+ normalizeInstanceUrl,+ REST_UNAVAILABLE,+ sendVtiger,+ VtigerApiError,+ VtigerCredentials,+ VtigerEnvelope,+} from './rest-client';++export function calculateAuthKey({+ challengeToken,+ accessKey,+}: {+ challengeToken: string;+ accessKey: string;+}): string {+ return crypto.MD5(challengeToken + accessKey).toString(crypto.enc.Hex);+}++export function webserviceUrl(creds: VtigerCredentials): string {+ return `${normalizeInstanceUrl(creds.instance_url)}/webservice.php`;+}++export async function vtwsLogin(creds: VtigerCredentials): Promise<VtwsSession> {+ const url = webserviceUrl(creds);+ const challenge = await sendVtiger<{ token?: string }>({+ url,+ method: HttpMethod.GET,+ query: { operation: 'getchallenge', username: creds.username },+ });+ const token = challenge.result?.token;+ if (typeof token !== 'string' || token === '') {+ throw new VtigerApiError({+ code: 'CHALLENGE_FAILED',+ message: 'Vtiger did not return a login challenge token. Check the instance URL and username.',+ });+ }+ const login = await sendVtiger<Instance>({+ url,+ method: HttpMethod.POST,+ form: {+ operation: 'login',+ username: creds.username,+ accessKey: calculateAuthKey({ challengeToken: token, accessKey: creds.password }),+ },+ });+ const sessionName = login.result?.sessionId || login.result?.sessionName;+ if (!login.result || typeof sessionName !== 'string' || sessionName === '') {+ throw new VtigerApiError({+ code: 'LOGIN_FAILED',+ message: 'Vtiger did not return a session. Check the username and access key.',+ });+ }+ return { sessionName, instance: login.result };+}++export async function vtwsCall<T>({+ creds,+ session,+ operation,+ params,+}: {+ creds: VtigerCredentials;+ session: VtwsSession;+ operation: VtwsOperation;+ params: Record<string, string>;+}): Promise<VtwsResult<T>> {+ const data = { ...params, operation, sessionName: session.sessionName };+ const envelope: VtigerEnvelope<T> = await sendVtiger<T>(+ READ_OPERATIONS.has(operation)+ ? { url: webserviceUrl(creds), method: HttpMethod.GET, query: data }+ : { url: webserviceUrl(creds), method: HttpMethod.POST, form: data }+ );+ if (envelope.result === undefined) {+ throw new VtigerApiError({+ code: 'UNEXPECTED_RESPONSE',+ message: `Vtiger returned no result for ${operation}`,+ });+ }+ return { success: true, result: envelope.result };+}++export async function vtwsQuery<R>({+ creds,+ session,+ query,+}: {+ creds: VtigerCredentials;+ session: VtwsSession;+ query: string;+}): Promise<R[]> {+ const { result } = await vtwsCall<R[]>({ creds, session, operation: 'query', params: { query } });+ return Array.isArray(result) ? result : [];+}++export async function restOrVtws<T>({+ rest,+ vtws,+}: {+ rest: () => Promise<T>;+ vtws: () => Promise<T>;+}): Promise<T> {+ try {+ return await rest();+ } catch (error) {+ if (error instanceof VtigerApiError && error.code === REST_UNAVAILABLE) {+ return vtws();+ }+ throw error;+ }+}++const READ_OPERATIONS = new Set<VtwsOperation>(['query', 'retrieve', 'describe', 'listtypes', 'sync']);++export type VtwsOperation =+ | 'create'+ | 'retrieve'+ | 'delete'+ | 'update'+ | 'revise'+ | 'query'+ | 'describe'+ | 'listtypes'+ | 'sync';++export type VtwsSession = {+ sessionName: string;+ instance: Instance;+};++export type VtwsResult<T> = {+ success: true;+ result: T;+};diff --git a/packages/pieces/community/vtiger/test/atomics.test.ts b/packages/pieces/community/vtiger/test/atomics.test.tsnew file mode 100644index 00000000000..1855bfa8c5c--- /dev/null+++ b/packages/pieces/community/vtiger/test/atomics.test.ts@@ -0,0 +1,528 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { vtiger } from '../src/index';+import { addTagsToRecordAction } from '../src/lib/actions/ai/add-tags-to-record';+import { convertLeadAction } from '../src/lib/actions/ai/convert-lead';+import { createModuleRecordAction } from '../src/lib/actions/ai/create-module-record';+import { deleteRecordByIdAction } from '../src/lib/actions/ai/delete-record-by-id';+import { describeModuleAction } from '../src/lib/actions/ai/describe-module';+import { downloadAttachmentAction } from '../src/lib/actions/ai/download-attachment';+import { findOrCreateRecordAction } from '../src/lib/actions/ai/find-or-create-record';+import { findRecordsByEmailOrPhoneAction } from '../src/lib/actions/ai/find-records-by-email-or-phone';+import { getAccountHierarchyAction } from '../src/lib/actions/ai/get-account-hierarchy';+import { getCurrentUserAction } from '../src/lib/actions/ai/get-current-user';+import { getPicklistDependencyAction } from '../src/lib/actions/ai/get-picklist-dependency';+import { getRecordByIdAction } from '../src/lib/actions/ai/get-record-by-id';+import { getRecordTagsAction } from '../src/lib/actions/ai/get-record-tags';+import { linkRecordsAction } from '../src/lib/actions/ai/link-records';+import { listChangedRecordsAction } from '../src/lib/actions/ai/list-changed-records';+import { listModulesAction } from '../src/lib/actions/ai/list-modules';+import { listRelatedRecordsAction } from '../src/lib/actions/ai/list-related-records';+import { listRelationTypesAction } from '../src/lib/actions/ai/list-relation-types';+import { queryRelatedRecordsAction } from '../src/lib/actions/ai/query-related-records';+import { removeTagsFromRecordAction } from '../src/lib/actions/ai/remove-tags-from-record';+import { reopenRecordAction } from '../src/lib/actions/ai/reopen-record';+import { searchModuleRecordsAction } from '../src/lib/actions/ai/search-module-records';+import { unlinkRecordsAction } from '../src/lib/actions/ai/unlink-records';+import { updateRecordFieldsAction } from '../src/lib/actions/ai/update-record-fields';+import { basic, fail, ok, REST, runAction, stubVtiger } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++function only<T>(seen: T[]): T {+ expect(seen).toHaveLength(1);+ return seen[0];+}++describe('piece surface', () => {+ const actions = Object.values(vtiger.actions());+ const ai = actions.filter((a) => a.audience === 'ai');++ test('24 ai atomics, 6 demoted, query_records stays both', () => {+ expect(ai).toHaveLength(24);+ expect(+ actions.filter((a) => a.audience === 'human' && a.name !== 'custom_api_call').map((a) => a.name).sort()+ ).toEqual(['create_record', 'delete_record', 'get_record', 'make_api_call', 'search_records', 'update_record']);+ expect(actions.find((a) => a.name === 'query_records')?.audience).toBe('both');+ });++ test('classification counts READ 7 / SEARCH 7 / WRITE 9 / DESTRUCTIVE 1', () => {+ const count = (c: string) => ai.filter((a) => a.classification === c).length;+ expect([count('READ'), count('SEARCH'), count('WRITE'), count('DESTRUCTIVE')]).toEqual([7, 7, 9, 1]);+ });++ test('every ai atomic has aiMetadata and an outputSchema', () => {+ for (const a of ai) {+ expect(a.aiMetadata?.description, a.name).toBeTruthy();+ expect(typeof a.aiMetadata?.idempotent, a.name).toBe('boolean');+ expect(a.outputSchema, a.name).toBeDefined();+ }+ });++ test('non-idempotent set matches the reviewed map (D7/D8)', () => {+ expect(ai.filter((a) => a.aiMetadata?.idempotent === false).map((a) => a.name).sort()).toEqual([+ 'convert_lead',+ 'create_module_record',+ 'delete_record_by_id',+ 'find_or_create_record',+ 'reopen_record',+ ]);+ });++ test('release floor and ai props are plain text (no dropdowns)', () => {+ expect(vtiger.minimumSupportedRelease).toBe('0.88.2');+ for (const a of ai) {+ for (const [key, prop] of Object.entries(a.props)) {+ const type = typeof prop === 'object' && prop !== null && 'type' in prop ? prop.type : undefined;+ expect(['DROPDOWN', 'DYNAMIC', 'MULTI_SELECT_DROPDOWN'], `${a.name}.${key}`).not.toContain(type);+ }+ }+ });+});++describe('open-source instance (no REST v1)', () => {+ test.each([+ [getCurrentUserAction, {}],+ [searchModuleRecordsAction, { module: 'Contacts' }],+ [createModuleRecordAction, { module: 'Contacts', fields: { lastname: 'x' } }],+ [listChangedRecordsAction, { module: 'Contacts', modifiedSince: '1' }],+ ])('%#: REST 404 gives the Cloud-only message', async (action, props) => {+ stubVtiger([]);+ await expect(runAction({ action, props })).rejects.toThrow('needs the Vtiger Cloud REST API (/restapi/v1)');+ });+});++describe('READ atomics', () => {+ test('get_current_user GET /me', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/me', reply: ok({ id: '19x1', user_name: 'pat' }) }]);+ expect(await runAction({ action: getCurrentUserAction, props: {} })).toEqual({ id: '19x1', user_name: 'pat' });+ const req = only(seen);+ expect(req.path).toBe(`${REST}/me`);+ expect(req.headers.get('authorization')).toBe(basic());+ });++ test('list_modules GET /listtypes?fieldTypeList=null shapes modules', async () => {+ const seen = stubVtiger([+ {+ method: 'GET',+ path: '/listtypes',+ reply: ok({+ types: ['Contacts', 'HelpDesk'],+ information: { Contacts: { isEntity: true, label: 'Contacts', singular: 'Contact' }, HelpDesk: { isEntity: '1', label: 'Tickets', singular: 'Ticket' } },+ }),+ },+ ]);+ expect(await runAction({ action: listModulesAction, props: {} })).toEqual({+ modules: [+ { name: 'Contacts', label: 'Contacts', singular: 'Contact', isEntity: true },+ { name: 'HelpDesk', label: 'Tickets', singular: 'Ticket', isEntity: true },+ ],+ count: 2,+ });+ expect(only(seen).query).toEqual({ fieldTypeList: 'null' });+ });++ test('describe_module trims fields', async () => {+ const seen = stubVtiger([+ {+ method: 'GET',+ path: '/describe',+ reply: ok({+ name: 'Leads',+ label: 'Leads',+ idPrefix: '10',+ createable: true,+ updateable: true,+ deleteable: true,+ labelFields: 'firstname,lastname',+ fields: [+ { name: 'lastname', label: 'Last Name', mandatory: true, editable: true, type: { name: 'string' } },+ { name: 'leadstatus', label: 'Status', mandatory: false, type: { name: 'picklist', picklistValues: [{ label: 'Hot', value: 'Hot' }] } },+ { name: 'assigned_user_id', label: 'Assigned To', mandatory: true, type: { name: 'owner', refersTo: ['Users'] } },+ ],+ }),+ },+ ]);+ const out = await runAction({ action: describeModuleAction, props: { module: 'Leads' } });+ expect(only(seen).query).toEqual({ elementType: 'Leads' });+ expect(out).toMatchObject({+ name: 'Leads',+ labelFields: 'firstname,lastname',+ fieldCount: 3,+ fields: [+ { name: 'lastname', type: 'string', mandatory: true, picklistValues: [], refersTo: [] },+ { name: 'leadstatus', type: 'picklist', mandatory: false, picklistValues: ['Hot'] },+ { name: 'assigned_user_id', type: 'owner', refersTo: ['Users'] },+ ],+ });+ });++ test('get_record_by_id GET /retrieve?id', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/retrieve', reply: ok({ id: '4x7', lastname: 'Smith' }) }]);+ expect(await runAction({ action: getRecordByIdAction, props: { recordId: ' 4x7 ' } })).toEqual({+ id: '4x7',+ record: { id: '4x7', lastname: 'Smith' },+ });+ expect(only(seen).query).toEqual({ id: '4x7' });+ });++ test('get_record_by_id rejects a bare number before any request', async () => {+ const seen = stubVtiger([]);+ await expect(runAction({ action: getRecordByIdAction, props: { recordId: '7' } })).rejects.toThrow('webservice ID');+ expect(seen).toHaveLength(0);+ });++ test('list_changed_records GET /sync with unix seconds from ISO', async () => {+ const seen = stubVtiger([+ { method: 'GET', path: '/sync', reply: ok({ updated: [{ id: '4x1' }, '4x2'], deleted: ['4x3'], more: true, lastModifiedTime: 1767225600 }) },+ ]);+ const out = await runAction({+ action: listChangedRecordsAction,+ props: { module: 'Contacts', modifiedSince: '2026-01-01T00:00:00Z', syncType: 'user' },+ });+ expect(only(seen).query).toEqual({ modifiedTime: '1767225600', elementType: 'Contacts', syncType: 'user' });+ expect(out).toEqual({+ updatedIds: ['4x1', '4x2'],+ deletedIds: ['4x3'],+ updatedCount: 2,+ deletedCount: 1,+ more: true,+ lastModifiedTime: 1767225600,+ });+ });++ test('list_changed_records accepts unix seconds and ms', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/sync', reply: ok({ updated: [], deleted: [], more: false }) }]);+ await runAction({ action: listChangedRecordsAction, props: { module: 'Contacts', modifiedSince: '1767225600000' } });+ expect(seen[0].query['modifiedTime']).toBe('1767225600');+ expect(seen[0].query['syncType']).toBe('application');+ });++ test('list_relation_types GET /relatedtypes', async () => {+ const seen = stubVtiger([+ {+ method: 'GET',+ path: '/relatedtypes',+ reply: ok({+ types: ['Contacts', 'Calendar'],+ information: {+ '1': { name: 'Contacts', label: 'Contacts', translated_label: 'Contacts', relation_id: '1', actions: 'add' },+ '6': { name: 'Calendar', label: 'Activities', translated_label: 'Activities', relation_id: '6', actions: 'ADD' },+ },+ }),+ },+ ]);+ expect(await runAction({ action: listRelationTypesAction, props: { module: 'Accounts' } })).toEqual({+ relations: [+ { relationId: '1', relatedModule: 'Contacts', relationLabel: 'Contacts', translatedLabel: 'Contacts', actions: 'add' },+ { relationId: '6', relatedModule: 'Calendar', relationLabel: 'Activities', translatedLabel: 'Activities', actions: 'add' },+ ],+ count: 2,+ });+ expect(only(seen).query).toEqual({ elementType: 'Accounts' });+ });++ test('get_record_tags GET /tags_retrieve', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/tags_retrieve', reply: ok({ tags: ['vip', 'hot'] }) }]);+ expect(await runAction({ action: getRecordTagsAction, props: { recordId: '4x7' } })).toEqual({+ recordId: '4x7',+ tags: ['vip', 'hot'],+ count: 2,+ });+ expect(only(seen).query).toEqual({ id: '4x7' });+ });++ test('get_account_hierarchy GET /get_account_hierarchy', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/get_account_hierarchy', reply: ok({ '11x1': { accountname: 'Acme' } }) }]);+ expect(await runAction({ action: getAccountHierarchyAction, props: { accountId: '11x1' } })).toEqual({+ accountId: '11x1',+ hierarchy: { '11x1': { accountname: 'Acme' } },+ });+ expect(only(seen).query).toEqual({ id: '11x1' });+ });++ test('get_picklist_dependency GET /picklist_dependency with lower-case vendor params', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/picklist_dependency', reply: ok({ sourcefield: 'leadstatus', targetfield: 'rating', valuemapping: [{ sourcevalue: 'Hot', targetvalues: ['A'] }] }) }]);+ const out = await runAction({+ action: getPicklistDependencyAction,+ props: { module: 'Leads', sourceField: 'leadstatus', targetField: 'rating' },+ });+ expect(only(seen).query).toEqual({ module: 'Leads', sourcefield: 'leadstatus', targetfield: 'rating' });+ expect(out).toEqual({ module: 'Leads', sourceField: 'leadstatus', targetField: 'rating',+ hasDependency: true,+ mappings: [{ sourceValue: 'Hot', targetValues: ['A'] }],+ });+ });++ test('get_picklist_dependency normalises the empty [] reply', async () => {+ stubVtiger([{ method: 'GET', path: '/picklist_dependency', reply: ok([]) }]);+ const out = await runAction({+ action: getPicklistDependencyAction,+ props: { module: 'Leads', sourceField: 'leadsource', targetField: 'leadstatus' },+ });+ expect(out).toEqual({ module: 'Leads', sourceField: 'leadsource', targetField: 'leadstatus', hasDependency: false, mappings: [] });+ });++ test('download_attachment writes the decoded file and never returns base64', async () => {+ const seen = stubVtiger([+ {+ method: 'GET',+ path: '/files_retrieve',+ reply: ok([{ fileid: '55', filename: 'photo.png', filetype: 'image/png', filesize: '5', filecontents: Buffer.from('hello').toString('base64') }]),+ },+ ]);+ const write = vi.fn(async () => 'https://files/1');+ const out = await runAction({ action: downloadAttachmentAction, props: { attachmentId: '4x7_55' }, files: { write } });+ expect(only(seen).query).toEqual({ id: '4x7_55' });+ expect(write).toHaveBeenCalledWith({ fileName: 'photo.png', data: Buffer.from('hello') });+ expect(out).toEqual({ attachmentId: '4x7_55', fileName: 'photo.png', fileType: 'image/png', fileSize: 5, file: 'https://files/1' });+ expect(JSON.stringify(out)).not.toContain('aGVsbG8');+ });++ test('download_attachment rejects ids with separators', async () => {+ stubVtiger([]);+ await expect(+ runAction({ action: downloadAttachmentAction, props: { attachmentId: '../x' }, files: { write: vi.fn() } })+ ).rejects.toThrow('imageattachmentids');+ });+});++describe('SEARCH atomics', () => {+ test('find_records_by_email_or_phone GET /lookup', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/lookup', reply: ok([{ id: '4x1', email: '[email protected]' }]) }]);+ const out = await runAction({+ action: findRecordsByEmailOrPhoneAction,+ props: { type: 'email', value: '[email protected]', modules: ['Contacts'] },+ });+ expect(only(seen).query).toEqual({ type: 'email', value: '[email protected]', searchIn: '["Contacts"]' });+ expect(out).toEqual({ records: [{ id: '4x1', email: '[email protected]' }], count: 1 });+ });++ test('lookup defaults modules and rejects a bad type', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/lookup', reply: ok([]) }]);+ await runAction({ action: findRecordsByEmailOrPhoneAction, props: { type: 'phone', value: '+1 555' } });+ expect(seen[0].query['searchIn']).toBe('["Contacts","Leads","Accounts"]');+ await expect(+ runAction({ action: findRecordsByEmailOrPhoneAction, props: { type: 'fax', value: '1' } })+ ).rejects.toThrow('email or phone');+ });++ test('list_related_records GET /retrieve_related', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/retrieve_related', reply: ok([{ id: '4x1' }]) }]);+ const out = await runAction({+ action: listRelatedRecordsAction,+ props: { recordId: '11x1', relatedLabel: 'Contacts', relatedModule: 'Contacts' },+ });+ expect(only(seen).query).toEqual({ id: '11x1', relatedLabel: 'Contacts', relatedType: 'Contacts' });+ expect(out).toEqual({ records: [{ id: '4x1' }], count: 1 });+ });++ test('query_related_records GET /query_related with built VTQL and paging', async () => {+ const rows = Array.from({ length: 10 }, (_, i) => ({ id: `4x${i}` }));+ const seen = stubVtiger([{ method: 'GET', path: '/query_related', reply: ok(rows) }]);+ const out = await runAction({+ action: queryRelatedRecordsAction,+ props: { recordId: '11x1', relatedModule: 'Calendar', relatedLabel: 'Activities', limit: 10, offset: 20 },+ });+ expect(only(seen).query).toEqual({ query: 'SELECT * FROM Calendar LIMIT 20, 10', id: '11x1', relatedLabel: 'Activities' });+ expect(out).toEqual({ records: rows, count: 10, offset: 20, hasMore: true });+ });++ test('query_related_records caps limit at 100 and validates offset', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/query_related', reply: ok([]) }]);+ await runAction({ action: queryRelatedRecordsAction, props: { recordId: '11x1', relatedModule: 'Contacts', relatedLabel: 'Contacts', limit: 500 } });+ expect(seen[0].query['query']).toBe('SELECT * FROM Contacts LIMIT 0, 100');+ await expect(+ runAction({ action: queryRelatedRecordsAction, props: { recordId: '11x1', relatedModule: 'Contacts', relatedLabel: 'Contacts', offset: -1 } })+ ).rejects.toThrow('Offset');+ await expect(+ runAction({ action: queryRelatedRecordsAction, props: { recordId: '11x1', relatedModule: 'Contacts' } })+ ).rejects.toThrow('Relation Label is required');+ });++ test('search_module_records builds an escaped server-side WHERE and pages', async () => {+ const page = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `4x${i}` }));+ const seen = stubVtiger([+ { method: 'GET', path: '/query', reply: (req) => ok(req.query['query'].includes('LIMIT 0,') ? page(100) : page(5)) },+ ]);+ const out = await runAction({+ action: searchModuleRecordsAction,+ props: { module: 'Contacts', filters: { lastname: "D'Arcy", emailoptout: true }, match: 'contains', limit: 500 },+ });+ expect(seen.map((s) => s.query['query'])).toEqual([+ "SELECT * FROM Contacts WHERE lastname LIKE '%D\\'Arcy%' AND emailoptout = '1' LIMIT 0, 100;",+ "SELECT * FROM Contacts WHERE lastname LIKE '%D\\'Arcy%' AND emailoptout = '1' LIMIT 100, 100;",+ ]);+ expect(out).toMatchObject({ count: 105, hasMore: false });+ });++ test('search_module_records exact match by default, JSON string filters accepted', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/query', reply: ok([]) }]);+ await runAction({ action: searchModuleRecordsAction, props: { module: 'Leads', filters: '{"email":"[email protected]"}' } });+ expect(seen[0].query['query']).toBe("SELECT * FROM Leads WHERE email = '[email protected]' LIMIT 0, 100;");+ });++ test('search_module_records rejects injected field names before any request', async () => {+ const seen = stubVtiger([]);+ await expect(+ runAction({ action: searchModuleRecordsAction, props: { module: 'Leads', filters: { '1=1 OR email': 'x' } } })+ ).rejects.toThrow('Invalid field name');+ expect(seen).toHaveLength(0);+ });+});++describe('WRITE / DESTRUCTIVE atomics', () => {+ test('create_module_record POST /create elementType + element JSON', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/create', reply: ok({ id: '4x9', lastname: 'Smith' }) }]);+ const out = await runAction({ action: createModuleRecordAction, props: { module: 'Contacts', fields: { lastname: 'Smith' } } });+ expect(only(seen).form).toEqual({ elementType: 'Contacts', element: '{"lastname":"Smith"}' });+ expect(out).toEqual({ id: '4x9', record: { id: '4x9', lastname: 'Smith' } });+ });++ test('create_module_record refuses empty fields or an id', async () => {+ stubVtiger([]);+ await expect(runAction({ action: createModuleRecordAction, props: { module: 'Contacts', fields: {} } })).rejects.toThrow('at least one');+ await expect(+ runAction({ action: createModuleRecordAction, props: { module: 'Contacts', fields: { id: '4x1', lastname: 'a' } } })+ ).rejects.toThrow('must not contain id');+ await expect(runAction({ action: createModuleRecordAction, props: { module: 'Contacts', fields: '[1]' } })).rejects.toThrow('JSON object');+ });++ test('update_record_fields POST /revise sends only the caller keys', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/revise', reply: ok({ id: '4x9', leadstatus: 'Hot' }) }]);+ const out = await runAction({ action: updateRecordFieldsAction, props: { recordId: '4x9', fields: { leadstatus: 'Hot', phone: '' } } });+ const req = only(seen);+ expect(req.path).toBe(`${REST}/revise`);+ expect(JSON.parse(req.form?.['element'] ?? '')).toEqual({ leadstatus: 'Hot', phone: '', id: '4x9' });+ expect(Object.keys(req.form ?? {})).toEqual(['element']);+ expect(out).toEqual({ id: '4x9', record: { id: '4x9', leadstatus: 'Hot' } });+ });++ test('update_record_fields rejects empty and mismatched id', async () => {+ stubVtiger([]);+ await expect(runAction({ action: updateRecordFieldsAction, props: { recordId: '4x9', fields: {} } })).rejects.toThrow('at least one');+ await expect(+ runAction({ action: updateRecordFieldsAction, props: { recordId: '4x9', fields: { id: '4x1', a: 'b' } } })+ ).rejects.toThrow('different from Record ID');+ });++ test('delete_record_by_id POST /delete', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/delete', reply: ok({ status: 'successful' }) }]);+ expect(await runAction({ action: deleteRecordByIdAction, props: { recordId: '4x9' } })).toEqual({ id: '4x9', deleted: true });+ expect(only(seen).form).toEqual({ id: '4x9' });+ });++ test('delete_record_by_id surfaces the vendor error on a missing record', async () => {+ stubVtiger([{ method: 'POST', path: '/delete', reply: fail({ code: 'RECORD_NOT_FOUND', message: 'not found' }) }]);+ await expect(runAction({ action: deleteRecordByIdAction, props: { recordId: '4x9' } })).rejects.toThrow('RECORD_NOT_FOUND: not found');+ });++ test('reopen_record POST /reopen', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/reopen', reply: ok({ message: 'Record reopened successfully.' }) }]);+ expect(await runAction({ action: reopenRecordAction, props: { recordId: '5x3' } })).toEqual({+ id: '5x3',+ reopened: true,+ message: 'Record reopened successfully.',+ });+ expect(only(seen).form).toEqual({ id: '5x3' });+ });++ test('link_records POST /add_related with relationIdLabel', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/add_related', reply: ok({ message: 'successful' }) }]);+ const out = await runAction({+ action: linkRecordsAction,+ props: { sourceRecordId: '11x1', relatedRecordId: '4x2', relationLabel: 'Contacts' },+ });+ expect(only(seen).form).toEqual({ sourceRecordId: '11x1', relatedRecordId: '4x2', relationIdLabel: 'Contacts' });+ expect(out).toMatchObject({ sourceRecordId: '11x1', relatedRecordId: '4x2', relationLabel: 'Contacts', linked: true });+ });++ test('unlink_records POST /delete_related', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/delete_related', reply: ok({ message: 'successful' }) }]);+ const out = await runAction({ action: unlinkRecordsAction, props: { sourceRecordId: '11x1', relatedRecordId: '4x2' } });+ expect(only(seen).form).toEqual({ sourceRecordId: '11x1', relatedRecordId: '4x2' });+ expect(out).toMatchObject({ unlinked: true });+ });++ test('add_tags_to_record POST /tags_add with a JSON array, deduplicated', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/tags_add', reply: ok({ message: 'tags added' }) }]);+ const out = await runAction({ action: addTagsToRecordAction, props: { recordId: '4x9', tags: ['vip', ' hot ', 'vip', ''] } });+ expect(only(seen).form).toEqual({ id: '4x9', tags: '["vip","hot"]' });+ expect(out).toEqual({ recordId: '4x9', tags: ['vip', 'hot'], message: 'tags added' });+ });++ test('remove_tags_from_record POST /tags_delete always sends delete_all=false (D1)', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/tags_delete', reply: ok([]) }]);+ await runAction({ action: removeTagsFromRecordAction, props: { recordId: '4x9', tags: ['vip'], delete_all: true } });+ expect(only(seen).form).toEqual({ id: '4x9', tags: '["vip"]', delete_all: 'false' });+ expect(Object.keys(removeTagsFromRecordAction.props)).not.toContain('delete_all');+ });++ test('tag actions refuse an empty tag list', async () => {+ stubVtiger([]);+ await expect(runAction({ action: addTagsToRecordAction, props: { recordId: '4x9', tags: [] } })).rejects.toThrow('at least one');+ });++ test('convert_lead POST /convertlead with the entities shape and /me as default owner', async () => {+ const seen = stubVtiger([+ { method: 'GET', path: '/me', reply: ok({ id: '19x1' }) },+ { method: 'POST', path: '/convertlead', reply: ok({ Contacts: '4x50', Accounts: '11x51', Potentials: '' }) },+ ]);+ const out = await runAction({+ action: convertLeadAction,+ props: {+ leadId: '10x5',+ createAccount: true,+ accountFields: { accountname: 'Acme' },+ createPotential: false,+ potentialFields: { potentialname: 'ignored' },+ },+ });+ expect(seen.map((s) => s.path)).toEqual([`${REST}/me`, `${REST}/convertlead`]);+ expect(JSON.parse(seen[1].form?.['element'] ?? '')).toEqual({+ leadId: '10x5',+ assignedTo: '19x1',+ entities: {+ Contacts: { create: true, name: 'Contacts' },+ Accounts: { accountname: 'Acme', create: true, name: 'Accounts' },+ },+ });+ expect(out).toMatchObject({ leadId: '10x5', contactId: '4x50', accountId: '11x51', potentialId: '' });+ });++ test('convert_lead requires the deal mandatory fields before any request', async () => {+ const seen = stubVtiger([]);+ await expect(+ runAction({+ action: convertLeadAction,+ props: { leadId: '10x5', assignedTo: '19x1', createPotential: true, potentialFields: { potentialname: 'X' } },+ })+ ).rejects.toThrow('closingdate, sales_stage');+ expect(seen).toHaveLength(0);+ });++ test('find_or_create_record returns the existing match without creating', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/query', reply: ok([{ id: '4x1', email: '[email protected]' }]) }]);+ const out = await runAction({+ action: findOrCreateRecordAction,+ props: { module: 'Contacts', matchField: 'email', matchValue: '[email protected]', fields: { lastname: 'A' } },+ });+ expect(only(seen).query['query']).toBe("SELECT * FROM Contacts WHERE email = '[email protected]' LIMIT 0, 2;");+ expect(out).toEqual({ created: false, matchCount: 1, id: '4x1', record: { id: '4x1', email: '[email protected]' } });+ });++ test('find_or_create_record creates with the match value when nothing matches', async () => {+ const seen = stubVtiger([+ { method: 'GET', path: '/query', reply: ok([]) },+ { method: 'POST', path: '/create', reply: ok({ id: '4x2', email: '[email protected]', lastname: 'A' }) },+ ]);+ const out = await runAction({+ action: findOrCreateRecordAction,+ props: { module: 'Contacts', matchField: 'email', matchValue: '[email protected]', fields: { lastname: 'A', email: 'other' } },+ });+ expect(JSON.parse(seen[1].form?.['element'] ?? '')).toEqual({ lastname: 'A', email: '[email protected]' });+ expect(out).toMatchObject({ created: true, matchCount: 0, id: '4x2' });+ });+});diff --git a/packages/pieces/community/vtiger/test/existing-actions.test.ts b/packages/pieces/community/vtiger/test/existing-actions.test.tsnew file mode 100644index 00000000000..6a220f4610c--- /dev/null+++ b/packages/pieces/community/vtiger/test/existing-actions.test.ts@@ -0,0 +1,442 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import { createRecord } from '../src/lib/actions/create-record';+import { deleteRecord } from '../src/lib/actions/delete-record';+import { getRecord } from '../src/lib/actions/get-record';+import { customApiCallAuthHeaders, makeAPICall, resolveCustomCallTarget } from '../src/lib/actions/make-api-call';+import { queryRecords } from '../src/lib/actions/query-records';+import { searchFiltersFromFields, searchRecords } from '../src/lib/actions/search-record';+import { updateRecord } from '../src/lib/actions/update-record';+import { getRecordReference, listModuleNames, moduleLabeler } from '../src/lib/common';+import {+ fetchChangedRecords,+ fetchNewestRecords,+ vtigerTimeToEpochMs,+} from '../src/lib/triggers/new-or-updated-record';+import { vtwsLogin } from '../src/lib/vtws';+import { auth, basic, creds, fail, INSTANCE, ok, REST, runAction, stubVtiger, vtwsRoutes } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('B3 VTWS login and failures throw', () => {+ test('getchallenge sends the username as an encoded query param', async () => {+ const seen = stubVtiger(vtwsRoutes());+ const session = await vtwsLogin(creds({ username: '[email protected]' }));+ expect(session.sessionName).toBe('sess1');+ expect(seen[0].query).toEqual({ operation: 'getchallenge', username: '[email protected]' });+ expect(seen[0].url).toContain('username=pat%2Bcrm%40acme.com');+ expect(seen[1].form).toEqual({+ operation: 'login',+ username: '[email protected]',+ accessKey: expect.stringMatching(/^[0-9a-f]{32}$/),+ });+ expect(seen.every((s) => s.dispatcher !== undefined)).toBe(true);+ });++ test('missing challenge token throws instead of a TypeError', async () => {+ stubVtiger([{ method: 'GET', path: '/webservice.php', operation: 'getchallenge', reply: ok({}) }]);+ await expect(vtwsLogin(creds())).rejects.toThrow('CHALLENGE_FAILED');+ });++ test('login failure fails the step (was: returned null)', async () => {+ stubVtiger([+ vtwsRoutes()[0],+ { method: 'POST', path: '/webservice.php', operation: 'login', reply: fail({ code: 'INVALID_AUTH_TOKEN', message: 'Specified token is invalid or expired' }) },+ ]);+ await expect(+ runAction({ action: getRecord, props: { elementType: 'Contacts', record: { id: '4x1' } } })+ ).rejects.toThrow('INVALID_AUTH_TOKEN: Specified token is invalid or expired');+ });++ test('delete of a missing id throws (was: returned the error envelope as success)', async () => {+ stubVtiger(+ vtwsRoutes([+ { method: 'POST', path: '/webservice.php', operation: 'delete', reply: fail({ code: 'INVALID_ID_ATTRIBUTE', message: 'Id specified is incorrect' }) },+ ])+ );+ await expect(+ runAction({ action: deleteRecord, props: { elementType: 'Contacts', record: { id: '4x999' } } })+ ).rejects.toThrow('INVALID_ID_ATTRIBUTE: Id specified is incorrect');+ });++ test('create keeps the envelope output shape and sends element JSON', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'POST', path: '/webservice.php', operation: 'create', reply: ok({ id: '4x7', lastname: 'Smith' }) }])+ );+ const out = await runAction({ action: createRecord, props: { elementType: 'Contacts', record: { lastname: 'Smith' } } });+ expect(out).toEqual({ success: true, result: { id: '4x7', lastname: 'Smith' } });+ expect(seen[2].form).toEqual({+ operation: 'create',+ sessionName: 'sess1',+ elementType: 'Contacts',+ element: '{"lastname":"Smith"}',+ });+ });++ test('get retrieves by id with GET query params', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'retrieve', reply: ok({ id: '4x7' }) }])+ );+ const out = await runAction({ action: getRecord, props: { elementType: 'Contacts', record: { id: '4x7' } } });+ expect(out).toEqual({ success: true, result: { id: '4x7' } });+ expect(seen[2].query).toEqual({ operation: 'retrieve', sessionName: 'sess1', elementType: 'Contacts', id: '4x7' });+ });+});++describe('B2 query_records', () => {+ test('success:false throws instead of returning {error}', async () => {+ stubVtiger(+ vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'query', reply: fail({ code: 'QUERY_SYNTAX_ERROR', message: 'Syntax error' }) }])+ );+ await expect(runAction({ action: queryRecords, props: { query: 'SELECT * FROM' } })).rejects.toThrow(+ 'QUERY_SYNTAX_ERROR: Syntax error'+ );+ });++ test('returns the row array and documents paging', async () => {+ const seen = stubVtiger(vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'query', reply: ok([{ count: '3' }]) }]));+ const out = await runAction({ action: queryRecords, props: { query: 'SELECT count(*) FROM Contacts;' } });+ expect(out).toEqual([{ count: '3' }]);+ expect(seen[2].query['query']).toBe('SELECT count(*) FROM Contacts;');+ expect(queryRecords.props.query.description).toContain('LIMIT offset, count');+ });+});++describe('B1 search_records searches past record 100 server-side', () => {+ test('pages with a WHERE clause instead of count(*) + client scan', async () => {+ const page = ({ n, from }: { n: number; from: number }) => Array.from({ length: n }, (_, i) => ({ id: `4x${from + i}` }));+ const seen = stubVtiger(+ vtwsRoutes([+ {+ method: 'GET',+ path: '/webservice.php',+ operation: 'query',+ reply: (req) => ok(req.query['query'].includes('LIMIT 0, 100') ? page({ n: 100, from: 0 }) : page({ n: 30, from: 100 })),+ },+ ])+ );+ const out = await runAction({+ action: searchRecords,+ props: { elementType: 'Contacts', fields: { lastname: "O'Hara", emailoptout: false, do_not_call: true }, limit: undefined },+ });+ expect(Array.isArray(out) && out.length).toBe(130);+ const queries = seen.filter((s) => s.query['operation'] === 'query').map((s) => s.query['query']);+ expect(queries).toEqual([+ "SELECT * FROM Contacts WHERE lastname LIKE '%O\\'Hara%' AND do_not_call = '1' LIMIT 0, 100;",+ "SELECT * FROM Contacts WHERE lastname LIKE '%O\\'Hara%' AND do_not_call = '1' LIMIT 100, 100;",+ ]);+ expect(queries.some((q) => q.includes('count(*)'))).toBe(false);+ });++ test('filter mapping skips empty text and unchecked boxes', () => {+ expect(searchFiltersFromFields({ a: '', b: false, c: undefined, d: 5, e: 'x' })).toEqual([+ { field: 'd', value: '5', operator: '=' },+ { field: 'e', value: 'x', operator: 'LIKE' },+ ]);+ });++ test('module name is validated before any request (B7)', async () => {+ const seen = stubVtiger(vtwsRoutes());+ await expect(+ runAction({ action: searchRecords, props: { elementType: 'Contacts WHERE 1=1', fields: {} } })+ ).rejects.toThrow('Invalid module name');+ expect(seen).toHaveLength(0);+ });+});++describe('B4/B11 update_record', () => {+ test('run uses revise (not full update) and the selected id wins over a field named id', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'POST', path: '/webservice.php', operation: 'revise', reply: ok({ id: '4x7', lastname: 'New' }) }])+ );+ const out = await runAction({+ action: updateRecord,+ props: { elementType: 'Contacts', id: '4x7', record: { lastname: 'New', id: '4x1' } },+ });+ expect(out).toEqual({ success: true, result: { id: '4x7', lastname: 'New' } });+ expect(seen[2].form?.['operation']).toBe('revise');+ expect(JSON.parse(seen[2].form?.['element'] ?? '{}')).toEqual({ lastname: 'New', id: '4x7' });+ });++ test('id dropdown logs in once (no retry loop / sleep after success) and caps at 100', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'query', reply: ok([{ id: '4x1', email: '[email protected]' }]) }])+ );+ const started = Date.now();+ const options = await Reflect.apply(updateRecord.props.id.options, undefined, [{ auth: auth(), elementType: 'Contacts' }, {}]);+ expect(Date.now() - started).toBeLessThan(1000);+ expect(options).toEqual({ disabled: false, options: [{ label: '[email protected]', value: '4x1' }] });+ expect(seen.filter((s) => s.query['operation'] === 'getchallenge')).toHaveLength(1);+ expect(seen[2].query['query']).toBe('SELECT * FROM Contacts LIMIT 100;');+ });++ test('id dropdown shows the reason when login fails', async () => {+ stubVtiger([{ method: 'GET', path: '/webservice.php', operation: 'getchallenge', reply: fail({ code: 'INVALID_USER', message: 'no such user' }) }]);+ const options = await Reflect.apply(updateRecord.props.id.options, undefined, [{ auth: auth(), elementType: 'Contacts' }, {}]);+ expect(options).toEqual({ disabled: true, options: [], placeholder: 'Could not load records: INVALID_USER: no such user' });+ });+});++describe('B5 module labels do not leak credentials across connections', () => {+ test('each connection describes with its own credentials', async () => {+ const seen = stubVtiger([+ { method: 'GET', path: '/describe', reply: ok({ labelFields: 'accountname', fields: [] }) },+ ]);+ const first = creds({ instance_url: 'https://one.od2.vtiger.com', username: 'a', password: 'A' });+ const second = creds({ instance_url: 'https://two.od2.vtiger.com', username: 'b', password: 'B' });+ expect(await moduleLabeler({ creds: first, module: 'Accounts' })({ accountname: 'Acme' })).toBe('Acme');+ expect(await moduleLabeler({ creds: second, module: 'Accounts' })({ accountname: 'Beta' })).toBe('Beta');+ expect(seen.map((s) => [s.origin, s.headers.get('authorization')])).toEqual([+ ['https://one.od2.vtiger.com', basic(first)],+ ['https://two.od2.vtiger.com', basic(second)],+ ]);+ });+});++describe('B10 reference dropdowns are capped and labelled', () => {+ test('getRecordReference queries LIMIT 100 and reports failures', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'query', reply: ok([{ id: '19x1', user_name: 'admin' }]) }])+ );+ const state = await getRecordReference({ auth: auth(), modules: ['Users'] });+ expect(state).toEqual({ disabled: false, options: [{ label: 'admin', value: '19x1' }] });+ expect(seen[2].query['query']).toBe('SELECT * FROM Users LIMIT 100;');+ const bad = await getRecordReference({ auth: auth(), modules: ['Users; x'] });+ expect(bad.disabled).toBe(true);+ });+});++describe('B6 deprecated make_api_call stays on the instance', () => {+ test.each([+ ['https://evil.example/x', 'must point to the connected instance'],+ ['https://acme.od2.vtiger.com.evil.io/webservice.php', 'must point to the connected instance'],+ ['http://acme.od2.vtiger.com/webservice.php', 'must point to the connected instance'],+ ['https://u:[email protected]/webservice.php', 'must point to the connected instance'],+ ['//evil.example/x', 'not a valid URL'],+ ])('rejects %s', (url, message) => {+ expect(() => resolveCustomCallTarget({ creds: creds(), url })).toThrow(message);+ });++ test('relative paths go to the REST base', () => {+ expect(resolveCustomCallTarget({ creds: creds(), url: '/me' })).toEqual({+ url: `${INSTANCE}/restapi/v1/vtiger/default/me`,+ useRestAuth: true,+ });+ expect(resolveCustomCallTarget({ creds: creds(), urlPath: '/me' }).useRestAuth).toBe(true);+ expect(() => resolveCustomCallTarget({ creds: creds(), urlPath: 'me' })).toThrow('must start with a slash');+ });++ test('cross-origin URL sends nothing, so no sessionName leaves the instance', async () => {+ const seen = stubVtiger(vtwsRoutes());+ await expect(+ runAction({ action: makeAPICall, props: { method: 'GET', url: 'https://evil.example/collect', data: {} } })+ ).rejects.toThrow('must point to the connected instance');+ expect(seen).toHaveLength(0);+ });++ test('same-origin webservice URL gets the session; a user Authorization header is dropped', async () => {+ const seen = stubVtiger(+ vtwsRoutes([{ method: 'GET', path: '/webservice.php', operation: 'listtypes', reply: ok({ types: ['Contacts'] }) }])+ );+ const out = await runAction({+ action: makeAPICall,+ props: {+ method: 'GET',+ url: `${INSTANCE}/webservice.php`,+ headers: { Authorization: 'Bearer x' },+ data: { operation: 'listtypes' },+ },+ });+ expect(out).toEqual({ success: true, result: { types: ['Contacts'] } });+ expect(seen[2].query).toEqual({ operation: 'listtypes', sessionName: 'sess1' });+ expect(seen[2].headers.get('authorization')).toBeNull();+ });++ test('non-2xx throws instead of returning {error}', async () => {+ stubVtiger([{ method: 'GET', path: '/me', reply: { status: 500, body: { message: 'boom' } } }]);+ await expect(runAction({ action: makeAPICall, props: { method: 'GET', url: '/me' } })).rejects.toThrow();+ });+});++describe('Custom API Call only sends credentials to the connected REST base', () => {+ test.each([+ 'https://evil.example/collect',+ 'https://acme.od2.vtiger.com.evil.io/restapi/v1/vtiger/default/me',+ 'http://acme.od2.vtiger.com/restapi/v1/vtiger/default/me',+ 'https://u:[email protected]/restapi/v1/vtiger/default/me',+ 'https://acme.od2.vtiger.com/webservice.php',+ 'https://acme.od2.vtiger.com/restapi/v1/vtiger/defaultx/me',+ ])('refuses %s', (url) => {+ expect(() => customApiCallAuthHeaders({ creds: creds(), url })).toThrow('must point to the connected instance');+ });++ test.each(['/me', 'me', `${INSTANCE}/restapi/v1/vtiger/default/me`, `${INSTANCE}/restapi/v1/vtiger/default`])(+ 'allows %s',+ (url) => {+ expect(customApiCallAuthHeaders({ creds: creds(), url })).toEqual({ Authorization: basic() });+ }+ );+});++describe('B9 trigger', () => {+ test('a record deleted between sync and retrieve is skipped; the rest are delivered', async () => {+ stubVtiger([+ { method: 'GET', path: '/sync', reply: ok({ updated: ['4x1', '4x2', '4x3'], deleted: [], more: false, lastModifiedTime: 200 }) },+ {+ method: 'GET',+ path: '/retrieve',+ reply: (req) => (req.query['id'] === '4x2' ? { status: 400 } : ok({ id: req.query['id'] })),+ },+ ]);+ const out = await fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 100_000 });+ expect(out.map((r) => r['id'])).toEqual(['4x1', '4x3']);+ });++ test('RECORD_NOT_FOUND from webservice.php is skipped', async () => {+ stubVtiger(+ vtwsRoutes([+ { method: 'GET', path: `${REST}/sync`, reply: { status: 404 } },+ { method: 'GET', path: '/webservice.php', operation: 'sync', reply: ok({ updated: ['12x4', '12x5'], deleted: [], more: false, lastModifiedTime: 5 }) },+ {+ method: 'GET',+ path: '/webservice.php',+ operation: 'retrieve',+ reply: (req) =>+ req.query['id'] === '12x4' ? fail({ code: 'RECORD_NOT_FOUND', message: 'Record not found' }) : ok({ id: '12x5' }),+ },+ ])+ );+ const out = await fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 1_000_000 });+ expect(out).toEqual([{ id: '12x5' }]);+ });++ test.each([+ ['permission', { status: 403 }],+ ['server error', { status: 500 }],+ ])('a %s error on retrieve still fails the poll', async (_label, reply) => {+ stubVtiger([+ { method: 'GET', path: '/sync', reply: ok({ updated: ['4x1'], deleted: [], more: false, lastModifiedTime: 200 }) },+ { method: 'GET', path: '/retrieve', reply },+ ]);+ await expect(+ fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 100_000 })+ ).rejects.toThrow();+ });++ test('Vtiger times are parsed as UTC', () => {+ expect(vtigerTimeToEpochMs('2026-01-02 03:04:05')).toBe(Date.UTC(2026, 0, 2, 3, 4, 5));+ expect(vtigerTimeToEpochMs('')).toBe(0);+ expect(vtigerTimeToEpochMs('garbage')).toBe(0);+ });++ test('test() reads the 5 newest records with one query (no full sync)', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/query', reply: ok([{ id: '4x9' }]) }]);+ const out = await fetchNewestRecords({ creds: creds(), module: 'Contacts', watchBy: 'createdtime' });+ expect(out).toEqual([{ id: '4x9' }]);+ expect(seen).toHaveLength(1);+ expect(seen[0].query['query']).toBe('SELECT * FROM Contacts ORDER BY createdtime DESC LIMIT 5;');+ });++ test('sync skips deleted ids, follows more with the cursor and stops if the cursor does not move', async () => {+ const seen = stubVtiger([+ {+ method: 'GET',+ path: '/sync',+ reply: (req) =>+ req.query['modifiedTime'] === '100'+ ? ok({ updated: ['4x1', '4x2'], deleted: ['4x2'], more: true, lastModifiedTime: 200 })+ : ok({ updated: [{ id: '4x3' }], deleted: [], more: true, lastModifiedTime: 200 }),+ },+ { method: 'GET', path: '/retrieve', reply: (req) => ok({ id: req.query['id'], modifiedtime: '2026-01-01 00:00:00' }) },+ ]);+ const out = await fetchChangedRecords({+ creds: creds(),+ module: 'Contacts',+ syncType: 'application',+ limit: 100,+ lastFetchEpochMS: 100_000,+ });+ expect(out.map((r) => r['id'])).toEqual(['4x1', '4x3']);+ expect(seen.filter((s) => s.path.endsWith('/sync')).map((s) => s.query['modifiedTime'])).toEqual(['100', '200']);+ });++ test('open-source fallback: REST 404 switches to webservice.php sync and uses the records it returns', async () => {+ const seen = stubVtiger(+ vtwsRoutes([+ { method: 'GET', path: `${REST}/sync`, reply: { status: 404, body: '<html>Not Found</html>' } },+ {+ method: 'GET',+ path: '/webservice.php',+ operation: 'sync',+ reply: ok({+ updated: [{ id: '12x4', lastname: 'A', modifiedtime: '2026-10-11 19:35:26' }, { id: '12x5', lastname: 'B' }],+ deleted: ['12x5'],+ more: false,+ lastModifiedTime: 1791747326,+ }),+ },+ ])+ );+ const out = await fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 1_000_000 });+ expect(out).toEqual([{ id: '12x4', lastname: 'A', modifiedtime: '2026-10-11 19:35:26' }]);+ const vtwsSync = seen.find((s) => s.query['operation'] === 'sync');+ expect(vtwsSync?.query).toEqual({ modifiedTime: '1000', elementType: 'Contacts', syncType: 'application', operation: 'sync', sessionName: 'sess1' });+ expect(seen.filter((s) => s.query['operation'] === 'retrieve')).toHaveLength(0);+ });++ test('open-source fallback retrieves ids through webservice.php when sync returns bare ids', async () => {+ const seen = stubVtiger(+ vtwsRoutes([+ { method: 'GET', path: `${REST}/sync`, reply: { status: 404 } },+ { method: 'GET', path: '/webservice.php', operation: 'sync', reply: ok({ updated: ['12x4'], deleted: [], more: false, lastModifiedTime: 5 }) },+ { method: 'GET', path: '/webservice.php', operation: 'retrieve', reply: ok({ id: '12x4' }) },+ ])+ );+ const out = await fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 0 });+ expect(out).toEqual([{ id: '12x4' }]);+ expect(seen.filter((s) => s.path.startsWith(REST))).toHaveLength(1);+ });++ test('open-source fallback for test(): VTWS query of the newest 5', async () => {+ const seen = stubVtiger(+ vtwsRoutes([+ { method: 'GET', path: `${REST}/query`, reply: { status: 404 } },+ { method: 'GET', path: '/webservice.php', operation: 'query', reply: ok([{ id: '12x4' }]) },+ ])+ );+ expect(await fetchNewestRecords({ creds: creds(), module: 'Contacts', watchBy: 'modifiedtime' })).toEqual([{ id: '12x4' }]);+ expect(seen.find((s) => s.query['operation'] === 'query')?.query['query']).toBe(+ 'SELECT * FROM Contacts ORDER BY modifiedtime DESC LIMIT 5;'+ );+ });++ test('Cloud path never calls webservice.php', async () => {+ const seen = stubVtiger([+ { method: 'GET', path: '/sync', reply: ok({ updated: ['4x1'], deleted: [], more: false, lastModifiedTime: 9 }) },+ { method: 'GET', path: '/retrieve', reply: ok({ id: '4x1' }) },+ ]);+ await fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 100, lastFetchEpochMS: 0 });+ expect(seen.every((s) => s.path.startsWith(REST))).toBe(true);+ });++ test('module dropdown falls back to webservice.php listtypes on open-source', async () => {+ stubVtiger(+ vtwsRoutes([+ { method: 'GET', path: `${REST}/listtypes`, reply: { status: 404 } },+ { method: 'GET', path: '/webservice.php', operation: 'listtypes', reply: ok({ types: ['Contacts', 'Leads'] }) },+ ])+ );+ const names = await listModuleNames(creds());+ expect(names).toContain('Leads');+ expect(names).toContain('Contacts');+ });++ test('sync failure throws instead of silently returning nothing', async () => {+ stubVtiger([{ method: 'GET', path: '/sync', reply: fail({ code: 'ACCESS_DENIED', message: 'denied' }) }]);+ await expect(+ fetchChangedRecords({ creds: creds(), module: 'Contacts', syncType: 'application', limit: 10, lastFetchEpochMS: 0 })+ ).rejects.toThrow('ACCESS_DENIED: denied');+ });+});diff --git a/packages/pieces/community/vtiger/test/helpers.ts b/packages/pieces/community/vtiger/test/helpers.tsnew file mode 100644index 00000000000..a26f6052a2a--- /dev/null+++ b/packages/pieces/community/vtiger/test/helpers.ts@@ -0,0 +1,126 @@+import { AppConnectionType } from '@activepieces/pieces-framework';+import { vi } from 'vitest';+import { VTigerAuthValue } from '../src/lib/common';++export const INSTANCE = 'https://acme.od2.vtiger.com';+export const REST = '/restapi/v1/vtiger/default';++export function creds(overrides: Partial<Creds> = {}): Creds {+ return { instance_url: INSTANCE, username: '[email protected]', password: 'KEY123', ...overrides };+}++export function auth(overrides: Partial<Creds> = {}): VTigerAuthValue {+ return { type: AppConnectionType.CUSTOM_AUTH, props: creds(overrides) };+}++export function ok(result: unknown): Reply {+ return { body: { success: true, result } };+}++export function fail({ code, message, status = 200 }: { code: string; message: string; status?: number }): Reply {+ return { status, body: { success: false, error: { code, message } } };+}++export function vtwsRoutes(extra: Route[] = []): Route[] {+ return [+ { method: 'GET', path: '/webservice.php', operation: 'getchallenge', reply: ok({ token: 'tok', serverTime: 1, expireTime: 2 }) },+ { method: 'POST', path: '/webservice.php', operation: 'login', reply: ok({ sessionName: 'sess1', userId: '19x1' }) },+ ...extra,+ ];+}++export function stubVtiger(routes: Route[]): Seen[] {+ const seen: Seen[] = [];+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit & { dispatcher?: unknown }) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ const method = (init?.method ?? 'GET').toUpperCase();+ const raw = typeof init?.body === 'string' ? init.body : undefined;+ const headers = new Headers(init?.headers);+ const form =+ raw !== undefined && (headers.get('content-type') ?? '').includes('x-www-form-urlencoded')+ ? Object.fromEntries(new URLSearchParams(raw).entries())+ : undefined;+ const query = Object.fromEntries(url.searchParams.entries());+ const entry: Seen = {+ method,+ url: url.toString(),+ origin: url.origin,+ path: url.pathname,+ query,+ headers,+ raw,+ form,+ dispatcher: init?.dispatcher,+ };+ seen.push(entry);+ const operation = query['operation'] ?? form?.['operation'];+ const route = routes.find(+ (r) =>+ r.method === method &&+ (r.path === url.pathname || r.path === url.pathname.replace(REST, '')) &&+ (r.operation === undefined || r.operation === operation) &&+ (r.match === undefined || r.match(entry))+ );+ if (route === undefined) {+ return new Response(JSON.stringify({ success: false, error: { code: 'NO_STUB', message: `${method} ${url.pathname}` } }), {+ status: 404,+ headers: { 'content-type': 'application/json' },+ });+ }+ const reply = typeof route.reply === 'function' ? route.reply(entry, seen) : route.reply;+ return new Response(reply.body === undefined ? '' : JSON.stringify(reply.body), {+ status: reply.status ?? 200,+ headers: { 'content-type': 'application/json', ...(reply.headers ?? {}) },+ });+ })+ );+ return seen;+}++export async function runAction({+ action,+ props,+ connection = auth(),+ files,+}: {+ action: { run: (ctx: never) => Promise<unknown> };+ props: Record<string, unknown>;+ connection?: unknown;+ files?: unknown;+}): Promise<unknown> {+ const context = { auth: connection, propsValue: props, files };+ return Reflect.apply(action.run, undefined, [context]);+}++export function basic(c: Creds = creds()): string {+ return `Basic ${Buffer.from(`${c.username}:${c.password}`).toString('base64')}`;+}++export const SERVER = { apiUrl: '', publicUrl: '', mintOidcToken: async () => '' };++export type Creds = { instance_url: string; username: string; password: string };++export type Reply = { status?: number; body?: unknown; headers?: Record<string, string> };++export type Route = {+ method: string;+ path: string;+ operation?: string;+ match?: (seen: Seen) => boolean;+ reply: Reply | ((request: Seen, all: Seen[]) => Reply);+};++export type Seen = {+ method: string;+ url: string;+ origin: string;+ path: string;+ query: Record<string, string>;+ headers: Headers;+ raw: string | undefined;+ form: Record<string, string> | undefined;+ dispatcher: unknown;+};diff --git a/packages/pieces/community/vtiger/test/rest-client.test.ts b/packages/pieces/community/vtiger/test/rest-client.test.tsnew file mode 100644index 00000000000..ac1c101a1cd--- /dev/null+++ b/packages/pieces/community/vtiger/test/rest-client.test.ts@@ -0,0 +1,184 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { vtigerAuth } from '../src/lib/auth';+import {+ assertPublicInstanceUrl,+ isBlockedHost,+ normalizeInstanceUrl,+ vtigerRest,+ REST_UNAVAILABLE_MESSAGE,+ VtigerApiError,+} from '../src/lib/rest-client';+import { vtwsLogin } from '../src/lib/vtws';+import { basic, creds, fail, ok, SERVER, stubVtiger, vtwsRoutes } from './helpers';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('B8 instance URL normalisation', () => {+ test.each([+ ['https://acme.od2.vtiger.com', 'https://acme.od2.vtiger.com'],+ ['https://acme.od2.vtiger.com/', 'https://acme.od2.vtiger.com'],+ [' https://acme.od2.vtiger.com// ', 'https://acme.od2.vtiger.com'],+ ['http://crm.example.com:8080', 'http://crm.example.com:8080'],+ ])('%s -> %s', (input, expected) => {+ expect(normalizeInstanceUrl(input)).toBe(expected);+ });++ test.each([+ ['ftp://acme.com', 'https:// or http://'],+ ['javascript:alert(1)', 'https:// or http://'],+ ['https://user:[email protected]', 'username or password'],+ ['https://acme.com/restapi/v1/vtiger/default', 'without the endpoint'],+ ['https://acme.com/crm', 'path, query or fragment'],+ ['https://acme.com?x=1', 'path, query or fragment'],+ ['not a url', 'not a valid URL'],+ ])('rejects %s', (input, message) => {+ expect(() => normalizeInstanceUrl(input)).toThrow(message);+ });++ test.each([+ 'localhost',+ 'app.localhost',+ '127.0.0.1',+ '10.1.2.3',+ '172.16.0.1',+ '172.31.255.255',+ '192.168.1.10',+ '169.254.169.254',+ '0.0.0.0',+ '100.64.0.1',+ 'metadata.google.internal',+ '[::1]',+ '[fd00::1]',+ '[fe80::1]',+ '[::ffff:7f00:1]',+ '[::ffff:a9fe:a9fe]',+ ])('blocks private host %s', (host) => {+ expect(isBlockedHost(host)).toBe(true);+ });++ test.each(['acme.od2.vtiger.com', '172.32.0.1', '8.8.8.8', '[2001:4860::8888]', 'crm.example.com'])(+ 'allows public host %s',+ (host) => {+ expect(isBlockedHost(host)).toBe(false);+ }+ );++ test('decimal-encoded loopback is caught after URL parsing', () => {+ expect(() => assertPublicInstanceUrl('http://2130706433')).toThrow('private, loopback');+ });++ test('validate keeps http for self-hosted, accepts trailing slash and logs in', async () => {+ const seen = stubVtiger(vtwsRoutes());+ const result = await vtigerAuth.validate?.({+ auth: creds({ instance_url: 'http://crm.example.com/' }),+ server: SERVER,+ });+ expect(result).toEqual({ valid: true });+ expect(seen[0].origin).toBe('http://crm.example.com');+ });++ test('validate rejects metadata host before any request', async () => {+ const seen = stubVtiger([]);+ const result = await vtigerAuth.validate?.({+ auth: creds({ instance_url: 'http://169.254.169.254' }),+ server: SERVER,+ });+ expect(result?.valid).toBe(false);+ expect(seen).toHaveLength(0);+ });++ test('validate surfaces the vendor login error', async () => {+ stubVtiger([+ vtwsRoutes()[0],+ { method: 'POST', path: '/webservice.php', operation: 'login', reply: fail({ code: 'INVALID_USER_CREDENTIALS', message: 'Invalid username or password' }) },+ ]);+ const result = await vtigerAuth.validate?.({ auth: creds(), server: SERVER });+ expect(result).toEqual({+ valid: false,+ error: expect.stringContaining('INVALID_USER_CREDENTIALS: Invalid username or password'),+ });+ });+});++describe('vtigerRest', () => {+ test('sends Basic auth, Accept JSON, a TLS-verifying dispatcher and keeps credentials out of the URL', async () => {+ const seen = stubVtiger([{ method: 'GET', path: '/me', reply: ok({ id: '19x1' }) }]);+ const result = await vtigerRest({ creds: creds({ instance_url: 'https://acme.od2.vtiger.com/' }), method: HttpMethod.GET, path: 'me' });+ expect(result).toEqual({ id: '19x1' });+ expect(seen[0].url).toBe('https://acme.od2.vtiger.com/restapi/v1/vtiger/default/me');+ expect(seen[0].headers.get('authorization')).toBe(basic());+ expect(seen[0].headers.get('accept')).toBe('application/json');+ expect(seen[0].url).not.toContain('KEY123');+ expect(seen[0].dispatcher).toBeDefined();+ expect(seen[0].dispatcher?.constructor?.name).toBe('Agent');+ });++ test('POST bodies are form-urlencoded', async () => {+ const seen = stubVtiger([{ method: 'POST', path: '/delete', reply: ok({ status: 'successful' }) }]);+ await vtigerRest({ creds: creds(), method: HttpMethod.POST, path: 'delete', form: { id: '12x1' } });+ expect(seen[0].headers.get('content-type')).toContain('application/x-www-form-urlencoded');+ expect(seen[0].raw).toBe('id=12x1');+ });++ test('HTTP 200 with success:false throws code: message', async () => {+ stubVtiger([{ method: 'GET', path: '/retrieve', reply: fail({ code: 'RECORD_NOT_FOUND', message: 'Record you are trying to access is not found' }) }]);+ const call = vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'retrieve', query: { id: '12x9' } });+ await expect(call).rejects.toThrow('RECORD_NOT_FOUND: Record you are trying to access is not found');+ await expect(call).rejects.toBeInstanceOf(VtigerApiError);+ });++ test('HTTP 401 without an envelope maps to a permission message', async () => {+ stubVtiger([{ method: 'GET', path: '/me', reply: { status: 401, body: 'Unauthorized' } }]);+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'me' })).rejects.toThrow(+ 'HTTP_401: Vtiger rejected the username or access key'+ );+ });++ test('error envelope on a 4xx keeps the vendor code', async () => {+ stubVtiger([{ method: 'GET', path: '/me', reply: fail({ code: 'ACCESS_DENIED', message: 'Permission to perform the operation is denied', status: 403 }) }]);+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'me' })).rejects.toThrow(+ 'ACCESS_DENIED: Permission to perform the operation is denied'+ );+ });++ test('a redirect is not followed', async () => {+ stubVtiger([{ method: 'GET', path: '/me', reply: { status: 301, headers: { location: 'https://evil.example/' } } }]);+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'me' })).rejects.toThrow('HTTP_301');+ });++ test('REST 404 with an HTML body explains that the action needs Vtiger Cloud', async () => {+ stubVtiger([]);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('<html><h1>Not Found</h1></html>', { status: 404, headers: { 'content-type': 'text/html' } }))+ );+ const call = vtigerRest({ creds: creds({ instance_url: 'http://crm.example.com' }), method: HttpMethod.GET, path: 'me' });+ await expect(call).rejects.toThrow(REST_UNAVAILABLE_MESSAGE);+ await expect(call).rejects.toMatchObject({ code: 'REST_API_UNAVAILABLE' });+ });++ test('a webservice.php 404 keeps the generic message', async () => {+ stubVtiger([]);+ await expect(vtwsLogin(creds())).rejects.toThrow('NO_STUB: GET /webservice.php');+ });++ test('HTTP 400 with an empty body gets a hint, 429 does not repeat the code', async () => {+ stubVtiger([+ { method: 'GET', path: '/me', reply: { status: 400 } },+ { method: 'GET', path: '/sync', reply: fail({ code: 'TOO_MANY_REQUESTS', message: 'TOO_MANY_REQUESTS', status: 429 }) },+ ]);+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'me' })).rejects.toThrow('may not exist');+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'sync' })).rejects.toThrow(+ 'TOO_MANY_REQUESTS: Vtiger rate limit reached; retry later'+ );+ });++ test('body without success flag is an error, not a success', async () => {+ stubVtiger([{ method: 'GET', path: '/me', reply: { body: { result: { id: 1 } } } }]);+ await expect(vtigerRest({ creds: creds(), method: HttpMethod.GET, path: 'me' })).rejects.toThrow('HTTP_200');+ });+});diff --git a/packages/pieces/community/vtiger/test/vtql.test.ts b/packages/pieces/community/vtiger/test/vtql.test.tsnew file mode 100644index 00000000000..f02112c0668--- /dev/null+++ b/packages/pieces/community/vtiger/test/vtql.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from 'vitest';+import {+ assertFieldName,+ assertModuleName,+ assertRecordId,+ buildWhere,+ clampLimit,+ escapeLikePattern,+ filterValueToString,+ pagedQuery,+ vtqlQuote,+} from '../src/lib/vtql';++describe('B7 VTQL safety', () => {+ test('quotes escape backslash then single quote', () => {+ expect(vtqlQuote("O'Brien")).toBe("'O\\'Brien'");+ expect(vtqlQuote('a\\b')).toBe("'a\\\\b'");+ expect(vtqlQuote("x\\' OR 1=1 --")).toBe("'x\\\\\\' OR 1=1 --'");+ });++ test.each(['Contacts; DELETE', 'Contacts WHERE 1=1', '', ' ', '1Contacts', "Leads'"])('module %j rejected', (name) => {+ expect(() => assertModuleName(name)).toThrow('Invalid module name');+ });++ test('module names are trimmed', () => {+ expect(assertModuleName(' HelpDesk ')).toBe('HelpDesk');+ });++ test.each(['email = 1', "lastname'", 'a-b', ''])('field %j rejected', (field) => {+ expect(() => assertFieldName(field)).toThrow('Invalid field name');+ });++ test.each(['12x345', ' 4x2063 '])('record id %j accepted', (id) => {+ expect(assertRecordId({ value: id })).toBe(id.trim());+ });++ test.each(['12345', 'x12', '12x', '12x3 OR 1', undefined])('record id %j rejected', (id) => {+ expect(() => assertRecordId({ value: id, label: 'Lead ID' })).toThrow('Lead ID');+ });++ test('buildWhere joins with AND and quotes every value', () => {+ expect(+ buildWhere({+ filters: [+ { field: 'lastname', value: "O'Neil", operator: '=' },+ { field: 'email', value: 'acme', operator: 'LIKE' },+ ],+ })+ ).toBe(" WHERE lastname = 'O\\'Neil' AND email LIKE '%acme%'");+ expect(buildWhere({ filters: [] })).toBe('');+ });++ test('buildWhere rejects injected field names', () => {+ expect(() => buildWhere({ filters: [{ field: '1=1 OR id', value: 'x', operator: '=' }] })).toThrow('Invalid field name');+ });++ test('filter values: booleans map to 1/0, numbers stay exact, objects rejected', () => {+ expect(filterValueToString(true)).toBe('1');+ expect(filterValueToString(false)).toBe('0');+ expect(filterValueToString(12.5)).toBe('12.5');+ expect(filterValueToString(null)).toBeUndefined();+ expect(() => filterValueToString({ a: 1 })).toThrow('text, numbers or booleans');+ expect(() => filterValueToString(Number.NaN)).toThrow('finite');+ });++ test('clampLimit validates and caps', () => {+ expect(clampLimit({ value: undefined, fallback: 100, max: 1000 })).toBe(100);+ expect(clampLimit({ value: '50', fallback: 100, max: 1000 })).toBe(50);+ expect(clampLimit({ value: 5000, fallback: 100, max: 1000 })).toBe(1000);+ expect(() => clampLimit({ value: 0, fallback: 100, max: 1000 })).toThrow('between 1 and 1000');+ expect(() => clampLimit({ value: 2.5, fallback: 100, max: 1000 })).toThrow();+ });+});++describe('D9 paging loops LIMIT off,100 until a short page', () => {+ test('reads 250 rows across three pages', async () => {+ const queries: string[] = [];+ const rows = Array.from({ length: 250 }, (_, i) => ({ id: `4x${i}` }));+ const { records, hasMore } = await pagedQuery({+ module: 'Contacts',+ where: " WHERE lastname = 'A'",+ limit: 1000,+ fetchPage: async (query) => {+ queries.push(query);+ const m = /LIMIT (\d+), (\d+);$/.exec(query);+ const offset = Number(m?.[1]);+ return rows.slice(offset, offset + Number(m?.[2]));+ },+ });+ expect(queries).toEqual([+ "SELECT * FROM Contacts WHERE lastname = 'A' LIMIT 0, 100;",+ "SELECT * FROM Contacts WHERE lastname = 'A' LIMIT 100, 100;",+ "SELECT * FROM Contacts WHERE lastname = 'A' LIMIT 200, 100;",+ ]);+ expect(records).toHaveLength(250);+ expect(hasMore).toBe(false);+ });++ test('stops at the limit and reports hasMore', async () => {+ const queries: string[] = [];+ const { records, hasMore } = await pagedQuery({+ module: 'Leads',+ where: '',+ limit: 150,+ fetchPage: async (query) => {+ queries.push(query);+ const size = Number(/, (\d+);$/.exec(query)?.[1]);+ return Array.from({ length: size }, (_, i) => ({ id: `10x${i}` }));+ },+ });+ expect(queries).toEqual(['SELECT * FROM Leads LIMIT 0, 100;', 'SELECT * FROM Leads LIMIT 100, 50;']);+ expect(records).toHaveLength(150);+ expect(hasMore).toBe(true);+ });++ test('a server that ignores LIMIT and returns more rows is trimmed per page', async () => {+ const { records } = await pagedQuery({+ module: 'Leads',+ where: '',+ limit: 3,+ fetchPage: async () => Array.from({ length: 100 }, (_, i) => ({ id: `10x${i}` })),+ });+ expect(records).toHaveLength(3);+ });++ test('orderBy is validated', async () => {+ await expect(+ pagedQuery({ module: 'Leads', where: '', orderBy: 'x; DROP', limit: 1, fetchPage: async () => [] })+ ).rejects.toThrow('Invalid field name');+ });+});++describe('LIKE patterns treat % and _ as literal characters', () => {+ test('escapeLikePattern escapes backslash, percent and underscore', () => {+ expect(escapeLikePattern('jo_ann%50\\x')).toBe('jo\\_ann\\%50\\\\x');+ });++ test('buildWhere sends escaped wildcards inside the quoted pattern', () => {+ expect(buildWhere({ filters: [{ field: 'email', value: '[email protected]', operator: 'LIKE' }] })).toBe(+ " WHERE email LIKE '%jo\\\\[email protected]%'"+ );+ expect(buildWhere({ filters: [{ field: 'title', value: '100%', operator: 'LIKE' }] })).toBe(+ " WHERE title LIKE '%100\\\\%%'"+ );+ });++ test('exact matches are not escaped', () => {+ expect(buildWhere({ filters: [{ field: 'email', value: '[email protected]', operator: '=' }] })).toBe(+ " WHERE email = '[email protected]'"+ );+ });+});diff --git a/packages/pieces/community/vtiger/vitest.config.ts b/packages/pieces/community/vtiger/vitest.config.tsnew file mode 100644index 00000000000..f520fc14113--- /dev/null+++ b/packages/pieces/community/vtiger/vitest.config.ts@@ -0,0 +1,18 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ resolve: {+ alias: {+ '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})