UNPKG

@memberjunction/actions-bizapps-crm

Version:

CRM system integration actions for MemberJunction

240 lines 9.45 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HubSpotBaseAction = void 0; const global_1 = require("@memberjunction/global"); const base_crm_action_1 = require("../../base/base-crm.action"); const actions_1 = require("@memberjunction/actions"); /** * Base class for all HubSpot CRM actions. * Handles HubSpot-specific authentication and API interaction patterns. */ let HubSpotBaseAction = class HubSpotBaseAction extends base_crm_action_1.BaseCRMAction { crmProvider = 'HubSpot'; integrationName = 'HubSpot'; /** * HubSpot API version */ apiVersion = 'v3'; /** * Current action parameters (set by the framework) */ params; /** * Makes an authenticated request to HubSpot API */ async makeHubSpotRequest(endpoint, method = 'GET', body, contextUser) { if (!contextUser) { throw new Error('Context user is required for HubSpot API calls'); } // Get company ID from action params const companyId = this.getParamValue(this.params, 'CompanyID'); if (!companyId) { throw new Error('CompanyID parameter is required'); } // Get the integration credentials const integration = await this.getCompanyIntegration(companyId, contextUser); // Get API credentials const credentials = await this.getAPICredentials(integration); if (!credentials.accessToken && !credentials.apiKey) { throw new Error('Access Token or API Key is required for HubSpot integration'); } // Build the full URL const baseUrl = `https://api.hubapi.com/crm/${this.apiVersion}`; const fullUrl = `${baseUrl}/${endpoint}`; // Prepare headers const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }; // Use access token if available (OAuth), otherwise use API key if (credentials.accessToken) { headers['Authorization'] = `Bearer ${credentials.accessToken}`; } else if (credentials.apiKey) { // For private app key, it's passed as a query parameter const url = new URL(fullUrl); url.searchParams.set('hapikey', credentials.apiKey); } try { const response = await fetch(fullUrl, { method, headers, body: body ? JSON.stringify(body) : undefined }); if (!response.ok) { const errorText = await response.text(); let errorMessage = `HubSpot API error: ${response.status} ${response.statusText}`; try { const errorJson = JSON.parse(errorText); if (errorJson.message) { errorMessage = `HubSpot API error: ${errorJson.message}`; } else if (errorJson.errors) { errorMessage = `HubSpot API error: ${errorJson.errors.map((e) => e.message).join(', ')}`; } } catch { errorMessage += ` - ${errorText}`; } throw new Error(errorMessage); } // Handle empty responses (like DELETE operations) if (response.status === 204 || response.headers.get('content-length') === '0') { return {}; } const result = await response.json(); return result; } catch (error) { if (error instanceof Error) { throw error; } throw new Error(`HubSpot API request failed: ${error}`); } } /** * Makes a paginated request to HubSpot API using cursor-based pagination */ async makeHubSpotPaginatedRequest(endpoint, params = {}, contextUser) { const results = []; let after; const limit = params.limit || 100; // Get max results if specified const maxResults = this.getParamValue(this.params, 'MaxResults'); while (true) { const queryParams = new URLSearchParams({ ...params, limit: limit.toString() }); if (after) { queryParams.set('after', after); } const response = await this.makeHubSpotRequest(`${endpoint}?${queryParams}`, 'GET', undefined, contextUser); if (response.results && Array.isArray(response.results)) { results.push(...response.results); } // Check if we've reached max results if (maxResults && results.length >= maxResults) { return results.slice(0, maxResults); } // Check for more pages if (response.paging?.next?.after) { after = response.paging.next.after; } else { break; } } return results; } /** * Search HubSpot objects using the search API */ async searchHubSpotObjects(objectType, filters, properties, contextUser) { const searchBody = { filterGroups: [{ filters: filters }], properties: properties || [], limit: 100 }; const response = await this.makeHubSpotRequest(`objects/${objectType}/search`, 'POST', searchBody, contextUser); return response.results || []; } /** * Batch create objects in HubSpot */ async batchCreateHubSpotObjects(objectType, objects, contextUser) { const batchBody = { inputs: objects }; const response = await this.makeHubSpotRequest(`objects/${objectType}/batch/create`, 'POST', batchBody, contextUser); return response.results || []; } /** * Batch update objects in HubSpot */ async batchUpdateHubSpotObjects(objectType, updates, contextUser) { const batchBody = { inputs: updates }; const response = await this.makeHubSpotRequest(`objects/${objectType}/batch/update`, 'POST', batchBody, contextUser); return response.results || []; } /** * Associate objects in HubSpot */ async associateObjects(fromObjectType, fromObjectId, toObjectType, toObjectId, associationType, contextUser) { const associationSpec = associationType || `${fromObjectType}_to_${toObjectType}`; await this.makeHubSpotRequest(`objects/${fromObjectType}/${fromObjectId}/associations/${toObjectType}/${toObjectId}/${associationSpec}`, 'PUT', undefined, contextUser); } /** * Convert HubSpot timestamp to Date */ parseHubSpotDate(timestamp) { // HubSpot returns timestamps as ISO strings or milliseconds if (typeof timestamp === 'number') { return new Date(timestamp); } return new Date(timestamp); } /** * Format date for HubSpot (ISO string or milliseconds) */ formatHubSpotDate(date) { return date.toISOString(); } /** * Map HubSpot object properties to a standard format */ mapHubSpotProperties(hubspotObject) { return { id: hubspotObject.id, ...hubspotObject.properties, createdAt: hubspotObject.createdAt, updatedAt: hubspotObject.updatedAt, archived: hubspotObject.archived }; } /** * Get HubSpot association type IDs * Based on HubSpot's default association type IDs */ getAssociationTypeId(fromType, toType) { const associationMap = { 'contact_to_company': 1, 'company_to_contact': 2, 'deal_to_contact': 3, 'contact_to_deal': 4, 'deal_to_company': 5, 'company_to_deal': 6, 'company_to_engagement': 7, 'engagement_to_company': 8, 'contact_to_engagement': 9, 'engagement_to_contact': 10, 'deal_to_engagement': 11, 'engagement_to_deal': 12, 'parent_company_to_child_company': 13, 'child_company_to_parent_company': 14, 'contact_to_ticket': 15, 'ticket_to_contact': 16, 'ticket_to_engagement': 17, 'engagement_to_ticket': 18, 'deal_to_line_item': 19, 'line_item_to_deal': 20 }; const key = `${fromType}_to_${toType}`; return associationMap[key] || 1; } }; exports.HubSpotBaseAction = HubSpotBaseAction; exports.HubSpotBaseAction = HubSpotBaseAction = __decorate([ (0, global_1.RegisterClass)(actions_1.BaseAction, 'HubSpotBaseAction') ], HubSpotBaseAction); //# sourceMappingURL=hubspot-base.action.js.map