@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.
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
@@ -1,275 +1,381 @@
1
+ /**
2
+ * Tests for the two enrichment actions, driven with fake clients, a fake metadata provider and a
3
+ * fake RunView. Each case is one row of the Apollo action bug inventory (plan Appendix A).
4
+ * Nothing here may reach api.apollo.io.
5
+ */
6
+ import { readFileSync } from 'node:fs';
7
+ import { fileURLToPath } from 'node:url';
1
8
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- // Mock all external dependencies
3
9
  vi.mock('@memberjunction/actions', () => ({
4
10
  BaseAction: class BaseAction {
11
+ async Run(params) {
12
+ return this.InternalRunAction(params);
13
+ }
5
14
  async InternalRunAction() { return {}; }
6
- }
7
- }));
8
- vi.mock('@memberjunction/global', () => ({
9
- RegisterClass: () => (target) => target
15
+ },
10
16
  }));
17
+ vi.mock('@memberjunction/global', async (importOriginal) => ({ ...(await importOriginal()), RegisterClass: () => (target) => target }));
18
+ vi.mock('@memberjunction/credentials', () => ({ CredentialEngine: { Instance: { Config: vi.fn(), Credentials: [], getCredential: vi.fn() } } }));
19
+ const runViewMock = vi.fn();
11
20
  vi.mock('@memberjunction/core', () => ({
12
21
  BaseEntity: class BaseEntity {
13
- constructor() {
14
- this.LatestResult = null;
15
- this.FirstPrimaryKey = { NeedsQuotes: true };
16
- }
17
- Set(_field, _value) { }
18
- Get(_field) { return ''; }
19
- async Save() { return true; }
20
22
  },
21
23
  LogError: vi.fn(),
22
24
  LogStatus: vi.fn(),
23
- Metadata: vi.fn().mockImplementation(() => ({
24
- GetEntityObject: vi.fn().mockResolvedValue({
25
- Set: vi.fn(),
26
- Get: vi.fn().mockReturnValue(1),
27
- Save: vi.fn().mockResolvedValue(true),
28
- NewRecord: vi.fn(),
29
- LatestResult: null
30
- })
31
- })),
32
- RunView: vi.fn().mockImplementation(() => ({
33
- RunView: vi.fn().mockResolvedValue({ Success: true, Results: [] })
34
- })),
25
+ Metadata: class Metadata {
26
+ static { this.Provider = null; }
27
+ },
28
+ RunView: class RunView {
29
+ static FromMetadataProvider() { return { RunView: runViewMock }; }
30
+ RunView(...args) { return runViewMock(...args); }
31
+ },
35
32
  UserInfo: class UserInfo {
36
33
  },
37
34
  CompositeKey: {
38
- FromID: vi.fn().mockReturnValue({}),
39
- // Records the (entity, row) pair so tests can assert the key was built from the entity's real PK columns.
40
- FromEntityRecord: vi.fn((entity, row) => ({
41
- KeyValuePairs: entity.PrimaryKeys.map(pk => ({ FieldName: pk.Name, Value: row[pk.Name] })),
42
- })),
35
+ FromEntityRecord: (entity, row) => ({
36
+ KeyValuePairs: entity.PrimaryKeys.map((pk) => ({ FieldName: pk.Name, Value: row[pk.Name] })),
37
+ }),
43
38
  },
44
- RunViewResult: class RunViewResult {
45
- }
46
39
  }));
47
- vi.mock('@memberjunction/core-entities', () => ({}));
48
- vi.mock('@memberjunction/actions-base', () => ({
49
- ActionParam: class ActionParam {
50
- constructor() {
51
- this.Name = '';
52
- this.Value = null;
53
- this.Type = 'Input';
54
- }
55
- },
56
- ActionResultSimple: class ActionResultSimple {
57
- constructor() {
58
- this.Success = false;
59
- this.ResultCode = '';
40
+ process.env.APOLLO_API_KEY = 'env-key';
41
+ const { ApolloEnrichmentContactsAction, BuildMatchInput, ContactKeyOf, ParseEmploymentMapping } = await import('../contacts.js');
42
+ const { ApolloEnrichmentAccountsAction, FieldPredicate } = await import('../accounts.js');
43
+ const { ApolloRateLimitError } = await import('../http/ApolloHttp.js');
44
+ const { MapMatch } = await import('../people/ApolloPeopleClient.js');
45
+ function entityDef(name, pks, fields = []) {
46
+ const all = [...pks.map((pk) => ({ Name: pk, NeedsQuotes: pk === 'ID', Length: 0 })), ...fields.map((f) => ({ Name: f.Name, NeedsQuotes: f.NeedsQuotes ?? true, Length: f.Length ?? 0 }))];
47
+ return { Name: name, PrimaryKeys: pks.map((Name) => ({ Name })), Fields: all, FirstPrimaryKey: { Name: pks[0] } };
48
+ }
49
+ /** A saved-row store per entity, so a fake RunView can answer from what the action wrote. */
50
+ class FakeEntity {
51
+ constructor(EntityInfo, row, world) {
52
+ this.EntityInfo = EntityInfo;
53
+ this.world = world;
54
+ this.LatestResult = null;
55
+ this.SaveCount = 0;
56
+ this.Sets = [];
57
+ this.Values = row ? { ...row } : {};
58
+ }
59
+ get PrimaryKeys() { return this.EntityInfo.PrimaryKeys; }
60
+ get FirstPrimaryKey() { const name = this.EntityInfo.FirstPrimaryKey.Name; return { Name: name, Value: this.Values[name], NeedsQuotes: name === 'ID' }; }
61
+ NewRecord() { this.Values = {}; }
62
+ Set(field, value) { this.Values[field] = value; this.Sets.push([field, value]); }
63
+ Get(field) { return this.Values[field]; }
64
+ async Save() {
65
+ this.SaveCount++;
66
+ if (this.world.failSave(this)) {
67
+ this.LatestResult = { CompleteMessage: 'simulated save failure' };
68
+ return false;
60
69
  }
61
- },
62
- RunActionParams: class RunActionParams {
63
- constructor() {
64
- this.Params = [];
65
- this.ContextUser = null;
66
- this.Action = null;
67
- this.Filters = [];
70
+ this.world.saved(this);
71
+ return true;
72
+ }
73
+ }
74
+ class FakeWorld {
75
+ constructor() {
76
+ this.entities = new Map();
77
+ this.rows = new Map();
78
+ this.savedEntities = [];
79
+ this.failSave = () => false;
80
+ this.md = {
81
+ EntityByName: (name) => this.entities.get(name) ?? null,
82
+ GetEntityObject: async (name, keyOrUser) => {
83
+ const info = this.entities.get(name);
84
+ const key = keyOrUser;
85
+ if (!key?.KeyValuePairs)
86
+ return new FakeEntity(info, null, this);
87
+ const row = (this.rows.get(name) ?? []).find((r) => key.KeyValuePairs?.every((kv) => r[kv.FieldName] === kv.Value));
88
+ if (!row)
89
+ throw new Error(`no row for ${name} ${JSON.stringify(key.KeyValuePairs)}`);
90
+ return new FakeEntity(info, row, this);
91
+ },
92
+ };
93
+ }
94
+ define(def, rows = []) { this.entities.set(def.Name, def); this.rows.set(def.Name, rows); }
95
+ saved(e) {
96
+ this.savedEntities.push(e);
97
+ const list = this.rows.get(e.EntityInfo.Name) ?? [];
98
+ const pk = e.EntityInfo.PrimaryKeys.map((p) => p.Name);
99
+ const existing = list.find((r) => pk.every((p) => r[p] === e.Values[p]) && pk.every((p) => e.Values[p] !== undefined));
100
+ if (existing)
101
+ Object.assign(existing, e.Values);
102
+ else {
103
+ if (e.Values.ID === undefined)
104
+ e.Values.ID = `new-${list.length + 1}`;
105
+ list.push({ ...e.Values });
68
106
  }
107
+ this.rows.set(e.EntityInfo.Name, list);
69
108
  }
70
- }));
71
- vi.mock('@memberjunction/network-utils', () => ({
72
- HttpGet: vi.fn(),
73
- HttpPost: vi.fn(),
74
- IsHttpError: vi.fn(() => false)
75
- }));
76
- vi.mock('../config', () => ({
77
- ApolloAPIEndpoint: 'https://api.apollo.io/v1',
78
- EmailSourceName: 'Apollo.io',
79
- GroupSize: 10,
80
- ConcurrentGroups: 1,
81
- MaxPeopleToEnrichPerOrg: 500,
82
- ApolloAPIKey: 'test-api-key'
83
- }));
84
- // Import after mocks
85
- import { ApolloEnrichmentAccountsAction } from '../accounts.js';
86
- import { ApolloEnrichmentContactsAction } from '../contacts.js';
87
- describe('ApolloEnrichmentAccountsAction', () => {
88
- let action;
109
+ savedFor(entityName) { return this.savedEntities.filter((e) => e.EntityInfo.Name === entityName); }
110
+ }
111
+ function match(over) {
112
+ return { ...MapMatch(null, over.Key ?? 'k', false), Matched: true, ApolloPersonID: 'ap-1', FirstName: 'Ada', LastName: 'Lovelace', Title: 'Engineer', Email: 'ada@acme.com', ...over };
113
+ }
114
+ const miss = (key) => MapMatch(null, key, false);
115
+ function contactsAction(client) {
116
+ const action = new ApolloEnrichmentContactsAction();
117
+ const createClient = vi.fn(async () => client);
118
+ action.CreateClient = createClient;
119
+ return { action, createClient };
120
+ }
121
+ const CONTACT_PARAMS = [
122
+ ['EntityName', 'Contacts'], ['EmailField', 'Email'], ['FirstNameField', 'FirstName'], ['LastNameField', 'LastName'],
123
+ ['TitleField', 'Title'], ['EnrichedAtField', 'EnrichedAt'], ['Filter', 'EnrichedAt IS NULL'], ['DomainField', 'Domain'],
124
+ ].map(([Name, Value]) => ({ Name, Value, Type: 'Input' }));
125
+ async function runContacts(action, world, extra = []) {
126
+ return action.Run({ Params: [...CONTACT_PARAMS, ...extra.map((p) => ({ ...p, Type: 'Input' }))], ContextUser: {}, Provider: world.md });
127
+ }
128
+ /** Contacts whose filter drains: unstamped rows, ordered by ID, after the key. */
129
+ function contactsRunView(world, pageSize = 500) {
130
+ runViewMock.mockImplementation(async (p) => {
131
+ if (p.EntityName !== 'Contacts') {
132
+ const [, field, value] = /\[(\w+)\] = ('?[^' ]+'?)/.exec(p.ExtraFilter) ?? [];
133
+ const rows = (world.rows.get(p.EntityName) ?? []).filter((r) => String(r[field]) === String(value).replace(/^'|'$/g, ''));
134
+ return { Success: true, Results: rows.map((r) => ({ ...r })) };
135
+ }
136
+ const after = p.AfterKey?.KeyValuePairs[0].Value;
137
+ const rows = (world.rows.get('Contacts') ?? []).filter((r) => r.EnrichedAt === undefined && (after === undefined || String(r.ID) > after)).sort((a, b) => String(a.ID).localeCompare(String(b.ID)));
138
+ return { Success: true, Results: rows.slice(0, p.MaxRows ?? pageSize).map((r) => ({ ...r })) };
139
+ });
140
+ }
141
+ const pad = (n) => String(n).padStart(5, '0');
142
+ describe('ApolloEnrichmentContactsAction', () => {
143
+ let world;
89
144
  beforeEach(() => {
90
- action = new ApolloEnrichmentAccountsAction();
145
+ world = new FakeWorld();
146
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'Email' }, { Name: 'FirstName' }, { Name: 'LastName' }, { Name: 'Title' }, { Name: 'EnrichedAt' }, { Name: 'Domain' }]));
147
+ runViewMock.mockReset();
91
148
  });
92
- it('should be instantiable', () => {
93
- expect(action).toBeDefined();
149
+ it('A-9: resolves the client through the CompanyID param and header auth lives in the client', async () => {
150
+ world.define(entityDef('Contacts', ['ID']), []);
151
+ contactsRunView(world);
152
+ const bulk = vi.fn(async () => ({ Matches: [], CreditsConsumed: 0 }));
153
+ const { action, createClient } = contactsAction({ BulkMatch: bulk });
154
+ const result = await runContacts(action, world, [{ Name: 'CompanyID', Value: 'co-1' }]);
155
+ expect(result.ResultCode).toBe('SUCCESS');
156
+ expect(createClient).toHaveBeenCalledWith('co-1', {});
94
157
  });
95
- describe('IsValidDate', () => {
96
- it('should return true for valid date strings', () => {
97
- expect(action.IsValidDate('2024-01-15')).toBe(true);
98
- expect(action.IsValidDate('2024-01-15T10:30:00Z')).toBe(true);
99
- });
100
- it('should return false for invalid date strings', () => {
101
- expect(action.IsValidDate('')).toBe(false);
102
- expect(action.IsValidDate('not-a-date')).toBe(false);
103
- });
104
- it('should return false for null/undefined', () => {
105
- expect(action.IsValidDate(null)).toBe(false);
106
- expect(action.IsValidDate(undefined)).toBe(false);
107
- });
158
+ it('A-6 and A-3: every row sent is stamped, a miss too, and a failed save does not skip the rows after it', async () => {
159
+ const rows = [1, 2, 3].map((n) => ({ ID: `c${n}`, Email: `p${n}@acme.com` }));
160
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'Email' }, { Name: 'EnrichedAt' }]), rows);
161
+ contactsRunView(world);
162
+ world.failSave = (e) => e.Values.ID === 'c1';
163
+ const bulk = vi.fn(async (inputs) => ({ Matches: inputs.map((i, n) => (n === 1 ? miss(i.Key) : match({ Key: i.Key, Email: `p${n + 1}@acme.com` }))), CreditsConsumed: 2 }));
164
+ const { action } = contactsAction({ BulkMatch: bulk });
165
+ const result = await runContacts(action, world);
166
+ expect(result.ResultCode).toBe('FAILED');
167
+ expect(result.Message).toContain('1 save failures');
168
+ const contacts = world.rows.get('Contacts');
169
+ expect(contacts[0].EnrichedAt).toBeUndefined(); // c1's save failed
170
+ expect(contacts[1].EnrichedAt).toBeInstanceOf(Date); // the miss is stamped
171
+ expect(contacts[2].EnrichedAt).toBeInstanceOf(Date); // and the row after the failure was still written
172
+ expect(contacts[2].Title).toBe('Engineer');
173
+ });
174
+ it('A-5: keyset paging over a filter that drains processes 1,203 rows exactly once', async () => {
175
+ const rows = Array.from({ length: 1203 }, (_, n) => ({ ID: `c${pad(n)}`, Email: `p${n}@acme.com` }));
176
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'Email' }, { Name: 'EnrichedAt' }]), rows);
177
+ contactsRunView(world);
178
+ const seen = [];
179
+ const bulk = vi.fn(async (inputs) => { inputs.forEach((i) => seen.push(i.Email)); return { Matches: inputs.map((i) => miss(i.Key)), CreditsConsumed: 0 }; });
180
+ const { action } = contactsAction({ BulkMatch: bulk });
181
+ const result = await runContacts(action, world);
182
+ expect(result.ResultCode).toBe('SUCCESS');
183
+ expect(seen).toHaveLength(1203);
184
+ expect(new Set(seen).size).toBe(1203);
185
+ expect(bulk).toHaveBeenCalledTimes(121);
186
+ expect(runViewMock.mock.calls.filter((c) => c[0].EntityName === 'Contacts').length).toBe(3);
187
+ expect(runViewMock.mock.calls[1][0].AfterKey).toEqual({ KeyValuePairs: [{ FieldName: 'ID', Value: 'c00499' }] });
188
+ });
189
+ it('stamps a row nothing identifies without sending it', async () => {
190
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'EnrichedAt' }]), [{ ID: 'c1', FirstName: 'Only' }]);
191
+ contactsRunView(world);
192
+ const bulk = vi.fn();
193
+ const { action } = contactsAction({ BulkMatch: bulk });
194
+ const result = await runContacts(action, world);
195
+ expect(result.ResultCode).toBe('SUCCESS');
196
+ expect(bulk).not.toHaveBeenCalled();
197
+ expect(world.rows.get('Contacts')[0].EnrichedAt).toBeInstanceOf(Date);
198
+ });
199
+ it('A-10: an hourly rate limit returns RATE_LIMIT_EXCEEDED at once, with no sleep in the action', async () => {
200
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'EnrichedAt' }]), [{ ID: 'c1', Email: 'a@acme.com' }]);
201
+ contactsRunView(world);
202
+ const { action } = contactsAction({ BulkMatch: vi.fn(async () => { throw new ApolloRateLimitError('hourly', '{"error":"Hourly rate limit exceeded"}', null, 'hour'); }) });
203
+ const started = Date.now();
204
+ const result = await runContacts(action, world);
205
+ expect(result.ResultCode).toBe('RATE_LIMIT_EXCEEDED');
206
+ expect(Date.now() - started).toBeLessThan(1000);
108
207
  });
109
- describe('IsExcludedTitle', () => {
110
- it('should exclude student titles', () => {
111
- expect(action.IsExcludedTitle('Student')).toBe(true);
112
- expect(action.IsExcludedTitle('student member')).toBe(true);
208
+ describe('history (A-4, A-7, A-8)', () => {
209
+ const employmentMapping = { EntityName: 'Employment', ContactIDFieldName: 'ContactID', OrganizationFieldName: 'Org', TitleFieldName: 'Role', StartDateFieldName: 'Began' };
210
+ const educationMapping = { EntityName: 'Education', ContactIDFieldName: 'ContactID', InstitutionFieldName: 'School', DegreeFieldName: 'Award' };
211
+ const withHistory = () => {
212
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'EnrichedAt' }]), [{ ID: 'c1', Email: 'a@acme.com' }]);
213
+ world.define(entityDef('Employment', ['ID'], [{ Name: 'ContactID' }, { Name: 'Org', Length: 50 }, { Name: 'Role' }, { Name: 'Began' }]));
214
+ world.define(entityDef('Education', ['ID'], [{ Name: 'ContactID' }, { Name: 'School' }, { Name: 'Award' }]));
215
+ contactsRunView(world);
216
+ };
217
+ const enriched = match({
218
+ Key: '0',
219
+ Employment: [{ OrganizationName: "O'Reilly Media", ApolloOrganizationID: null, OrganizationDomain: null, Title: 'Editor', StartDate: '2010-01-01', EndDate: null, IsCurrent: true }],
220
+ Education: [{ InstitutionName: 'MIT', ApolloOrganizationID: null, Degree: 'MS', FieldOfStudy: null, GradeLevel: null, StartDate: null, EndDate: null }],
113
221
  });
114
- it('should exclude volunteer titles', () => {
115
- expect(action.IsExcludedTitle('Volunteer')).toBe(true);
222
+ it('A-7: education-only mappings write education rows and no employment rows', async () => {
223
+ withHistory();
224
+ const { action } = contactsAction({ BulkMatch: vi.fn(async () => ({ Matches: [enriched], CreditsConsumed: 1 })) });
225
+ const result = await runContacts(action, world, [{ Name: 'EducationHistoryFieldMappings', Value: JSON.stringify(educationMapping) }]);
226
+ expect(result.ResultCode).toBe('SUCCESS');
227
+ expect(world.savedFor('Education')).toHaveLength(1);
228
+ expect(world.savedFor('Employment')).toHaveLength(0);
229
+ expect(world.savedFor('Education')[0].Values).toMatchObject({ ContactID: 'c1', School: 'MIT', Award: 'MS' });
116
230
  });
117
- it('should exclude member titles', () => {
118
- expect(action.IsExcludedTitle('Member')).toBe(true);
231
+ it("A-4 and A-8: stores O'Reilly with one quote, escapes it only in the filter, and writes only mapped columns", async () => {
232
+ withHistory();
233
+ const { action } = contactsAction({ BulkMatch: vi.fn(async () => ({ Matches: [enriched], CreditsConsumed: 1 })) });
234
+ await runContacts(action, world, [{ Name: 'EmploymentHistoryFieldMappings', Value: employmentMapping }]);
235
+ const row = world.savedFor('Employment')[0];
236
+ expect(row.Values.Org).toBe("O'Reilly Media");
237
+ expect(row.Values.Role).toBe('Editor');
238
+ expect(row.Values.Began).toBeInstanceOf(Date);
239
+ expect(row.Sets.map(([f]) => f).sort()).toEqual(['Began', 'ContactID', 'Org', 'Role']);
240
+ const lookup = runViewMock.mock.calls.find((c) => c[0].EntityName === 'Employment')?.[0].ExtraFilter;
241
+ expect(lookup).toContain("[Org] = 'O''Reilly Media'");
242
+ expect(lookup).toContain("[ContactID] = 'c1'");
243
+ expect(lookup).toContain('[Role] =');
119
244
  });
120
- it('should not exclude regular titles', () => {
121
- expect(action.IsExcludedTitle('CEO')).toBe(false);
122
- expect(action.IsExcludedTitle('Software Engineer')).toBe(false);
245
+ it('a second run on the same history finds the row and updates it instead of inserting a duplicate', async () => {
246
+ withHistory();
247
+ const { action } = contactsAction({ BulkMatch: vi.fn(async () => ({ Matches: [enriched], CreditsConsumed: 1 })) });
248
+ await runContacts(action, world, [{ Name: 'EmploymentHistoryFieldMappings', Value: employmentMapping }]);
249
+ world.rows.get('Contacts')[0].EnrichedAt = undefined;
250
+ await runContacts(action, world, [{ Name: 'EmploymentHistoryFieldMappings', Value: employmentMapping }]);
251
+ expect(world.rows.get('Employment')).toHaveLength(1);
123
252
  });
124
- it('should return false for null/undefined title', () => {
125
- expect(action.IsExcludedTitle(null)).toBe(false);
126
- expect(action.IsExcludedTitle(undefined)).toBe(false);
253
+ it('refuses to build a single-column FK filter for a composite-keyed contact entity', async () => {
254
+ withHistory();
255
+ world.define(entityDef('Contacts', ['OrgID', 'PersonNo'], [{ Name: 'EnrichedAt' }]), [{ OrgID: 1, PersonNo: 2, Email: 'a@acme.com' }]);
256
+ runViewMock.mockImplementation(async (p) => ({ Success: true, Results: p.EntityName === 'Contacts' ? [{ OrgID: 1, PersonNo: 2, Email: 'a@acme.com' }] : [] }));
257
+ const { action } = contactsAction({ BulkMatch: vi.fn(async () => ({ Matches: [enriched], CreditsConsumed: 1 })) });
258
+ const { LogError } = await import('@memberjunction/core');
259
+ await runContacts(action, world, [{ Name: 'EmploymentHistoryFieldMappings', Value: employmentMapping }]);
260
+ expect(world.savedFor('Employment')).toHaveLength(0);
261
+ expect(LogError).toHaveBeenCalledWith(expect.stringContaining('composite primary key'));
127
262
  });
128
263
  });
129
- describe('EscapeSingleQuotes', () => {
130
- it('should escape single quotes', () => {
131
- expect(action.EscapeSingleQuotes("O'Brien")).toBe("O''Brien");
132
- });
133
- it('should handle strings without quotes', () => {
134
- expect(action.EscapeSingleQuotes('Hello')).toBe('Hello');
135
- });
136
- it('should return empty string for null/undefined', () => {
137
- expect(action.EscapeSingleQuotes(null)).toBe('');
138
- expect(action.EscapeSingleQuotes(undefined)).toBe('');
139
- });
140
- it('should handle multiple quotes', () => {
141
- expect(action.EscapeSingleQuotes("it's a 'test'")).toBe("it''s a ''test''");
142
- });
264
+ it('A-12: reads the mapping keys the metadata documents (EntityName, ContactIDFieldName, …), case-insensitively', () => {
265
+ expect(ParseEmploymentMapping({ entityname: 'E', contactidfieldname: 'C', organizationfieldname: 'O', titlefieldname: 'T' })).toMatchObject({ EntityName: 'E', TitleFieldName: 'T' });
266
+ expect(ParseEmploymentMapping({ EmploymentHistoryEntityName: 'E' })).toBeNull();
267
+ });
268
+ it('BuildMatchInput needs an email, or a name with a domain or an account name', () => {
269
+ const p = { EntityName: 'C', EmailField: 'Email', FirstNameField: 'First', LastNameField: 'Last', TitleField: 'T', EnrichedAtField: 'E', Filter: '', DomainField: 'Domain', AccountNameField: 'Account', CompanyID: null };
270
+ expect(BuildMatchInput(p, { Email: 'a@b.c' }, '0')).toMatchObject({ Email: 'a@b.c' });
271
+ expect(BuildMatchInput(p, { First: 'A', Last: 'B', Account: 'Acme' }, '0')).toMatchObject({ OrganizationName: 'Acme' });
272
+ expect(BuildMatchInput(p, { First: 'A', Last: 'B' }, '0')).toBeNull();
273
+ });
274
+ it('ContactKeyOf quotes a string key and not an integer key', () => {
275
+ const stringKey = { PrimaryKeys: [{ Name: 'ID' }], FirstPrimaryKey: { Name: 'ID', Value: "o'k", NeedsQuotes: true } };
276
+ const intKey = { PrimaryKeys: [{ Name: 'individual_id' }], FirstPrimaryKey: { Name: 'individual_id', Value: 9001, NeedsQuotes: false } };
277
+ expect(ContactKeyOf(stringKey)?.Predicate('ContactKey')).toBe("[ContactKey] = 'o''k'");
278
+ expect(ContactKeyOf(intKey)?.Predicate('ContactKey')).toBe('[ContactKey] = 9001');
279
+ expect(ContactKeyOf({ PrimaryKeys: [{}, {}] })).toBeNull();
143
280
  });
144
281
  });
145
- describe('ApolloEnrichmentContactsAction', () => {
146
- let action;
282
+ const apiSearch = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/api-search.redacted.json', import.meta.url)), 'utf8'));
283
+ function accountsAction(people, search) {
284
+ const action = new ApolloEnrichmentAccountsAction();
285
+ action.CreateClients = vi.fn(async () => ({ People: people, Search: search }));
286
+ return action;
287
+ }
288
+ const ACCOUNT_MAPPING = { EntityName: 'Accounts', DomainField: 'Domain', AccountIDField: 'ID', EnrichedAtField: 'EnrichedAt', Filter: 'EnrichedAt IS NULL', CityField: 'City' };
289
+ const CONTACT_MAPPING = { EntityName: 'Contacts', EmailField: 'Email', AccountIDField: 'AccountID', EnrichedAtField: 'EnrichedAt', FirstNameField: 'FirstName', LastNameField: 'LastName', TitleField: 'Title', EmailSourceField: 'EmailSource', ActivityCountField: 'ActivityCount' };
290
+ async function runAccounts(action, world, extra = []) {
291
+ return action.Run({
292
+ Params: [{ Name: 'AccountEntityFieldMappings', Value: ACCOUNT_MAPPING, Type: 'Input' }, ...extra.map((p) => ({ ...p, Type: 'Input' }))], ContextUser: {}, Provider: world.md,
293
+ });
294
+ }
295
+ /** Accounts whose filter drains; contacts answered from the store by the predicates in the filter. */
296
+ function accountsRunView(world) {
297
+ runViewMock.mockImplementation(async (p) => {
298
+ if (p.EntityName === 'Accounts')
299
+ return { Success: true, Results: (world.rows.get('Accounts') ?? []).filter((r) => r.EnrichedAt === undefined).map((r) => ({ ...r })) };
300
+ const rows = world.rows.get(p.EntityName) ?? [];
301
+ const email = /\[Email\] = '([^']*)'/.exec(p.ExtraFilter)?.[1];
302
+ const account = /\[AccountID\] (=|<>) ('?)([^' ]+)\2/.exec(p.ExtraFilter);
303
+ const hits = rows.filter((r) => (email === undefined || r.Email === email) && (!account || (account[1] === '=' ? String(r.AccountID) === account[3] : String(r.AccountID) !== account[3])));
304
+ return { Success: true, Results: hits.map((r) => ({ ...r })) };
305
+ });
306
+ }
307
+ describe('ApolloEnrichmentAccountsAction', () => {
308
+ let world;
147
309
  beforeEach(() => {
148
- action = new ApolloEnrichmentContactsAction();
310
+ world = new FakeWorld();
311
+ world.define(entityDef('Accounts', ['ID'], [{ Name: 'Domain' }, { Name: 'EnrichedAt' }, { Name: 'City' }]), [{ ID: 'acc-uuid-1', Domain: 'leoninepa.com' }]);
312
+ world.define(entityDef('Contacts', ['ID'], [{ Name: 'Email' }, { Name: 'AccountID', NeedsQuotes: true }, { Name: 'FirstName' }, { Name: 'LastName' }, { Name: 'Title' }, { Name: 'EnrichedAt' }]));
313
+ runViewMock.mockReset();
314
+ accountsRunView(world);
149
315
  });
150
- it('should be instantiable', () => {
151
- expect(action).toBeDefined();
316
+ it('A-13: discovers people through api_search and matches them by Apollo id, creating contacts for in-domain emails', async () => {
317
+ const searchPeople = vi.fn(async () => ({ people: apiSearch.body.people.map((p) => ({ id: p.id, firstName: 'x', lastName: '', lastNameObfuscated: 'D***', name: '', title: 'Analyst', linkedinUrl: '', hasEmail: true, organizationId: null, organizationName: '' })), pagination: { page: 1, perPage: 100, totalEntries: 1, totalPages: 1 } }));
318
+ const bulk = vi.fn(async (inputs) => ({ Matches: inputs.map((i) => match({ Key: i.Key, ApolloPersonID: i.ApolloPersonID ?? null, Email: 'ana@leoninepa.com', LastName: 'Dean' })), CreditsConsumed: inputs.length }));
319
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => ({ city: 'Montpelier', current_technologies: [] })), BulkMatch: bulk }, { searchPeople });
320
+ const result = await runAccounts(action, world, [{ Name: 'ContactEntityFieldMappings', Value: CONTACT_MAPPING }]);
321
+ expect(result.ResultCode).toBe('SUCCESS');
322
+ expect(searchPeople).toHaveBeenCalledWith({ organizationDomains: ['leoninepa.com'] }, { page: 1, perPage: 100 });
323
+ expect(bulk).toHaveBeenCalledWith([{ Key: 'pdl-fixture-9', ApolloPersonID: 'pdl-fixture-9' }], { RevealPersonalEmails: true });
324
+ const contacts = world.rows.get('Contacts');
325
+ expect(contacts).toHaveLength(1);
326
+ expect(contacts[0]).toMatchObject({ Email: 'ana@leoninepa.com', AccountID: 'acc-uuid-1', LastName: 'Dean', EmailSource: 'Apollo.io' });
327
+ expect(world.rows.get('Accounts')[0]).toMatchObject({ City: 'Montpelier' });
152
328
  });
153
- describe('getParamValue', () => {
154
- it('should return param value by name case-insensitively', () => {
155
- const params = {
156
- Params: [{ Name: 'EntityName', Value: 'Contacts', Type: 'Input' }]
157
- };
158
- const result = action.getParamValue(params, 'entityname');
159
- expect(result).toBe('Contacts');
160
- });
161
- it('should return null for "null" string values', () => {
162
- const params = {
163
- Params: [{ Name: 'EntityName', Value: 'null', Type: 'Input' }]
164
- };
165
- const result = action.getParamValue(params, 'EntityName');
166
- expect(result).toBeNull();
167
- });
168
- it('should return undefined for missing params', () => {
169
- const params = {
170
- Params: [{ Name: 'EntityName', Value: 'Contacts', Type: 'Input' }]
171
- };
172
- const result = action.getParamValue(params, 'NonExistent');
173
- expect(result).toBeUndefined();
174
- });
329
+ it('A-1: the contact lookups quote a UUID account key', async () => {
330
+ const searchPeople = vi.fn(async () => ({ people: [{ id: 'p1', firstName: 'x', lastName: '', lastNameObfuscated: '', name: '', title: '', linkedinUrl: '', hasEmail: true, organizationId: null, organizationName: '' }], pagination: { page: 1, perPage: 100, totalEntries: 1, totalPages: 1 } }));
331
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => null), BulkMatch: vi.fn(async () => ({ Matches: [match({ Key: 'p1', Email: 'a@leoninepa.com' })], CreditsConsumed: 1 })) }, { searchPeople });
332
+ await runAccounts(action, world, [{ Name: 'ContactEntityFieldMappings', Value: CONTACT_MAPPING }]);
333
+ const filters = runViewMock.mock.calls.filter((c) => c[0].EntityName === 'Contacts').map((c) => c[0].ExtraFilter);
334
+ expect(filters[0]).toContain("[AccountID] <> 'acc-uuid-1'");
335
+ expect(filters[1]).toContain("[AccountID] = 'acc-uuid-1'");
175
336
  });
176
- describe('EscapeSingleQuotes', () => {
177
- it('should escape single quotes in strings', () => {
178
- expect(action.EscapeSingleQuotes("it's")).toBe("it''s");
179
- });
180
- it('should return empty string for falsy input', () => {
181
- expect(action.EscapeSingleQuotes('')).toBe('');
182
- expect(action.EscapeSingleQuotes(null)).toBe('');
183
- });
337
+ it('A-2: an existing contact is loaded by its real key and updated, not replaced by a blank object', async () => {
338
+ world.define(world.entities.get('Contacts'), [{ ID: 'existing-7', Email: 'a@leoninepa.com', AccountID: 'acc-uuid-1', Title: 'Old' }]);
339
+ const searchPeople = vi.fn(async () => ({ people: [{ id: 'p1', firstName: 'x', lastName: '', lastNameObfuscated: '', name: '', title: '', linkedinUrl: '', hasEmail: true, organizationId: null, organizationName: '' }], pagination: { page: 1, perPage: 100, totalEntries: 1, totalPages: 1 } }));
340
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => null), BulkMatch: vi.fn(async () => ({ Matches: [match({ Key: 'p1', Email: 'a@leoninepa.com', Title: 'New' })], CreditsConsumed: 1 })) }, { searchPeople });
341
+ await runAccounts(action, world, [{ Name: 'ContactEntityFieldMappings', Value: CONTACT_MAPPING }]);
342
+ const contacts = world.rows.get('Contacts');
343
+ expect(contacts).toHaveLength(1);
344
+ expect(contacts[0]).toMatchObject({ ID: 'existing-7', Title: 'New' });
184
345
  });
185
- describe('IsValidDate', () => {
186
- it('should return true for valid dates', () => {
187
- expect(action.IsValidDate('2024-06-15')).toBe(true);
188
- });
189
- it('should return false for empty or invalid dates', () => {
190
- expect(action.IsValidDate('')).toBe(false);
191
- expect(action.IsValidDate('xyz')).toBe(false);
192
- });
346
+ it('A-3: a failed contact save does not skip the people after it', async () => {
347
+ const people = ['p1', 'p2', 'p3'].map((id) => ({ id, firstName: 'x', lastName: '', lastNameObfuscated: '', name: '', title: '', linkedinUrl: '', hasEmail: true, organizationId: null, organizationName: '' }));
348
+ const bulk = vi.fn(async (inputs) => ({ Matches: inputs.map((i) => match({ Key: i.Key, Email: `${i.Key}@leoninepa.com`, LastName: i.Key })), CreditsConsumed: 3 }));
349
+ world.failSave = (e) => e.Values.Email === 'p1@leoninepa.com';
350
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => null), BulkMatch: bulk }, { searchPeople: vi.fn(async () => ({ people, pagination: { page: 1, perPage: 100, totalEntries: 3, totalPages: 1 } })) });
351
+ const result = await runAccounts(action, world, [{ Name: 'ContactEntityFieldMappings', Value: CONTACT_MAPPING }]);
352
+ expect(result.ResultCode).toBe('FAILED');
353
+ expect(world.rows.get('Contacts').map((c) => c.Email)).toEqual(['p2@leoninepa.com', 'p3@leoninepa.com']);
193
354
  });
194
- describe('IsExcludedTitle', () => {
195
- it('should exclude configured titles', () => {
196
- expect(action.IsExcludedTitle('Student')).toBe(true);
197
- expect(action.IsExcludedTitle('VOLUNTEER')).toBe(true);
198
- });
199
- it('should not exclude business titles', () => {
200
- expect(action.IsExcludedTitle('VP of Sales')).toBe(false);
201
- });
202
- it('should return false for empty/null title', () => {
203
- expect(action.IsExcludedTitle(null)).toBe(false);
204
- });
355
+ it('A-10: an hourly rate limit on organizations/enrich returns RATE_LIMIT_EXCEEDED at once', async () => {
356
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => { throw new ApolloRateLimitError('hourly', '', null, 'hour'); }) }, {});
357
+ const result = await runAccounts(action, world);
358
+ expect(result.ResultCode).toBe('RATE_LIMIT_EXCEEDED');
205
359
  });
206
- });
207
- // ---------------------------------------------------------------------------
208
- // Primary-key handling on the CONFIGURED account / contact entities (not MJ core entities):
209
- // keys must come from the entity's real primary key column(s), never a literal `ID`.
210
- // ---------------------------------------------------------------------------
211
- describe('ApolloEnrichmentAccountsAction primary-key handling', () => {
212
- it('updateAccountEnrichedTimestamp loads the configured account entity by its real (composite) key', async () => {
213
- const action = new ApolloEnrichmentAccountsAction();
214
- const accountsEntityInfo = { Name: 'Accounts', PrimaryKeys: [{ Name: 'OrgID' }, { Name: 'Region' }] };
215
- const accountEntity = { Set: vi.fn(), Save: vi.fn().mockResolvedValue(true), LatestResult: null };
216
- const md = {
217
- EntityByName: vi.fn().mockReturnValue(accountsEntityInfo),
218
- GetEntityObject: vi.fn().mockResolvedValue(accountEntity),
219
- };
220
- const record = { OrgID: 42, Region: 'EMEA', Domain: 'example.com' };
221
- const params = { AccountEntity: { EntityName: 'Accounts', EnrichedAtField: 'EnrichedAt' }, Record: record };
222
- const ok = await action.updateAccountEnrichedTimestamp(params, record, md, {});
223
- expect(ok).toBe(true);
224
- expect(md.EntityByName).toHaveBeenCalledWith('Accounts');
225
- const [entityName, key] = md.GetEntityObject.mock.calls[0];
226
- expect(entityName).toBe('Accounts');
227
- expect(key).toEqual({ KeyValuePairs: [{ FieldName: 'OrgID', Value: 42 }, { FieldName: 'Region', Value: 'EMEA' }] });
228
- expect(accountEntity.Set).toHaveBeenCalledWith('EnrichedAt', expect.any(Date));
360
+ it('stamps an account Apollo has no organization for, with its real (composite) key', async () => {
361
+ world.define(entityDef('Accounts', ['OrgID', 'Region'], [{ Name: 'Domain' }, { Name: 'EnrichedAt' }]), [{ OrgID: 42, Region: 'EMEA', Domain: 'example.com' }]);
362
+ const action = accountsAction({ EnrichOrganization: vi.fn(async () => null) }, {});
363
+ const result = await runAccounts(action, world);
364
+ expect(result.ResultCode).toBe('SUCCESS');
365
+ expect(world.savedFor('Accounts')[0].Values).toMatchObject({ OrgID: 42, Region: 'EMEA', EnrichedAt: expect.any(Date) });
229
366
  });
230
- });
231
- describe('ApolloEnrichmentContactsAction primary-key handling', () => {
232
- const employment = { organization_name: 'Acme', title: 'Engineer', current: true, start_date: null, end_date: null, degree: null };
233
- const baseParams = {
234
- EmploymentHistoryEntityName: 'Employment History',
235
- EmploymentHistoryContactIDFieldName: 'ContactKey',
236
- EmploymentHistoryOrganizationFieldName: 'Organization',
237
- EmploymentHistoryTitleFieldName: 'Title',
238
- CurrentUser: {},
239
- };
240
- it("filters history by the contact's real primary key value and column type, not a literal ID", async () => {
241
- const action = new ApolloEnrichmentContactsAction();
242
- const runView = vi.fn().mockResolvedValue({ Success: true, Results: [] });
243
- const { RunView } = await import('@memberjunction/core');
244
- RunView.mockImplementation(function () { return { RunView: runView }; });
245
- const historyEntity = { NewRecord: vi.fn(), Set: vi.fn(), Save: vi.fn().mockResolvedValue(true), LatestResult: null };
246
- const params = { ...baseParams, Md: { GetEntityObject: vi.fn().mockResolvedValue(historyEntity), EntityByName: vi.fn() } };
247
- const contactEntity = {
248
- PrimaryKeys: [{ Name: 'individual_id' }],
249
- FirstPrimaryKey: { Name: 'individual_id', Value: 9001, NeedsQuotes: false },
250
- EntityInfo: { Name: 'Contacts' },
251
- Get: vi.fn(() => { throw new Error('Get("ID") must not be used for the contact key'); }),
252
- };
253
- await action.UpsertContactEmploymentAndEducationHistory({ employment_history: [employment] }, contactEntity, params);
254
- expect(runView).toHaveBeenCalledTimes(1);
255
- expect(runView.mock.calls[0][0].ExtraFilter).toContain('ContactKey = 9001');
256
- expect(historyEntity.Set).toHaveBeenCalledWith('ContactKey', 9001);
367
+ it('FieldPredicate quotes per the column type: UUID and string keys quoted, integer keys bare', () => {
368
+ const md = { EntityByName: () => ({ Fields: [{ Name: 'AccountID', NeedsQuotes: true }, { Name: 'ContactID', NeedsQuotes: false }] }) };
369
+ expect(FieldPredicate(md, 'X', 'AccountID', "6F9619FF-8B86-D011-B42D-00C04FC964FF")).toBe("[AccountID] = '6F9619FF-8B86-D011-B42D-00C04FC964FF'");
370
+ expect(FieldPredicate(md, 'X', 'ContactID', 9001)).toBe('[ContactID] = 9001');
371
+ expect(FieldPredicate(md, 'X', 'AccountID', "o'k", '<>')).toBe("[AccountID] <> 'o''k'");
257
372
  });
258
- it('refuses to build a single-column FK filter for a composite-keyed contact entity', async () => {
259
- const action = new ApolloEnrichmentContactsAction();
260
- const runView = vi.fn();
261
- const { RunView, LogError } = await import('@memberjunction/core');
262
- RunView.mockImplementation(function () { return { RunView: runView }; });
263
- const params = { ...baseParams, Md: { GetEntityObject: vi.fn(), EntityByName: vi.fn() } };
264
- const contactEntity = {
265
- PrimaryKeys: [{ Name: 'OrgID' }, { Name: 'PersonNo' }],
266
- FirstPrimaryKey: { Name: 'OrgID', Value: 1, NeedsQuotes: false },
267
- EntityInfo: { Name: 'Org People' },
268
- };
269
- await action.UpsertContactEmploymentAndEducationHistory({ employment_history: [employment] }, contactEntity, params);
270
- expect(runView).not.toHaveBeenCalled();
271
- expect(params.Md.GetEntityObject).not.toHaveBeenCalled();
272
- expect(LogError).toHaveBeenCalledWith(expect.stringContaining('composite primary key'));
373
+ it('IsExcludedTitle and IsValidDate keep their behaviour', () => {
374
+ const action = new ApolloEnrichmentAccountsAction();
375
+ expect(action.IsExcludedTitle(' Student ')).toBe(true);
376
+ expect(action.IsExcludedTitle('CEO')).toBe(false);
377
+ expect(action.IsValidDate('2024-01-15')).toBe(true);
378
+ expect(action.IsValidDate('not-a-date')).toBe(false);
273
379
  });
274
380
  });
275
381
  //# sourceMappingURL=apollo-enrichment.test.js.map