@app-connect/core 1.7.35 → 1.7.37

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 (48) hide show
  1. package/connector/mock.js +9 -4
  2. package/connector/proxy/engine.js +3 -2
  3. package/connector/proxy/index.js +2 -2
  4. package/docs/architecture.md +1 -0
  5. package/docs/handlers.md +1 -1
  6. package/docs/models.md +2 -0
  7. package/docs/routes.md +1 -1
  8. package/handlers/disposition.js +3 -2
  9. package/handlers/log.js +16 -6
  10. package/handlers/plugin.js +13 -6
  11. package/index.js +19 -4
  12. package/lib/callLogLookup.js +82 -9
  13. package/lib/migrateCallLogsSchema.js +315 -7
  14. package/models/callLogModel.js +6 -0
  15. package/package.json +1 -1
  16. package/releaseNotes.json +20 -0
  17. package/test/connector/developerPortal.test.js +166 -0
  18. package/test/connector/mock.test.js +131 -0
  19. package/test/connector/proxy/engine.test.js +85 -0
  20. package/test/connector/proxy/index.test.js +246 -0
  21. package/test/connector/proxy/sample.json +1 -0
  22. package/test/handlers/admin.test.js +344 -0
  23. package/test/handlers/appointment.test.js +260 -0
  24. package/test/handlers/calldown.test.js +310 -0
  25. package/test/handlers/disposition.test.js +396 -0
  26. package/test/handlers/log.test.js +324 -1
  27. package/test/handlers/managedOAuth.test.js +262 -0
  28. package/test/handlers/plugin.test.js +305 -0
  29. package/test/handlers/user.test.js +381 -0
  30. package/test/index.test.js +102 -0
  31. package/test/lib/analytics.test.js +146 -0
  32. package/test/lib/authSession.test.js +173 -0
  33. package/test/lib/encode.test.js +59 -0
  34. package/test/lib/errorHandler.test.js +246 -0
  35. package/test/lib/generalErrorMessage.test.js +82 -0
  36. package/test/lib/s3ErrorLogReport.test.js +187 -0
  37. package/test/mcp/mcpHandlerMore.test.js +384 -0
  38. package/test/mcp/tools/appointmentTools.test.js +362 -0
  39. package/test/models/callDownListModel.test.js +125 -0
  40. package/test/models/dynamo/lockSchema.test.js +37 -0
  41. package/test/models/dynamo/noteCacheSchema.test.js +45 -0
  42. package/test/models/llmSessionModel.test.js +91 -0
  43. package/test/models/models.test.js +92 -0
  44. package/test/routes/calldownRoutes.test.js +224 -0
  45. package/test/routes/coreRouterBroadRoutes.test.js +855 -0
  46. package/test/routes/dispositionRoutes.test.js +192 -0
  47. package/test/routes/managedAuthRoutes.test.js +151 -0
  48. package/test/routes/pluginRoutes.test.js +262 -0
@@ -16,6 +16,7 @@ const { CacheModel } = require('../../models/cacheModel');
16
16
  const { AccountDataModel } = require('../../models/accountDataModel');
17
17
  const axios = require('axios');
18
18
  const { sequelize } = require('../../models/sequelize');
19
+ const logger = require('../../lib/logger');
19
20
 
20
21
  describe('Plugin Handler', () => {
21
22
  beforeAll(async () => {
@@ -28,6 +29,7 @@ describe('Plugin Handler', () => {
28
29
  await CacheModel.destroy({ where: {} });
29
30
  await AccountDataModel.destroy({ where: {} });
30
31
  jest.clearAllMocks();
32
+ jest.restoreAllMocks();
31
33
  });
32
34
 
33
35
  afterAll(async () => {
@@ -108,8 +110,302 @@ describe('Plugin Handler', () => {
108
110
  pluginName: 'plugin.sample'
109
111
  })).rejects.toThrow('Plugin register API did not return jwtToken');
110
112
  });
113
+
114
+ test('should throw when resolved plugin manifest has no endpoint URL', async () => {
115
+ axios.get.mockResolvedValue({
116
+ data: {
117
+ platforms: {
118
+ 'plugin.sample': {
119
+ userRegisterEndpointUrl: 'https://plugins.example.com/plugin/auth/register'
120
+ }
121
+ }
122
+ }
123
+ });
124
+
125
+ await expect(pluginHandler.registerPluginAccount({
126
+ pluginId: 'missing-endpoint',
127
+ rcAccessToken: 'rc-access-token',
128
+ rcAccountId: '12345',
129
+ pluginAccess: 'public',
130
+ pluginName: 'plugin.sample'
131
+ })).rejects.toThrow('Plugin endpoint URL not found for missing-endpoint');
132
+ });
111
133
  });
112
134
 
135
+ describe('plugin data helpers', () => {
136
+ test('should list persisted plugin data for an RC account', async () => {
137
+ await AccountDataModel.bulkCreate([
138
+ {
139
+ rcAccountId: '12345',
140
+ platformName: 'plugin-one',
141
+ dataKey: 'pluginData',
142
+ data: { endpointUrl: 'https://plugin-one.example.com' }
143
+ },
144
+ {
145
+ rcAccountId: '12345',
146
+ platformName: 'plugin-two',
147
+ dataKey: 'pluginData',
148
+ data: { endpointUrl: 'https://plugin-two.example.com' }
149
+ },
150
+ {
151
+ rcAccountId: '12345',
152
+ platformName: 'not-plugin',
153
+ dataKey: 'otherData',
154
+ data: { ignored: true }
155
+ }
156
+ ]);
157
+
158
+ await expect(pluginHandler.getPluginsFromRcAccountId({ rcAccountId: '12345' }))
159
+ .resolves.toEqual([
160
+ { id: 'plugin-one', data: { endpointUrl: 'https://plugin-one.example.com' } },
161
+ { id: 'plugin-two', data: { endpointUrl: 'https://plugin-two.example.com' } }
162
+ ]);
163
+ });
164
+
165
+ test('should resolve plugin config from user settings and return null for missing config', () => {
166
+ expect(pluginHandler.getPluginConfigFromUserSettings({
167
+ userSettings: null,
168
+ pluginId: 'plugin-one'
169
+ })).toBeNull();
170
+ expect(pluginHandler.getPluginConfigFromUserSettings({
171
+ userSettings: {
172
+ 'plugin_plugin-one': {
173
+ value: {}
174
+ }
175
+ },
176
+ pluginId: 'plugin-one'
177
+ })).toBeNull();
178
+ expect(pluginHandler.getPluginConfigFromUserSettings({
179
+ userSettings: {
180
+ 'plugin_plugin-one': {
181
+ value: {
182
+ config: {
183
+ queueId: 'q-1'
184
+ }
185
+ }
186
+ }
187
+ },
188
+ pluginId: 'plugin-one'
189
+ })).toEqual({ queueId: 'q-1' });
190
+ });
191
+
192
+ test('should update existing plugin data and log persist failures without throwing', async () => {
193
+ await AccountDataModel.create({
194
+ rcAccountId: '12345',
195
+ platformName: 'plugin-one',
196
+ dataKey: 'pluginData',
197
+ data: {
198
+ jwtToken: 'old-token',
199
+ endpointUrl: 'https://old.example.com'
200
+ }
201
+ });
202
+
203
+ await pluginHandler.persistPluginData({
204
+ rcAccountId: '12345',
205
+ pluginId: 'plugin-one',
206
+ jwtToken: 'new-token',
207
+ pluginData: {
208
+ endpointUrl: 'https://new.example.com'
209
+ }
210
+ });
211
+
212
+ const updated = await AccountDataModel.findOne({
213
+ where: {
214
+ rcAccountId: '12345',
215
+ platformName: 'plugin-one'
216
+ }
217
+ });
218
+ expect(updated.data).toEqual({
219
+ jwtToken: 'new-token',
220
+ endpointUrl: 'https://new.example.com'
221
+ });
222
+
223
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => {});
224
+ jest.spyOn(AccountDataModel, 'findOne').mockRejectedValueOnce(new Error('db unavailable'));
225
+ await expect(pluginHandler.persistPluginData({
226
+ rcAccountId: '12345',
227
+ pluginId: 'plugin-one',
228
+ jwtToken: 'ignored'
229
+ })).resolves.toBeUndefined();
230
+ expect(errorSpy).toHaveBeenCalledWith('Failed to persist plugin data', {
231
+ pluginId: 'plugin-one',
232
+ rcAccountId: '12345',
233
+ message: 'db unavailable'
234
+ });
235
+ });
236
+ });
237
+
238
+ describe('resolvePluginManifest', () => {
239
+ test('should load private manifests with owner account id and infer the platform key', async () => {
240
+ axios.get.mockResolvedValue({
241
+ data: {
242
+ platforms: {
243
+ 'plugin.private': {
244
+ endpointUrl: 'https://plugins.example.com/private',
245
+ userRegisterEndpointUrl: 'https://plugins.example.com/private/register'
246
+ }
247
+ }
248
+ }
249
+ });
250
+
251
+ const result = await pluginHandler.resolvePluginManifest({
252
+ pluginId: 'private-plugin',
253
+ pluginAccess: 'private',
254
+ ownerRcAccountId: 'owner-account'
255
+ });
256
+
257
+ expect(axios.get).toHaveBeenCalledWith(
258
+ 'https://appconnect.labs.ringcentral.com/public-api/connectors/private-plugin/manifest?access=internal&type=plugin&accountId=owner-account'
259
+ );
260
+ expect(result.platformKey).toBe('plugin.private');
261
+ expect(result.pluginManifest.endpointUrl).toBe('https://plugins.example.com/private');
262
+ });
263
+
264
+ test('should fall back from public to internal manifest when access is unspecified', async () => {
265
+ axios.get
266
+ .mockRejectedValueOnce(new Error('public missing'))
267
+ .mockResolvedValueOnce({
268
+ data: {
269
+ platforms: {
270
+ 'plugin.shared': {
271
+ endpointUrl: 'https://plugins.example.com/shared'
272
+ }
273
+ }
274
+ }
275
+ });
276
+
277
+ const result = await pluginHandler.resolvePluginManifest({
278
+ pluginId: 'shared-plugin',
279
+ ownerRcAccountId: 'owner-account'
280
+ });
281
+
282
+ expect(axios.get).toHaveBeenCalledTimes(2);
283
+ expect(axios.get.mock.calls[0][0]).toBe(
284
+ 'https://appconnect.labs.ringcentral.com/public-api/connectors/shared-plugin/manifest?type=plugin'
285
+ );
286
+ expect(axios.get.mock.calls[1][0]).toBe(
287
+ 'https://appconnect.labs.ringcentral.com/public-api/connectors/shared-plugin/manifest?access=internal&type=plugin&accountId=owner-account'
288
+ );
289
+ expect(result.platformKey).toBe('plugin.shared');
290
+ });
291
+
292
+ test('should throw the last manifest fetch error or platform resolution error', async () => {
293
+ axios.get.mockRejectedValueOnce(new Error('manifest unavailable'));
294
+
295
+ await expect(pluginHandler.resolvePluginManifest({
296
+ pluginId: 'missing-plugin',
297
+ pluginAccess: 'public'
298
+ })).rejects.toThrow('manifest unavailable');
299
+
300
+ axios.get.mockResolvedValueOnce({
301
+ data: {
302
+ platforms: {}
303
+ }
304
+ });
305
+ await expect(pluginHandler.resolvePluginManifest({
306
+ pluginId: 'empty-plugin',
307
+ pluginAccess: 'public',
308
+ pluginName: 'plugin.missing'
309
+ })).rejects.toThrow('Unable to resolve platform manifest for plugin empty-plugin');
310
+ });
311
+ });
312
+
313
+ describe('getPluginLicenseStatus', () => {
314
+ test('should return null and skip provider call when plugin account data is missing', async () => {
315
+ const result = await pluginHandler.getPluginLicenseStatus({
316
+ rcAccountId: '12345',
317
+ pluginId: 'sync-all-caps'
318
+ });
319
+
320
+ expect(result).toBeNull();
321
+ expect(axios.get).not.toHaveBeenCalled();
322
+ });
323
+
324
+ test('should call plugin license status endpoint with stored plugin bearer token', async () => {
325
+ const rcAccountId = '12345';
326
+ const pluginId = 'sync-all-caps';
327
+ await AccountDataModel.create({
328
+ rcAccountId,
329
+ platformName: pluginId,
330
+ dataKey: 'pluginData',
331
+ data: {
332
+ jwtToken: 'plugin-jwt-token',
333
+ licenseStatusUrl: `https://plugins.example.com/plugin/${pluginId}/license`
334
+ }
335
+ });
336
+ axios.get.mockResolvedValue({
337
+ data: {
338
+ licenseStatus: true,
339
+ licenseStatusDescription: 'Active'
340
+ }
341
+ });
342
+
343
+ const result = await pluginHandler.getPluginLicenseStatus({ rcAccountId, pluginId });
344
+
345
+ expect(axios.get).toHaveBeenCalledWith(
346
+ `https://plugins.example.com/plugin/${pluginId}/license`,
347
+ {
348
+ headers: {
349
+ Authorization: 'Bearer plugin-jwt-token'
350
+ }
351
+ }
352
+ );
353
+ expect(result).toEqual({
354
+ licenseStatus: true,
355
+ licenseStatusDescription: 'Active'
356
+ });
357
+ });
358
+ test('should normalize non-standard plugin license provider responses to invalid status', async () => {
359
+ const rcAccountId = '12345';
360
+ const pluginId = 'sync-all-caps';
361
+ await AccountDataModel.create({
362
+ rcAccountId,
363
+ platformName: pluginId,
364
+ dataKey: 'pluginData',
365
+ data: {
366
+ jwtToken: 'plugin-jwt-token',
367
+ licenseStatusUrl: `https://plugins.example.com/plugin/${pluginId}/license`
368
+ }
369
+ });
370
+ axios.get.mockResolvedValue({
371
+ data: {
372
+ message: 'temporary unavailable'
373
+ }
374
+ });
375
+
376
+ const result = await pluginHandler.getPluginLicenseStatus({ rcAccountId, pluginId });
377
+
378
+ expect(result).toEqual({
379
+ licenseStatus: false,
380
+ licenseStatusDescription: 'Plugin license status unavailable'
381
+ });
382
+ });
383
+ });
384
+ describe('unregisterPluginAccount', () => {
385
+ test('should remove persisted plugin account data', async () => {
386
+ const rcAccountId = '12345';
387
+ const pluginId = 'sync-all-caps';
388
+ await AccountDataModel.create({
389
+ rcAccountId,
390
+ platformName: pluginId,
391
+ dataKey: 'pluginData',
392
+ data: {
393
+ jwtToken: 'plugin-jwt-token'
394
+ }
395
+ });
396
+
397
+ await pluginHandler.unregisterPluginAccount({ rcAccountId, pluginId });
398
+
399
+ const accountData = await AccountDataModel.findOne({
400
+ where: {
401
+ rcAccountId,
402
+ platformName: pluginId,
403
+ dataKey: 'pluginData'
404
+ }
405
+ });
406
+ expect(accountData).toBeNull();
407
+ });
408
+ });
113
409
  describe('token header helper', () => {
114
410
  test('should parse refreshed jwt token from response headers', () => {
115
411
  const token = pluginHandler.getRefreshedJwtTokenFromHeaders({
@@ -119,6 +415,15 @@ describe('Plugin Handler', () => {
119
415
  });
120
416
  expect(token).toBe('new-plugin-token');
121
417
  });
418
+
419
+ test('should parse uppercase refreshed jwt token header and return null without headers', () => {
420
+ expect(pluginHandler.getRefreshedJwtTokenFromHeaders({ headers: null })).toBeNull();
421
+ expect(pluginHandler.getRefreshedJwtTokenFromHeaders({
422
+ headers: {
423
+ 'X-Refreshed-Jwt-Token': 'upper-token'
424
+ }
425
+ })).toBe('upper-token');
426
+ });
122
427
  });
123
428
  });
124
429
 
@@ -0,0 +1,381 @@
1
+ jest.mock('axios');
2
+ jest.mock('../../models/adminConfigModel', () => ({
3
+ AdminConfigModel: {
4
+ findByPk: jest.fn()
5
+ }
6
+ }));
7
+ jest.mock('../../models/userModel', () => ({
8
+ UserModel: {
9
+ findOne: jest.fn()
10
+ }
11
+ }));
12
+ jest.mock('../../connector/registry', () => ({
13
+ getConnector: jest.fn()
14
+ }));
15
+ jest.mock('../../lib/oauth', () => ({
16
+ getOAuthApp: jest.fn(() => ({ app: true })),
17
+ checkAndRefreshAccessToken: jest.fn()
18
+ }));
19
+ jest.mock('../../lib/util', () => ({
20
+ getHashValue: jest.fn((value) => `hash-${value}`)
21
+ }));
22
+ jest.mock('../../models/dynamo/connectorSchema', () => ({
23
+ Connector: {
24
+ getProxyConfig: jest.fn()
25
+ }
26
+ }));
27
+
28
+ const axios = require('axios');
29
+ const userHandler = require('../../handlers/user');
30
+ const { AdminConfigModel } = require('../../models/adminConfigModel');
31
+ const { UserModel } = require('../../models/userModel');
32
+ const connectorRegistry = require('../../connector/registry');
33
+ const oauth = require('../../lib/oauth');
34
+ const { Connector } = require('../../models/dynamo/connectorSchema');
35
+
36
+ describe('User Handler', () => {
37
+ beforeEach(() => {
38
+ jest.clearAllMocks();
39
+ process.env.HASH_KEY = 'hash-key';
40
+ });
41
+
42
+ test('refreshUserInfo returns warning when user is missing or has no access token', async () => {
43
+ UserModel.findOne.mockResolvedValueOnce(null);
44
+
45
+ await expect(userHandler.refreshUserInfo({
46
+ platform: 'testCRM',
47
+ userId: 'user-1'
48
+ })).resolves.toMatchObject({
49
+ successful: false,
50
+ returnMessage: {
51
+ message: 'User not found',
52
+ messageType: 'warning'
53
+ }
54
+ });
55
+
56
+ UserModel.findOne.mockResolvedValueOnce({ id: 'user-2' });
57
+ const noTokenResult = await userHandler.refreshUserInfo({
58
+ platform: 'testCRM',
59
+ userId: 'user-2'
60
+ });
61
+
62
+ expect(noTokenResult.returnMessage.message).toBe('User not found');
63
+ });
64
+
65
+ test('refreshUserInfo handles oauth proxy config and expired refreshed session', async () => {
66
+ const user = {
67
+ id: 'user-1',
68
+ hostname: 'crm.example.com',
69
+ accessToken: 'expired-token',
70
+ platformAdditionalInfo: {
71
+ proxyId: 'proxy-1',
72
+ tokenUrl: 'https://token.example.com'
73
+ }
74
+ };
75
+ const platformModule = {
76
+ getAuthType: jest.fn().mockResolvedValue('oauth'),
77
+ getOauthInfo: jest.fn().mockResolvedValue({ tokenUrl: 'https://token.example.com' })
78
+ };
79
+ UserModel.findOne.mockResolvedValue(user);
80
+ Connector.getProxyConfig.mockResolvedValue({ id: 'proxy-1' });
81
+ connectorRegistry.getConnector.mockReturnValue(platformModule);
82
+ oauth.checkAndRefreshAccessToken.mockResolvedValue(null);
83
+
84
+ const result = await userHandler.refreshUserInfo({
85
+ platform: 'testCRM',
86
+ userId: 'user-1',
87
+ tracer: {
88
+ trace: jest.fn(),
89
+ traceError: jest.fn()
90
+ }
91
+ });
92
+
93
+ expect(platformModule.getOauthInfo).toHaveBeenCalledWith({
94
+ tokenUrl: 'https://token.example.com',
95
+ hostname: 'crm.example.com',
96
+ proxyId: 'proxy-1',
97
+ proxyConfig: { id: 'proxy-1' }
98
+ });
99
+ expect(result).toMatchObject({
100
+ successful: false,
101
+ isRevokeUserSession: true,
102
+ returnMessage: {
103
+ message: 'User session expired. Please connect again.'
104
+ }
105
+ });
106
+ });
107
+
108
+ test('refreshUserInfo supports apiKey auth and maps platform result', async () => {
109
+ const user = {
110
+ id: 'user-1',
111
+ hostname: 'crm.example.com',
112
+ accessToken: 'api-key',
113
+ platformAdditionalInfo: {}
114
+ };
115
+ const platformModule = {
116
+ getAuthType: jest.fn().mockResolvedValue('apiKey'),
117
+ getBasicAuth: jest.fn(() => 'encoded-key'),
118
+ refreshUserInfo: jest.fn().mockResolvedValue({
119
+ successful: true,
120
+ returnMessage: {
121
+ messageType: 'success',
122
+ message: 'Refreshed'
123
+ }
124
+ })
125
+ };
126
+ UserModel.findOne.mockResolvedValue(user);
127
+ connectorRegistry.getConnector.mockReturnValue(platformModule);
128
+
129
+ const result = await userHandler.refreshUserInfo({
130
+ platform: 'testCRM',
131
+ userId: 'user-1'
132
+ });
133
+
134
+ expect(platformModule.refreshUserInfo).toHaveBeenCalledWith({
135
+ user,
136
+ authHeader: 'Basic encoded-key',
137
+ proxyConfig: null
138
+ });
139
+ expect(result.successful).toBe(true);
140
+ });
141
+
142
+ test('refreshUserInfo maps unexpected errors through API error handler', async () => {
143
+ UserModel.findOne.mockRejectedValueOnce(new Error('database unavailable'));
144
+
145
+ const result = await userHandler.refreshUserInfo({
146
+ platform: 'testCRM',
147
+ userId: 'user-1'
148
+ });
149
+
150
+ expect(result.successful).toBe(false);
151
+ expect(result.returnMessage.messageType).toBe('warning');
152
+ });
153
+
154
+ test('getUserSettingsByAdmin resolves account from explicit account id or RC token', async () => {
155
+ AdminConfigModel.findByPk.mockResolvedValueOnce({
156
+ userSettings: {
157
+ theme: { value: 'dark' }
158
+ }
159
+ });
160
+
161
+ await expect(userHandler.getUserSettingsByAdmin({
162
+ rcAccountId: 'hashed-account'
163
+ })).resolves.toEqual({
164
+ userSettings: {
165
+ theme: { value: 'dark' }
166
+ }
167
+ });
168
+ expect(AdminConfigModel.findByPk).toHaveBeenCalledWith('hashed-account');
169
+
170
+ axios.get.mockResolvedValueOnce({
171
+ data: {
172
+ account: {
173
+ id: 'rc-account-1'
174
+ }
175
+ }
176
+ });
177
+ AdminConfigModel.findByPk.mockResolvedValueOnce({
178
+ userSettings: {
179
+ language: { value: 'en' }
180
+ }
181
+ });
182
+
183
+ const result = await userHandler.getUserSettingsByAdmin({
184
+ rcAccessToken: 'rc-token'
185
+ });
186
+
187
+ expect(axios.get).toHaveBeenCalledWith(
188
+ 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
189
+ {
190
+ headers: {
191
+ Authorization: 'Bearer rc-token'
192
+ }
193
+ }
194
+ );
195
+ expect(AdminConfigModel.findByPk).toHaveBeenLastCalledWith('hash-rc-account-1');
196
+ expect(result.userSettings.language.value).toBe('en');
197
+ });
198
+
199
+ test('getUserSettings merges admin defaults, user overrides, removed keys, and plugin config rules', async () => {
200
+ AdminConfigModel.findByPk.mockResolvedValueOnce({
201
+ userSettings: {
202
+ removedSetting: { isRemoved: true, value: 'hidden' },
203
+ adminOnly: { value: 'admin-only', customizable: false },
204
+ userEditable: { value: 'admin-default', customizable: true },
205
+ plugin_sample: {
206
+ customizable: true,
207
+ value: {
208
+ config: {
209
+ locked: { value: 'admin-locked', customizable: false },
210
+ fillsEmpty: { value: 'admin-fill', customizable: true },
211
+ staysUserEditable: { value: 'admin-stay', customizable: true }
212
+ }
213
+ }
214
+ },
215
+ plugin_empty: {
216
+ customizable: true,
217
+ value: {
218
+ config: {
219
+ adminProvided: { value: 'admin-provided', customizable: true }
220
+ }
221
+ }
222
+ },
223
+ plugin_deleted: {
224
+ customizable: true,
225
+ value: {
226
+ config: null
227
+ }
228
+ }
229
+ }
230
+ });
231
+
232
+ const result = await userHandler.getUserSettings({
233
+ user: {
234
+ userSettings: {
235
+ removedSetting: { value: 'user-hidden' },
236
+ userEditable: { value: 'user-value', defaultValue: 'user-default', options: ['a'] },
237
+ userOnly: { value: 'user-only' },
238
+ plugin_sample: {
239
+ value: {
240
+ config: {
241
+ locked: { value: 'user-locked', customizable: true },
242
+ fillsEmpty: { value: '', customizable: true },
243
+ staysUserEditable: { value: 'user-stay', customizable: true }
244
+ }
245
+ }
246
+ },
247
+ plugin_empty: {
248
+ value: {
249
+ config: {}
250
+ }
251
+ },
252
+ plugin_deleted: {
253
+ value: {
254
+ config: {}
255
+ }
256
+ }
257
+ }
258
+ },
259
+ rcAccountId: 'hashed-account'
260
+ });
261
+
262
+ expect(result.removedSetting).toBeUndefined();
263
+ expect(result.adminOnly.value).toBe('admin-only');
264
+ expect(result.userOnly.value).toBe('user-only');
265
+ expect(result.userEditable).toEqual({
266
+ customizable: true,
267
+ value: 'user-value',
268
+ defaultValue: 'user-default',
269
+ options: ['a']
270
+ });
271
+ expect(result.plugin_sample.value.config.locked.value).toBe('admin-locked');
272
+ expect(result.plugin_sample.value.config.fillsEmpty.value).toBe('admin-fill');
273
+ expect(result.plugin_sample.value.config.staysUserEditable).toMatchObject({
274
+ value: 'user-stay',
275
+ customizable: true
276
+ });
277
+ expect(result.plugin_empty.value.config.adminProvided.value).toBe('admin-provided');
278
+ expect(result.plugin_deleted).toBeUndefined();
279
+ });
280
+
281
+ test('getUserSettings falls back to user settings when admin lookup fails', async () => {
282
+ AdminConfigModel.findByPk.mockRejectedValueOnce(new Error('admin settings unavailable'));
283
+
284
+ const result = await userHandler.getUserSettings({
285
+ user: {
286
+ userSettings: {
287
+ localOnly: { value: 'local' }
288
+ }
289
+ },
290
+ rcAccountId: 'hashed-account'
291
+ });
292
+
293
+ expect(result).toEqual({
294
+ localOnly: { value: 'local' }
295
+ });
296
+ });
297
+
298
+ test('updateUserSettings supports connector hooks, removals, and database error mapping', async () => {
299
+ const user = {
300
+ userSettings: {
301
+ oldKey: { value: 'old' },
302
+ removeMe: { value: 'remove' }
303
+ },
304
+ update: jest.fn().mockImplementation(async function update(values) {
305
+ user.userSettings = values.userSettings;
306
+ })
307
+ };
308
+
309
+ connectorRegistry.getConnector.mockReturnValueOnce({});
310
+ const defaultResult = await userHandler.updateUserSettings({
311
+ user,
312
+ userSettings: {
313
+ newKey: { value: 'new' }
314
+ },
315
+ settingKeysToRemove: ['removeMe'],
316
+ platformName: 'testCRM'
317
+ });
318
+
319
+ expect(defaultResult.userSettings).toEqual({
320
+ oldKey: { value: 'old' },
321
+ newKey: { value: 'new' }
322
+ });
323
+ expect(user.update).toHaveBeenCalledWith({
324
+ userSettings: {
325
+ oldKey: { value: 'old' },
326
+ newKey: { value: 'new' }
327
+ }
328
+ });
329
+
330
+ const hookUser = {
331
+ userSettings: {},
332
+ update: jest.fn()
333
+ };
334
+ connectorRegistry.getConnector.mockReturnValueOnce({
335
+ onUpdateUserSettings: jest.fn().mockResolvedValue({
336
+ successful: false,
337
+ returnMessage: {
338
+ messageType: 'warning',
339
+ message: 'Rejected by connector'
340
+ }
341
+ })
342
+ });
343
+ const rejectedResult = await userHandler.updateUserSettings({
344
+ user: hookUser,
345
+ userSettings: {
346
+ key: { value: 'value' }
347
+ },
348
+ settingKeysToRemove: [],
349
+ platformName: 'testCRM'
350
+ });
351
+
352
+ expect(rejectedResult.successful).toBe(false);
353
+ expect(hookUser.update).not.toHaveBeenCalled();
354
+
355
+ const failingUser = {
356
+ userSettings: {},
357
+ update: jest.fn().mockRejectedValue(new Error('write failed'))
358
+ };
359
+ connectorRegistry.getConnector.mockReturnValueOnce({
360
+ onUpdateUserSettings: jest.fn().mockResolvedValue({
361
+ successful: true,
362
+ returnMessage: {
363
+ messageType: 'success',
364
+ message: 'Allowed'
365
+ }
366
+ })
367
+ });
368
+
369
+ const failedUpdateResult = await userHandler.updateUserSettings({
370
+ user: failingUser,
371
+ userSettings: {
372
+ key: { value: 'value' }
373
+ },
374
+ settingKeysToRemove: [],
375
+ platformName: 'testCRM'
376
+ });
377
+
378
+ expect(failedUpdateResult.successful).toBe(false);
379
+ expect(failedUpdateResult.returnMessage.messageType).toBe('warning');
380
+ });
381
+ });