@memberjunction/actions-apollo 6.2.0-edge.3 → 6.2.0-edge.5

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.
Files changed (44) hide show
  1. package/README.md +88 -53
  2. package/dist/__tests__/apollo-enrichment.test.js +339 -233
  3. package/dist/__tests__/apollo-enrichment.test.js.map +1 -1
  4. package/dist/__tests__/apollo-lists.test.js +29 -1
  5. package/dist/__tests__/apollo-lists.test.js.map +1 -1
  6. package/dist/__tests__/apollo-people-client.test.d.ts +2 -0
  7. package/dist/__tests__/apollo-people-client.test.d.ts.map +1 -0
  8. package/dist/__tests__/apollo-people-client.test.js +153 -0
  9. package/dist/__tests__/apollo-people-client.test.js.map +1 -0
  10. package/dist/accounts.d.ts +80 -291
  11. package/dist/accounts.d.ts.map +1 -1
  12. package/dist/accounts.js +391 -782
  13. package/dist/accounts.js.map +1 -1
  14. package/dist/contacts.d.ts +140 -207
  15. package/dist/contacts.d.ts.map +1 -1
  16. package/dist/contacts.js +372 -724
  17. package/dist/contacts.js.map +1 -1
  18. package/dist/generic/apollo-lists.types.d.ts +18 -3
  19. package/dist/generic/apollo-lists.types.d.ts.map +1 -1
  20. package/dist/http/ApolloHttp.d.ts +42 -0
  21. package/dist/http/ApolloHttp.d.ts.map +1 -0
  22. package/dist/http/ApolloHttp.js +117 -0
  23. package/dist/http/ApolloHttp.js.map +1 -0
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/lists/ApolloRESTClient.d.ts +2 -0
  29. package/dist/lists/ApolloRESTClient.d.ts.map +1 -1
  30. package/dist/lists/ApolloRESTClient.js +33 -52
  31. package/dist/lists/ApolloRESTClient.js.map +1 -1
  32. package/dist/lists/ApolloSearchActions.d.ts +6 -1
  33. package/dist/lists/ApolloSearchActions.d.ts.map +1 -1
  34. package/dist/lists/ApolloSearchActions.js +19 -4
  35. package/dist/lists/ApolloSearchActions.js.map +1 -1
  36. package/dist/people/ApolloPeopleClient.d.ts +114 -0
  37. package/dist/people/ApolloPeopleClient.d.ts.map +1 -0
  38. package/dist/people/ApolloPeopleClient.js +168 -0
  39. package/dist/people/ApolloPeopleClient.js.map +1 -0
  40. package/dist/people/apollo-people.types.d.ts +55 -0
  41. package/dist/people/apollo-people.types.d.ts.map +1 -0
  42. package/dist/people/apollo-people.types.js +8 -0
  43. package/dist/people/apollo-people.types.js.map +1 -0
  44. package/package.json +8 -8
package/dist/contacts.js CHANGED
@@ -4,815 +4,463 @@ 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 "@memberjunction/actions";
8
- import { RegisterClass } from "@memberjunction/global";
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 { LogError, LogStatus, Metadata, RunView, CompositeKey } from "@memberjunction/core";
11
- import { HttpGet, HttpPost, IsHttpError } from '@memberjunction/network-utils';
11
+ import { ApolloAuthError, ApolloRateLimitError } from './http/ApolloHttp.js';
12
+ import { ApolloPeopleClient } from './people/ApolloPeopleClient.js';
13
+ const PAGE_SIZE = 500;
12
14
  /**
13
- * Action that enriches contact records using Apollo.io's people matching and search APIs
15
+ * Apollo.io Contact Enrichment Action
14
16
  *
15
- * This action performs contact enrichment by:
16
- * 1. Bulk matching existing contacts against Apollo's database
17
- * 2. Updating contact records with enriched social profiles and company data
18
- * 3. Creating employment and education history records
19
- * 4. Processing contacts in configurable batch sizes for optimal performance
17
+ * Enriches contact records with data from Apollo.io, including verified email addresses,
18
+ * employment history, education details and social profiles. Records are read in pages
19
+ * (keyset paging on a single-column key, see {@link processAllContactRecords}) and sent to
20
+ * `people/bulk_match` ten at a time through {@link ApolloPeopleClient}.
20
21
  *
21
- * @example
22
- * ```typescript
23
- * // Basic contact enrichment
24
- * await runAction({
25
- * ActionName: 'ApolloEnrichmentContactsAction',
26
- * Params: [{
27
- * Name: 'EntityName',
28
- * Value: 'Contacts'
29
- * }, {
30
- * Name: 'EmailField',
31
- * Value: 'Email'
32
- * }, {
33
- * Name: 'FirstNameField',
34
- * Value: 'FirstName'
35
- * }, {
36
- * Name: 'LastNameField',
37
- * Value: 'LastName'
38
- * }, {
39
- * Name: 'TitleField',
40
- * Value: 'Title'
41
- * }, {
42
- * Name: 'EnrichedAtField',
43
- * Value: 'EnrichedAt'
44
- * }, {
45
- * Name: 'Filter',
46
- * Value: 'Email IS NOT NULL AND EnrichedAt IS NULL'
47
- * }]
48
- * });
22
+ * Every record sent to Apollo is stamped with `EnrichedAtField`, matched or not, so a filter
23
+ * on that stamp never re-selects (and never pays for) the same miss twice.
49
24
  *
50
- * // Full enrichment with history tracking
51
- * await runAction({
52
- * ActionName: 'ApolloEnrichmentContactsAction',
53
- * Params: [
54
- * // ... basic params ...
55
- * {
56
- * Name: 'EmploymentHistoryFieldMappings',
57
- * Value: JSON.stringify({
58
- * EmploymentHistoryEntityName: 'Contact Employment Histories',
59
- * EmploymentHistoryContactIDFieldName: 'ContactID',
60
- * EmploymentHistoryOrganizationFieldName: 'Organization',
61
- * EmploymentHistoryTitleFieldName: 'Title'
62
- * })
63
- * }
64
- * ]
65
- * });
66
- * ```
25
+ * Params: EntityName, EmailField, FirstNameField, LastNameField, TitleField, EnrichedAtField,
26
+ * Filter (required); ProfilePictureURLField, AccountNameField, DomainField, LinkedInField,
27
+ * TwitterField, FacebookField, CompanyID, EmploymentHistoryFieldMappings,
28
+ * EducationHistoryFieldMappings (optional). The mapping params take the keys of
29
+ * {@link EmploymentHistoryMapping} and {@link EducationHistoryMapping}, as an object or a JSON string.
30
+ *
31
+ * Result codes: SUCCESS, VALIDATION_ERROR, CONFIGURATION_ERROR, RATE_LIMIT_EXCEEDED, FAILED.
67
32
  */
68
33
  let ApolloEnrichmentContactsAction = class ApolloEnrichmentContactsAction extends BaseAction {
69
- constructor() {
70
- super(...arguments);
71
- /**
72
- * Job titles to exclude when processing contacts
73
- * These are typically not business decision-makers
74
- */
75
- this.excludeTitles = ['member', 'student member', 'student', 'volunteer'];
76
- }
77
- /**
78
- * Main entry point for the Apollo contact enrichment action
79
- *
80
- * @param params - The action parameters containing:
81
- * - EntityName: Required - Name of the contact entity to enrich
82
- * - EmailField: Required - Field name containing email addresses
83
- * - FirstNameField: Required - Field name containing first names
84
- * - LastNameField: Required - Field name containing last names
85
- * - TitleField: Required - Field name containing job titles
86
- * - EnrichedAtField: Required - Field to track enrichment timestamp
87
- * - Filter: Required - SQL filter to select contacts for enrichment
88
- * - ProfilePictureURLField: Optional - Field for profile picture URLs
89
- * - AccountNameField: Optional - Field for company/account names
90
- * - DomainField: Optional - Field for email domains
91
- * - LinkedInField: Optional - Field for LinkedIn profile URLs
92
- * - TwitterField: Optional - Field for Twitter profile URLs
93
- * - FacebookField: Optional - Field for Facebook profile URLs
94
- * - EmploymentHistoryFieldMappings: Optional - JSON mapping for employment history entity
95
- * - EducationHistoryFieldMappings: Optional - JSON mapping for education history entity
96
- *
97
- * @returns Promise<ActionResultSimple> indicating success/failure and any error messages
98
- */
99
34
  async InternalRunAction(params) {
35
+ const parsed = this.extractAndValidateParameters(params);
36
+ if (parsed.success === false)
37
+ return parsed.error;
38
+ const { actionParams, historyMappings } = parsed.data;
39
+ const md = params.Provider ?? Metadata.Provider;
40
+ const entity = md.EntityByName(actionParams.EntityName);
41
+ if (!entity)
42
+ return Failure('VALIDATION_ERROR', `Entity '${actionParams.EntityName}' was not found`);
43
+ let client;
100
44
  try {
101
- // Validate API configuration
102
- const configValidation = this.validateConfiguration();
103
- if (!configValidation.success) {
104
- return configValidation.error;
105
- }
106
- // Extract and validate parameters
107
- const paramValidation = this.extractAndValidateParameters(params);
108
- if (!paramValidation.success) {
109
- return paramValidation.error;
110
- }
111
- const { actionParams, historyMappings } = paramValidation.data;
112
- // Process all contact records
113
- return await this.processAllContactRecords(actionParams, historyMappings, params.ContextUser, params.Provider);
45
+ const resolved = await this.CreateClient(actionParams.CompanyID, params.ContextUser);
46
+ if (!resolved)
47
+ return Failure('CONFIGURATION_ERROR', 'Apollo.io API key not found in configuration');
48
+ client = resolved;
49
+ }
50
+ catch (error) {
51
+ return Failure('CONFIGURATION_ERROR', MessageOf(error));
52
+ }
53
+ const ctx = { Client: client, Md: md, Entity: entity, User: params.ContextUser, Params: actionParams, History: historyMappings, StartedAt: new Date() };
54
+ const tally = { Sent: 0, Matched: 0, Unmatched: 0, Unidentifiable: 0, SaveFailures: 0, GroupFailures: 0, CreditsConsumed: 0 };
55
+ try {
56
+ await this.processAllContactRecords(ctx, tally);
114
57
  }
115
58
  catch (error) {
116
- LogError('Unexpected error in ApolloContactsEnrichmentAction', undefined, error);
117
- return {
118
- Success: false,
119
- Message: `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`,
120
- ResultCode: "FAILED"
121
- };
59
+ return this.failureFor(error, tally);
122
60
  }
61
+ const summary = Summarize(tally);
62
+ if (tally.GroupFailures > 0 || tally.SaveFailures > 0)
63
+ return Failure('FAILED', `ApolloContactsEnrichment finished with errors. ${summary}`);
64
+ return { Success: true, Message: `ApolloContactsEnrichment executed successfully. ${summary}`, ResultCode: 'SUCCESS' };
123
65
  }
124
66
  /**
125
- * Validates that the Apollo.io API key is configured properly
126
- * @returns Validation result with success flag and potential error details
67
+ * Resolve the key (company credential first, then `APOLLO_API_KEY`) and build the client.
68
+ * A protected seam so tests can substitute a client that never reaches api.apollo.io.
127
69
  */
128
- validateConfiguration() {
129
- if (!Config.ApolloAPIKey) {
130
- return {
131
- success: false,
132
- error: {
133
- Success: false,
134
- Message: 'Apollo.io API key not found in configuration',
135
- ResultCode: "CONFIGURATION_ERROR"
136
- }
137
- };
70
+ async CreateClient(companyID, contextUser) {
71
+ const resolved = await ApolloPeopleClient.ForCompany(companyID, contextUser);
72
+ return resolved ? resolved.Client : null;
73
+ }
74
+ failureFor(error, tally) {
75
+ const summary = Summarize(tally);
76
+ if (error instanceof ApolloRateLimitError) {
77
+ LogStatus(`ApolloContactsEnrichment stopped at Apollo's ${error.Window} rate limit. ${summary}`);
78
+ return Failure('RATE_LIMIT_EXCEEDED', `Apollo.io rate limit (${error.Window}) reached; run again later. ${summary}`);
138
79
  }
139
- return { success: true };
80
+ if (error instanceof ApolloAuthError)
81
+ return Failure('CONFIGURATION_ERROR', `${error.message} ${summary}`);
82
+ LogError('Unexpected error in ApolloContactsEnrichment', undefined, error);
83
+ return Failure('FAILED', `Unexpected error: ${MessageOf(error)}. ${summary}`);
140
84
  }
141
85
  /**
142
86
  * Extracts and validates all action parameters from the request
143
87
  * Processes both required and optional parameters for contact enrichment
144
- *
145
- * @param params - The action parameters containing entity and field configurations
146
- * @returns Object with success flag, validated parameters, or error details
147
88
  */
148
89
  extractAndValidateParameters(params) {
149
- // Extract required parameters
150
- const entityName = this.getParamValue(params, 'EntityName');
151
- const emailField = this.getParamValue(params, 'EmailField');
152
- const firstNameField = this.getParamValue(params, 'FirstNameField');
153
- const lastNameField = this.getParamValue(params, 'LastNameField');
154
- const titleField = this.getParamValue(params, 'TitleField');
155
- const enrichedAtField = this.getParamValue(params, 'EnrichedAtField');
156
- const filter = this.getParamValue(params, 'Filter');
157
- // Check for any missing required parameters
158
- const missingParams = [];
159
- if (!entityName)
160
- missingParams.push('EntityName');
161
- if (!emailField)
162
- missingParams.push('EmailField');
163
- if (!firstNameField)
164
- missingParams.push('FirstNameField');
165
- if (!lastNameField)
166
- missingParams.push('LastNameField');
167
- if (!titleField)
168
- missingParams.push('TitleField');
169
- if (!enrichedAtField)
170
- missingParams.push('EnrichedAtField');
171
- if (!filter)
172
- missingParams.push('Filter');
173
- if (missingParams.length > 0) {
174
- return {
175
- success: false,
176
- error: {
177
- Success: false,
178
- Message: `Missing required parameters: ${missingParams.join(', ')}`,
179
- ResultCode: "VALIDATION_ERROR"
180
- }
181
- };
90
+ const required = ['EntityName', 'EmailField', 'FirstNameField', 'LastNameField', 'TitleField', 'EnrichedAtField', 'Filter'];
91
+ const values = new Map(required.map((name) => [name, StringOrNull(this.getParamValue(params, name))]));
92
+ const missing = required.filter((name) => !values.get(name));
93
+ if (missing.length > 0) {
94
+ return { success: false, error: Failure('VALIDATION_ERROR', `Missing required parameters: ${missing.join(', ')}`) };
182
95
  }
183
- // Extract optional parameters
184
- const profilePictureURLField = this.getParamValue(params, 'ProfilePictureURLField');
185
- const accountNameField = this.getParamValue(params, 'AccountNameField');
186
- const domainField = this.getParamValue(params, 'DomainField');
187
- const linkedInField = this.getParamValue(params, 'LinkedInField');
188
- const twitterField = this.getParamValue(params, 'TwitterField');
189
- const facebookField = this.getParamValue(params, 'FacebookField');
190
- // Extract history mappings
191
- const educationHistoryMappings = this.parseHistoryMappings(params, 'EducationHistoryFieldMappings');
192
- const employmentHistoryMappings = this.parseHistoryMappings(params, 'EmploymentHistoryFieldMappings');
96
+ const optional = (name) => StringOrNull(this.getParamValue(params, name)) ?? undefined;
193
97
  const actionParams = {
194
- EntityName: entityName,
195
- EmailField: emailField,
196
- FirstNameField: firstNameField,
197
- LastNameField: lastNameField,
198
- TitleField: titleField,
199
- EnrichedAtField: enrichedAtField,
200
- Filter: filter,
201
- ProfilePictureURLField: profilePictureURLField,
202
- AccountNameField: accountNameField,
203
- DomainField: domainField,
204
- LinkedInField: linkedInField,
205
- TwitterField: twitterField,
206
- FacebookField: facebookField
98
+ EntityName: values.get('EntityName'),
99
+ EmailField: values.get('EmailField'),
100
+ FirstNameField: values.get('FirstNameField'),
101
+ LastNameField: values.get('LastNameField'),
102
+ TitleField: values.get('TitleField'),
103
+ EnrichedAtField: values.get('EnrichedAtField'),
104
+ Filter: values.get('Filter'),
105
+ ProfilePictureURLField: optional('ProfilePictureURLField'),
106
+ AccountNameField: optional('AccountNameField'),
107
+ DomainField: optional('DomainField'),
108
+ LinkedInField: optional('LinkedInField'),
109
+ TwitterField: optional('TwitterField'),
110
+ FacebookField: optional('FacebookField'),
111
+ CompanyID: optional('CompanyID') ?? null,
207
112
  };
208
113
  const historyMappings = {
209
- education: educationHistoryMappings,
210
- employment: employmentHistoryMappings
114
+ employment: ParseEmploymentMapping(this.parseHistoryMappings(params, 'EmploymentHistoryFieldMappings')),
115
+ education: ParseEducationMapping(this.parseHistoryMappings(params, 'EducationHistoryFieldMappings')),
211
116
  };
212
117
  return { success: true, data: { actionParams, historyMappings } };
213
118
  }
214
119
  /**
215
120
  * Extract parameter value by name (case-insensitive)
216
121
  * Handles special case where 'null' string should be treated as null value
217
- *
218
- * @param params - The action parameters
219
- * @param paramName - Name of the parameter to extract
220
- * @returns Parameter value or null if not found or explicitly 'null'
221
122
  */
222
123
  getParamValue(params, paramName) {
223
- const param = params.Params.find(p => p.Name.trim().toLowerCase() === paramName.toLowerCase());
224
- if (param && param.Value && param.Value === 'null') {
124
+ const param = params.Params.find((p) => p.Name.trim().toLowerCase() === paramName.toLowerCase());
125
+ if (param && param.Value === 'null')
225
126
  return null;
226
- }
227
- else {
228
- return param?.Value;
229
- }
127
+ return param?.Value;
230
128
  }
231
129
  /**
232
130
  * Parses JSON field mappings for employment/education history entities
233
- * Used to configure how history records should be created and updated
234
- *
235
- * @param params - The action parameters
236
- * @param paramName - Name of the history mapping parameter
237
- * @returns Parsed field mappings or empty object if invalid/missing
131
+ * Accepts an object or a JSON string; the param name is matched case-insensitively.
238
132
  */
239
133
  parseHistoryMappings(params, paramName) {
240
- const param = params.Params.find(p => p.Name === paramName);
241
- if (!param || !param.Value) {
242
- return {};
243
- }
244
- // If it's already an object, use it directly
245
- if (typeof param.Value === 'object' && param.Value !== null) {
246
- return param.Value;
247
- }
248
- // If it's a string, try to parse it as JSON
249
- if (typeof param.Value === 'string') {
134
+ const value = this.getParamValue(params, paramName);
135
+ if (typeof value === 'object' && value !== null)
136
+ return value;
137
+ if (typeof value === 'string' && value.trim().length > 0) {
250
138
  try {
251
- return JSON.parse(param.Value) || {};
139
+ const parsed = JSON.parse(value);
140
+ return typeof parsed === 'object' && parsed !== null ? parsed : {};
252
141
  }
253
142
  catch (error) {
254
143
  LogError(`Error parsing ${paramName}`, undefined, error);
255
- return {};
256
144
  }
257
145
  }
258
146
  return {};
259
147
  }
148
+ // ─── Paging ──────────────────────────────────────────────────────────────
260
149
  /**
261
- * Processes all contact records using paginated queries
262
- * Continues processing until all matching records have been enriched
150
+ * Reads every record the filter selects and processes it exactly once.
263
151
  *
264
- * @param actionParams - Configuration parameters for contact enrichment
265
- * @param historyMappings - Field mappings for employment/education history
266
- * @param contextUser - User context for data access and security
267
- * @returns Promise indicating overall success/failure of the enrichment
152
+ * A single-column key pages by keyset (`AfterKey`): each page starts after the last key of the
153
+ * previous one, so stamping rows out of the filter as we go cannot skip anything. A composite
154
+ * key cannot use `AfterKey`, so it re-reads the first page with an extra predicate that excludes
155
+ * rows this run already stamped; rows that failed to save are remembered and skipped so a save
156
+ * failure cannot loop.
268
157
  */
269
- async processAllContactRecords(actionParams, historyMappings, contextUser, provider) {
270
- let pageNumber = 0;
271
- let hasMore = true;
272
- const md = provider ?? new Metadata();
273
- while (hasMore) {
274
- LogStatus(`Fetching page ${pageNumber + 1} of records...`);
275
- const pageResult = await this.processContactRecordsPage(actionParams, historyMappings, pageNumber, md, contextUser);
276
- if (!pageResult.success) {
277
- return pageResult.error;
278
- }
279
- hasMore = pageResult.hasMore;
280
- pageNumber++;
158
+ async processAllContactRecords(ctx, tally) {
159
+ const keyset = ctx.Entity.PrimaryKeys.length === 1;
160
+ const seen = new Set();
161
+ let afterKey = null;
162
+ for (;;) {
163
+ const rows = await this.readPage(ctx, keyset, afterKey);
164
+ const fresh = rows.filter((row) => !seen.has(RowKey(ctx.Entity, row)));
165
+ if (fresh.length === 0)
166
+ break;
167
+ fresh.forEach((row) => seen.add(RowKey(ctx.Entity, row)));
168
+ LogStatus(`Fetched ${fresh.length} records to enrich`);
169
+ await this.processRecordGroups(ctx, fresh, tally);
170
+ if (rows.length < PAGE_SIZE)
171
+ break;
172
+ if (keyset)
173
+ afterKey = CompositeKey.FromEntityRecord(ctx.Entity, rows[rows.length - 1]);
281
174
  }
282
- return {
283
- Success: true,
284
- Message: "ApolloContactsEnrichment executed successfully.",
285
- ResultCode: "SUCCESS"
286
- };
287
175
  }
288
- /**
289
- * Processes a single page of contact records for enrichment
290
- * Retrieves records using pagination and processes them in concurrent groups
291
- *
292
- * @param actionParams - Configuration parameters for contact enrichment
293
- * @param historyMappings - Field mappings for employment/education history
294
- * @param pageNumber - Current page number (zero-based)
295
- * @param md - Metadata instance for entity operations
296
- * @param contextUser - User context for data access
297
- * @returns Object indicating success, whether more pages exist, and any errors
298
- */
299
- async processContactRecordsPage(actionParams, historyMappings, pageNumber, md, contextUser) {
300
- const pageConfig = {
301
- EntityName: actionParams.EntityName,
302
- PageNumber: pageNumber,
303
- PageSize: 500,
304
- Filter: actionParams.Filter
305
- };
306
- const results = await this.PageRecordsByEntityName(pageConfig, contextUser);
307
- if (!results) {
308
- return {
309
- success: false,
310
- hasMore: false,
311
- error: {
312
- Success: false,
313
- Message: "Error querying entity records",
314
- ResultCode: "FAILED"
315
- }
316
- };
317
- }
318
- LogStatus(`Fetched ${results.length} records with max page size of ${pageConfig.PageSize}`);
319
- // Process records in concurrent groups
320
- await this.processRecordGroups(results, actionParams, historyMappings, md, contextUser);
321
- const hasMore = results.length >= pageConfig.PageSize;
322
- return { success: true, hasMore };
176
+ async readPage(ctx, keyset, afterKey) {
177
+ const rv = RunView.FromMetadataProvider(ctx.Md);
178
+ const orderBy = ctx.Entity.PrimaryKeys.map((pk) => `[${pk.Name}]`).join(', ');
179
+ const stamp = ctx.Params.EnrichedAtField;
180
+ const filter = keyset
181
+ ? `(${ctx.Params.Filter})`
182
+ : `(${ctx.Params.Filter}) AND ([${stamp}] IS NULL OR [${stamp}] < '${ctx.StartedAt.toISOString()}')`;
183
+ const result = await rv.RunView({
184
+ EntityName: ctx.Params.EntityName,
185
+ ExtraFilter: filter,
186
+ OrderBy: orderBy,
187
+ MaxRows: PAGE_SIZE,
188
+ IgnoreMaxRows: true,
189
+ ...(keyset && afterKey ? { AfterKey: afterKey } : {}),
190
+ }, ctx.User);
191
+ if (!result.Success)
192
+ throw new Error(`Error querying entity '${ctx.Params.EntityName}': ${result.ErrorMessage}`);
193
+ return result.Results;
323
194
  }
324
- /**
325
- * Processes contact records in concurrent groups for optimal performance
326
- * Respects configured group size and concurrency limits
327
- *
328
- * @param results - Array of contact records to process
329
- * @param actionParams - Configuration parameters for enrichment
330
- * @param historyMappings - Field mappings for history entities
331
- * @param md - Metadata instance for entity operations
332
- * @param contextUser - User context for data access
333
- */
334
- async processRecordGroups(results, actionParams, historyMappings, md, contextUser) {
335
- const tasks = [];
336
- for (let i = 0; i < results.length; i += Config.GroupSize) {
337
- const processParams = {
338
- Records: results,
339
- Startrow: i,
340
- GroupLength: Config.GroupSize,
341
- Md: md,
342
- CurrentUser: contextUser,
343
- EmailField: actionParams.EmailField,
344
- FirstNameField: actionParams.FirstNameField,
345
- LastNameField: actionParams.LastNameField,
346
- TitleField: actionParams.TitleField,
347
- EntityName: actionParams.EntityName,
348
- EnrichedAtField: actionParams.EnrichedAtField,
349
- ProfilePictureURLField: actionParams.ProfilePictureURLField,
350
- AccountNameField: actionParams.AccountNameField,
351
- DomainField: actionParams.DomainField,
352
- LinkedInField: actionParams.LinkedInField,
353
- TwitterField: actionParams.TwitterField,
354
- FacebookField: actionParams.FacebookField,
355
- EmploymentHistoryEntityName: historyMappings.employment.EntityName,
356
- EmploymentHistoryContactIDFieldName: historyMappings.employment.ContactIDFieldName,
357
- EmploymentHistoryOrganizationFieldName: historyMappings.employment.OrganizationFieldName,
358
- EmploymentHistoryTitleFieldName: historyMappings.employment.TitleFieldName,
359
- EducationHistoryEntityName: historyMappings.education.EntityName,
360
- EducationHistoryContactIDFieldName: historyMappings.education.ContactIDFieldName,
361
- EducationHistoryInstitutionFieldName: historyMappings.education.InstitutionFieldName,
362
- EducationHistoryDegreeFieldName: historyMappings.education.DegreeFieldName
363
- };
364
- const task = this.ProcessPersonRecordGroup(processParams);
365
- tasks.push(task);
366
- if (tasks.length === Config.ConcurrentGroups || i + Config.GroupSize >= results.length) {
367
- await Promise.all(tasks);
368
- tasks.length = 0;
369
- }
195
+ /** Sends the rows to Apollo in groups of {@link ApolloPeopleClient.MaxBatchSize}, one group at a time. */
196
+ async processRecordGroups(ctx, rows, tally) {
197
+ const size = Math.min(Config.GroupSize, ApolloPeopleClient.MaxBatchSize);
198
+ for (let i = 0; i < rows.length; i += size) {
199
+ await this.ProcessPersonRecordGroup(ctx, rows.slice(i, i + size), tally);
370
200
  }
371
201
  }
202
+ // ─── One group ───────────────────────────────────────────────────────────
372
203
  /**
373
- * Retrieves a page of records from a specified entity using RunView
374
- * Supports pagination with configurable page size and filtering
375
- *
376
- * @param params - Parameters defining entity, page, and filter criteria
377
- * @param currentUser - User context for data access
378
- * @returns Array of records or null if query failed
204
+ * Matches one group through `people/bulk_match` and writes every row of it. A row nothing
205
+ * identifies is stamped and skipped before the call. A rate-limit or auth error stops the run
206
+ * (it is rethrown); any other Apollo error fails this group only.
379
207
  */
380
- async PageRecordsByEntityName(params, currentUser) {
381
- const rv = new RunView();
382
- const rvResult = await rv.RunView({
383
- EntityName: params.EntityName,
384
- MaxRows: params.PageSize,
385
- StartRow: Math.max(0, (params.PageNumber - 1) * params.PageSize),
386
- ExtraFilter: params.Filter
387
- }, currentUser);
388
- if (!rvResult.Success) {
389
- LogError('Error querying entity: ', undefined, rvResult.ErrorMessage);
390
- return null;
208
+ async ProcessPersonRecordGroup(ctx, rows, tally) {
209
+ const inputs = [];
210
+ const sendable = [];
211
+ for (const [index, row] of rows.entries()) {
212
+ const input = BuildMatchInput(ctx.Params, row, String(index));
213
+ if (input) {
214
+ inputs.push(input);
215
+ sendable.push(row);
216
+ }
217
+ else {
218
+ tally.Unidentifiable++;
219
+ await this.writeContact(ctx, row, null, tally);
220
+ }
391
221
  }
392
- return rvResult.Results;
393
- }
394
- /**
395
- * Processes a group of contact records using Apollo's bulk people matching API
396
- * Enriches contacts with social profiles, company data, and employment history
397
- *
398
- * @param params - Group processing parameters with contact data and entity mappings
399
- * @returns Promise<boolean> indicating success/failure of the group processing
400
- */
401
- async ProcessPersonRecordGroup(params) {
222
+ if (inputs.length === 0)
223
+ return;
224
+ let matches;
402
225
  try {
403
- const md = params.Md;
404
- const ApolloParams = {
405
- api_key: Config.ApolloAPIKey,
406
- reveal_personal_emails: true,
407
- details: params.Records.slice(params.Startrow, params.Startrow + params.GroupLength).map((record) => {
408
- const first_name = record[params.FirstNameField];
409
- const last_name = record[params.LastNameField];
410
- const email = record[params.EmailField];
411
- let domain = params.DomainField ? record[params.DomainField] : undefined;
412
- const detail = { first_name, last_name, email, domain };
413
- return detail;
414
- })
415
- };
416
- const headers = {
417
- 'Cache-Control': 'no-cache',
418
- 'Content-Type': 'application/json'
419
- };
420
- const response = await this.WrapApolloCall('post', 'people/bulk_match', ApolloParams, { Headers: headers });
421
- if (response.Status === 200) {
422
- // here we want to iterate through all the results and update the contacts with the enriched data if
423
- // the API returned a match
424
- const result = response.Data;
425
- let bSuccess = true;
426
- if (result && result.missing_records <= ApolloParams.details.length) {
427
- if (result.status.trim().toLowerCase() === 'success') {
428
- // iterate through the matches array
429
- for (const [index, match] of result.matches.entries()) {
430
- if (!match) {
431
- LogStatus('No match found for record at index ' + params.Startrow + index);
432
- continue;
433
- }
434
- const email = match.email;
435
- if (email && email.trim().length > 0) {
436
- // update the contact record
437
- let entityRecord = params.Records[index + params.Startrow];
438
- if (!entityRecord) {
439
- LogError('Error updating contact record with enriched data, entity record not found', undefined, entityRecord);
440
- bSuccess = false;
441
- continue;
442
- }
443
- // The contact entity is configured, not fixed — build the key from its real primary key column(s).
444
- const contactEntity = await md.GetEntityObject(params.EntityName, CompositeKey.FromEntityRecord(md.EntityByName(params.EntityName), entityRecord), params.CurrentUser);
445
- contactEntity.Set(params.EmailField, match.email);
446
- contactEntity.Set(params.EnrichedAtField, new Date());
447
- if (params.TitleField && match.title) {
448
- contactEntity.Set(params.TitleField, match.title);
449
- }
450
- if (params.AccountNameField && match.organization && match.organization.name) {
451
- contactEntity.Set(params.AccountNameField, match.organization.name);
452
- }
453
- if (params.ProfilePictureURLField && match.photo_url) {
454
- contactEntity.Set(params.ProfilePictureURLField, match.photo_url);
455
- }
456
- if (params.LinkedInField && match.linkedin_url) {
457
- contactEntity.Set(params.LinkedInField, match.linkedin_url);
458
- }
459
- if (params.TwitterField && match.twitter_url) {
460
- contactEntity.Set(params.TwitterField, match.twitter_url);
461
- }
462
- if (params.FacebookField && match.facebook_url) {
463
- contactEntity.Set(params.FacebookField, match.facebook_url);
464
- }
465
- bSuccess = bSuccess && (await contactEntity.Save());
466
- if (!bSuccess) {
467
- LogError('Error updating contact record with enriched data', undefined, contactEntity.LatestResult);
468
- }
469
- if (match.employment_history && params.EmploymentHistoryEntityName) {
470
- LogStatus('Upserting contact employment and education history...');
471
- await this.UpsertContactEmploymentAndEducationHistory(match, contactEntity, params);
472
- }
473
- }
474
- else {
475
- LogStatus("Match does not contain an email");
476
- }
477
- }
478
- if (bSuccess) {
479
- console.log('Successfully processed group ' + params.Startrow + ' to ' + (params.Startrow + params.GroupLength));
480
- }
481
- else {
482
- LogStatus('Processed group ' + params.Startrow + ' to ' + (params.Startrow + params.GroupLength) + 'but with errors');
483
- }
484
- return bSuccess;
485
- }
486
- else {
487
- LogStatus('Apollo.io API response did not return a success status');
488
- }
489
- }
490
- else {
491
- // missing records == details.length means no matches were found
492
- console.log('No matches found for this group of records ' + params.Startrow + ' to ' + (params.Startrow + params.GroupLength));
493
- }
494
- }
495
- return false;
226
+ const result = await ctx.Client.BulkMatch(inputs, { RevealPersonalEmails: true });
227
+ matches = result.Matches;
228
+ tally.CreditsConsumed += result.CreditsConsumed;
496
229
  }
497
230
  catch (error) {
498
- console.error('Error occurred:', error);
499
- if (error && error.code && error.code === 429)
500
- throw error; // we want this exception to bubble up so we can catch it and stop the process
501
- else
502
- return false;
231
+ if (error instanceof ApolloRateLimitError || error instanceof ApolloAuthError)
232
+ throw error;
233
+ LogError('Apollo.io bulk match failed for a group of contacts', undefined, error);
234
+ tally.GroupFailures++;
235
+ return;
503
236
  }
504
- }
505
- /**
506
- * Enriches contacts by searching for people at a specific organization domain
507
- * Uses Apollo's people search to find contacts and update their employment/education history
508
- *
509
- * @param domain - Organization domain to search for people
510
- * @param params - Processing parameters with entity configurations
511
- */
512
- async UpsertContactEmploymentAndEducationHistoryByOrganizationID(domain, params) {
513
- try {
514
- const api_params = {
515
- api_key: process.env.APOLLO_API_KEY,
516
- reveal_personal_emails: true,
517
- q_organization_domains: domain,
518
- page: 1
519
- };
520
- const headers = {
521
- 'Cache-Control': 'no-cache',
522
- 'Content-Type': 'application/json'
523
- };
524
- const response = await this.WrapApolloCall('post', 'mixed_people/search', api_params, { Headers: headers });
525
- if (response.Status !== 200) {
526
- console.error(`Error fetching mixed_people data from Apollo.io: ${response.StatusText}`);
527
- return;
528
- }
529
- // here we want to iterate through all the results and update the contacts with the enriched data if
530
- // the API returned a match
531
- const result = response.Data;
532
- const allPeople = result.people;
533
- for (let i = 1; i < result.pagination.total_pages && i < (Config.MaxPeopleToEnrichPerOrg / 10); i++) {
534
- // get additional pages
535
- api_params.page = i + 1;
536
- LogStatus(`Fetching page ${i + 1} of ${result.pagination.total_pages} people for domain: ${domain}`);
537
- const nextResponse = await this.WrapApolloCall('post', 'mixed_people/search', api_params, { Headers: headers });
538
- if (nextResponse.Status !== 200) {
539
- console.error(`Error fetching mixed_people data from Apollo.io: ${nextResponse.StatusText}`);
540
- return;
541
- }
542
- else {
543
- // here we want to iterate through all the results and update the contacts with the enriched data if
544
- // the API returned a match
545
- const nextResult = nextResponse.Data;
546
- allPeople.push(...nextResult.people);
547
- }
548
- }
549
- if (allPeople && allPeople.length > 0) {
550
- let i = 0;
551
- for (let p of allPeople) {
552
- // first, check to make sure that the person has an email and the domain matches the
553
- // account domain, we don't want people who's primary email doesn't match the domain
554
- if (!p.last_name || p.last_name.trim().length === 0 ||
555
- !p.email || p.email.trim().length === 0 || p.email.split('@')[1] !== domain) {
556
- // skip this person
557
- console.log(' * Skipping person: ' + p.first_name + ' ' + p.last_name + ' because email is missing or does not match domain');
558
- }
559
- else if (this.IsExcludedTitle(p.title)) {
560
- console.log(' * Skipping person: ' + p.first_name + ' ' + p.last_name + ' because ' + p.title + ' is an excluded title');
561
- }
562
- else {
563
- const rv = new RunView();
564
- const rvContactResults = await rv.RunView({
565
- EntityName: params.EntityName,
566
- ExtraFilter: `${params.EmailField} = '${p.email}' AND ${params.FirstNameField} = '${p.first_name}'`
567
- }, params.CurrentUser);
568
- if (!rvContactResults.Success) {
569
- LogError('Error querying contact entity: ', undefined, rvContactResults.ErrorMessage);
570
- i++;
571
- continue;
572
- }
573
- if (rvContactResults.Results.length === 0) {
574
- console.log(' * Skipping person: ' + p.first_name + ' ' + p.last_name + ' because no matching contact record was found');
575
- i++;
576
- continue;
577
- }
578
- // Load the matched contact from its row so its primary key (any column name/type) is populated for the history FK filters.
579
- const contactEntity = await params.Md.GetEntityObject(params.EntityName, CompositeKey.FromEntityRecord(params.Md.EntityByName(params.EntityName), rvContactResults.Results[0]), params.CurrentUser);
580
- await this.UpsertContactEmploymentAndEducationHistory(p, contactEntity, params);
581
- }
582
- i++;
583
- }
584
- }
585
- else {
586
- // missing records == details.length means no matches were found
587
- console.log('No matches found for this domain: ' + domain);
588
- }
589
- }
590
- catch (ex) {
591
- LogError('Error upserting contact education and employment history by organization ID: ', undefined, ex);
237
+ tally.Sent += inputs.length;
238
+ for (const [index, match] of matches.entries()) {
239
+ await this.writeContact(ctx, sendable[index], match, tally);
592
240
  }
593
241
  }
594
242
  /**
595
- * Creates or updates employment and education history records for a contact
596
- * Processes Apollo employment history data to create both employment and education records
597
- *
598
- * @param contact - Apollo person data containing employment history
599
- * @param contactEntity - Contact entity to create history for
600
- * @param params - Processing parameters with history entity configurations
243
+ * Writes one contact: the matched fields when there is a match, and the `EnrichedAtField`
244
+ * stamp either way. The save always runs; a failure is counted, never allowed to skip the
245
+ * rows after it.
601
246
  */
602
- async UpsertContactEmploymentAndEducationHistory(contact, contactEntity, params) {
603
- try {
604
- // loop through the person.employment_history array and create/update the employment history records
605
- if (!contact || !contact.employment_history || !params.EmploymentHistoryEntityName || !params.EmploymentHistoryContactIDFieldName || !params.EmploymentHistoryOrganizationFieldName || !params.EmploymentHistoryTitleFieldName) {
606
- LogStatus('Unable to upsert contact employment history: missing one or many required parameters');
607
- return;
608
- }
609
- // The history entities' contact FK column references the contact's key, so that key must be a single column.
610
- if (contactEntity.PrimaryKeys.length !== 1) {
611
- LogError(`Unable to upsert contact employment history: entity '${contactEntity.EntityInfo.Name}' has a composite primary key, which the single ${params.EmploymentHistoryContactIDFieldName} foreign key column cannot reference`);
612
- return;
613
- }
614
- const contactPK = contactEntity.FirstPrimaryKey; // first-pk-ok: FK target — the history entities' contact FK column references the contact's single-column key (guarded above)
615
- const quotes = contactPK.NeedsQuotes ? "'" : "";
616
- const contactID = contactPK.Value;
617
- const rv = new RunView();
618
- for (const employment of contact.employment_history) {
619
- const rvResults = await rv.RunView({
620
- EntityName: params.EmploymentHistoryEntityName,
621
- ExtraFilter: `${params.EmploymentHistoryContactIDFieldName} = ${quotes}${contactID}${quotes}
622
- AND ${params.EmploymentHistoryOrganizationFieldName} = '${this.EscapeSingleQuotes(employment.organization_name)}'
623
- AND Title = '${this.EscapeSingleQuotes(employment.title)}'`,
624
- }, params.CurrentUser);
625
- if (!rvResults.Success) {
626
- LogError('Error querying employment history entity: ', undefined, rvResults.ErrorMessage);
627
- continue;
628
- }
629
- const results = rvResults.Results;
630
- let historyEntity = null;
631
- if (results.length > 0) {
632
- // update the existing record
633
- historyEntity = await params.Md.GetEntityObject(params.EmploymentHistoryEntityName, CompositeKey.FromEntityRecord(params.Md.EntityByName(params.EmploymentHistoryEntityName), results[0]), params.CurrentUser);
634
- }
635
- else {
636
- historyEntity = await params.Md.GetEntityObject(params.EmploymentHistoryEntityName, params.CurrentUser);
637
- historyEntity.NewRecord();
638
- historyEntity.Set(params.EmploymentHistoryContactIDFieldName, contactID);
639
- historyEntity.Set("CreatedAt", new Date());
640
- }
641
- historyEntity.Set(params.EmploymentHistoryOrganizationFieldName, this.EscapeSingleQuotes(employment.organization_name).substring(0, 50));
642
- historyEntity.Set(params.EmploymentHistoryTitleFieldName, this.EscapeSingleQuotes(employment.title));
643
- if (this.IsValidDate(employment.start_date)) {
644
- historyEntity.Set('StartedAt', employment.start_date);
645
- }
646
- if (this.IsValidDate(employment.end_date)) {
647
- historyEntity.Set('EndedAt', employment.end_date);
648
- }
649
- historyEntity.Set("UpdatedAt", new Date());
650
- historyEntity.Set("IsCurrent", employment.current);
651
- const saveResult = await historyEntity.Save();
652
- if (!saveResult) {
653
- LogError('Error upserting contact employment history', undefined, historyEntity.LatestResult);
654
- }
655
- if (employment.degree) {
656
- if (!params.EducationHistoryEntityName || !params.EducationHistoryContactIDFieldName || !params.EducationHistoryInstitutionFieldName || !params.EducationHistoryDegreeFieldName) {
657
- LogStatus('Unable to upsert contact education history, missing one or many required parameters');
658
- continue;
659
- }
660
- const rvEducationResults = await rv.RunView({
661
- EntityName: params.EducationHistoryEntityName,
662
- ExtraFilter: `${params.EducationHistoryContactIDFieldName} = ${quotes}${contactID}${quotes}
663
- AND ${params.EducationHistoryInstitutionFieldName} = '${this.EscapeSingleQuotes(employment.organization_name)}'
664
- AND ${params.EducationHistoryDegreeFieldName} = '${this.EscapeSingleQuotes(employment.degree)}'`,
665
- }, params.CurrentUser);
666
- if (!rvEducationResults.Success) {
667
- LogError('Error querying education history entity: ', undefined, rvEducationResults.ErrorMessage);
668
- continue;
669
- }
670
- const educationResults = rvEducationResults.Results;
671
- let educationEntity = null;
672
- if (educationResults.length > 0) {
673
- // update the existing record
674
- educationEntity = await params.Md.GetEntityObject(params.EducationHistoryEntityName, CompositeKey.FromEntityRecord(params.Md.EntityByName(params.EducationHistoryEntityName), educationResults[0]), params.CurrentUser);
675
- }
676
- else {
677
- educationEntity = await params.Md.GetEntityObject(params.EducationHistoryEntityName, params.CurrentUser);
678
- educationEntity.NewRecord();
679
- educationEntity.Set(params.EducationHistoryContactIDFieldName, contactID);
680
- educationEntity.Set("CreatedAt", new Date());
681
- }
682
- educationEntity.Set(params.EducationHistoryInstitutionFieldName, this.EscapeSingleQuotes(employment.organization_name));
683
- educationEntity.Set(params.EducationHistoryDegreeFieldName, this.EscapeSingleQuotes(employment.degree));
684
- //TODO - add this to mapping
685
- educationEntity.Set("GradeLevel", employment.grade_level);
686
- educationEntity.Set("UpdatedAt", new Date());
687
- if (this.IsValidDate(employment.start_date)) {
688
- educationEntity.Set('StartedAt', employment.start_date);
689
- }
690
- if (this.IsValidDate(employment.end_date)) {
691
- educationEntity.Set('EndedAt', employment.end_date);
692
- }
693
- const saveResult = await educationEntity.Save();
694
- if (!saveResult) {
695
- LogError('Error upserting contact education history: ', undefined, educationEntity.LatestResult);
696
- }
697
- }
698
- }
247
+ async writeContact(ctx, row, match, tally) {
248
+ const contact = await ctx.Md.GetEntityObject(ctx.Params.EntityName, CompositeKey.FromEntityRecord(ctx.Entity, row), ctx.User);
249
+ const matched = match?.Matched === true;
250
+ if (match && matched) {
251
+ ApplyMatch(contact, match, ctx.Params);
252
+ tally.Matched++;
699
253
  }
700
- catch (ex) {
701
- LogError('Error upserting contact education and employment history: ', undefined, ex);
254
+ else if (match) {
255
+ tally.Unmatched++;
702
256
  }
703
- }
704
- /**
705
- * Escapes single quotes in strings for SQL query safety
706
- * Prevents SQL injection in dynamic filter construction
707
- *
708
- * @param str - String to escape
709
- * @returns Escaped string with doubled single quotes
710
- */
711
- EscapeSingleQuotes(str) {
712
- if (str) {
713
- return str.replace(/'/g, "''");
257
+ contact.Set(ctx.Params.EnrichedAtField, new Date());
258
+ const saved = await contact.Save();
259
+ if (!saved) {
260
+ LogError(`Error updating contact record with enriched data: ${contact.LatestResult?.CompleteMessage ?? 'no details'}`);
261
+ tally.SaveFailures++;
262
+ return;
714
263
  }
715
- return '';
264
+ if (match && matched)
265
+ await this.UpsertContactHistory(ctx, contact, match, tally);
716
266
  }
267
+ // ─── History ─────────────────────────────────────────────────────────────
717
268
  /**
718
- * Validates if a date string represents a valid date
719
- * Used for employment/education history date validation
720
- *
721
- * @param dateString - Date string to validate
722
- * @returns boolean - true if valid date
269
+ * Writes employment rows when `EmploymentHistoryFieldMappings` is configured and education rows
270
+ * when `EducationHistoryFieldMappings` is, independently of each other. The history entities'
271
+ * contact FK column references the contact's key, so that key must be a single column.
723
272
  */
724
- IsValidDate(dateString) {
725
- if (dateString && dateString.length > 0) {
726
- const date = new Date(dateString);
727
- return date instanceof Date && !isNaN(date.getTime());
273
+ async UpsertContactHistory(ctx, contact, match, tally) {
274
+ const { employment, education } = ctx.History;
275
+ if (!employment && !education)
276
+ return;
277
+ const key = ContactKeyOf(contact);
278
+ if (!key) {
279
+ LogError(`Unable to upsert contact history: entity '${contact.EntityInfo.Name}' has a composite primary key, which a single foreign key column cannot reference`);
280
+ return;
728
281
  }
729
- return false;
730
- }
731
- /**
732
- * Wraps Apollo.io API calls with intelligent retry logic for rate limiting
733
- * Handles both per-minute and hourly rate limits with appropriate backoff
734
- *
735
- * @param method - HTTP method ('get' or 'post')
736
- * @param endpoint - Apollo API endpoint path
737
- * @param data - Request payload for POST requests
738
- * @param config - request configuration (headers / query params)
739
- * @param retryAttempts - Number of retry attempts remaining (default: 1)
740
- * @returns Promise<HttpResponse> - Apollo API response
741
- * @throws Error if rate limit exceeded or other API errors
742
- */
743
- async WrapApolloCall(method, endpoint, data, config, retryAttempts = 1) {
744
- try {
745
- const url = `${Config.ApolloAPIEndpoint}/${endpoint}`;
746
- // ThrowOnError stays on by default, so a 429 surfaces in the catch below;
747
- // the explicit status check here mirrors the original belt-and-braces handling.
748
- const response = method === 'get' ? await HttpGet(url, config) : await HttpPost(url, data, config);
749
- if (response.Status === 429) {
750
- if (retryAttempts > 0) {
751
- LogStatus(' >>> Too many requests to Apollo.io API, waiting 1 minute and trying again...');
752
- await this.timeout(60000); // wait 1 minute
753
- return await this.WrapApolloCall(method, endpoint, data, config, retryAttempts - 1);
754
- }
755
- else {
756
- throw { message: 'Too many requests to Apollo.io API', code: 429 };
757
- }
282
+ if (employment) {
283
+ for (const entry of match.Employment) {
284
+ const ok = await this.upsertEmployment(ctx, employment, key, entry);
285
+ if (!ok)
286
+ tally.SaveFailures++;
758
287
  }
759
- return response;
760
288
  }
761
- catch (apolloError) {
762
- // A 429 arrives as a thrown HttpError rather than a returned response, so handle it here too
763
- if (IsHttpError(apolloError) && apolloError.Status === 429) {
764
- let waitTime = 60000; // default to 1 minute
765
- //this is a rough guesstimate, check the response headers for more accurate info
766
- if (apolloError.Data) {
767
- const errorMessage = typeof apolloError.Data === 'string'
768
- ? apolloError.Data
769
- : JSON.stringify(apolloError.Data);
770
- if (errorMessage.includes('times per hour')) {
771
- LogStatus(" >>> Hourly rate limit reached");
772
- //we reached out hourly rate limit, so wait an hour
773
- waitTime = 3600000; // wait 1 hour
774
- }
775
- }
776
- if (retryAttempts > 0) {
777
- LogStatus(` >>> Too many requests to Apollo.io API, waiting ${waitTime / 60000} minute(s) and trying again...`);
778
- await this.timeout(waitTime); // wait 1 minute
779
- return await this.WrapApolloCall(method, endpoint, data, config, retryAttempts - 1);
780
- }
781
- else {
782
- throw { message: 'Too many requests to Apollo.io API', code: 429 };
783
- }
784
- }
785
- else {
786
- throw apolloError;
289
+ if (education) {
290
+ for (const entry of match.Education) {
291
+ const ok = await this.upsertEducation(ctx, education, key, entry);
292
+ if (!ok)
293
+ tally.SaveFailures++;
787
294
  }
788
295
  }
789
296
  }
790
- /**
791
- * Utility method for creating delays in async operations
792
- * Used for rate limit backoff and API throttling
793
- *
794
- * @param ms - Number of milliseconds to wait
795
- * @returns Promise that resolves after the specified delay
796
- */
797
- async timeout(ms) {
798
- return new Promise(resolve => setTimeout(resolve, ms));
297
+ async upsertEmployment(ctx, m, key, entry) {
298
+ const info = ctx.Md.EntityByName(m.EntityName);
299
+ if (!info) {
300
+ LogError(`Employment history entity '${m.EntityName}' was not found`);
301
+ return false;
302
+ }
303
+ const organization = FitToColumn(info, m.OrganizationFieldName, entry.OrganizationName);
304
+ const title = FitToColumn(info, m.TitleFieldName, entry.Title ?? '');
305
+ const filter = `${key.Predicate(m.ContactIDFieldName)} AND [${m.OrganizationFieldName}] = '${EscapeSQLString(organization)}' AND [${m.TitleFieldName}] = '${EscapeSQLString(title)}'`;
306
+ const row = await this.loadOrNewHistoryRow(ctx, m.EntityName, m.ContactIDFieldName, key, filter);
307
+ if (!row)
308
+ return false;
309
+ row.Set(m.OrganizationFieldName, organization);
310
+ row.Set(m.TitleFieldName, title);
311
+ SetIfMapped(row, m.StartDateFieldName, ToDate(entry.StartDate));
312
+ SetIfMapped(row, m.EndDateFieldName, ToDate(entry.EndDate));
313
+ SetIfMapped(row, m.IsCurrentFieldName, entry.IsCurrent);
314
+ return this.saveHistoryRow(row, 'employment');
799
315
  }
800
- /**
801
- * Checks if a job title should be excluded from contact processing
802
- * Filters out non-business contacts like students and volunteers
803
- *
804
- * @param title - Job title to check
805
- * @returns boolean - true if title should be excluded
806
- */
807
- IsExcludedTitle(title) {
808
- if (!title) {
316
+ async upsertEducation(ctx, m, key, entry) {
317
+ const info = ctx.Md.EntityByName(m.EntityName);
318
+ if (!info) {
319
+ LogError(`Education history entity '${m.EntityName}' was not found`);
320
+ return false;
321
+ }
322
+ const institution = FitToColumn(info, m.InstitutionFieldName, entry.InstitutionName);
323
+ const degree = FitToColumn(info, m.DegreeFieldName, entry.Degree ?? '');
324
+ const filter = `${key.Predicate(m.ContactIDFieldName)} AND [${m.InstitutionFieldName}] = '${EscapeSQLString(institution)}' AND [${m.DegreeFieldName}] = '${EscapeSQLString(degree)}'`;
325
+ const row = await this.loadOrNewHistoryRow(ctx, m.EntityName, m.ContactIDFieldName, key, filter);
326
+ if (!row)
809
327
  return false;
328
+ row.Set(m.InstitutionFieldName, institution);
329
+ row.Set(m.DegreeFieldName, degree);
330
+ SetIfMapped(row, m.GradeLevelFieldName, entry.GradeLevel);
331
+ SetIfMapped(row, m.StartDateFieldName, ToDate(entry.StartDate));
332
+ SetIfMapped(row, m.EndDateFieldName, ToDate(entry.EndDate));
333
+ return this.saveHistoryRow(row, 'education');
334
+ }
335
+ /** The existing row the filter finds, or a new one keyed to the contact. Null when the lookup fails. */
336
+ async loadOrNewHistoryRow(ctx, entityName, contactIDField, key, filter) {
337
+ const rv = RunView.FromMetadataProvider(ctx.Md);
338
+ const existing = await rv.RunView({ EntityName: entityName, ExtraFilter: filter }, ctx.User);
339
+ if (!existing.Success) {
340
+ LogError(`Error querying history entity '${entityName}': ${existing.ErrorMessage}`);
341
+ return null;
810
342
  }
811
- return this.excludeTitles.includes(title.trim().toLowerCase());
343
+ if (existing.Results.length > 0) {
344
+ const info = ctx.Md.EntityByName(entityName);
345
+ return ctx.Md.GetEntityObject(entityName, CompositeKey.FromEntityRecord(info, existing.Results[0]), ctx.User);
346
+ }
347
+ const row = await ctx.Md.GetEntityObject(entityName, ctx.User);
348
+ row.NewRecord();
349
+ row.Set(contactIDField, key.Value);
350
+ return row;
351
+ }
352
+ async saveHistoryRow(row, kind) {
353
+ const saved = await row.Save();
354
+ if (!saved)
355
+ LogError(`Error upserting contact ${kind} history: ${row.LatestResult?.CompleteMessage ?? 'no details'}`);
356
+ return saved;
812
357
  }
813
358
  };
814
359
  ApolloEnrichmentContactsAction = __decorate([
815
- RegisterClass(BaseAction, "ApolloEnrichmentContactsAction")
360
+ RegisterClass(BaseAction, 'ApolloEnrichmentContactsAction')
816
361
  ], ApolloEnrichmentContactsAction);
817
362
  export { ApolloEnrichmentContactsAction };
363
+ // ─── Pure helpers ────────────────────────────────────────────────────────────
364
+ function Failure(code, message) {
365
+ return { Success: false, Message: message, ResultCode: code };
366
+ }
367
+ function MessageOf(error) {
368
+ return error instanceof Error ? error.message : String(error);
369
+ }
370
+ function StringOrNull(value) {
371
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
372
+ }
373
+ function Summarize(t) {
374
+ return `Sent ${t.Sent} to Apollo (${t.Matched} matched, ${t.Unmatched} not matched, ${t.CreditsConsumed} credits); ` +
375
+ `${t.Unidentifiable} stamped without a lookup (nothing to match on); ${t.SaveFailures} save failures; ${t.GroupFailures} failed groups.`;
376
+ }
377
+ /** A string key for a row, from its real primary key column(s). */
378
+ function RowKey(entity, row) {
379
+ return entity.PrimaryKeys.map((pk) => String(row[pk.Name])).join('|');
380
+ }
381
+ /**
382
+ * The bulk_match `details` entry for a row, or null when the row carries nothing Apollo can
383
+ * match on: an email, or a first and last name with a domain or an account name.
384
+ */
385
+ export function BuildMatchInput(p, row, key) {
386
+ const text = (field) => (field ? StringOrNull(row[field]) ?? undefined : undefined);
387
+ const input = {
388
+ Key: key,
389
+ Email: text(p.EmailField),
390
+ FirstName: text(p.FirstNameField),
391
+ LastName: text(p.LastNameField),
392
+ OrganizationDomain: text(p.DomainField),
393
+ OrganizationName: text(p.AccountNameField),
394
+ };
395
+ const byName = !!input.FirstName && !!input.LastName && (!!input.OrganizationDomain || !!input.OrganizationName);
396
+ return input.Email || byName ? input : null;
397
+ }
398
+ /** Copies the matched values onto the mapped columns. Values are stored as Apollo sent them. */
399
+ function ApplyMatch(contact, match, p) {
400
+ SetIfMapped(contact, p.EmailField, match.Email);
401
+ SetIfMapped(contact, p.TitleField, match.Title);
402
+ SetIfMapped(contact, p.AccountNameField, match.Organization?.Name ?? null);
403
+ SetIfMapped(contact, p.ProfilePictureURLField, match.PhotoURL);
404
+ SetIfMapped(contact, p.LinkedInField, match.LinkedInURL);
405
+ SetIfMapped(contact, p.TwitterField, match.TwitterURL);
406
+ SetIfMapped(contact, p.FacebookField, match.FacebookURL);
407
+ }
408
+ /** Sets a column only when it was mapped and the value is present. Never touches an unnamed column. */
409
+ function SetIfMapped(entity, fieldName, value) {
410
+ if (fieldName && value !== null && value !== undefined && value !== '')
411
+ entity.Set(fieldName, value);
412
+ }
413
+ /** Truncates to the column's declared length so a long vendor value fails nothing; unchanged when the length is unknown. */
414
+ export function FitToColumn(entity, fieldName, value) {
415
+ const length = entity.Fields.find((f) => f.Name.toLowerCase() === fieldName.toLowerCase())?.Length ?? 0;
416
+ return length > 0 && value.length > length ? value.slice(0, length) : value;
417
+ }
418
+ /** A `YYYY-MM-DD` string to a Date; null for anything that does not parse. */
419
+ export function ToDate(value) {
420
+ if (!value)
421
+ return null;
422
+ const date = new Date(value);
423
+ return Number.isNaN(date.getTime()) ? null : date;
424
+ }
425
+ /**
426
+ * The contact's single-column key and a predicate builder for the history FK filters, quoted
427
+ * per the key column's type. Null for a composite key, which a single FK column cannot reference.
428
+ */
429
+ export function ContactKeyOf(contact) {
430
+ if (contact.PrimaryKeys.length !== 1)
431
+ return null;
432
+ const pk = contact.FirstPrimaryKey; // first-pk-ok: FK target — the history entities' contact FK column references the contact's single-column key (guarded above)
433
+ const literal = pk.NeedsQuotes ? `'${EscapeSQLString(String(pk.Value))}'` : String(pk.Value);
434
+ return { Value: pk.Value, Predicate: (fieldName) => `[${fieldName}] = ${literal}` };
435
+ }
436
+ function MappedString(raw, key) {
437
+ const entry = Object.entries(raw).find(([k]) => k.toLowerCase() === key.toLowerCase());
438
+ return entry ? StringOrNull(entry[1]) ?? undefined : undefined;
439
+ }
440
+ export function ParseEmploymentMapping(raw) {
441
+ const get = (key) => MappedString(raw, key);
442
+ const entityName = get('EntityName');
443
+ const contactID = get('ContactIDFieldName');
444
+ const organization = get('OrganizationFieldName');
445
+ const title = get('TitleFieldName');
446
+ if (!entityName || !contactID || !organization || !title) {
447
+ if (Object.keys(raw).length > 0)
448
+ LogStatus('EmploymentHistoryFieldMappings is missing EntityName, ContactIDFieldName, OrganizationFieldName or TitleFieldName; employment history will not be written');
449
+ return null;
450
+ }
451
+ return { EntityName: entityName, ContactIDFieldName: contactID, OrganizationFieldName: organization, TitleFieldName: title, StartDateFieldName: get('StartDateFieldName'), EndDateFieldName: get('EndDateFieldName'), IsCurrentFieldName: get('IsCurrentFieldName') };
452
+ }
453
+ export function ParseEducationMapping(raw) {
454
+ const get = (key) => MappedString(raw, key);
455
+ const entityName = get('EntityName');
456
+ const contactID = get('ContactIDFieldName');
457
+ const institution = get('InstitutionFieldName');
458
+ const degree = get('DegreeFieldName');
459
+ if (!entityName || !contactID || !institution || !degree) {
460
+ if (Object.keys(raw).length > 0)
461
+ LogStatus('EducationHistoryFieldMappings is missing EntityName, ContactIDFieldName, InstitutionFieldName or DegreeFieldName; education history will not be written');
462
+ return null;
463
+ }
464
+ return { EntityName: entityName, ContactIDFieldName: contactID, InstitutionFieldName: institution, DegreeFieldName: degree, GradeLevelFieldName: get('GradeLevelFieldName'), StartDateFieldName: get('StartDateFieldName'), EndDateFieldName: get('EndDateFieldName') };
465
+ }
818
466
  //# sourceMappingURL=contacts.js.map