@tuanltntu/n8n-nodes-bitrix24
Version:
Comprehensive n8n community node for Bitrix24 API integration with CRM, Tasks, Chat, Telephony, and more
371 lines • 16.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutomationResourceHandler = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const ResourceHandlerBase_1 = require("./ResourceHandlerBase");
/**
* Handle Bitrix24 Automation rule operations
*/
class AutomationResourceHandler extends ResourceHandlerBase_1.ResourceHandlerBase {
constructor(executeFunctions, returnData, options = {}) {
super(executeFunctions, returnData, options);
this.resourceEndpoints = {
addRule: "bizproc.robot.add",
updateRule: "bizproc.robot.update",
deleteRule: "bizproc.robot.delete",
getRule: "bizproc.robot.get",
getAllRules: "bizproc.robot.list",
};
}
/**
* Process automation operations
*/
async process() {
for (let i = 0; i < this.items.length; i++) {
try {
const operation = this.getNodeParameter("operation", i);
switch (operation) {
case "createRule":
await this.handleCreateRule(i);
break;
case "updateRule":
await this.handleUpdateRule(i);
break;
case "deleteRule":
await this.handleDeleteRule(i);
break;
case "getRule":
await this.handleGetRule(i);
break;
case "getAllRules":
await this.handleGetAllRules(i);
break;
default:
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), `Unsupported operation "${operation}" for Automation resource`, { itemIndex: i });
}
}
catch (error) {
if (this.executeFunctions.continueOnFail()) {
this.returnData.push({ json: { error: error.message } });
continue;
}
throw error;
}
}
return this.returnData;
}
/**
* Get endpoint for the specified operation
*/
getEndpoint(operation) {
const endpointMap = {
createRule: "addRule",
updateRule: "updateRule",
deleteRule: "deleteRule",
getRule: "getRule",
getAllRules: "getAllRules",
};
const endpoint = this.resourceEndpoints[endpointMap[operation]];
if (!endpoint) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), `Unsupported operation "${operation}" for Automation resource`);
}
return endpoint;
}
/**
* Format properties from UI format to API format
*/
formatProperties(itemIndex) {
const properties = {};
// Get common properties
const commonProperties = this.getNodeParameter("commonProperties", itemIndex, {});
// Add common properties
if (Object.keys(commonProperties).length > 0) {
Object.assign(properties, commonProperties);
}
// Handle custom properties collection
const propertiesCollection = this.getNodeParameter("propertiesCollection", itemIndex, { properties: [] });
if (propertiesCollection.properties &&
Array.isArray(propertiesCollection.properties)) {
const customProps = propertiesCollection.properties;
for (const prop of customProps) {
const name = prop.name;
if (prop.type === "string") {
properties[name] = prop.stringValue;
}
else if (prop.type === "number") {
properties[name] = prop.numberValue;
}
else if (prop.type === "boolean") {
properties[name] = prop.booleanValue;
}
else if (prop.type === "array" || prop.type === "object") {
try {
properties[name] = JSON.parse(prop.complexValue);
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), `Invalid JSON in property "${name}": ${error.message}`, { itemIndex });
}
}
}
}
// Handle direct JSON properties input
const useJsonProperties = this.getNodeParameter("useJsonProperties", itemIndex, false);
if (useJsonProperties) {
const jsonProperties = this.getNodeParameter("properties", itemIndex, "");
if (jsonProperties) {
try {
const parsedProps = JSON.parse(jsonProperties);
Object.assign(properties, parsedProps);
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), `Invalid JSON in properties: ${error.message}`, { itemIndex });
}
}
}
return properties;
}
/**
* Handle creating an automation rule
*/
async handleCreateRule(itemIndex) {
const documentType = this.getNodeParameter("documentType", itemIndex);
const ruleName = this.getNodeParameter("name", itemIndex);
const ruleCode = this.getNodeParameter("code", itemIndex);
const handlerUrl = this.getNodeParameter("handler", itemIndex);
const authUserId = this.getNodeParameter("authUserId", itemIndex);
const useSubscription = this.getNodeParameter("useSubscription", itemIndex, false);
// Xử lý đặc biệt cho document type là SPA
let documentTypeArray = [documentType];
console.log("handleCreateRule processing document type:", documentType);
if (documentType === "spa_placement") {
// Lấy SPA ID từ spaPlacement
const spaId = this.getNodeParameter("spaPlacement", itemIndex);
console.log("SPA placement ID:", spaId);
if (!spaId) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), "SPA Placement ID is required when Document Type is SPA", { itemIndex });
}
// Format document type theo định dạng yêu cầu cho SPA
// ['crm', 'Bitrix\Crm\Integration\BizProc\Document\Dynamic', 'DYNAMIC_XXX']
documentTypeArray = [
"crm",
"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic",
spaId,
];
console.log("Final document type array for SPA:", documentTypeArray);
}
else {
// Xử lý các document type thông thường
documentTypeArray = [documentType];
console.log("Using standard document type:", documentTypeArray);
}
// Get additional properties for the rule
const commonProperties = this.getNodeParameter("commonProperties", itemIndex, {});
// Get custom properties for the rule
const propertiesCollection = this.getNodeParameter("propertiesCollection.properties", itemIndex, []);
// Build properties object from collection
const properties = {};
if (propertiesCollection && propertiesCollection.length > 0) {
for (const prop of propertiesCollection) {
if (prop.name && prop.type && prop.value) {
properties[prop.name] = {
Name: prop.label || prop.name,
Type: prop.type,
Default: prop.value,
Required: prop.required === true,
};
}
}
}
// Build final request parameters
const requestParams = {
DOCUMENT_TYPE: documentTypeArray,
CODE: ruleCode,
NAME: ruleName,
HANDLER: handlerUrl,
AUTH_USER_ID: authUserId,
USE_SUBSCRIPTION: useSubscription ? "Y" : "N",
PROPERTIES: properties,
};
// Add additional common properties
if (commonProperties && Object.keys(commonProperties).length > 0) {
for (const [key, value] of Object.entries(commonProperties)) {
requestParams[key] = value;
}
}
// Log the final request for debugging
console.log("Final request parameters for bizproc.robot.add:", JSON.stringify(requestParams));
try {
// Make API call to create rule using the standard makeApiCall method
const endpoint = this.getEndpoint("createRule");
console.log(`Making API call to ${endpoint} with itemIndex: ${itemIndex}`);
const responseData = await this.makeApiCall(endpoint, requestParams, {}, itemIndex);
console.log("API call successful, response:", JSON.stringify(responseData));
this.addResponseToReturnData(responseData, itemIndex);
}
catch (error) {
console.error("API call failed:", error.message);
throw error;
}
}
/**
* Handle updating an automation rule
*/
async handleUpdateRule(itemIndex) {
const ruleId = this.getNodeParameter("ruleId", itemIndex);
const documentType = this.getNodeParameter("documentType", itemIndex);
const ruleName = this.getNodeParameter("name", itemIndex);
const handlerUrl = this.getNodeParameter("handler", itemIndex);
const authUserId = this.getNodeParameter("authUserId", itemIndex);
const useSubscription = this.getNodeParameter("useSubscription", itemIndex, false);
// Xử lý đặc biệt cho document type là SPA
let documentTypeArray = [documentType];
console.log("handleUpdateRule processing document type:", documentType);
if (documentType === "spa_placement") {
// Lấy SPA ID từ spaPlacement
const spaId = this.getNodeParameter("spaPlacement", itemIndex);
console.log("SPA placement ID:", spaId);
if (!spaId) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), "SPA Placement ID is required when Document Type is SPA", { itemIndex });
}
// Format document type theo định dạng yêu cầu cho SPA
// ['crm', 'Bitrix\Crm\Integration\BizProc\Document\Dynamic', 'DYNAMIC_XXX']
documentTypeArray = [
"crm",
"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic",
spaId,
];
console.log("Final document type array for SPA:", documentTypeArray);
}
else {
// Xử lý các document type thông thường
documentTypeArray = [documentType];
console.log("Using standard document type:", documentTypeArray);
}
// Get additional properties for the rule
const commonProperties = this.getNodeParameter("commonProperties", itemIndex, {});
// Get custom properties for the rule
const propertiesCollection = this.getNodeParameter("propertiesCollection.properties", itemIndex, []);
// Build properties object from collection
const properties = {};
if (propertiesCollection && propertiesCollection.length > 0) {
for (const prop of propertiesCollection) {
if (prop.name && prop.type && prop.value) {
properties[prop.name] = {
Name: prop.label || prop.name,
Type: prop.type,
Default: prop.value,
Required: prop.required === true,
};
}
}
}
// Build final request parameters
const requestParams = {
ID: ruleId,
DOCUMENT_TYPE: documentTypeArray,
NAME: ruleName,
HANDLER: handlerUrl,
AUTH_USER_ID: authUserId,
USE_SUBSCRIPTION: useSubscription ? "Y" : "N",
PROPERTIES: properties,
};
// Add additional common properties
if (commonProperties && Object.keys(commonProperties).length > 0) {
for (const [key, value] of Object.entries(commonProperties)) {
requestParams[key] = value;
}
}
// Log the final request for debugging
console.log("Final request parameters for bizproc.robot.update:", JSON.stringify(requestParams));
try {
// Make API call to update rule
const endpoint = this.getEndpoint("updateRule");
console.log(`Making API call to ${endpoint} with itemIndex: ${itemIndex}`);
const responseData = await this.makeApiCall(endpoint, requestParams, {}, itemIndex);
console.log("API call successful, response:", JSON.stringify(responseData));
this.addResponseToReturnData(responseData, itemIndex);
}
catch (error) {
console.error("API call failed:", error.message);
throw error;
}
}
/**
* Handle deleting an automation rule
*/
async handleDeleteRule(itemIndex) {
const ruleId = this.getNodeParameter("ruleId", itemIndex);
console.log(`Deleting automation rule with ID: ${ruleId}, itemIndex: ${itemIndex}`);
try {
const endpoint = this.getEndpoint("deleteRule");
console.log(`Making API call to ${endpoint} with itemIndex: ${itemIndex}`);
const responseData = await this.makeApiCall(endpoint, { CODE: ruleId }, {}, itemIndex);
console.log("API call successful, response:", JSON.stringify(responseData));
this.addResponseToReturnData(responseData, itemIndex);
}
catch (error) {
console.error("API call failed:", error.message);
throw error;
}
}
/**
* Handle getting an automation rule
*/
async handleGetRule(itemIndex) {
const ruleId = this.getNodeParameter("ruleId", itemIndex);
const documentType = this.getNodeParameter("documentType", itemIndex);
console.log(`Getting automation rule with ID: ${ruleId}, documentType: ${documentType}, itemIndex: ${itemIndex}`);
try {
const endpoint = this.getEndpoint("getRule");
console.log(`Making API call to ${endpoint} with itemIndex: ${itemIndex}`);
const responseData = await this.makeApiCall(endpoint, { id: ruleId, documentType }, {}, itemIndex);
console.log("API call successful, response:", JSON.stringify(responseData));
this.addResponseToReturnData(responseData, itemIndex);
}
catch (error) {
console.error("API call failed:", error.message);
throw error;
}
}
/**
* Handle getting all automation rules
*/
async handleGetAllRules(itemIndex) {
const documentType = this.getNodeParameter("documentType", itemIndex);
const options = this.getNodeParameter("options", itemIndex, {});
const requestParams = { documentType };
// Add filter if provided
if (options.filter) {
try {
requestParams.filter =
typeof options.filter === "string"
? JSON.parse(options.filter)
: options.filter;
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), "Filter must be a valid JSON", { itemIndex });
}
}
// Add order if provided
if (options.order) {
try {
requestParams.order =
typeof options.order === "string"
? JSON.parse(options.order)
: options.order;
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.executeFunctions.getNode(), "Order must be a valid JSON", { itemIndex });
}
}
// Add select if specified
if (options.select) {
requestParams.select = options.select;
}
const endpoint = this.getEndpoint("getAllRules");
const responseData = await this.makeApiCall(endpoint, requestParams, {}, itemIndex);
this.addResponseToReturnData(responseData, itemIndex);
}
}
exports.AutomationResourceHandler = AutomationResourceHandler;
//# sourceMappingURL=AutomationResourceHandler.js.map