@memberjunction/actions-apollo 6.2.0-edge.3 → 6.2.0-edge.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -53
- package/dist/__tests__/apollo-enrichment.test.js +339 -233
- package/dist/__tests__/apollo-enrichment.test.js.map +1 -1
- package/dist/__tests__/apollo-lists.test.js +29 -1
- package/dist/__tests__/apollo-lists.test.js.map +1 -1
- package/dist/__tests__/apollo-people-client.test.d.ts +2 -0
- package/dist/__tests__/apollo-people-client.test.d.ts.map +1 -0
- package/dist/__tests__/apollo-people-client.test.js +153 -0
- package/dist/__tests__/apollo-people-client.test.js.map +1 -0
- package/dist/accounts.d.ts +80 -291
- package/dist/accounts.d.ts.map +1 -1
- package/dist/accounts.js +391 -782
- package/dist/accounts.js.map +1 -1
- package/dist/contacts.d.ts +140 -207
- package/dist/contacts.d.ts.map +1 -1
- package/dist/contacts.js +372 -724
- package/dist/contacts.js.map +1 -1
- package/dist/generic/apollo-lists.types.d.ts +18 -3
- package/dist/generic/apollo-lists.types.d.ts.map +1 -1
- package/dist/http/ApolloHttp.d.ts +42 -0
- package/dist/http/ApolloHttp.d.ts.map +1 -0
- package/dist/http/ApolloHttp.js +117 -0
- package/dist/http/ApolloHttp.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/lists/ApolloRESTClient.d.ts +2 -0
- package/dist/lists/ApolloRESTClient.d.ts.map +1 -1
- package/dist/lists/ApolloRESTClient.js +33 -52
- package/dist/lists/ApolloRESTClient.js.map +1 -1
- package/dist/lists/ApolloSearchActions.d.ts +6 -1
- package/dist/lists/ApolloSearchActions.d.ts.map +1 -1
- package/dist/lists/ApolloSearchActions.js +19 -4
- package/dist/lists/ApolloSearchActions.js.map +1 -1
- package/dist/people/ApolloPeopleClient.d.ts +114 -0
- package/dist/people/ApolloPeopleClient.d.ts.map +1 -0
- package/dist/people/ApolloPeopleClient.js +168 -0
- package/dist/people/ApolloPeopleClient.js.map +1 -0
- package/dist/people/apollo-people.types.d.ts +55 -0
- package/dist/people/apollo-people.types.d.ts.map +1 -0
- package/dist/people/apollo-people.types.js +8 -0
- package/dist/people/apollo-people.types.js.map +1 -0
- package/package.json +8 -8
package/dist/accounts.js
CHANGED
|
@@ -4,188 +4,110 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
4
|
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;
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
-
import { BaseAction } from
|
|
8
|
-
import { RegisterClass } from
|
|
7
|
+
import { BaseAction } from '@memberjunction/actions';
|
|
8
|
+
import { EscapeSQLString, RegisterClass } from '@memberjunction/global';
|
|
9
|
+
import { CompositeKey, LogError, LogStatus, Metadata, RunView } from '@memberjunction/core';
|
|
9
10
|
import * as Config from './config.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
11
|
+
import { ApolloAuthError, ApolloRateLimitError } from './http/ApolloHttp.js';
|
|
12
|
+
import { ApolloRESTClient } from './lists/ApolloRESTClient.js';
|
|
13
|
+
import { ResolveApolloAPIKey } from './lists/credentials.js';
|
|
14
|
+
import { ApolloPeopleClient, DomainOf } from './people/ApolloPeopleClient.js';
|
|
15
|
+
const MAX_EXECUTIONS = 5;
|
|
16
|
+
const SEARCH_PAGE_SIZE = 100;
|
|
12
17
|
/**
|
|
13
|
-
*
|
|
18
|
+
* Apollo.io Account Enrichment Action
|
|
14
19
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
+
* Enriches account records with organization data (`organizations/enrich`), their technology
|
|
21
|
+
* stack, and the people Apollo lists at the account's domain. People discovery is two steps:
|
|
22
|
+
* `mixed_people/api_search` (free, obfuscated: ids, first names and titles only) and then a paid
|
|
23
|
+
* `people/bulk_match` by id, ten at a time, for emails and profiles. Each matched person costs
|
|
24
|
+
* one Apollo credit; a domain with no people costs nothing.
|
|
20
25
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* await runAction({
|
|
25
|
-
* ActionName: 'ApolloEnrichmentAccountsAction',
|
|
26
|
-
* Params: [{
|
|
27
|
-
* Name: 'AccountEntityFieldMappings',
|
|
28
|
-
* Value: JSON.stringify({
|
|
29
|
-
* EntityName: 'Accounts',
|
|
30
|
-
* Filter: 'Domain IS NOT NULL AND EnrichedAt IS NULL',
|
|
31
|
-
* DomainField: 'Domain',
|
|
32
|
-
* AccountIDField: 'ID',
|
|
33
|
-
* EnrichedAtField: 'EnrichedAt'
|
|
34
|
-
* })
|
|
35
|
-
* }]
|
|
36
|
-
* });
|
|
26
|
+
* Params: AccountEntityFieldMappings (required); ContactEntityFieldMappings,
|
|
27
|
+
* AccountTechnologyEntityFieldMappings, TechnologyCategoryEntityFieldMappings,
|
|
28
|
+
* ContactEducationHistoryEntityFieldMappings, CompanyID (optional).
|
|
37
29
|
*
|
|
38
|
-
*
|
|
39
|
-
* await runAction({
|
|
40
|
-
* ActionName: 'ApolloEnrichmentAccountsAction',
|
|
41
|
-
* Params: [{
|
|
42
|
-
* Name: 'AccountEntityFieldMappings',
|
|
43
|
-
* Value: JSON.stringify(accountConfig)
|
|
44
|
-
* }, {
|
|
45
|
-
* Name: 'ContactEntityFieldMappings',
|
|
46
|
-
* Value: JSON.stringify(contactConfig)
|
|
47
|
-
* }, {
|
|
48
|
-
* Name: 'AccountTechnologyEntityFieldMappings',
|
|
49
|
-
* Value: JSON.stringify(technologyConfig)
|
|
50
|
-
* }]
|
|
51
|
-
* });
|
|
52
|
-
* ```
|
|
30
|
+
* Result codes: SUCCESS, VALIDATION_ERROR, CONFIGURATION_ERROR, RATE_LIMIT_EXCEEDED, FAILED.
|
|
53
31
|
*/
|
|
54
32
|
let ApolloEnrichmentAccountsAction = class ApolloEnrichmentAccountsAction extends BaseAction {
|
|
55
33
|
constructor() {
|
|
56
34
|
super(...arguments);
|
|
57
|
-
/**
|
|
58
|
-
* Job titles to exclude when creating contact records
|
|
59
|
-
* These are typically not decision-makers or relevant contacts
|
|
60
|
-
*/
|
|
35
|
+
/** Job titles to exclude when creating contact records (not decision-makers). */
|
|
61
36
|
this.excludeTitles = ['member', 'student member', 'student', 'volunteer'];
|
|
62
37
|
}
|
|
63
|
-
/**
|
|
64
|
-
* Main entry point for the Apollo account enrichment action
|
|
65
|
-
*
|
|
66
|
-
* @param params - The action parameters containing:
|
|
67
|
-
* - AccountEntityFieldMappings: Required JSON configuration for account entity field mappings
|
|
68
|
-
* - ContactEntityFieldMappings: Optional JSON configuration for contact entity field mappings
|
|
69
|
-
* - AccountTechnologyEntityFieldMappings: Optional JSON configuration for technology tracking
|
|
70
|
-
* - TechnologyCategoryEntityFieldMappings: Optional JSON configuration for technology categories
|
|
71
|
-
* - ContactEducationHistoryEntityFieldMappings: Optional JSON configuration for education history
|
|
72
|
-
*
|
|
73
|
-
* @returns Promise<ActionResultSimple> indicating success/failure and any error messages
|
|
74
|
-
*/
|
|
75
38
|
async InternalRunAction(params) {
|
|
39
|
+
const parsed = this.extractAndValidateParameters(params);
|
|
40
|
+
if (parsed.success === false)
|
|
41
|
+
return parsed.error;
|
|
42
|
+
let clients;
|
|
76
43
|
try {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
// Process all account records
|
|
89
|
-
return await this.processAllAccountRecords(actionParams, params.ContextUser, 1, params.Provider);
|
|
44
|
+
const resolved = await this.CreateClients(parsed.data.companyID, params.ContextUser);
|
|
45
|
+
if (!resolved)
|
|
46
|
+
return Failure('CONFIGURATION_ERROR', 'Apollo.io API key not found in configuration');
|
|
47
|
+
clients = resolved;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
return Failure('CONFIGURATION_ERROR', MessageOf(error));
|
|
51
|
+
}
|
|
52
|
+
const ctx = { Clients: clients, Md: params.Provider ?? Metadata.Provider, User: params.ContextUser, Params: parsed.data };
|
|
53
|
+
try {
|
|
54
|
+
return await this.processAllAccountRecords(ctx, 1);
|
|
90
55
|
}
|
|
91
56
|
catch (error) {
|
|
57
|
+
if (error instanceof ApolloRateLimitError) {
|
|
58
|
+
return Failure('RATE_LIMIT_EXCEEDED', `Apollo.io rate limit (${error.Window}) reached; run again later.`);
|
|
59
|
+
}
|
|
60
|
+
if (error instanceof ApolloAuthError)
|
|
61
|
+
return Failure('CONFIGURATION_ERROR', error.message);
|
|
92
62
|
LogError('Unexpected error in ApolloAccountsEnrichmentAction', undefined, error);
|
|
93
|
-
return {
|
|
94
|
-
Success: false,
|
|
95
|
-
Message: `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
96
|
-
ResultCode: "FAILED"
|
|
97
|
-
};
|
|
63
|
+
return Failure('FAILED', `Unexpected error: ${MessageOf(error)}`);
|
|
98
64
|
}
|
|
99
65
|
}
|
|
100
66
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
67
|
+
* Resolve the key (company credential first, then `APOLLO_API_KEY`) and build both clients.
|
|
68
|
+
* A protected seam so tests can substitute clients that never reach api.apollo.io.
|
|
103
69
|
*/
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
Success: false,
|
|
110
|
-
Message: 'Apollo.io API key not found in configuration',
|
|
111
|
-
ResultCode: "CONFIGURATION_ERROR"
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
return { success: true };
|
|
70
|
+
async CreateClients(companyID, contextUser) {
|
|
71
|
+
const key = await ResolveApolloAPIKey(companyID, contextUser);
|
|
72
|
+
if (!key)
|
|
73
|
+
return null;
|
|
74
|
+
return { People: new ApolloPeopleClient(key.apiKey), Search: new ApolloRESTClient(key.apiKey) };
|
|
116
75
|
}
|
|
117
|
-
|
|
118
|
-
* Extracts and validates all action parameters from the request
|
|
119
|
-
*
|
|
120
|
-
* @param params - The action parameters containing JSON configurations
|
|
121
|
-
* @returns Object with success flag, validated parameters, or error details
|
|
122
|
-
*/
|
|
76
|
+
// ─── Parameters ──────────────────────────────────────────────────────────
|
|
123
77
|
extractAndValidateParameters(params) {
|
|
124
78
|
const accountEntityFieldsParam = this.getRequiredParam(params, 'AccountEntityFieldMappings');
|
|
125
79
|
if (!accountEntityFieldsParam) {
|
|
126
|
-
return {
|
|
127
|
-
success: false,
|
|
128
|
-
error: {
|
|
129
|
-
Success: false,
|
|
130
|
-
Message: 'Missing required parameter: AccountEntityFieldMappings',
|
|
131
|
-
ResultCode: "VALIDATION_ERROR"
|
|
132
|
-
}
|
|
133
|
-
};
|
|
80
|
+
return { success: false, error: Failure('VALIDATION_ERROR', 'Missing required parameter: AccountEntityFieldMappings') };
|
|
134
81
|
}
|
|
135
82
|
let accountEntityFields;
|
|
136
83
|
try {
|
|
137
84
|
accountEntityFields = this.parseJSONParam(accountEntityFieldsParam.Value);
|
|
138
|
-
if (!accountEntityFields)
|
|
85
|
+
if (!accountEntityFields)
|
|
139
86
|
throw new Error('Parsed AccountEntityFieldMappings is empty');
|
|
140
|
-
}
|
|
141
87
|
}
|
|
142
|
-
catch
|
|
143
|
-
return {
|
|
144
|
-
success: false,
|
|
145
|
-
error: {
|
|
146
|
-
Success: false,
|
|
147
|
-
Message: 'Invalid AccountEntityFieldMappings parameter: must be valid JSON or object',
|
|
148
|
-
ResultCode: "VALIDATION_ERROR"
|
|
149
|
-
}
|
|
150
|
-
};
|
|
88
|
+
catch {
|
|
89
|
+
return { success: false, error: Failure('VALIDATION_ERROR', 'Invalid AccountEntityFieldMappings parameter: must be valid JSON or object') };
|
|
151
90
|
}
|
|
152
|
-
|
|
153
|
-
const accountTechnologyEntityFields = this.parseOptionalJSONParam(params, 'AccountTechnologyEntityFieldMappings');
|
|
154
|
-
const technologyCategoryEntityFields = this.parseOptionalJSONParam(params, 'TechnologyCategoryEntityFieldMappings');
|
|
155
|
-
const contactEntityFields = this.parseOptionalJSONParam(params, 'ContactEntityFieldMappings');
|
|
156
|
-
const contactEducationHistoryEntityFields = this.parseOptionalJSONParam(params, 'ContactEducationHistoryEntityFieldMappings');
|
|
91
|
+
const companyRaw = params.Params.find((p) => p.Name.trim().toLowerCase() === 'companyid')?.Value;
|
|
157
92
|
return {
|
|
158
93
|
success: true,
|
|
159
94
|
data: {
|
|
160
95
|
accountEntityFields,
|
|
161
|
-
accountTechnologyEntityFields,
|
|
162
|
-
technologyCategoryEntityFields,
|
|
163
|
-
contactEntityFields,
|
|
164
|
-
contactEducationHistoryEntityFields
|
|
165
|
-
|
|
96
|
+
accountTechnologyEntityFields: this.parseOptionalJSONParam(params, 'AccountTechnologyEntityFieldMappings'),
|
|
97
|
+
technologyCategoryEntityFields: this.parseOptionalJSONParam(params, 'TechnologyCategoryEntityFieldMappings'),
|
|
98
|
+
contactEntityFields: this.parseOptionalJSONParam(params, 'ContactEntityFieldMappings'),
|
|
99
|
+
contactEducationHistoryEntityFields: this.parseOptionalJSONParam(params, 'ContactEducationHistoryEntityFieldMappings'),
|
|
100
|
+
companyID: typeof companyRaw === 'string' && companyRaw.trim().length > 0 && companyRaw !== 'null' ? companyRaw.trim() : null,
|
|
101
|
+
},
|
|
166
102
|
};
|
|
167
103
|
}
|
|
168
|
-
/**
|
|
169
|
-
* Gets a required parameter from the action parameters
|
|
170
|
-
* @param params - The action parameters
|
|
171
|
-
* @param paramName - Name of the required parameter
|
|
172
|
-
* @returns The parameter if found, null otherwise
|
|
173
|
-
*/
|
|
174
104
|
getRequiredParam(params, paramName) {
|
|
175
|
-
|
|
176
|
-
return param || null;
|
|
105
|
+
return params.Params.find((p) => p.Name === paramName) ?? null;
|
|
177
106
|
}
|
|
178
|
-
/**
|
|
179
|
-
* Parses an optional JSON parameter with error handling
|
|
180
|
-
* @param params - The action parameters
|
|
181
|
-
* @param paramName - Name of the optional JSON parameter
|
|
182
|
-
* @returns Parsed object of type T or null if not provided/invalid
|
|
183
|
-
*/
|
|
184
107
|
parseOptionalJSONParam(params, paramName) {
|
|
185
|
-
const param = params.Params.find(p => p.Name === paramName);
|
|
186
|
-
if (!param || !param.Value)
|
|
108
|
+
const param = params.Params.find((p) => p.Name === paramName);
|
|
109
|
+
if (!param || !param.Value)
|
|
187
110
|
return null;
|
|
188
|
-
}
|
|
189
111
|
try {
|
|
190
112
|
return this.parseJSONParam(param.Value) || null;
|
|
191
113
|
}
|
|
@@ -194,203 +116,96 @@ let ApolloEnrichmentAccountsAction = class ApolloEnrichmentAccountsAction extend
|
|
|
194
116
|
return null;
|
|
195
117
|
}
|
|
196
118
|
}
|
|
197
|
-
/**
|
|
198
|
-
* Parses a parameter value that may be a JSON string or already parsed object
|
|
199
|
-
* Handles the case where action parameters ending with JSON can be either strings or objects
|
|
200
|
-
*
|
|
201
|
-
* @param value - The parameter value to parse (string or object)
|
|
202
|
-
* @returns Parsed object of type T
|
|
203
|
-
* @throws Error if value cannot be parsed as JSON (when it's a string)
|
|
204
|
-
*/
|
|
119
|
+
/** A parameter value that may be a JSON string or an already-parsed object. */
|
|
205
120
|
parseJSONParam(value) {
|
|
206
|
-
|
|
207
|
-
if (typeof value === 'object' && value !== null) {
|
|
121
|
+
if (typeof value === 'object' && value !== null)
|
|
208
122
|
return value;
|
|
209
|
-
}
|
|
210
|
-
// If value is a string, try to parse it as JSON
|
|
211
|
-
if (typeof value === 'string') {
|
|
212
|
-
return JSON.parse(value);
|
|
213
|
-
}
|
|
214
|
-
// For other types, try to convert to string first then parse
|
|
215
123
|
return JSON.parse(String(value));
|
|
216
124
|
}
|
|
125
|
+
// ─── Accounts ────────────────────────────────────────────────────────────
|
|
217
126
|
/**
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* @param actionParams - Validated action parameters with entity field mappings
|
|
222
|
-
* @param contextUser - User context for data access and security
|
|
223
|
-
* @param executionCount - Current execution count to prevent infinite recursion (max 5)
|
|
224
|
-
* @returns Promise indicating overall success/failure of the batch
|
|
127
|
+
* Processes every account the filter selects, re-running the query until it drains or
|
|
128
|
+
* {@link MAX_EXECUTIONS} passes have run. The filter is expected to exclude stamped rows
|
|
129
|
+
* (every processed account is stamped, matched or not).
|
|
225
130
|
*/
|
|
226
|
-
async processAllAccountRecords(
|
|
227
|
-
const
|
|
228
|
-
const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
ExtraFilter: actionParams.accountEntityFields.Filter,
|
|
233
|
-
}, contextUser);
|
|
234
|
-
if (!runViewResult.Success) {
|
|
235
|
-
return {
|
|
236
|
-
Success: false,
|
|
237
|
-
Message: runViewResult.ErrorMessage,
|
|
238
|
-
ResultCode: "FAILED"
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
const results = runViewResult.Results;
|
|
242
|
-
const resultLength = results.length;
|
|
243
|
-
if (resultLength === 0) {
|
|
131
|
+
async processAllAccountRecords(ctx, executionCount) {
|
|
132
|
+
const rv = RunView.FromMetadataProvider(ctx.Md);
|
|
133
|
+
const result = await rv.RunView({ EntityName: ctx.Params.accountEntityFields.EntityName, ExtraFilter: ctx.Params.accountEntityFields.Filter }, ctx.User);
|
|
134
|
+
if (!result.Success)
|
|
135
|
+
return Failure('FAILED', result.ErrorMessage);
|
|
136
|
+
if (result.Results.length === 0) {
|
|
244
137
|
LogStatus('+++ Completed domain enrichment, no records left to process.');
|
|
245
|
-
return {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
};
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
await this.processAccountGroups(results, actionParams, md, contextUser);
|
|
262
|
-
// Check if there are more records to process by running the query again
|
|
263
|
-
LogStatus(`--- Checking for remaining records... (execution ${executionCount + 1}/5)`);
|
|
264
|
-
return await this.processAllAccountRecords(actionParams, contextUser, executionCount + 1);
|
|
138
|
+
return { Success: true, Message: 'ApolloAccountsEnrichment executed successfully.', ResultCode: 'SUCCESS' };
|
|
139
|
+
}
|
|
140
|
+
if (executionCount > MAX_EXECUTIONS) {
|
|
141
|
+
LogStatus(`+++ Reached maximum execution limit (${MAX_EXECUTIONS}), stopping to prevent infinite recursion.`);
|
|
142
|
+
return { Success: true, Message: `ApolloAccountsEnrichment stopped after ${MAX_EXECUTIONS} executions to prevent infinite recursion. ${result.Results.length} records may remain unprocessed.`, ResultCode: 'SUCCESS' };
|
|
143
|
+
}
|
|
144
|
+
let failures = 0;
|
|
145
|
+
for (const record of result.Results) {
|
|
146
|
+
const ok = await this.ProcessSingleDomain(ctx, record);
|
|
147
|
+
if (!ok)
|
|
148
|
+
failures++;
|
|
149
|
+
}
|
|
150
|
+
if (failures > 0)
|
|
151
|
+
return Failure('FAILED', `ApolloAccountsEnrichment finished with ${failures} of ${result.Results.length} accounts failing; see the log.`);
|
|
152
|
+
LogStatus(`--- Checking for remaining records... (execution ${executionCount + 1}/${MAX_EXECUTIONS})`);
|
|
153
|
+
return this.processAllAccountRecords(ctx, executionCount + 1);
|
|
265
154
|
}
|
|
266
|
-
/**
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
};
|
|
287
|
-
const task = this.ProcessSingleDomain(processParams, index, resultLength, md, contextUser);
|
|
288
|
-
tasks.push(task);
|
|
289
|
-
if (tasks.length === Config.ConcurrentGroups || index + 1 >= resultLength) {
|
|
290
|
-
await Promise.all(tasks);
|
|
291
|
-
tasks.length = 0;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
155
|
+
/** Enriches one account and, when contacts are configured, the people at its domain. */
|
|
156
|
+
async ProcessSingleDomain(ctx, record) {
|
|
157
|
+
const p = ctx.Params;
|
|
158
|
+
const params = {
|
|
159
|
+
Record: record,
|
|
160
|
+
AccountEntity: p.accountEntityFields,
|
|
161
|
+
AccountTechnologyEntity: p.accountTechnologyEntityFields ?? null,
|
|
162
|
+
TechnologyCategoryEntity: p.technologyCategoryEntityFields ?? null,
|
|
163
|
+
ContactEntity: p.contactEntityFields ?? null,
|
|
164
|
+
ContactEducationHistoryEntity: p.contactEducationHistoryEntityFields ?? null,
|
|
165
|
+
};
|
|
166
|
+
const domain = StringOf(record[p.accountEntityFields.DomainField]);
|
|
167
|
+
if (!domain) {
|
|
168
|
+
LogStatus(' > Account has no domain; stamping it without a lookup');
|
|
169
|
+
return this.updateAccountEnrichedTimestamp(params, record, ctx.Md, ctx.User);
|
|
170
|
+
}
|
|
171
|
+
const accountID = record[p.accountEntityFields.AccountIDField];
|
|
172
|
+
const enriched = await this.enrichOrganization(ctx, params, domain);
|
|
173
|
+
const people = await this.createAndEnrichPeople(ctx, params, accountID, domain);
|
|
174
|
+
return enriched && people;
|
|
294
175
|
}
|
|
295
|
-
/**
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
const record = params.Record;
|
|
308
|
-
const accountID = record[params.AccountEntity.AccountIDField];
|
|
309
|
-
const domain = record[params.AccountEntity.DomainField];
|
|
310
|
-
const enrichOrganizationResult = await this.enrichOrganization(params, startRow, totalRows, md, currentUser);
|
|
311
|
-
const createAndEnrichPeopleResult = await this.createAndEnrichPeople(params, accountID, domain, startRow, md, currentUser);
|
|
312
|
-
return enrichOrganizationResult && createAndEnrichPeopleResult;
|
|
176
|
+
/** `organizations/enrich` for the account's domain; a miss still stamps the account. */
|
|
177
|
+
async enrichOrganization(ctx, params, domain) {
|
|
178
|
+
const organization = await ctx.Clients.People.EnrichOrganization(domain);
|
|
179
|
+
if (!organization) {
|
|
180
|
+
LogStatus(` > No matches found for this domain: ${domain}`);
|
|
181
|
+
return this.updateAccountEnrichedTimestamp(params, params.Record, ctx.Md, ctx.User);
|
|
182
|
+
}
|
|
183
|
+
const saved = await this.updateAccountWithOrganizationData(organization, params, params.Record, ctx.Md, ctx.User);
|
|
184
|
+
if (!saved || !params.AccountTechnologyEntity)
|
|
185
|
+
return saved;
|
|
186
|
+
const accountID = params.Record[params.AccountEntity.AccountIDField];
|
|
187
|
+
return this.CreateAccountTechnologyRecords(params, accountID, organization.current_technologies, ctx.Md, ctx.User);
|
|
313
188
|
}
|
|
314
|
-
/**
|
|
315
|
-
* Enriches organization data using Apollo.io's organization enrichment endpoint
|
|
316
|
-
* Updates account record with company information and triggers technology processing
|
|
317
|
-
*
|
|
318
|
-
* @param params - Domain processing parameters
|
|
319
|
-
* @param startRow - Current row for progress tracking
|
|
320
|
-
* @param totalRows - Total rows for progress tracking
|
|
321
|
-
* @param md - Metadata instance for entity operations
|
|
322
|
-
* @param currentUser - User context for data access
|
|
323
|
-
* @returns Promise<boolean> indicating success/failure
|
|
324
|
-
*/
|
|
325
|
-
async enrichOrganization(params, startRow, totalRows, md, currentUser) {
|
|
326
|
-
try {
|
|
327
|
-
const record = params.Record;
|
|
328
|
-
const orgQueryString = {
|
|
329
|
-
api_key: Config.ApolloAPIKey,
|
|
330
|
-
domain: record[params.AccountEntity.DomainField]
|
|
331
|
-
};
|
|
332
|
-
const headers = {
|
|
333
|
-
'Cache-Control': 'no-cache',
|
|
334
|
-
'Content-Type': 'application/json'
|
|
335
|
-
};
|
|
336
|
-
// Get the organization enrichment data
|
|
337
|
-
const orgResponse = await this.WrapApolloCall('get', 'organizations/enrich', null, { Query: orgQueryString, Headers: headers });
|
|
338
|
-
if (!orgResponse || orgResponse.Status !== 200) {
|
|
339
|
-
return false;
|
|
340
|
-
}
|
|
341
|
-
const result = orgResponse.Data;
|
|
342
|
-
let bSuccess = true;
|
|
343
|
-
if (result && result.organization) {
|
|
344
|
-
bSuccess = await this.updateAccountWithOrganizationData(result.organization, params, record, md, currentUser);
|
|
345
|
-
if (params.AccountTechnologyEntity && bSuccess) {
|
|
346
|
-
const accountID = record[params.AccountEntity.AccountIDField];
|
|
347
|
-
bSuccess = bSuccess && await this.CreateAccountTechnologyRecords(params, accountID, result.organization.current_technologies, md, currentUser);
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
else {
|
|
351
|
-
// No match found, but still update enriched timestamp
|
|
352
|
-
LogStatus(` > No matches found for this domain: ${params.Record[params.AccountEntity.DomainField]}`);
|
|
353
|
-
bSuccess = await this.updateAccountEnrichedTimestamp(params, record, md, currentUser);
|
|
354
|
-
}
|
|
355
|
-
return bSuccess;
|
|
356
|
-
}
|
|
357
|
-
catch (error) {
|
|
358
|
-
LogError('Error enriching organization', undefined, error);
|
|
359
|
-
return false;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
/**
|
|
363
|
-
* Updates an account entity with enriched organization data from Apollo.io
|
|
364
|
-
* Maps Apollo organization fields to the configured account entity fields
|
|
365
|
-
*
|
|
366
|
-
* @param organization - Apollo organization data
|
|
367
|
-
* @param params - Processing parameters with field mappings
|
|
368
|
-
* @param record - Current account record data
|
|
369
|
-
* @param md - Metadata instance for entity operations
|
|
370
|
-
* @param currentUser - User context for data access
|
|
371
|
-
* @returns Promise<boolean> indicating save success/failure
|
|
372
|
-
*/
|
|
189
|
+
/** Maps Apollo organization fields to the configured account entity fields and stamps the account. */
|
|
373
190
|
async updateAccountWithOrganizationData(organization, params, record, md, currentUser) {
|
|
374
191
|
try {
|
|
375
|
-
|
|
376
|
-
const accountEntity = await md.GetEntityObject(
|
|
377
|
-
|
|
378
|
-
this.setFieldIfExists(accountEntity,
|
|
379
|
-
this.setFieldIfExists(accountEntity,
|
|
380
|
-
this.setFieldIfExists(accountEntity,
|
|
381
|
-
this.setFieldIfExists(accountEntity,
|
|
382
|
-
this.setFieldIfExists(accountEntity,
|
|
383
|
-
this.setFieldIfExists(accountEntity,
|
|
384
|
-
this.setFieldIfExists(accountEntity,
|
|
385
|
-
this.setFieldIfExists(accountEntity,
|
|
386
|
-
this.setFieldIfExists(accountEntity,
|
|
387
|
-
this.setFieldIfExists(accountEntity,
|
|
388
|
-
|
|
389
|
-
this.setFieldIfExists(accountEntity, params.AccountEntity.EnrichedAtField, new Date());
|
|
192
|
+
const a = params.AccountEntity;
|
|
193
|
+
const accountEntity = await md.GetEntityObject(a.EntityName, CompositeKey.FromEntityRecord(EntityOf(md, a.EntityName), record), currentUser);
|
|
194
|
+
this.setFieldIfExists(accountEntity, a.AddressField, organization.street_address);
|
|
195
|
+
this.setFieldIfExists(accountEntity, a.CityField, organization.city);
|
|
196
|
+
this.setFieldIfExists(accountEntity, a.StateProvinceField, organization.state);
|
|
197
|
+
this.setFieldIfExists(accountEntity, a.PostalCodeField, organization.postal_code);
|
|
198
|
+
this.setFieldIfExists(accountEntity, a.DescriptionField, organization.short_description);
|
|
199
|
+
this.setFieldIfExists(accountEntity, a.PhoneNumberField, organization.phone);
|
|
200
|
+
this.setFieldIfExists(accountEntity, a.CountryField, organization.country);
|
|
201
|
+
this.setFieldIfExists(accountEntity, a.LinkedInField, organization.linkedin_url);
|
|
202
|
+
this.setFieldIfExists(accountEntity, a.LogoURLField, organization.logo_url);
|
|
203
|
+
this.setFieldIfExists(accountEntity, a.FacebookField, organization.facebook_url);
|
|
204
|
+
this.setFieldIfExists(accountEntity, a.TwitterField, organization.twitter_url);
|
|
205
|
+
accountEntity.Set(a.EnrichedAtField, new Date());
|
|
390
206
|
const saveResult = await accountEntity.Save();
|
|
391
|
-
if (!saveResult)
|
|
392
|
-
LogError(
|
|
393
|
-
}
|
|
207
|
+
if (!saveResult)
|
|
208
|
+
LogError(`Error updating account record with enriched data: ${accountEntity.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
394
209
|
return saveResult;
|
|
395
210
|
}
|
|
396
211
|
catch (error) {
|
|
@@ -398,25 +213,15 @@ let ApolloEnrichmentAccountsAction = class ApolloEnrichmentAccountsAction extend
|
|
|
398
213
|
return false;
|
|
399
214
|
}
|
|
400
215
|
}
|
|
401
|
-
/**
|
|
402
|
-
* Updates the enrichment timestamp on an account even when no data was found
|
|
403
|
-
* Prevents repeated attempts to enrich accounts with no Apollo data
|
|
404
|
-
*
|
|
405
|
-
* @param params - Processing parameters with field mappings
|
|
406
|
-
* @param record - Current account record data
|
|
407
|
-
* @param md - Metadata instance for entity operations
|
|
408
|
-
* @param currentUser - User context for data access
|
|
409
|
-
* @returns Promise<boolean> indicating save success/failure
|
|
410
|
-
*/
|
|
216
|
+
/** Stamps the account's enrichment timestamp when Apollo had nothing, so it is not retried every run. */
|
|
411
217
|
async updateAccountEnrichedTimestamp(params, record, md, currentUser) {
|
|
412
218
|
try {
|
|
413
|
-
|
|
414
|
-
const accountEntity = await md.GetEntityObject(
|
|
415
|
-
accountEntity.Set(
|
|
219
|
+
const a = params.AccountEntity;
|
|
220
|
+
const accountEntity = await md.GetEntityObject(a.EntityName, CompositeKey.FromEntityRecord(EntityOf(md, a.EntityName), record), currentUser);
|
|
221
|
+
accountEntity.Set(a.EnrichedAtField, new Date());
|
|
416
222
|
const saveResult = await accountEntity.Save();
|
|
417
|
-
if (!saveResult)
|
|
418
|
-
LogError(
|
|
419
|
-
}
|
|
223
|
+
if (!saveResult)
|
|
224
|
+
LogError(`Error updating account record with enriched timestamp: ${accountEntity.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
420
225
|
return saveResult;
|
|
421
226
|
}
|
|
422
227
|
catch (error) {
|
|
@@ -424,120 +229,87 @@ let ApolloEnrichmentAccountsAction = class ApolloEnrichmentAccountsAction extend
|
|
|
424
229
|
return false;
|
|
425
230
|
}
|
|
426
231
|
}
|
|
427
|
-
/**
|
|
428
|
-
* Safely sets a field on an entity if the field name is defined and value is not null
|
|
429
|
-
* Prevents errors from undefined field mappings
|
|
430
|
-
*
|
|
431
|
-
* @param entity - Target entity to update
|
|
432
|
-
* @param fieldName - Name of the field (can be undefined)
|
|
433
|
-
* @param value - Value to set (checked for null/undefined)
|
|
434
|
-
*/
|
|
232
|
+
/** Sets a field when the mapping names it and the value is present. */
|
|
435
233
|
setFieldIfExists(entity, fieldName, value) {
|
|
436
|
-
if (fieldName && value
|
|
234
|
+
if (fieldName && value !== null && value !== undefined)
|
|
437
235
|
entity.Set(fieldName, value);
|
|
438
|
-
}
|
|
439
236
|
}
|
|
237
|
+
// ─── Technologies ────────────────────────────────────────────────────────
|
|
440
238
|
/**
|
|
441
|
-
* Creates
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
* @param params - Processing parameters with technology entity configuration
|
|
446
|
-
* @param accountID - ID of the account to associate technologies with
|
|
447
|
-
* @param technologies - Array of technology data from Apollo
|
|
448
|
-
* @param md - Metadata instance for entity operations
|
|
449
|
-
* @param currentUser - User context for data access
|
|
450
|
-
* @returns Promise<boolean> indicating overall success/failure
|
|
239
|
+
* Creates account-technology rows for technologies Apollo reports and marks the rows for
|
|
240
|
+
* technologies it no longer reports as ended. Every save runs; a failure is counted, never
|
|
241
|
+
* allowed to skip the rows after it.
|
|
451
242
|
*/
|
|
452
243
|
async CreateAccountTechnologyRecords(params, accountID, technologies, md, currentUser) {
|
|
453
|
-
|
|
244
|
+
const ATEntity = params.AccountTechnologyEntity;
|
|
245
|
+
if (!ATEntity || !technologies || technologies.length === 0)
|
|
246
|
+
return true;
|
|
247
|
+
if (!ATEntity.TechnologyIDField || !ATEntity.TechnologyField || !ATEntity.CategoryField)
|
|
454
248
|
return true;
|
|
455
|
-
}
|
|
456
249
|
try {
|
|
250
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
251
|
+
const existing = await rv.RunView({ EntityName: ATEntity.EntityName, ExtraFilter: FieldPredicate(md, ATEntity.EntityName, ATEntity.AccountIDField, accountID) }, currentUser);
|
|
252
|
+
if (!existing.Success) {
|
|
253
|
+
LogError(`Error querying for existing Account Technologies: ${existing.ErrorMessage}`);
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
const matched = new Set();
|
|
457
257
|
let bSuccess = true;
|
|
458
|
-
const
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
ExtraFilter: `${ATEntity.AccountIDField} = ${accountID}`
|
|
464
|
-
}, currentUser);
|
|
465
|
-
if (!runViewResult.Success) {
|
|
466
|
-
LogError('Error querying for existing Account Technologies', undefined, runViewResult.ErrorMessage);
|
|
467
|
-
return false;
|
|
468
|
-
}
|
|
469
|
-
// Process each technology
|
|
470
|
-
for (const technology of technologies) {
|
|
471
|
-
const categoryId = await this.getOrCreateTechnologyCategoryId(params, technology.category, md, currentUser);
|
|
472
|
-
const existingRow = runViewResult.Results.find((r) => r[ATEntity.CategoryField]?.trim().toLowerCase() === technology.category.trim().toLowerCase() &&
|
|
473
|
-
r[ATEntity.TechnologyField]?.trim().toLowerCase() === technology.name.trim().toLowerCase());
|
|
474
|
-
if (!existingRow) {
|
|
475
|
-
// Create new technology record
|
|
476
|
-
const at = await md.GetEntityObject(ATEntity.EntityName, currentUser);
|
|
477
|
-
at.NewRecord();
|
|
478
|
-
at.Set(ATEntity.AccountIDField, accountID);
|
|
479
|
-
at.Set(ATEntity.TechnologyIDField, await this.getOrCreateTechnologyId(technology.name, categoryId, md, currentUser));
|
|
480
|
-
bSuccess = bSuccess && await at.Save();
|
|
481
|
-
}
|
|
482
|
-
else {
|
|
483
|
-
existingRow.matchFound = true;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
// Mark unmatched technologies as ended
|
|
487
|
-
for (const record of runViewResult.Results) {
|
|
488
|
-
if (!record.matchFound) {
|
|
489
|
-
const entity = await md.GetEntityObject(ATEntity.EntityName, CompositeKey.FromEntityRecord(md.EntityByName(ATEntity.EntityName), record), currentUser);
|
|
490
|
-
entity.Set(ATEntity.EndedUseAtField, new Date());
|
|
491
|
-
const saveResult = await entity.Save();
|
|
492
|
-
if (!saveResult) {
|
|
493
|
-
LogError('Error updating Account Technology record', undefined, entity.LatestResult);
|
|
494
|
-
}
|
|
495
|
-
bSuccess = bSuccess && saveResult;
|
|
496
|
-
}
|
|
258
|
+
for (const technology of technologies) {
|
|
259
|
+
const row = existing.Results.find((r) => SameText(r[ATEntity.CategoryField], technology.category) && SameText(r[ATEntity.TechnologyField], technology.name));
|
|
260
|
+
if (row) {
|
|
261
|
+
matched.add(row);
|
|
262
|
+
continue;
|
|
497
263
|
}
|
|
498
|
-
|
|
499
|
-
|
|
264
|
+
const categoryId = await this.getOrCreateTechnologyCategoryId(params, technology.category, md, currentUser);
|
|
265
|
+
const at = await md.GetEntityObject(ATEntity.EntityName, currentUser);
|
|
266
|
+
at.NewRecord();
|
|
267
|
+
at.Set(ATEntity.AccountIDField, accountID);
|
|
268
|
+
at.Set(ATEntity.TechnologyIDField, await this.getOrCreateTechnologyId(technology.name, categoryId, md, currentUser));
|
|
269
|
+
const saved = await at.Save();
|
|
270
|
+
if (!saved)
|
|
271
|
+
LogError(`Error creating Account Technology record: ${at.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
272
|
+
bSuccess = bSuccess && saved;
|
|
273
|
+
}
|
|
274
|
+
const ended = await this.endUnmatchedTechnologies(ATEntity, existing.Results.filter((r) => !matched.has(r)), md, currentUser);
|
|
275
|
+
return bSuccess && ended;
|
|
500
276
|
}
|
|
501
277
|
catch (error) {
|
|
502
278
|
LogError('Error creating account technology records', undefined, error);
|
|
503
279
|
return false;
|
|
504
280
|
}
|
|
505
281
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
282
|
+
async endUnmatchedTechnologies(ATEntity, rows, md, currentUser) {
|
|
283
|
+
let bSuccess = true;
|
|
284
|
+
for (const record of rows) {
|
|
285
|
+
const entity = await md.GetEntityObject(ATEntity.EntityName, CompositeKey.FromEntityRecord(EntityOf(md, ATEntity.EntityName), record), currentUser);
|
|
286
|
+
entity.Set(ATEntity.EndedUseAtField, new Date());
|
|
287
|
+
const saved = await entity.Save();
|
|
288
|
+
if (!saved)
|
|
289
|
+
LogError(`Error updating Account Technology record: ${entity.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
290
|
+
bSuccess = bSuccess && saved;
|
|
291
|
+
}
|
|
292
|
+
return bSuccess;
|
|
293
|
+
}
|
|
294
|
+
/** The configured category entity's key for a category name, creating the row when absent. 0 on error. */
|
|
516
295
|
async getOrCreateTechnologyCategoryId(params, categoryName, md, currentUser) {
|
|
517
296
|
const TCEntity = params.TechnologyCategoryEntity;
|
|
518
|
-
if (!TCEntity)
|
|
297
|
+
if (!TCEntity)
|
|
519
298
|
return 0;
|
|
520
|
-
}
|
|
521
299
|
try {
|
|
522
|
-
const rv =
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
}, currentUser);
|
|
527
|
-
if (!runViewResult.Success) {
|
|
528
|
-
LogError('Error querying for existing Technology Categories', undefined, runViewResult.ErrorMessage);
|
|
300
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
301
|
+
const existing = await rv.RunView({ EntityName: TCEntity.EntityName, ExtraFilter: `[${TCEntity.NameField}] = '${EscapeSQLString(categoryName)}'` }, currentUser);
|
|
302
|
+
if (!existing.Success) {
|
|
303
|
+
LogError(`Error querying for existing Technology Categories: ${existing.ErrorMessage}`);
|
|
529
304
|
return 0;
|
|
530
305
|
}
|
|
531
|
-
if (
|
|
532
|
-
return
|
|
533
|
-
}
|
|
534
|
-
// Create new record
|
|
306
|
+
if (existing.Results.length > 0)
|
|
307
|
+
return existing.Results[0][TCEntity.IDField];
|
|
535
308
|
const entity = await md.GetEntityObject(TCEntity.EntityName, currentUser);
|
|
536
309
|
entity.NewRecord();
|
|
537
310
|
entity.Set(TCEntity.NameField, categoryName);
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
LogError('Error creating new Technology Category record', undefined, entity.LatestResult);
|
|
311
|
+
if (!(await entity.Save())) {
|
|
312
|
+
LogError(`Error creating new Technology Category record: ${entity.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
541
313
|
return 0;
|
|
542
314
|
}
|
|
543
315
|
return entity.Get(TCEntity.IDField);
|
|
@@ -547,426 +319,263 @@ let ApolloEnrichmentAccountsAction = class ApolloEnrichmentAccountsAction extend
|
|
|
547
319
|
return 0;
|
|
548
320
|
}
|
|
549
321
|
}
|
|
550
|
-
/**
|
|
551
|
-
* Gets or creates a technology record by name and category
|
|
552
|
-
* Maintains referential integrity between technologies and categories
|
|
553
|
-
*
|
|
554
|
-
* @param name - Name of the technology
|
|
555
|
-
* @param categoryId - ID of the technology category
|
|
556
|
-
* @param md - Metadata instance for entity operations
|
|
557
|
-
* @param currentUser - User context for data access
|
|
558
|
-
* @returns Promise<number> - ID of the technology (0 if error)
|
|
559
|
-
*/
|
|
322
|
+
/** The `Technologies` entity's key for a name within a category, creating the row when absent. 0 on error. */
|
|
560
323
|
async getOrCreateTechnologyId(name, categoryId, md, currentUser) {
|
|
561
324
|
try {
|
|
562
|
-
const
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
if (!runViewResult.Success) {
|
|
568
|
-
LogError('Error querying for existing Technologies', undefined, runViewResult.ErrorMessage);
|
|
325
|
+
const info = EntityOf(md, 'Technologies');
|
|
326
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
327
|
+
const existing = await rv.RunView({ EntityName: 'Technologies', ExtraFilter: `[Name] = '${EscapeSQLString(name)}' AND ${FieldPredicate(md, 'Technologies', 'CategoryID', categoryId)}` }, currentUser);
|
|
328
|
+
if (!existing.Success) {
|
|
329
|
+
LogError(`Error querying for existing Technologies: ${existing.ErrorMessage}`);
|
|
569
330
|
return 0;
|
|
570
331
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
// Create new technology record
|
|
332
|
+
const pkName = info.FirstPrimaryKey.Name; // first-pk-ok: Technologies is a single-key MJ entity; the value is returned for a single FK column
|
|
333
|
+
if (existing.Results.length > 0)
|
|
334
|
+
return existing.Results[0][pkName];
|
|
575
335
|
const technologyEntity = await md.GetEntityObject('Technologies', currentUser);
|
|
576
336
|
technologyEntity.NewRecord();
|
|
577
337
|
technologyEntity.Set('Name', name);
|
|
578
338
|
technologyEntity.Set('CategoryID', categoryId);
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
LogError('Error creating new Technology record', undefined, technologyEntity.LatestResult);
|
|
339
|
+
if (!(await technologyEntity.Save())) {
|
|
340
|
+
LogError(`Error creating new Technology record: ${technologyEntity.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
582
341
|
return 0;
|
|
583
342
|
}
|
|
584
|
-
return technologyEntity.Get(
|
|
343
|
+
return technologyEntity.Get(pkName);
|
|
585
344
|
}
|
|
586
345
|
catch (error) {
|
|
587
346
|
LogError('Error getting or creating technology', undefined, error);
|
|
588
347
|
return 0;
|
|
589
348
|
}
|
|
590
349
|
}
|
|
350
|
+
// ─── People ──────────────────────────────────────────────────────────────
|
|
591
351
|
/**
|
|
592
|
-
*
|
|
593
|
-
*
|
|
594
|
-
* Handles pagination to retrieve all available contacts (up to configured limit)
|
|
595
|
-
*
|
|
596
|
-
* @param params - Processing parameters with contact entity configuration
|
|
597
|
-
* @param accountID - ID of the account to associate contacts with
|
|
598
|
-
* @param domain - Organization domain to search for people
|
|
599
|
-
* @param startRow - Current row for progress tracking
|
|
600
|
-
* @param md - Metadata instance for entity operations
|
|
601
|
-
* @param currentUser - User context for data access
|
|
602
|
-
* @returns Promise<boolean> indicating success/failure of people processing
|
|
352
|
+
* Discovers the people Apollo lists at the domain (free search, ids only), then matches them
|
|
353
|
+
* ten at a time by id (one credit per match) and creates or updates a contact for each.
|
|
603
354
|
*/
|
|
604
|
-
async createAndEnrichPeople(params, accountID, domain
|
|
605
|
-
if (!params.ContactEntity)
|
|
606
|
-
return true;
|
|
355
|
+
async createAndEnrichPeople(ctx, params, accountID, domain) {
|
|
356
|
+
if (!params.ContactEntity)
|
|
357
|
+
return true;
|
|
358
|
+
const ids = await this.discoverPeopleIDs(ctx, domain);
|
|
359
|
+
if (ids.length === 0) {
|
|
360
|
+
LogStatus(`No people found for this domain: ${domain}`);
|
|
361
|
+
return true;
|
|
607
362
|
}
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
'Cache-Control': 'no-cache',
|
|
617
|
-
'Content-Type': 'application/json'
|
|
618
|
-
};
|
|
619
|
-
const response = await this.WrapApolloCall('post', 'mixed_people/search', APIparams, { Headers: headers });
|
|
620
|
-
if (!response || response.Status !== 200) {
|
|
621
|
-
LogError(`Error fetching data from Apollo.io: ${response?.StatusText}`);
|
|
622
|
-
return false;
|
|
623
|
-
}
|
|
624
|
-
const data = response.Data;
|
|
625
|
-
const allPeople = data.people;
|
|
626
|
-
// Fetch additional pages
|
|
627
|
-
for (let i = 1; i < data.pagination.total_pages && i < (Config.MaxPeopleToEnrichPerOrg / 10); i++) {
|
|
628
|
-
APIparams.page = i + 1;
|
|
629
|
-
const nextResponse = await this.WrapApolloCall('post', 'mixed_people/search', APIparams, { Headers: headers });
|
|
630
|
-
if (nextResponse.Status !== 200) {
|
|
631
|
-
console.error(`Error fetching data from Apollo.io: ${nextResponse.StatusText}`);
|
|
632
|
-
return false;
|
|
633
|
-
}
|
|
634
|
-
const nextResult = nextResponse.Data;
|
|
635
|
-
allPeople.push(...nextResult.people);
|
|
636
|
-
}
|
|
637
|
-
if (allPeople.length === 0) {
|
|
638
|
-
LogStatus(`No people found for this domain: ${domain}`);
|
|
639
|
-
return true;
|
|
640
|
-
}
|
|
641
|
-
// Process all people
|
|
642
|
-
let bSuccess = true;
|
|
643
|
-
for (let i = 0; i < allPeople.length; i++) {
|
|
644
|
-
const person = allPeople[i];
|
|
645
|
-
if (this.shouldSkipPerson(person, domain)) {
|
|
363
|
+
let bSuccess = true;
|
|
364
|
+
let sequence = 0;
|
|
365
|
+
for (let i = 0; i < ids.length; i += ApolloPeopleClient.MaxBatchSize) {
|
|
366
|
+
const group = ids.slice(i, i + ApolloPeopleClient.MaxBatchSize);
|
|
367
|
+
const result = await ctx.Clients.People.BulkMatch(group.map((id) => ({ Key: id, ApolloPersonID: id })), { RevealPersonalEmails: true });
|
|
368
|
+
for (const match of result.Matches) {
|
|
369
|
+
sequence++;
|
|
370
|
+
if (this.shouldSkipPerson(match, domain))
|
|
646
371
|
continue;
|
|
647
|
-
|
|
648
|
-
bSuccess = bSuccess &&
|
|
372
|
+
const ok = await this.createAndEnrichContact(ctx, params, accountID, match, sequence, ids.length);
|
|
373
|
+
bSuccess = bSuccess && ok;
|
|
649
374
|
}
|
|
650
|
-
return bSuccess;
|
|
651
|
-
}
|
|
652
|
-
catch (error) {
|
|
653
|
-
LogError('Error creating and enriching people', undefined, error);
|
|
654
|
-
return false;
|
|
655
375
|
}
|
|
376
|
+
return bSuccess;
|
|
656
377
|
}
|
|
657
|
-
/**
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
378
|
+
/** Apollo ids of the people at the domain, from `api_search`, up to `MaxPeopleToEnrichPerOrg`. */
|
|
379
|
+
async discoverPeopleIDs(ctx, domain) {
|
|
380
|
+
const ids = [];
|
|
381
|
+
const maxPages = Math.max(1, Math.ceil(Config.MaxPeopleToEnrichPerOrg / SEARCH_PAGE_SIZE));
|
|
382
|
+
for (let page = 1; page <= maxPages; page++) {
|
|
383
|
+
const result = await ctx.Clients.Search.searchPeople({ organizationDomains: [domain] }, { page, perPage: SEARCH_PAGE_SIZE });
|
|
384
|
+
for (const person of result.people) {
|
|
385
|
+
if (person.id && ids.length < Config.MaxPeopleToEnrichPerOrg)
|
|
386
|
+
ids.push(person.id);
|
|
387
|
+
}
|
|
388
|
+
if (result.people.length < SEARCH_PAGE_SIZE || page >= result.pagination.totalPages || ids.length >= Config.MaxPeopleToEnrichPerOrg)
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
return ids;
|
|
392
|
+
}
|
|
393
|
+
/** Skips a miss, a person with no last name or email, an email outside the domain, and an excluded title. */
|
|
394
|
+
shouldSkipPerson(match, domain) {
|
|
395
|
+
if (!match.Matched || !match.LastName || !match.Email || DomainOf(match.Email.split('@')[1]) !== domain.toLowerCase()) {
|
|
396
|
+
LogStatus(`Skipping person: ${match.FirstName ?? ''} ${match.LastName ?? ''} because email is missing or does not match domain`);
|
|
669
397
|
return true;
|
|
670
398
|
}
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
LogStatus(`Skipping person: ${person.first_name} ${person.last_name} because title is excluded`);
|
|
399
|
+
if (this.IsExcludedTitle(match.Title ?? '')) {
|
|
400
|
+
LogStatus(`Skipping person: ${match.FirstName} ${match.LastName} because title is excluded`);
|
|
674
401
|
return true;
|
|
675
402
|
}
|
|
676
403
|
return false;
|
|
677
404
|
}
|
|
678
|
-
/**
|
|
679
|
-
|
|
680
|
-
* Handles contact deduplication and data validation
|
|
681
|
-
*
|
|
682
|
-
* @param params - Processing parameters with contact entity configuration
|
|
683
|
-
* @param accountID - ID of the account to associate contact with
|
|
684
|
-
* @param person - Person data from Apollo search response
|
|
685
|
-
* @param md - Metadata instance for entity operations
|
|
686
|
-
* @param currentUser - User context for data access
|
|
687
|
-
* @param sequence - Current contact number for progress tracking
|
|
688
|
-
* @param total - Total contacts for progress tracking
|
|
689
|
-
* @returns Promise<boolean> indicating success/failure
|
|
690
|
-
*/
|
|
691
|
-
async createAndEnrichContact(params, accountID, person, md, currentUser, sequence, total) {
|
|
405
|
+
/** Creates or updates one contact and, when configured, its education history. */
|
|
406
|
+
async createAndEnrichContact(ctx, params, accountID, match, sequence, total) {
|
|
692
407
|
const CEntity = params.ContactEntity;
|
|
693
|
-
if (!CEntity)
|
|
408
|
+
if (!CEntity)
|
|
694
409
|
return false;
|
|
695
|
-
}
|
|
696
410
|
try {
|
|
697
|
-
LogStatus(`Enriching contact for person: ${
|
|
698
|
-
const contact = await this.getOrCreateContact(params, accountID,
|
|
699
|
-
if (!contact)
|
|
411
|
+
LogStatus(`Enriching contact for person: ${match.FirstName} ${match.LastName}, accountID: ${accountID} (${sequence} of ${total})`);
|
|
412
|
+
const contact = await this.getOrCreateContact(ctx, params, accountID, match);
|
|
413
|
+
if (!contact)
|
|
700
414
|
return false;
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
if (!saveResult) {
|
|
706
|
-
LogError('Error updating contact record with enriched data', undefined, contact.LatestResult);
|
|
415
|
+
this.updateContactFields(contact, match, CEntity);
|
|
416
|
+
const saved = await contact.Save();
|
|
417
|
+
if (!saved) {
|
|
418
|
+
LogError(`Error updating contact record with enriched data: ${contact.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
707
419
|
return false;
|
|
708
420
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
}
|
|
713
|
-
return true;
|
|
421
|
+
if (!params.ContactEducationHistoryEntity)
|
|
422
|
+
return true;
|
|
423
|
+
return this.createUpdateContactEducationHistory(ctx, params, contact, match);
|
|
714
424
|
}
|
|
715
425
|
catch (error) {
|
|
426
|
+
if (error instanceof ApolloRateLimitError || error instanceof ApolloAuthError)
|
|
427
|
+
throw error;
|
|
716
428
|
LogError('Error creating and enriching contact', undefined, error);
|
|
717
429
|
return false;
|
|
718
430
|
}
|
|
719
431
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
contact.Set(CEntity.LastNameField, person.last_name);
|
|
731
|
-
contact.Set(CEntity.TitleField, person.title);
|
|
732
|
-
if (person.email) {
|
|
733
|
-
contact.Set(CEntity.EmailField, person.email);
|
|
734
|
-
}
|
|
735
|
-
this.setFieldIfExists(contact, CEntity.FacebookField, person.facebook_url);
|
|
736
|
-
this.setFieldIfExists(contact, CEntity.LinkedInField, person.linkedin_url);
|
|
737
|
-
this.setFieldIfExists(contact, CEntity.TwitterField, person.twitter_url);
|
|
738
|
-
this.setFieldIfExists(contact, CEntity.ProfilePictureURLField, person.photo_url);
|
|
432
|
+
updateContactFields(contact, match, CEntity) {
|
|
433
|
+
contact.Set(CEntity.FirstNameField, match.FirstName);
|
|
434
|
+
contact.Set(CEntity.LastNameField, match.LastName);
|
|
435
|
+
contact.Set(CEntity.TitleField, match.Title);
|
|
436
|
+
if (match.Email)
|
|
437
|
+
contact.Set(CEntity.EmailField, match.Email);
|
|
438
|
+
this.setFieldIfExists(contact, CEntity.FacebookField, match.FacebookURL);
|
|
439
|
+
this.setFieldIfExists(contact, CEntity.LinkedInField, match.LinkedInURL);
|
|
440
|
+
this.setFieldIfExists(contact, CEntity.TwitterField, match.TwitterURL);
|
|
441
|
+
this.setFieldIfExists(contact, CEntity.ProfilePictureURLField, match.PhotoURL);
|
|
739
442
|
contact.Set(CEntity.EnrichedAtField, new Date());
|
|
740
443
|
}
|
|
741
444
|
/**
|
|
742
|
-
*
|
|
743
|
-
*
|
|
744
|
-
* Supports matching by email or name combination
|
|
745
|
-
*
|
|
746
|
-
* @param params - Processing parameters with contact entity configuration
|
|
747
|
-
* @param accountID - ID of the account to associate contact with
|
|
748
|
-
* @param person - Person data from Apollo
|
|
749
|
-
* @param md - Metadata instance for entity operations
|
|
750
|
-
* @param currentUser - User context for data access
|
|
751
|
-
* @returns Promise<BaseEntity | null> - Contact entity or null if conflict/error
|
|
445
|
+
* The existing contact for this account (by email, or by first and last name), or a new one.
|
|
446
|
+
* Null when the person is already a contact of a different account, or on a lookup error.
|
|
752
447
|
*/
|
|
753
|
-
async getOrCreateContact(params, accountID,
|
|
448
|
+
async getOrCreateContact(ctx, params, accountID, match) {
|
|
754
449
|
const CEntity = params.ContactEntity;
|
|
755
|
-
if (!CEntity)
|
|
450
|
+
if (!CEntity)
|
|
451
|
+
return null;
|
|
452
|
+
const md = ctx.Md;
|
|
453
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
454
|
+
const email = `[${CEntity.EmailField}] = '${EscapeSQLString(match.Email ?? '')}'`;
|
|
455
|
+
const conflict = await rv.RunView({ EntityName: CEntity.EntityName, ExtraFilter: `${email} AND ${FieldPredicate(md, CEntity.EntityName, CEntity.AccountIDField, accountID, '<>')}` }, ctx.User);
|
|
456
|
+
if (!conflict.Success) {
|
|
457
|
+
LogError(`Error querying for existing Contacts: ${conflict.ErrorMessage}`);
|
|
756
458
|
return null;
|
|
757
459
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
const conflictResult = await rv.RunView({
|
|
762
|
-
EntityName: CEntity.EntityName,
|
|
763
|
-
ExtraFilter: `${CEntity.EmailField} = '${this.EscapeSingleQuotes(person.email)}' AND ${CEntity.AccountIDField} <> ${accountID}`
|
|
764
|
-
}, currentUser);
|
|
765
|
-
if (!conflictResult.Success) {
|
|
766
|
-
LogError('Error querying for existing Contacts', undefined, conflictResult.ErrorMessage);
|
|
767
|
-
return null;
|
|
768
|
-
}
|
|
769
|
-
if (conflictResult.Results.length > 0) {
|
|
770
|
-
const existing = conflictResult.Results[0];
|
|
771
|
-
LogError(`*** SKIPPING new contact record for ${person.first_name} ${person.last_name} because they are already associated with AccountID: ${existing.AccountID} - ContactID: ${existing.ID}`);
|
|
772
|
-
return null;
|
|
773
|
-
}
|
|
774
|
-
// Check if contact exists for this account
|
|
775
|
-
const existingResult = await rv.RunView({
|
|
776
|
-
EntityName: CEntity.EntityName,
|
|
777
|
-
ExtraFilter: `(${CEntity.EmailField} = '${this.EscapeSingleQuotes(person.email)}' OR (${CEntity.FirstNameField} = '${this.EscapeSingleQuotes(person.first_name)}' AND ${CEntity.LastNameField} = '${this.EscapeSingleQuotes(person.last_name)}')) AND ${CEntity.AccountIDField} = ${accountID}`
|
|
778
|
-
}, currentUser);
|
|
779
|
-
if (!existingResult.Success) {
|
|
780
|
-
LogError('Error querying for existing Contacts', undefined, existingResult.ErrorMessage);
|
|
781
|
-
return null;
|
|
782
|
-
}
|
|
783
|
-
let contactEntity = null;
|
|
784
|
-
if (existingResult.Results.length > 0) {
|
|
785
|
-
// Update existing contact
|
|
786
|
-
contactEntity = await md.GetEntityObject(CEntity.EntityName, existingResult.Results[0].ID, currentUser);
|
|
787
|
-
contactEntity.Set(CEntity.EmailField, person.email);
|
|
788
|
-
}
|
|
789
|
-
else {
|
|
790
|
-
// Create new contact
|
|
791
|
-
LogStatus(` > Creating new contact record for ${person.first_name} ${person.last_name}`);
|
|
792
|
-
contactEntity = await md.GetEntityObject(CEntity.EntityName, currentUser);
|
|
793
|
-
contactEntity.NewRecord();
|
|
794
|
-
contactEntity.Set(CEntity.EmailField, person.email);
|
|
795
|
-
contactEntity.Set(CEntity.AccountIDField, accountID);
|
|
796
|
-
contactEntity.Set(CEntity.ActivityCountField, 0);
|
|
797
|
-
contactEntity.Set(CEntity.EmailSourceField, Config.EmailSourceName);
|
|
798
|
-
}
|
|
799
|
-
return contactEntity;
|
|
460
|
+
if (conflict.Results.length > 0) {
|
|
461
|
+
LogError(`*** SKIPPING new contact record for ${match.FirstName} ${match.LastName} because they are already associated with another account (${CEntity.AccountIDField}: ${String(conflict.Results[0][CEntity.AccountIDField])})`);
|
|
462
|
+
return null;
|
|
800
463
|
}
|
|
801
|
-
|
|
802
|
-
|
|
464
|
+
const byName = `([${CEntity.FirstNameField}] = '${EscapeSQLString(match.FirstName ?? '')}' AND [${CEntity.LastNameField}] = '${EscapeSQLString(match.LastName ?? '')}')`;
|
|
465
|
+
const existing = await rv.RunView({ EntityName: CEntity.EntityName, ExtraFilter: `(${email} OR ${byName}) AND ${FieldPredicate(md, CEntity.EntityName, CEntity.AccountIDField, accountID)}` }, ctx.User);
|
|
466
|
+
if (!existing.Success) {
|
|
467
|
+
LogError(`Error querying for existing Contacts: ${existing.ErrorMessage}`);
|
|
803
468
|
return null;
|
|
804
469
|
}
|
|
470
|
+
if (existing.Results.length > 0) {
|
|
471
|
+
return md.GetEntityObject(CEntity.EntityName, CompositeKey.FromEntityRecord(EntityOf(md, CEntity.EntityName), existing.Results[0]), ctx.User);
|
|
472
|
+
}
|
|
473
|
+
LogStatus(` > Creating new contact record for ${match.FirstName} ${match.LastName}`);
|
|
474
|
+
const contactEntity = await md.GetEntityObject(CEntity.EntityName, ctx.User);
|
|
475
|
+
contactEntity.NewRecord();
|
|
476
|
+
contactEntity.Set(CEntity.AccountIDField, accountID);
|
|
477
|
+
contactEntity.Set(CEntity.ActivityCountField, 0);
|
|
478
|
+
contactEntity.Set(CEntity.EmailSourceField, Config.EmailSourceName);
|
|
479
|
+
return contactEntity;
|
|
805
480
|
}
|
|
806
|
-
/**
|
|
807
|
-
|
|
808
|
-
* Processes Apollo employment history data to create education records
|
|
809
|
-
*
|
|
810
|
-
* @param params - Processing parameters with education entity configuration
|
|
811
|
-
* @param contactID - ID of the contact to create history for
|
|
812
|
-
* @param person - Person data containing employment history
|
|
813
|
-
* @param md - Metadata instance for entity operations
|
|
814
|
-
* @param currentUser - User context for data access
|
|
815
|
-
* @returns Promise<boolean> indicating success/failure
|
|
816
|
-
*/
|
|
817
|
-
async createUpdateContactEmploymentAndEducationHistory(params, contactID, person, md, currentUser) {
|
|
481
|
+
/** Writes the match's education entries to the configured education history entity. */
|
|
482
|
+
async createUpdateContactEducationHistory(ctx, params, contact, match) {
|
|
818
483
|
const CEntity = params.ContactEducationHistoryEntity;
|
|
819
|
-
if (!CEntity ||
|
|
484
|
+
if (!CEntity || match.Education.length === 0)
|
|
820
485
|
return true;
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
let bSuccess = true;
|
|
824
|
-
const rv = new RunView();
|
|
825
|
-
for (const history of person.employment_history) {
|
|
826
|
-
if (history.degree && history.degree.length > 0) {
|
|
827
|
-
const EHRunViewResult = await rv.RunView({
|
|
828
|
-
EntityName: CEntity.EntityName,
|
|
829
|
-
ExtraFilter: `${CEntity.ContactIDField} = ${contactID} AND ${CEntity.InstitutionField} = '${this.EscapeSingleQuotes(history.organization_name)}' AND ${CEntity.DegreeField} = '${this.EscapeSingleQuotes(history.degree)}'`
|
|
830
|
-
}, currentUser);
|
|
831
|
-
if (!EHRunViewResult.Success) {
|
|
832
|
-
LogError('Error querying for existing Employment History', undefined, EHRunViewResult.ErrorMessage);
|
|
833
|
-
bSuccess = false;
|
|
834
|
-
continue;
|
|
835
|
-
}
|
|
836
|
-
let historyEntity = null;
|
|
837
|
-
if (EHRunViewResult.Results.length > 0) {
|
|
838
|
-
historyEntity = await md.GetEntityObject(CEntity.EntityName, CompositeKey.FromEntityRecord(md.EntityByName(CEntity.EntityName), EHRunViewResult.Results[0]), currentUser);
|
|
839
|
-
}
|
|
840
|
-
else {
|
|
841
|
-
historyEntity = await md.GetEntityObject(CEntity.EntityName, currentUser);
|
|
842
|
-
historyEntity.NewRecord();
|
|
843
|
-
historyEntity.Set(CEntity.ContactIDField, contactID);
|
|
844
|
-
}
|
|
845
|
-
// Set history data
|
|
846
|
-
historyEntity.Set(CEntity.InstitutionField, history.organization_name);
|
|
847
|
-
historyEntity.Set(CEntity.DegreeField, history.degree);
|
|
848
|
-
historyEntity.Set(CEntity.GradeLevelField, !isNaN(history.grade_level) ? parseInt(history.grade_level) : 0);
|
|
849
|
-
if (this.IsValidDate(history.start_date)) {
|
|
850
|
-
historyEntity.Set(CEntity.StartDateField, new Date(history.start_date));
|
|
851
|
-
}
|
|
852
|
-
if (this.IsValidDate(history.end_date)) {
|
|
853
|
-
historyEntity.Set(CEntity.EndDateField, new Date(history.end_date));
|
|
854
|
-
}
|
|
855
|
-
historyEntity.Set(CEntity.IsCurrentField, history.current);
|
|
856
|
-
const saveResult = await historyEntity.Save();
|
|
857
|
-
if (!saveResult) {
|
|
858
|
-
LogError('Error saving Employment History record', undefined, historyEntity.LatestResult);
|
|
859
|
-
bSuccess = false;
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
return bSuccess;
|
|
864
|
-
}
|
|
865
|
-
catch (error) {
|
|
866
|
-
LogError('Error creating/updating contact employment and education history', undefined, error);
|
|
486
|
+
if (contact.PrimaryKeys.length !== 1) {
|
|
487
|
+
LogError(`Unable to write education history: entity '${contact.EntityInfo.Name}' has a composite primary key, which a single foreign key column cannot reference`);
|
|
867
488
|
return false;
|
|
868
489
|
}
|
|
490
|
+
const contactID = contact.FirstPrimaryKey.Value; // first-pk-ok: FK target — the education entity's contact FK column references the contact's single-column key (guarded above)
|
|
491
|
+
const md = ctx.Md;
|
|
492
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
493
|
+
let bSuccess = true;
|
|
494
|
+
for (const history of match.Education) {
|
|
495
|
+
const filter = `${FieldPredicate(md, CEntity.EntityName, CEntity.ContactIDField, contactID)} AND [${CEntity.InstitutionField}] = '${EscapeSQLString(history.InstitutionName)}' AND [${CEntity.DegreeField}] = '${EscapeSQLString(history.Degree ?? '')}'`;
|
|
496
|
+
const existing = await rv.RunView({ EntityName: CEntity.EntityName, ExtraFilter: filter }, ctx.User);
|
|
497
|
+
if (!existing.Success) {
|
|
498
|
+
LogError(`Error querying for existing Education History: ${existing.ErrorMessage}`);
|
|
499
|
+
bSuccess = false;
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const saved = await this.saveEducationRow(ctx, CEntity, contactID, history, existing.Results[0]);
|
|
503
|
+
bSuccess = bSuccess && saved;
|
|
504
|
+
}
|
|
505
|
+
return bSuccess;
|
|
869
506
|
}
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
507
|
+
async saveEducationRow(ctx, CEntity, contactID, history, existingRow) {
|
|
508
|
+
const md = ctx.Md;
|
|
509
|
+
let row;
|
|
510
|
+
if (existingRow) {
|
|
511
|
+
row = await md.GetEntityObject(CEntity.EntityName, CompositeKey.FromEntityRecord(EntityOf(md, CEntity.EntityName), existingRow), ctx.User);
|
|
512
|
+
}
|
|
513
|
+
else {
|
|
514
|
+
row = await md.GetEntityObject(CEntity.EntityName, ctx.User);
|
|
515
|
+
row.NewRecord();
|
|
516
|
+
row.Set(CEntity.ContactIDField, contactID);
|
|
517
|
+
}
|
|
518
|
+
row.Set(CEntity.InstitutionField, history.InstitutionName);
|
|
519
|
+
row.Set(CEntity.DegreeField, history.Degree);
|
|
520
|
+
const grade = history.GradeLevel !== null && !Number.isNaN(Number(history.GradeLevel)) ? Number.parseInt(history.GradeLevel, 10) : 0;
|
|
521
|
+
this.setFieldIfExists(row, CEntity.GradeLevelField, grade);
|
|
522
|
+
if (this.IsValidDate(history.StartDate ?? ''))
|
|
523
|
+
this.setFieldIfExists(row, CEntity.StartDateField, new Date(history.StartDate));
|
|
524
|
+
if (this.IsValidDate(history.EndDate ?? ''))
|
|
525
|
+
this.setFieldIfExists(row, CEntity.EndDateField, new Date(history.EndDate));
|
|
526
|
+
this.setFieldIfExists(row, CEntity.IsCurrentField, history.EndDate === null);
|
|
527
|
+
const saved = await row.Save();
|
|
528
|
+
if (!saved)
|
|
529
|
+
LogError(`Error saving Education History record: ${row.LatestResult?.CompleteMessage ?? 'no details'}`);
|
|
530
|
+
return saved;
|
|
531
|
+
}
|
|
532
|
+
// ─── Small helpers ───────────────────────────────────────────────────────
|
|
533
|
+
/** True when the string parses as a date. */
|
|
877
534
|
IsValidDate(dateString) {
|
|
878
535
|
if (dateString && dateString.length > 0) {
|
|
879
536
|
const date = new Date(dateString);
|
|
880
|
-
return
|
|
537
|
+
return !Number.isNaN(date.getTime());
|
|
881
538
|
}
|
|
882
539
|
return false;
|
|
883
540
|
}
|
|
884
|
-
/**
|
|
885
|
-
* Checks if a job title should be excluded from contact creation
|
|
886
|
-
* Filters out non-business contacts like students and volunteers
|
|
887
|
-
*
|
|
888
|
-
* @param title - Job title to check
|
|
889
|
-
* @returns boolean - true if title should be excluded
|
|
890
|
-
*/
|
|
541
|
+
/** True for titles that are not decision-makers (members, students, volunteers). */
|
|
891
542
|
IsExcludedTitle(title) {
|
|
892
|
-
if (!title)
|
|
543
|
+
if (!title)
|
|
893
544
|
return false;
|
|
894
|
-
|
|
895
|
-
return this.excludeTitles.includes(title.toLowerCase());
|
|
896
|
-
}
|
|
897
|
-
/**
|
|
898
|
-
* Escapes single quotes in strings for SQL query safety
|
|
899
|
-
* Prevents SQL injection in dynamic filter construction
|
|
900
|
-
*
|
|
901
|
-
* @param str - String to escape
|
|
902
|
-
* @returns string - Escaped string with doubled single quotes
|
|
903
|
-
*/
|
|
904
|
-
EscapeSingleQuotes(str) {
|
|
905
|
-
if (str) {
|
|
906
|
-
return str.replace(/'/g, "''");
|
|
907
|
-
}
|
|
908
|
-
return '';
|
|
909
|
-
}
|
|
910
|
-
/**
|
|
911
|
-
* Wraps Apollo.io API calls with retry logic for rate limiting
|
|
912
|
-
* Handles 429 (Too Many Requests) responses with exponential backoff
|
|
913
|
-
*
|
|
914
|
-
* @param method - HTTP method ('get' or 'post')
|
|
915
|
-
* @param endpoint - Apollo API endpoint path
|
|
916
|
-
* @param data - Request payload for POST requests
|
|
917
|
-
* @param config - request configuration (headers / query params)
|
|
918
|
-
* @param retryAttempts - Number of retry attempts remaining (default: 1)
|
|
919
|
-
* @returns Promise<HttpResponse> - Apollo API response
|
|
920
|
-
* @throws Error if rate limit exceeded or other API errors
|
|
921
|
-
*/
|
|
922
|
-
async WrapApolloCall(method, endpoint, data, config, retryAttempts = 1) {
|
|
923
|
-
try {
|
|
924
|
-
const url = `${Config.ApolloAPIEndpoint}/${endpoint}`;
|
|
925
|
-
// ThrowOnError stays on by default, so a 429 surfaces in the catch below;
|
|
926
|
-
// the explicit status check here mirrors the original belt-and-braces handling.
|
|
927
|
-
const response = method === 'get' ? await HttpGet(url, config) : await HttpPost(url, data, config);
|
|
928
|
-
if (response.Status === 429) {
|
|
929
|
-
if (retryAttempts > 0) {
|
|
930
|
-
LogStatus(' >>> Too many requests to Apollo.io API, waiting 1 minute and trying again...');
|
|
931
|
-
await this.timeout(60000); // wait 1 minute
|
|
932
|
-
return await this.WrapApolloCall(method, endpoint, data, config, retryAttempts - 1);
|
|
933
|
-
}
|
|
934
|
-
else {
|
|
935
|
-
throw { message: 'Too many requests to Apollo.io API', code: 429 };
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
return response;
|
|
939
|
-
}
|
|
940
|
-
catch (apolloError) {
|
|
941
|
-
// A 429 arrives as a thrown HttpError rather than a returned response, so handle it here too
|
|
942
|
-
if (IsHttpError(apolloError) && apolloError.Status === 429) {
|
|
943
|
-
if (retryAttempts > 0) {
|
|
944
|
-
LogStatus(' >>> Too many requests to Apollo.io API, waiting 1 minute and trying again...');
|
|
945
|
-
await this.timeout(60000); // wait 1 minute
|
|
946
|
-
return await this.WrapApolloCall(method, endpoint, data, config, retryAttempts - 1);
|
|
947
|
-
}
|
|
948
|
-
else {
|
|
949
|
-
throw { message: 'Too many requests to Apollo.io API', code: 429 };
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
else {
|
|
953
|
-
throw apolloError;
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
/**
|
|
958
|
-
* Utility method for creating delays in async operations
|
|
959
|
-
* Used for rate limit backoff and API throttling
|
|
960
|
-
*
|
|
961
|
-
* @param ms - Number of milliseconds to wait
|
|
962
|
-
* @returns Promise that resolves after the specified delay
|
|
963
|
-
*/
|
|
964
|
-
async timeout(ms) {
|
|
965
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
545
|
+
return this.excludeTitles.includes(title.trim().toLowerCase());
|
|
966
546
|
}
|
|
967
547
|
};
|
|
968
548
|
ApolloEnrichmentAccountsAction = __decorate([
|
|
969
|
-
RegisterClass(BaseAction,
|
|
549
|
+
RegisterClass(BaseAction, 'ApolloEnrichmentAccountsAction')
|
|
970
550
|
], ApolloEnrichmentAccountsAction);
|
|
971
551
|
export { ApolloEnrichmentAccountsAction };
|
|
552
|
+
// ─── Module helpers ──────────────────────────────────────────────────────────
|
|
553
|
+
function Failure(code, message) {
|
|
554
|
+
return { Success: false, Message: message, ResultCode: code };
|
|
555
|
+
}
|
|
556
|
+
function MessageOf(error) {
|
|
557
|
+
return error instanceof Error ? error.message : String(error);
|
|
558
|
+
}
|
|
559
|
+
function StringOf(value) {
|
|
560
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
|
|
561
|
+
}
|
|
562
|
+
function SameText(a, b) {
|
|
563
|
+
return typeof a === 'string' && a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
564
|
+
}
|
|
565
|
+
function EntityOf(md, entityName) {
|
|
566
|
+
const info = md.EntityByName(entityName);
|
|
567
|
+
if (!info)
|
|
568
|
+
throw new Error(`Entity '${entityName}' was not found`);
|
|
569
|
+
return info;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* `[field] <op> <literal>` with the literal quoted per the column's type, so a UUID or string key
|
|
573
|
+
* is quoted and an integer key is not. An unknown column is treated as needing quotes.
|
|
574
|
+
*/
|
|
575
|
+
export function FieldPredicate(md, entityName, fieldName, value, op = '=') {
|
|
576
|
+
const field = md.EntityByName(entityName)?.Fields.find((f) => f.Name.toLowerCase() === fieldName.toLowerCase());
|
|
577
|
+
const needsQuotes = field ? field.NeedsQuotes : typeof value !== 'number';
|
|
578
|
+
const literal = needsQuotes ? `'${EscapeSQLString(String(value))}'` : String(value);
|
|
579
|
+
return `[${fieldName}] ${op} ${literal}`;
|
|
580
|
+
}
|
|
972
581
|
//# sourceMappingURL=accounts.js.map
|