cordova-plugin-unvired-universal-sdk 1.0.1

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 (82) hide show
  1. package/README.md +59 -0
  2. package/aar/README.md +3 -0
  3. package/aar/Unvired_Kernel_Android.aar +0 -0
  4. package/aar/Unvired_Kernel_HTML5_Android.aar +0 -0
  5. package/package.json +69 -0
  6. package/plugin.xml +23 -0
  7. package/src/android/build.gradle +35 -0
  8. package/src/android/xml/provider_paths.xml +21 -0
  9. package/src/browser/UnviredPluginProxy.js +2430 -0
  10. package/src/browser/bootstrap.min.js +17 -0
  11. package/src/browser/codemirror.js +9755 -0
  12. package/src/browser/jquery-3.2.1.js +10253 -0
  13. package/src/browser/sql-wasm.wasm +0 -0
  14. package/src/browser/sql.js +203 -0
  15. package/src/browser/src_index_worker_js.unvired-db-worker.js +231 -0
  16. package/src/browser/unvired-db-worker.js +166 -0
  17. package/src/browser/vendors-node_modules_comlink_dist_esm_comlink_mjs.unvired-db-worker.js +22 -0
  18. package/src/ios/AttachmentPlugin.h +21 -0
  19. package/src/ios/AttachmentPlugin.m +180 -0
  20. package/src/ios/DataStructureHelper.h +28 -0
  21. package/src/ios/DataStructureHelper.m +188 -0
  22. package/src/ios/IOSAuthPlugin.h +14 -0
  23. package/src/ios/IOSAuthPlugin.m +13 -0
  24. package/src/ios/IOSDatabasePlugin.h +28 -0
  25. package/src/ios/IOSDatabasePlugin.m +253 -0
  26. package/src/ios/IOSFWSettingsPlugin.h +65 -0
  27. package/src/ios/IOSFWSettingsPlugin.m +363 -0
  28. package/src/ios/IOSLoggerPlugin.h +34 -0
  29. package/src/ios/IOSLoggerPlugin.m +198 -0
  30. package/src/ios/IOSLoginPlugin.h +29 -0
  31. package/src/ios/IOSLoginPlugin.m +480 -0
  32. package/src/ios/IOSProxyPlugin.h +21 -0
  33. package/src/ios/IOSProxyPlugin.m +172 -0
  34. package/src/ios/IOSSyncEnginePlugin.h +54 -0
  35. package/src/ios/IOSSyncEnginePlugin.m +847 -0
  36. package/src/ios/PluginConstants.h +195 -0
  37. package/src/ios/PluginHelper.h +29 -0
  38. package/src/ios/PluginHelper.m +74 -0
  39. package/src/ios/SyncHTML5Response.h +50 -0
  40. package/src/ios/SyncHTML5Response.m +68 -0
  41. package/www/applicationMeta/applicationMetadataParser.ts +285 -0
  42. package/www/applicationMeta/fieldConstants.ts +92 -0
  43. package/www/attachment/attachmentHelper.ts +326 -0
  44. package/www/attachment/attachmentQHelper.ts +158 -0
  45. package/www/attachment/attachmentService.ts +259 -0
  46. package/www/authenticationService.ts +746 -0
  47. package/www/bootstrap.min.js +17 -0
  48. package/www/codemirror.js +9755 -0
  49. package/www/database/appDatabaseManager.ts +54 -0
  50. package/www/database/databaseManager.ts +616 -0
  51. package/www/helper/dbCreateTablesManager.ts +354 -0
  52. package/www/helper/frameworkHelper.ts +127 -0
  53. package/www/helper/frameworkSettingsManager.ts +287 -0
  54. package/www/helper/getMessageTimerManager.ts +81 -0
  55. package/www/helper/httpConnection.ts +1051 -0
  56. package/www/helper/logger.ts +312 -0
  57. package/www/helper/notificationListnerHelper.ts +56 -0
  58. package/www/helper/passcodeGenerator.ts +61 -0
  59. package/www/helper/reconciler.ts +1062 -0
  60. package/www/helper/serverResponseHandler.ts +677 -0
  61. package/www/helper/serviceConstants.ts +254 -0
  62. package/www/helper/settingsHelper.ts +386 -0
  63. package/www/helper/status.ts +83 -0
  64. package/www/helper/syncInputDataManager.ts +205 -0
  65. package/www/helper/unviredAccount.ts +104 -0
  66. package/www/helper/unviredAccountManager.ts +120 -0
  67. package/www/helper/urlService.ts +43 -0
  68. package/www/helper/userSettingsManager.ts +172 -0
  69. package/www/helper/utils.ts +110 -0
  70. package/www/inbox/downloadMessageService.ts +270 -0
  71. package/www/inbox/inboxHelper.ts +132 -0
  72. package/www/inbox/inboxService.ts +223 -0
  73. package/www/jquery-3.2.1.js +10253 -0
  74. package/www/kernel.js +1380 -0
  75. package/www/outbox/outboxAttachmentManager.ts +152 -0
  76. package/www/outbox/outboxHelper.ts +67 -0
  77. package/www/outbox/outboxService.ts +519 -0
  78. package/www/sql-wasm.wasm +0 -0
  79. package/www/sql.js +209 -0
  80. package/www/subtract.ts +5 -0
  81. package/www/sum.ts +4 -0
  82. package/www/syncEngine.ts +687 -0
@@ -0,0 +1,2430 @@
1
+ var loginParameters;
2
+ var pushEvent;
3
+
4
+ /**
5
+ * Srinidhi: 04 Jan 2024
6
+ * This variable holds the UMP Rest api version.
7
+ * Some applications require the previous version (v2) because of older UMP versions. This is the default version.
8
+ * As of this date, the latest version is 3, which returns unescaped JSON. For these cases, users can specify UMP Rest API version by setting a loginParameter umpRESTapiVersion to '3'
9
+ *
10
+ */
11
+ var UMP_REST_API_VERSION = '2'
12
+ var restApis = {}
13
+
14
+ //Parse metadata.json and hold it in metadata in localstorage
15
+ var metadata = {
16
+ sMeta: [],
17
+ fMeta: [],
18
+ bMeta: [],
19
+ appMeta: "",
20
+ };
21
+ var loginType = {
22
+ unvired: "UNVIRED_ID",
23
+ ads: "ADS",
24
+ sap: "SAP",
25
+ custom: "CUSTOM",
26
+ email: "EMAIL",
27
+
28
+ /**
29
+ * SAML SSO Login setup. To authenticate using SAML, set this value in the |loginType|.
30
+ * While developing you face this issue of cross-origin restrictions if the SAML implementation is on an other server.
31
+ * Safari browser provides a way to debug in such a scenario.
32
+ * Disable cross-origin restrictions in the Develop Menu.
33
+ * https://stackoverflow.com/questions/4556429/disabling-same-origin-policy-in-safari
34
+ *
35
+ */
36
+ saml2: "SAML2"
37
+ };
38
+ var requestType = {
39
+ RQST: "RQST",
40
+ PULL: "PULL",
41
+ PUSH: "PUSH",
42
+ QUERY: "QUERY",
43
+ REQ: "REQ",
44
+ };
45
+ var loginMode = {
46
+ authActivate: 0,
47
+ authLocal: 1,
48
+ forgotPassword: 2,
49
+ };
50
+
51
+ var loginListenerType = {
52
+ auth_activation_required: 0, // Mobile app not yet activated and requires authentication and activation
53
+ app_requires_login: 1, // Mobile app requires offline / local login
54
+ auth_activation_success: 2, // Account authenticated and activated on the server
55
+ auth_activation_error: 3, // Acoount authentication or aactivation failed on the server
56
+ login_success: 4, // Mobile app login successful
57
+ login_error: 5, // Mobile app login failure
58
+ app_requires_current_account: 6, // Multiple account found hence app has to set current active account
59
+ };
60
+
61
+ var resultType = {
62
+ success: 0,
63
+ error: 1,
64
+ };
65
+
66
+ var LogLevel = {
67
+ important: 7,
68
+ error: 8,
69
+ debug: 9,
70
+ };
71
+
72
+ var printLogs = false;
73
+
74
+ /**
75
+ * This gets updated during the build time. Check the build.xml file for the details.
76
+ */
77
+ var PACKAGE_NUMBER = "1.0.1"
78
+
79
+ //#endregion
80
+
81
+ //#region Login Apis
82
+ module.exports.login = function (successCallback, errorCallback, options) {
83
+ loginParameters = options[0];
84
+
85
+ if (loginParameters.url && loginParameters.url.length > 0) {
86
+ loginParameters.url = helper.sanitizeURL(loginParameters.url);
87
+ }
88
+
89
+ // Print Framework and app version numbers.
90
+ console.log('cordova-plugin-unvired-universal-sdk version Number:', PACKAGE_NUMBER)
91
+ console.log('App version number:', loginParameters.appVersion)
92
+
93
+ // UMP Rest API Version
94
+ if (loginParameters.umpRESTapiVersion) {
95
+ UMP_REST_API_VERSION = loginParameters.umpRESTapiVersion
96
+ }
97
+ console.log('UMP REST API Version:', UMP_REST_API_VERSION)
98
+
99
+ // Define REST API endpoints
100
+ defineRestAPIEndpoints()
101
+
102
+ // TODO - Clear db based on login parameters
103
+ // helper.clearApplicationDb();
104
+
105
+ metadataParser.initialize();
106
+
107
+ var cbResult = {};
108
+
109
+ if (!loginParameters.appName) {
110
+ cbResult.message = "Application name not initialized";
111
+ cbResult.type = loginListenerType.auth_activation_required;
112
+ successCallback(cbResult);
113
+ return;
114
+ }
115
+
116
+ // Return auth activation required if requireClientCredentials is set to true but not passed
117
+ if (loginParameters.requireClientCredentials) {
118
+ if (!loginParameters.clientCredentials || loginParameters.clientCredentials.length <= 0) {
119
+ cbResult.message = "Backend credentials not passed";
120
+ cbResult.type = loginListenerType.auth_activation_required;
121
+ successCallback(cbResult);
122
+ return;
123
+ }
124
+ }
125
+
126
+ webDb.reloadAppMeta(function (hasAppmeta) {
127
+ if (hasAppmeta) {
128
+ cbResult.type = loginListenerType.login_success;
129
+
130
+ // Check whether we have received a SAML token as part of LoginParameters
131
+ // If there is a SAML token, then use the token here.
132
+ // We do receive the SAML tokem for IDP initiated login process.
133
+ if (loginParameters.samlToken) {
134
+ localStorage.setItem("token", loginParameters.samlToken);
135
+ restUtil.appMeta.authorization = "Bearer:" + loginParameters.samlToken;
136
+ }
137
+ successCallback(cbResult);
138
+ return;
139
+ } else {
140
+ if (successCallback) {
141
+ cbResult.type = loginListenerType.auth_activation_required;
142
+ successCallback(cbResult);
143
+ }
144
+ }
145
+ });
146
+ };
147
+
148
+ defineRestAPIEndpoints = function () {
149
+ restApis = {
150
+ defaultApi: `/API/v${UMP_REST_API_VERSION}/applications/`,
151
+ activate: `/activate/`,
152
+ authenticate: `/authenticate`,
153
+ session: `/session/`,
154
+ execute: `/execute/`,
155
+ users: `/API/v${UMP_REST_API_VERSION}/users/`,
156
+ };
157
+ }
158
+
159
+ module.exports.logout = function (successCallback, errorCallback, options) {
160
+ doLogout(successCallback, errorCallback)
161
+ };
162
+
163
+ doLogout = function (successCallback, errorCallback) {
164
+ console.log('Logout: Login Parameter Type: ' + loginParameters.loginType)
165
+
166
+ /**
167
+ * Srinidhi: 24 June 2022
168
+ * By default, Unvired SDK does not call the logout function.
169
+ * If the endpoint needs to be called, then the login parameter, |callLogoutEndpoint| needs to be set.
170
+ */
171
+ if (loginParameters.loginType == loginType.saml2 && loginParameters.callLogoutEndpoint) {
172
+ let token = localStorage.getItem('token')
173
+ let endpoint = loginParameters.url + '/sso/saml/dologout?token=' + token
174
+
175
+ console.log('Logout URL: ' + endpoint)
176
+
177
+ $.ajax({
178
+ type: "GET",
179
+ url: endpoint,
180
+ success: function (res, textStatus, request) {
181
+ console.log('Successfully logged out out of SAML: ' + JSON.stringify(res))
182
+ clearAllData(function () {
183
+ restUtil.handleRestApiCallback(true, res, successCallback);
184
+ })
185
+ },
186
+ error: function (res) {
187
+ console.log('Failure in calling SAML logout URL: ' + JSON.stringify(res))
188
+ clearAllData(function () {
189
+ restUtil.handleRestApiCallback(false, res, errorCallback);
190
+ })
191
+ }
192
+ });
193
+ }
194
+ else {
195
+ clearAllData(function () {
196
+ restUtil.handleRestApiCallback(true, {}, successCallback);
197
+ })
198
+
199
+ // Tarak: 15 March 2022
200
+ // Reset Client Credentials upon logging out.
201
+ loginParameters.clientCredentials = '';
202
+ }
203
+ }
204
+
205
+ clearAllData = function (callback) {
206
+ console.log('Clearing Application DB and closing push events if any')
207
+ helper.clearApplicationDb();
208
+ if (pushEvent) {
209
+ pushEvent.close();
210
+ }
211
+ callback()
212
+ }
213
+
214
+ module.exports.getListOfFrontEndUsers = function (successCallback, errorCallback, options) {
215
+ if (!helper.validateLoginParameters(loginMode.authActivate, successCallback)) return;
216
+
217
+ restUtil.appMeta = {};
218
+ restUtil.appMeta.appName = loginParameters.appName;
219
+ restUtil.appMeta.url = loginParameters.url;
220
+ restUtil.appMeta.authorization =
221
+ "Basic " + window.btoa(loginParameters.company + "\\" + loginParameters.username + ":" + loginParameters.password);
222
+ var endpoint = restUtil.appMeta.url + restApis.users + loginParameters.username;
223
+ restUtil.performRequest(
224
+ endpoint,
225
+ "",
226
+ function (result) {
227
+ successCallback(result);
228
+ },
229
+ restUtil.httpType.get,
230
+ false
231
+ );
232
+ };
233
+
234
+ module.exports.authenticateAndActivate = function (successCallback, errorCallback, options) {
235
+ loginParameters = options[0];
236
+
237
+ if (loginParameters.url && loginParameters.url.length > 0) {
238
+ loginParameters.url = helper.sanitizeURL(loginParameters.url);
239
+ }
240
+
241
+ if (!helper.validateLoginParameters(loginMode.authActivate, successCallback)) return;
242
+
243
+ // For Web sdk choose frontend type as Web and it is auto activate while deployed
244
+ restUtil.appMeta = {};
245
+ restUtil.appMeta.frontEnd = loginParameters.feUserId;
246
+ restUtil.appMeta.appName = loginParameters.appName;
247
+ restUtil.appMeta.url = loginParameters.url;
248
+ restUtil.appMeta.username = loginParameters.username;
249
+ var endpoint;
250
+ var credentials;
251
+ switch (loginParameters.loginType) {
252
+ case loginType.email:
253
+ case loginType.unvired:
254
+ restUtil.appMeta.authorization =
255
+ "Basic " +
256
+ window.btoa(loginParameters.company + "\\" + loginParameters.username + ":" + loginParameters.password);
257
+ endpoint = restUtil.appMeta.url + restApis.defaultApi + restUtil.appMeta.appName + restApis.session;
258
+ break;
259
+ case loginType.sap:
260
+ restUtil.appMeta.authorization =
261
+ "Basic " + window.btoa(loginParameters.company + "\\" + loginParameters.username);
262
+ endpoint = restUtil.appMeta.url + restApis.defaultApi + restUtil.appMeta.appName + restApis.session;
263
+ credentials = JSON.stringify([
264
+ {
265
+ port: loginParameters.port,
266
+ user: loginParameters.username,
267
+ password: loginParameters.password,
268
+ },
269
+ ]);
270
+ break;
271
+ case loginType.ads:
272
+ restUtil.appMeta.authorization =
273
+ "Basic " + window.btoa(loginParameters.company + "\\" + loginParameters.username);
274
+ endpoint = restUtil.appMeta.url + restApis.defaultApi + restUtil.appMeta.appName + restApis.session;
275
+ credentials = JSON.stringify([
276
+ {
277
+ port: loginParameters.port,
278
+ user: loginParameters.domain + "\\" + loginParameters.username,
279
+ password: loginParameters.password,
280
+ },
281
+ ]);
282
+ break;
283
+ }
284
+
285
+ // SAML2 setup
286
+ if (loginParameters.loginType == loginType.saml2) {
287
+ handleSAML2Login(loginParameters, successCallback, errorCallback)
288
+ }
289
+ else {
290
+
291
+ /**
292
+ * Session call. Use authKey for successive calls.
293
+ * Check users for any frontentd of type web to continue else return frontend not found
294
+ */
295
+ restUtil.performRequest(
296
+ endpoint,
297
+ "",
298
+ function (result) {
299
+ if (result.type == resultType.success) {
300
+ webDb.initialize(function () {
301
+ //On activation success save app meta for further calls.
302
+ delete restUtil.appMeta.authorization;
303
+ webDb.saveAppMeta(restUtil.appMeta);
304
+ localStorage.setItem("token", result.data.token);
305
+ restUtil.appMeta.authorization = "Bearer:" + result.data.token;
306
+ //Loginlistener callback
307
+ var cbResult = {};
308
+
309
+ storeLoggedInUserDetailsInLocalStorage().then(() => {
310
+ cbResult.type = 2; //ump.loginListenerType.auth_activation_success;
311
+ cbResult.data = result;
312
+ successCallback(cbResult);
313
+ })
314
+ });
315
+ } else {
316
+ var errText = "";
317
+ if (!helper.isEmpty(result)) {
318
+ errText = helper.isEmpty(result.error)
319
+ ? "No error description returned from server"
320
+ : JSON.parse(result.error).error;
321
+ }
322
+
323
+ // Loginlistener callback
324
+ var cbResult = {};
325
+ cbResult.type = 3;
326
+ cbResult.error = errText;
327
+ successCallback(cbResult);
328
+ }
329
+ },
330
+ restUtil.httpType.post,
331
+ false,
332
+ credentials,
333
+ loginParameters.jwtOptions
334
+ );
335
+ }
336
+ };
337
+
338
+ /**
339
+ * Code to handle SAML2 login
340
+ */
341
+ handleSAML2Login = function (loginParameters, successCallback, errorCallback) {
342
+ let baseURL = loginParameters.url
343
+ let company = loginParameters.company
344
+ let applicationName = loginParameters.appName
345
+ let device = 'browser'
346
+ let redirectURL = loginParameters.redirectURL
347
+
348
+ // If a token is already present, then just initiate the App DB and return a Success Callback
349
+ // This is scenario for IDP initiated SAML login, where the web-app receives a callback with the token.
350
+ // Framework in this case would simply store that token and initializes DB and other machansims.
351
+ if (loginParameters.samlToken) {
352
+ webDb.initialize(function () {
353
+ //On activation success save app meta for further calls.
354
+ delete restUtil.appMeta.authorization;
355
+ webDb.saveAppMeta(restUtil.appMeta);
356
+ localStorage.setItem("token", loginParameters.samlToken);
357
+ restUtil.appMeta.authorization = "Bearer:" + loginParameters.samlToken;
358
+
359
+ storeLoggedInUserDetailsInLocalStorage().then(() => {
360
+ var cbResult = {};
361
+ cbResult.type = 2; // Authentication Activation Success.
362
+ successCallback(cbResult);
363
+ })
364
+ });
365
+ return;
366
+ }
367
+
368
+ let options = {
369
+ width: 600,
370
+ height: 600,
371
+ top: window.screenY + ((window.outerHeight - 600) / 2.5),
372
+ left: window.screenX + ((window.outerWidth - 600) / 2)
373
+ };
374
+
375
+ let popupurl = `${baseURL}/sso/saml/dologin?company=${company}&application=${applicationName}&device=${device}&redirect=${redirectURL}`;
376
+ // let popupurl = "http://localhost:3000/something_else"
377
+ try {
378
+ var popup = window.open(popupurl, '_blank', stringifyOptions(options));
379
+ if (popup && popup.focus) {
380
+ popup.focus();
381
+ }
382
+ if (popupurl === 'about://blank') {
383
+ popup.document.body.innerHTML = 'Loading...';
384
+ }
385
+ pollPopup(popup, loginParameters).then(
386
+ (params) => {
387
+ let token = params.get('token')
388
+ webDb.initialize(function () {
389
+ //On activation success save app meta for further calls.
390
+ delete restUtil.appMeta.authorization;
391
+ webDb.saveAppMeta(restUtil.appMeta);
392
+ localStorage.setItem("token", token);
393
+ restUtil.appMeta.authorization = "Bearer:" + token;
394
+
395
+ storeLoggedInUserDetailsInLocalStorage().then(() => {
396
+ var cbResult = {};
397
+ cbResult.type = 2; // Authentication Activation Success.
398
+ successCallback(cbResult);
399
+ })
400
+ });
401
+ }
402
+ ).catch(
403
+ error => {
404
+ console.log("Caught Promise Error. Sending the error information up the chain.")
405
+ errorCallback(error);
406
+ }
407
+ );
408
+
409
+ } catch (e) {
410
+ console.log('Error opening popup:', e);
411
+ errorCallback('Error during SAML-SSO Login Process:', e)
412
+ }
413
+ };
414
+
415
+ isUndefined = function (value) {
416
+ return typeof value === 'undefined';
417
+ }
418
+
419
+ stringifyOptions = function (popupOptions) {
420
+ const options = [];
421
+ for (const optionKey in popupOptions) {
422
+ if (!this.isUndefined(popupOptions[optionKey])) {
423
+ options.push(`${optionKey}=${popupOptions[optionKey]}`);
424
+ }
425
+ }
426
+ return options.join(',');
427
+ }
428
+
429
+ pollPopup = function (window, loginParameters) {
430
+
431
+ return new Promise((resolve, reject) => {
432
+ const polling = setInterval(() => {
433
+ if (!window || window.closed || window.closed === undefined) {
434
+ clearInterval(polling);
435
+ reject('SAML authentication could not be performed because the user closed the popup window.');
436
+ }
437
+ try {
438
+ const popupUrlPath = window.location.protocol + '//' + window.location.host + window.location.pathname;
439
+ if (popupUrlPath === 'about://blank') {
440
+ popup.document.body.innerHTML = 'Loading...';
441
+ }
442
+ if (popupUrlPath.startsWith(loginParameters.redirectURL)) {
443
+ if (window.location.search) {
444
+ const urlParams = new URLSearchParams(window.location.search);
445
+ const error = urlParams.get('error');
446
+ if (error) {
447
+ let decodedError = decodeURIComponent(error)
448
+ console.log('Error from UMP: ' + decodedError)
449
+
450
+ clearInterval(polling)
451
+ window.close();
452
+ reject(decodedError)
453
+
454
+ } else {
455
+ // cleanup
456
+ resolve(urlParams);
457
+ clearInterval(polling);
458
+ window.close();
459
+ }
460
+ } else {
461
+ reject(new Error('OAuth redirect has occurred but no query parameters were found.'));
462
+ }
463
+ }
464
+ } catch (error) {
465
+ // Ignore DOMException: Blocked a frame with origin from accessing a cross-origin frame.
466
+ // A hack to get around same-origin security policy errors in Internet Explorer.
467
+ }
468
+ }, 100);
469
+ });
470
+ }
471
+
472
+ /**
473
+ * Retreive the user details from the local storage with the key |localStorage|
474
+ */
475
+ storeLoggedInUserDetailsInLocalStorage = function () {
476
+ return new Promise((resolve, reject) => {
477
+ let endpoint = restUtil.appMeta.url + restApis.users + ':me';
478
+ restUtil.performRequest(
479
+ endpoint,
480
+ "",
481
+ function (result) {
482
+ if (result.type == resultType.success) {
483
+ localStorage.setItem('userDetails', JSON.stringify(result))
484
+ }
485
+ return resolve(result);
486
+ },
487
+ restUtil.httpType.get,
488
+ false,
489
+ loginParameters.clientCredentials
490
+ );
491
+ })
492
+ }
493
+
494
+ module.exports.authenticateLocal = function (sucessCallback, errorCallback, options) {
495
+ loginParameters = options[0];
496
+
497
+ if (loginParameters.url && loginParameters.url.length > 0) {
498
+ loginParameters.url = helper.sanitizeURL(loginParameters.url);
499
+ }
500
+
501
+ if (!helper.validateLoginParameters(loginMode.authLocal, sucessCallback)) return;
502
+ console.log("authenticateLocal: Api not supported on Web!");
503
+ };
504
+
505
+ //TODO- Implement Api
506
+ module.exports.getAllAccount = function (sucessCallback, errorCallback, options) {
507
+ console.log("getAllAccount: Api not implemented!");
508
+ };
509
+
510
+ //TODO- Implement Api
511
+ module.exports.switchAccount = function (sucessCallback, errorCallback, options) {
512
+ console.log("switchAccount: Api not implemented!");
513
+ };
514
+
515
+ //TODO- Implement Api
516
+ module.exports.deleteAccount = function (sucessCallback, errorCallback, options) {
517
+ console.log("deleteAccount: Api not implemented!");
518
+ };
519
+
520
+ module.exports.setClientCredentials = function (sucessCallback, errorCallback, options) {
521
+ loginParameters.clientCredentials = JSON.stringify(options);
522
+ return helper.sendSuccess("", sucessCallback);
523
+ };
524
+
525
+ module.exports.isClientCredentialsSet = function (sucessCallback, errorCallback, options) {
526
+ if (helper.isEmpty(loginParameters.clientCredentials) || loginParameters.clientCredentials.length <= 0)
527
+ return helper.sendSuccess("", sucessCallback, false);
528
+ return helper.sendSuccess("", sucessCallback, true);
529
+ };
530
+
531
+ //#endregion
532
+
533
+ //#region Sync Apis
534
+ module.exports.submitInSync = function (successCallback, errorCallback, options) {
535
+ var reqType = options[0].requestType;
536
+ var header = options[0].header;
537
+ var paFunction = options[0].paFunction;
538
+ var customData = options[0].customData;
539
+ var autoSave = options[0].autoSave;
540
+
541
+ if (!restUtil.appMeta.url || restUtil.appMeta.url === "") {
542
+ restUtil.appMeta = webDb.getAppMeta();
543
+ }
544
+
545
+ if (!restUtil.appMeta) {
546
+ let result = {}
547
+ result.type = resultType.error;
548
+ result.error = 'No login credentials found or the app timed out. Please re-login.'
549
+ result.message = 'No login credentials found or the app timed out. Please re-login.'
550
+ result.code = 0;
551
+ return successCallback(result)
552
+ }
553
+
554
+ var endpoint = restUtil.appMeta.url + restApis.defaultApi + restUtil.appMeta.appName + restApis.execute + paFunction;
555
+ console.log("End Point: " + endpoint);
556
+
557
+ 'End Point: undefined/API/v2/applications/undefined/execute/LIME_SALES_PA_GET_CUSTOMIZATION'
558
+
559
+ var postMessage = "";
560
+ var headerLid = ""
561
+ if (header === null || header === "") postMessage = customData;
562
+ else {
563
+
564
+ console.log('SubmitInSync: Header: ' + JSON.stringify(header))
565
+
566
+ postMessage = helper.getUBJsonFromHeader(header);
567
+ var headerName = Object.keys(header)[0];
568
+ var header = header[headerName];
569
+
570
+ /**
571
+ * For other request types we don't co-relate the sending BE's LID.
572
+ */
573
+ if (reqType == requestType.RQST) {
574
+ headerLid = header.LID;
575
+ }
576
+ }
577
+
578
+ restUtil.performRequest(
579
+ endpoint,
580
+ postMessage,
581
+ function (result) {
582
+ if (result.type == resultType.success && result.data) {
583
+
584
+ /**
585
+ * Srinidhi: 04 Jan 2024
586
+ * UMP Rest API version 2 returns JSON string from server whereas version 3 and above would be returning JSON object.
587
+ */
588
+ let parsedJSONData
589
+ switch (UMP_REST_API_VERSION) {
590
+ case '2':
591
+ parsedJSONData = JSON.parse(result.data)
592
+ break
593
+
594
+ default:
595
+ parsedJSONData = result.data
596
+ }
597
+
598
+ result = parser.parseServerResponse(parsedJSONData, reqType, headerLid, autoSave);
599
+ return successCallback(result);
600
+ }
601
+ return successCallback(result);
602
+ },
603
+ restUtil.httpType.post,
604
+ false,
605
+ loginParameters.clientCredentials
606
+ );
607
+ };
608
+
609
+ module.exports.submitInASync = function (successCallback, errorCallback, options) {
610
+ /**
611
+ * In Web Async call works same as in Sync. Receives response data in callback instead of NotificationListener callback in Mobile.
612
+ * App has to handle async response differently for both
613
+ */
614
+ var header = options[0].header;
615
+ var paFunction = options[0].paFunction;
616
+ var customData = options[0].customData;
617
+
618
+ //webDb.appDb.loadDatabase({});
619
+
620
+ if (!restUtil.appMeta.url || restUtil.appMeta.url === "") {
621
+ restUtil.appMeta = webDb.getAppMeta();
622
+ }
623
+ var endpoint = restUtil.appMeta.url + restApis.defaultApi + restUtil.appMeta.appName + restApis.execute + paFunction;
624
+ var postMessage = "";
625
+ if (header === null || header === "") postMessage = customData;
626
+ else {
627
+ postMessage = helper.getUBJsonFromHeader(header);
628
+ }
629
+
630
+ restUtil.performRequest(
631
+ endpoint,
632
+ postMessage,
633
+ function (result) {
634
+ return successCallback(result);
635
+ },
636
+ restUtil.httpType.post,
637
+ true,
638
+ loginParameters.clientCredentials
639
+ );
640
+ };
641
+
642
+ module.exports.getMessages = function (successCallback, errorCallback, options) {
643
+ console.log("getMessages: Api not supported on Web!");
644
+ };
645
+
646
+ module.exports.registerNotifListener = function (successCallback, errorCallback, options) {
647
+ console.log("registerNotifListener: Api not supported on Web! Web supports only sync call");
648
+ };
649
+
650
+ module.exports.unRegisterNotifListener = function (successCallback, errorCallback, options) {
651
+ console.log("unRegisterNotifListener: Api not supported on Web! Web supports only sync call");
652
+ };
653
+
654
+ module.exports.generateUBJson = function (successCallback, errorCallback, options) {
655
+ var headerName = options[0].headerName;
656
+ var header = options[0].header;
657
+ var itemName = options[0].itemName;
658
+ var items = options[0].items;
659
+
660
+ var beName = helper.getBeName(headerName);
661
+ var temp = {};
662
+ var be = {};
663
+ be[headerName] = header;
664
+ be[itemName] = items;
665
+ temp[beName] = [be];
666
+ helper.sendSuccess("", successCallback, temp);
667
+ };
668
+
669
+ module.exports.parseRawUBJson = function (successCallback, errorCallback, options) {
670
+ var json = "";
671
+ json = options[0].json;
672
+ var data = JSON.parse(json);
673
+ var response = {
674
+ infoMessage: [],
675
+ be: [],
676
+ };
677
+ var bes = [];
678
+ for (var property in data) {
679
+ if (data.hasOwnProperty(property)) {
680
+ if (property === "InfoMessage") {
681
+ var infoArr = data[property];
682
+ response.infoMessage = infoArr;
683
+ } else {
684
+ var beArr = data[property];
685
+ beArr.forEach(function (beElement) {
686
+ var be = {
687
+ header: "",
688
+ items: [],
689
+ };
690
+ for (var property in beElement) {
691
+ if (beElement.hasOwnProperty(property)) {
692
+ var value = beElement[property];
693
+ if (value.constructor === Array) {
694
+ value.forEach(function (item) {
695
+ be.items.push(item);
696
+ });
697
+ } else if (value.constructor === Object) {
698
+ be.header = value;
699
+ }
700
+ }
701
+ }
702
+ bes.push(be);
703
+ });
704
+ }
705
+ }
706
+ }
707
+ response.be = bes;
708
+ successCallback(response);
709
+ };
710
+
711
+ /**
712
+ * Not supported in Web. Returning success callback all the time.
713
+ */
714
+ module.exports.lockDataSender = function (sucessCallback, errorCallback, options) {
715
+ return helper.sendSuccess("", sucessCallback, 0);
716
+ };
717
+
718
+ /**
719
+ * Not supported in Web. Returning success callback all the time.
720
+ */
721
+ module.exports.unlockDataSender = function (sucessCallback, errorCallback, options) {
722
+ return helper.sendSuccess("", sucessCallback, []);
723
+ };
724
+
725
+ module.exports.registerForPushNotification = function (successCallback, errorCallback, options) {
726
+ var appMeta = webDb.getAppMeta();
727
+ var url = appMeta.url;
728
+ var token = localStorage.getItem("token");
729
+ var sessionId = helper.guid();
730
+ var pushUrl = `${url}/push?apiToken=${token}&sessionid=${sessionId}`;
731
+ pushEvent = new EventSource(pushUrl);
732
+ successCallback(pushEvent);
733
+ }
734
+
735
+ //#endregion
736
+
737
+ //#region Database Apis
738
+
739
+ module.exports.select = function (sucessCallback, errorCallback, options) {
740
+ var tableName = options[0].tableName;
741
+ var whereClause = options[0].whereClause || "";
742
+ var resultSet = webDb.select(tableName, whereClause);
743
+
744
+
745
+
746
+
747
+
748
+
749
+ return helper.sendSuccess("", sucessCallback, resultSet);
750
+
751
+
752
+
753
+
754
+
755
+ };
756
+
757
+ module.exports.insert = function (sucessCallback, errorCallback, options) {
758
+ var tableName = options[0].tableName;
759
+ var isHeader = options[0].isHeader || false;
760
+ var structureObject = options[0].fields;
761
+
762
+ if (!isHeader) {
763
+ if (helper.isEmpty(structureObject.FID)) {
764
+ helper.sendError("Invalid FID", sucessCallback);
765
+ }
766
+ }
767
+ try {
768
+ webDb.insert(tableName, structureObject, false);
769
+ }
770
+ catch (error) {
771
+ console.error('Error while inserting data: ' + error, options)
772
+ return helper.sendError('Error while inserting data: ' + error + JSON.stringify(options), sucessCallback)
773
+ }
774
+ return helper.sendSuccess("", sucessCallback, "");
775
+ };
776
+
777
+ module.exports.insertOrUpdate = function (sucessCallback, errorCallback, options) {
778
+ var tableName = options[0].tableName;
779
+ var isHeader = options[0].isHeader || false;
780
+ var structureObject = options[0].fields;
781
+
782
+ if (!isHeader) {
783
+ if (helper.isEmpty(structureObject.FID)) {
784
+ helper.sendError("Invalid FID", sucessCallback);
785
+ }
786
+ }
787
+ try {
788
+ webDb.insertOrUpdateBasedOnGid(tableName, structureObject);
789
+ }
790
+ catch (error) {
791
+ console.error('Error while inserting/updating data: ' + error, options)
792
+ return helper.sendError('Error while inserting/updating data: ' + error + JSON.stringify(options), sucessCallback)
793
+ }
794
+ return helper.sendSuccess("", sucessCallback, "");
795
+ };
796
+
797
+ module.exports.deleteRecord = function (sucessCallback, errorCallback, options) {
798
+ var tableName = options[0].tableName;
799
+ var whereClause = options[0].whereClause;
800
+ webDb.deleteRecord(tableName, whereClause);
801
+ helper.sendSuccess("", sucessCallback);
802
+ };
803
+
804
+ module.exports.update = function (sucessCallback, errorCallback, options) {
805
+ var tableName = options[0].tableName;
806
+ var whereClause = options[0].whereClause;
807
+ var updatedObject = options[0].fields;
808
+ try {
809
+ webDb.updateStructure(tableName, updatedObject, whereClause);
810
+ }
811
+ catch (error) {
812
+ console.error('Error while updating data: ' + error, options)
813
+ return helper.sendError('Error while updating data: ' + error + JSON.stringify(options), sucessCallback)
814
+ }
815
+ helper.sendSuccess("", sucessCallback);
816
+ };
817
+
818
+ // Execute raw query with returned result
819
+ module.exports.executeQuery = function (sucessCallback, errorCallback, options) {
820
+ var query = options[0];
821
+ try {
822
+ var resultSet = webDb.executeQuery(query);
823
+ }
824
+ catch (error) {
825
+ console.error('Error while executing a query: ' + error, options)
826
+ return helper.sendError('Error while executing a query: ' + error + JSON.stringify(options), sucessCallback)
827
+ }
828
+ return helper.sendSuccess("", sucessCallback, resultSet);
829
+ };
830
+
831
+ // Execute raw query without returned result
832
+ module.exports.execute = function (sucessCallback, errorCallback, options) {
833
+ var query = options[0];
834
+ webDb.execute(query);
835
+ helper.sendSuccess("", sucessCallback);
836
+ };
837
+
838
+ // module.exports.dbGetCollection = function (successCallback, errorCallback, options) {
839
+ // var tableName = ''
840
+ // tableName = options['tableName']
841
+ // successCallback(webDb.appDb.getCollection(tableName));
842
+ // };
843
+ module.exports.createSavePoint = function (successCallback, errorCallback, options) {
844
+ console.log("createSavePoint: Api not supported on web!.");
845
+ };
846
+ module.exports.releaseSavePoint = function (successCallback, errorCallback, options) {
847
+ console.log("releaseSavePoint: Api not supported on web!.");
848
+ };
849
+ module.exports.rollbackSavePoint = function (successCallback, errorCallback, options) {
850
+ console.log("rollbackSavePoint: Api not supported on web!.");
851
+ };
852
+ module.exports.beginTransaction = function (successCallback, errorCallback, options) {
853
+ console.log("beginTransaction: Api not supported on web!.");
854
+ };
855
+ module.exports.endTransaction = function (successCallback, errorCallback, options) {
856
+ console.log("endTransaction: Api not supported on web!.");
857
+ };
858
+
859
+ module.exports.saveWebDb = function (successCallback, errorCallback, options) {
860
+ if (loginParameters.cacheWebData) {
861
+ webDb.saveWebDb().then( function() {
862
+ successCallback()
863
+ }, function(errorMessage) {
864
+ errorCallback(errorMessage)
865
+ })
866
+ } else {
867
+ helper.sendError("Caching web data is not enabled for this application", successCallback);
868
+ }
869
+ };
870
+
871
+ module.exports.exportWebDb = function (successCallback, errorCallback, options) {
872
+ webDb.exportWebDb();
873
+ return helper.sendSuccess("", sucessCallback, "");
874
+ };
875
+
876
+ //#endregion
877
+
878
+ //#region Proxy Apis
879
+
880
+ module.exports.launchFile = function (successCallback, errorCallback, options) {
881
+ console.log("launchFile: Api not supported on web!.");
882
+ };
883
+ module.exports.unzip = function (successCallback, errorCallback, options) {
884
+ console.log("unzip: Api not supported on web!.");
885
+ };
886
+ module.exports.launchBase64 = function (successCallback, errorCallback, options) {
887
+ console.log("launchBase64: Api not supported on web!.");
888
+ };
889
+
890
+ //#endregion
891
+
892
+ //#region Attachment Apis
893
+
894
+ module.exports.getAttachmentFolderPath = function (successCallback, errorCallback, options) {
895
+ console.log("getAttachmentFolderPath: Api not supported in browser!");
896
+ };
897
+ module.exports.createAttachmentItem = function (successCallback, errorCallback, options) {
898
+ console.log("createAttachmentItem: Api not supported in browser!");
899
+ };
900
+ module.exports.uploadAttachment = function (successCallback, errorCallback, options) {
901
+ console.log("uploadAttachment: Api not supported yet in browser!");
902
+ };
903
+ module.exports.downloadAttachment = function (successCallback, errorCallback, options) {
904
+ console.log("downloadAttachment: Api not supported yet in browser!");
905
+ };
906
+
907
+ //#endregion
908
+
909
+ //#region Settings Apis
910
+
911
+ module.exports.getInfoMessages = function (successCallback, errorCallback, options) {
912
+ // var headerName = options[0].headerName;
913
+ var lid = options[0].LID;
914
+ var InfoMessages = webDb.select("INFO_MESSAGE", `BE_LID='${lid}'`);
915
+ helper.sendSuccess("", sucessCallback, InfoMessages);
916
+ };
917
+
918
+ module.exports.showSettings = function (successCallback, errorCallback, options) {
919
+ console.log("showSettings: Api not supported on Web!");
920
+ };
921
+
922
+ module.exports.userSettings = function (successCallback, errorCallback, options) {
923
+ var appMeta = webDb.getAppMeta();
924
+ appMeta.USER_ID = appMeta.username;
925
+ if (loginParameters.loginType == loginType.email) {
926
+ appMeta.EMAIL = appMeta.username;
927
+ }
928
+
929
+ // Read Unvired ID & other parameters from the token
930
+ let token = localStorage.getItem("token");
931
+ let tokenComponents = token.split(".");
932
+ let tokenContainingUnviredId;
933
+ if (tokenComponents.length > 2) {
934
+ tokenContainingUnviredId = tokenComponents[1];
935
+ let jsonString = atob(tokenContainingUnviredId);
936
+ if (jsonString) {
937
+ let tokenObject = JSON.parse(jsonString);
938
+ if (tokenObject) {
939
+ appMeta.UNVIRED_ID = tokenObject["userName"];
940
+ appMeta.FNAME = tokenObject["FNAME"];
941
+ appMeta.LNAME = tokenObject["LNAME"];
942
+ appMeta.frontendUser = tokenObject["frontendUser"];
943
+ }
944
+ }
945
+ }
946
+
947
+ // Update the appMeta based on the information stored in the local storage.
948
+ if (localStorage.getItem('userDetails')) {
949
+ let userDetails = JSON.parse(localStorage.getItem('userDetails'))
950
+ appMeta.USER_ID = userDetails.data.user.userName
951
+ appMeta.FIRST_NAME = userDetails.data.user.firstName
952
+ appMeta.LAST_NAME = userDetails.data.user.lastName
953
+ appMeta.EMAIL = userDetails.data.user.email
954
+ appMeta.FULL_NAME = appMeta.FIRST_NAME + ' ' + appMeta.LAST_NAME
955
+ }
956
+
957
+ return helper.sendSuccess("", successCallback, appMeta);
958
+ };
959
+
960
+ module.exports.updateSystemCredentials = function (successCallback, errorCallback, options) {
961
+ console.log("updateSystemCredentials: Api not supported on web!.");
962
+ };
963
+
964
+ module.exports.getSystemCredentials = function (successCallback, errorCallback, options) {
965
+ console.log("getSystemCredentials: Api not supported on web!.");
966
+ };
967
+
968
+ module.exports.getVersionNumbers = function (successCallback, errorCallback, options) {
969
+ console.log("getVersionNumbers: Api not implemented on Web!");
970
+ };
971
+
972
+ module.exports.clearData = function (successCallback, errorCallback, options) {
973
+ helper.clearApplicationDb();
974
+ };
975
+
976
+ /**
977
+ * reCreateAppDB - Recreate application database.
978
+ * Helps in updating application database without reauthenticating with server which requires to drop both app and framework database.
979
+ */
980
+ module.exports.reCreateAppDB = function (successCallback, errorCallback, options) {
981
+ webDb.reCreateAppDb();
982
+ helper.sendSuccess("", sucessCallback, true);
983
+ };
984
+ module.exports.pullDb = function (successCallback, errorCallback, options) {
985
+ console.log("pullDb: Api not supported on Web!");
986
+ };
987
+ module.exports.pushDb = function (successCallback, errorCallback, options) {
988
+ console.log("pushDb: Api not supported on Web!");
989
+ };
990
+ module.exports.encrypt = function (successCallback, errorCallback, options) {
991
+ console.log("encrypt: Api not supported on Web!");
992
+ };
993
+ module.exports.encrypt = function (successCallback, errorCallback, options) {
994
+ console.log("decrypt: Api not supported on Web!");
995
+ };
996
+ module.exports.getAppMeta = function (successCallback, errorCallback, options) {
997
+ successCallback(webDb.getAppMeta());
998
+ };
999
+ module.exports.guid = function (successCallback, errorCallback, options) {
1000
+ successCallback(helper.guid());
1001
+ };
1002
+ module.exports.hasInternet = function (successCallback, errorCallback, options) {
1003
+ helper.sendSuccess("", successCallback, true);
1004
+ };
1005
+ module.exports.platform = function (successCallback, errorCallback, options) {
1006
+ successCallback("browser");
1007
+ };
1008
+
1009
+ //#endregion
1010
+
1011
+ //#region Log Apis
1012
+
1013
+ module.exports.logError = function (successCallback, errorCallback, options) {
1014
+ var sourceClass = options[0].srcClass;
1015
+ var method = options[0].srcMethod;
1016
+ var message = options[0].message;
1017
+ if (printLogs) {
1018
+ console.log("ERROR | " + sourceClass + " | " + method + " | " + message);
1019
+ }
1020
+ };
1021
+ module.exports.logDebug = function (successCallback, errorCallback, options) {
1022
+ var sourceClass = options[0].srcClass;
1023
+ var method = options[0].srcMethod;
1024
+ var message = options[0].message;
1025
+ if (printLogs) {
1026
+ console.log("DEBUG | " + sourceClass + " | " + method + " | " + message);
1027
+ }
1028
+ };
1029
+ module.exports.logImportant = function (successCallback, errorCallback, options) {
1030
+ var sourceClass = options[0].srcClass;
1031
+ var method = options[0].srcMethod;
1032
+ var message = options[0].message;
1033
+ if (printLogs) {
1034
+ console.log("IMPORTANT | " + sourceClass + " | " + method + " | " + message);
1035
+ }
1036
+ };
1037
+ module.exports.getLogs = function (successCallback, errorCallback, options) {
1038
+ console.log("getLogs: Api not supported on Web!");
1039
+ };
1040
+ module.exports.deleteLogs = function (successCallback, errorCallback, options) {
1041
+ console.log("deleteLogs: Api not supported on Web!");
1042
+ };
1043
+ module.exports.sendViaServer = function (successCallback, errorCallback, options) {
1044
+ console.log("sendViaServer: Api not supported on Web!");
1045
+ };
1046
+ module.exports.sendViaEmail = function (successCallback, errorCallback, options) {
1047
+ console.log("sendViaEmail: Api not supported on Web!");
1048
+ };
1049
+ module.exports.setLogLevel = function (successCallback, errorCallback, options) {
1050
+ var logLevel = options[0].logLevel;
1051
+ if (logLevel == LogLevel.debug) {
1052
+ printLogs = true;
1053
+ } else {
1054
+ printLogs = false;
1055
+ }
1056
+ };
1057
+ module.exports.startDiscoveryService = function (successCallback, errorCallback, options) {
1058
+ console.log("startDiscoveryService: Api not supported on Web!");
1059
+ };
1060
+
1061
+ //#endregion
1062
+
1063
+ //#region Internal modules
1064
+
1065
+ var helper = /** @class */ (function () {
1066
+ function helper() { }
1067
+ helper.getBeName = function (name) {
1068
+ var sMetas = metadata.sMeta.filter(function (e) {
1069
+ return e.name === name;
1070
+ });
1071
+ return sMetas[0].beName;
1072
+ };
1073
+ helper.getBeHeaderName = function (beName) {
1074
+ var headerName = "";
1075
+ metadata.sMeta.forEach(function (e) {
1076
+ if (e.beName === beName && e.isheader === true) {
1077
+ headerName = e.name;
1078
+ }
1079
+ });
1080
+ return headerName;
1081
+ };
1082
+ helper.getBeChildrenNames = function (structureName) {
1083
+ var sMetas = metadata.sMeta.filter(function (e) {
1084
+ return e.name === structureName;
1085
+ });
1086
+ sMetas = metadata.sMeta.filter(function (e) {
1087
+ return e.beName === sMetas[0].beName && e.isheader === false;
1088
+ });
1089
+ return sMetas;
1090
+ };
1091
+
1092
+ helper.getUBJsonFromHeader = function (headerObject) {
1093
+ if (!headerObject) return "";
1094
+ var headerCopy = JSON.parse(JSON.stringify(headerObject));
1095
+ var headerName = Object.keys(headerCopy)[0];
1096
+ var header = headerCopy[headerName];
1097
+ var beName = helper.getBeName(headerName);
1098
+ var final = {};
1099
+ var be = {};
1100
+ var headerLid = header.LID;
1101
+
1102
+ var fwFields = ["LID", "FID", "TIMESTAMP", "OBJECT_STATUS", "SYNC_STATUS"];
1103
+ fwFields.forEach((f) => {
1104
+ delete header[f];
1105
+ });
1106
+ be[headerName] = header;
1107
+ final[beName] = [be];
1108
+
1109
+ var childrenNames = helper.getBeChildrenNames(headerName);
1110
+ childrenNames.forEach((child) => {
1111
+ var childrenRecords = webDb.select(child.name, `FID = '${headerLid}' AND OBJECT_STATUS IN ('1','2','3')`);
1112
+ if (childrenRecords.length > 0) {
1113
+ for (i = 0; i < childrenRecords.length; i++) {
1114
+ var ch = childrenRecords[i];
1115
+ fwFields.forEach((f1) => {
1116
+ delete ch[f1];
1117
+ });
1118
+ childrenRecords[i] = ch;
1119
+ }
1120
+ be[child.name] = childrenRecords;
1121
+ }
1122
+ });
1123
+ return final;
1124
+ };
1125
+
1126
+ helper.getBeTableNames = function (beName) {
1127
+ var sMetas = metadata.sMeta.filter(function (e) {
1128
+ return e.beName === beName;
1129
+ });
1130
+ return sMetas;
1131
+ };
1132
+ helper.getStructureFields = function (structureName) {
1133
+ var beName = helper.getBeName(structureName);
1134
+ var sFieldMeta = metadata.fMeta.filter((f) => f.beName == beName && f.sName == structureName);
1135
+ var fwFields = ["LID", "FID", "TIMESTAMP", "OBJECT_STATUS", "SYNC_STATUS"];
1136
+ var mandatory = [true, false, false, false, false];
1137
+ var sqlTypes = ["TEXT", "TEXT", "INTEGER", "INTEGER", "INTEGER"];
1138
+
1139
+ for (var i = 0; i < fwFields.length; i++) {
1140
+ let fMeta = {};
1141
+ fMeta.beName = beName;
1142
+ fMeta.sName = structureName;
1143
+ fMeta.name = fwFields[i];
1144
+ fMeta.isGid = false;
1145
+ fMeta.isMandatory = mandatory[i];
1146
+ fMeta.sqlType = sqlTypes[i];
1147
+ sFieldMeta.push(fMeta);
1148
+ }
1149
+
1150
+ return sFieldMeta;
1151
+ };
1152
+
1153
+ helper.isEmpty = function (value) {
1154
+ if (value == undefined || value === null || value === "") return true;
1155
+ return false;
1156
+ };
1157
+ helper.copyProperty = function (src, dest) {
1158
+ for (var k in src) dest[k] = src[k];
1159
+ return dest;
1160
+ };
1161
+ helper.validateLoginParameters = function (mode, callback) {
1162
+ if (helper.isEmpty(loginParameters.appName)) {
1163
+ helper.sendError("Please provide Application Name!", callback);
1164
+ return false;
1165
+ }
1166
+
1167
+ if (helper.isEmpty(loginParameters.loginType)) {
1168
+ helper.sendError("Incorrect Login Type!", callback);
1169
+ return false;
1170
+ }
1171
+ if (loginParameters.loginType === loginType.sap || loginParameters.loginType === loginType.ads) {
1172
+ if (!loginParameters.domain) {
1173
+ helper.sendError("Please provide Domain!", callback);
1174
+ return false;
1175
+ }
1176
+ }
1177
+ if (helper.isEmpty(mode)) {
1178
+ helper.sendError("Please set Login Mode!", callback);
1179
+ return false;
1180
+ }
1181
+ var err = undefined;
1182
+ switch (mode) {
1183
+ case loginMode.authActivate:
1184
+ if (loginParameters.loginType == loginType.saml2) {
1185
+ if (this.isEmpty(loginParameters.url)) err = "Please provide Url!";
1186
+ else if (this.isEmpty(loginParameters.company)) err = "Please provide Company Name!";
1187
+ else if (this.isEmpty(loginParameters.redirectURL)) err = "Please provide SAML redirect URL!";
1188
+ break;
1189
+ }
1190
+ else {
1191
+ if (helper.isEmpty(loginParameters.url)) err = "Please provide Url!";
1192
+ else if (helper.isEmpty(loginParameters.company)) err = "Please provide Company Name!";
1193
+ else if (helper.isEmpty(loginParameters.username)) err = "Please provide User Id!";
1194
+ else if (helper.isEmpty(loginParameters.password)) err = "Please provide Password!";
1195
+ if (err) {
1196
+ helper.sendError(err, callback);
1197
+ return false;
1198
+ }
1199
+ }
1200
+ break;
1201
+ case loginMode.authLocal:
1202
+ if (helper.isEmpty(loginParameters.username)) err = "Please provide User Id!";
1203
+ else if (helper.isEmpty(loginParameters.password)) err = "Please provide Password!";
1204
+ if (err) {
1205
+ helper.sendError(err, callback);
1206
+ return false;
1207
+ }
1208
+ break;
1209
+ case loginMode.forgotPassword:
1210
+ break;
1211
+ }
1212
+ return true;
1213
+ };
1214
+ helper.guid = function () {
1215
+ function s4() {
1216
+ return Math.floor((1 + Math.random()) * 0x10000)
1217
+ .toString(16)
1218
+ .substring(1)
1219
+ .toUpperCase();
1220
+ }
1221
+ return s4() + s4() + "-" + s4() + "-" + s4();
1222
+ };
1223
+ helper.clearApplicationDb = function () {
1224
+ localStorage.removeItem(loginParameters.appName);
1225
+ localStorage.removeItem("token");
1226
+ webDb.appDb = null;
1227
+ webDb.fwDb = null;
1228
+
1229
+ var req = indexedDB.deleteDatabase(loginParameters.appName || "UNVIRED_DB");
1230
+ req.onsuccess = function () {
1231
+ console.log("Deleted database successfully");
1232
+ };
1233
+ req.onerror = function () {
1234
+ console.log("Couldn't delete database");
1235
+ };
1236
+ req.onblocked = function () {
1237
+ console.log("Couldn't delete database due to the operation being blocked");
1238
+ };
1239
+ };
1240
+ helper.sendError = function (msg, callback) {
1241
+ var cbResult = {};
1242
+ cbResult.type = resultType.error;
1243
+ cbResult.error = msg;
1244
+ callback(cbResult);
1245
+ };
1246
+ helper.sendSuccess = function (msg, callback, data) {
1247
+ var cbResult = {};
1248
+ cbResult.type = resultType.success;
1249
+ cbResult.error = msg;
1250
+ cbResult.data = data;
1251
+ callback(cbResult);
1252
+ };
1253
+ helper.sanitizeURL = function (url) {
1254
+ if (!url) {
1255
+ return "";
1256
+ }
1257
+ if (url.endsWith("UMP/")) {
1258
+ return url.replace("UMP/", "UMP");
1259
+ }
1260
+ if (url.endsWith("?local")) {
1261
+ return url.replace("?local", "");
1262
+ }
1263
+ return url;
1264
+ };
1265
+
1266
+ helper.currentDateTime = function () {
1267
+ var date = new Date();
1268
+ var aaaa = date.getFullYear();
1269
+ var gg = date.getDate();
1270
+ var mm = date.getMonth() + 1;
1271
+
1272
+ if (gg < 10) gg = "0" + gg;
1273
+
1274
+ if (mm < 10) mm = "0" + mm;
1275
+
1276
+ var cur_day = aaaa + "-" + mm + "-" + gg;
1277
+ var hours = date.getHours();
1278
+ var minutes = date.getMinutes();
1279
+ var seconds = date.getSeconds();
1280
+
1281
+ if (hours < 10) hours = "0" + hours;
1282
+ if (minutes < 10) minutes = "0" + minutes;
1283
+ if (seconds < 10) seconds = "0" + seconds;
1284
+ return cur_day + " " + hours + ":" + minutes + ":" + seconds;
1285
+ };
1286
+
1287
+ return helper;
1288
+ })();
1289
+
1290
+ var restUtil = /** @class */ (function () {
1291
+ function restUtil() { }
1292
+ /**
1293
+ * Rest Api call
1294
+ * TODO : Remove JQuery dependency for ajax call
1295
+ */
1296
+ restUtil.performRequest = function (endpoint, msg, callback, httpType, isAsync, credentials, jwtOption) {
1297
+ var headers = {
1298
+ Accept: "application/json",
1299
+ "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
1300
+ Authorization: restUtil.appMeta.authorization,
1301
+ };
1302
+
1303
+ var postData = {
1304
+ frontendUser: restUtil.appMeta.frontEnd,
1305
+ messageFormat: "standard",
1306
+ inputMessage: JSON.stringify(msg),
1307
+ externalReference: helper.guid(),
1308
+ queuedExecute: isAsync,
1309
+ cltFwkVer: PACKAGE_NUMBER
1310
+ };
1311
+
1312
+ // Send the app version to the server for every call.
1313
+ if (loginParameters.appVersion) {
1314
+ postData['cltAppVer'] = loginParameters.appVersion;
1315
+ }
1316
+
1317
+ if (!helper.isEmpty(jwtOption)) {
1318
+ postData.jwtOptions = JSON.stringify(jwtOption);
1319
+ }
1320
+
1321
+ // Pass diff login credentials for session call ans Other credentials for execute call
1322
+ if (!helper.isEmpty(credentials)) {
1323
+ postData.credentials = credentials;
1324
+ }
1325
+
1326
+ var methodType = httpType ? httpType : "POST";
1327
+ $.ajax({
1328
+ type: methodType,
1329
+ url: endpoint,
1330
+ data: postData,
1331
+ success: function (res, textStatus, request) {
1332
+ var refreshToken = request.getResponseHeader("jwttoken");
1333
+ if (refreshToken) {
1334
+ localStorage.setItem("token", refreshToken);
1335
+ restUtil.appMeta.authorization = "Bearer:" + refreshToken;
1336
+ }
1337
+ restUtil.handleRestApiCallback(true, res, callback);
1338
+ },
1339
+ error: function (res) {
1340
+ restUtil.handleRestApiCallback(false, res, callback);
1341
+ },
1342
+ headers: headers,
1343
+ dataType: "json",
1344
+ });
1345
+ };
1346
+ restUtil.handleRestApiCallback = function (isSuccess, result, callback) {
1347
+ var cbResult = {};
1348
+ if (isSuccess) {
1349
+ cbResult.type = resultType.success;
1350
+ cbResult.message = result && result.message ? result.message : "";
1351
+ cbResult.data = result;
1352
+ } else {
1353
+ cbResult.type = resultType.error;
1354
+ cbResult.error = result && result.responseText ? result.responseText : "";
1355
+ cbResult.message = result && result.message ? result.message : "";
1356
+ }
1357
+ cbResult.code = result && result.status ? result.status : '';
1358
+ callback(cbResult);
1359
+ };
1360
+
1361
+ restUtil.appMeta = {};
1362
+ restUtil.httpType = {
1363
+ get: "GET",
1364
+ post: "POST",
1365
+ del: "DELETE",
1366
+ };
1367
+ return restUtil;
1368
+ })();
1369
+
1370
+ var parser = /** @class */ (function () {
1371
+ function parser() { }
1372
+ parser.parseServerResponse = function (data, reqype, headerLid, autoSave) {
1373
+ var cbResult = {};
1374
+ cbResult.type = resultType.success;
1375
+ cbResult.data = data;
1376
+ cbResult.message = "";
1377
+
1378
+ //Save InfoMessages and return Failure response if any Failure Infomessage
1379
+ if (data.hasOwnProperty("InfoMessage")) {
1380
+ var infoArr = data.InfoMessage;
1381
+ infoArr.forEach(function (infoMessage) {
1382
+ // infoMessage.beName = beName;
1383
+ if (!helper.isEmpty(headerLid)) {
1384
+ infoMessage.beLid = headerLid;
1385
+ }
1386
+ webDb.insert("INFO_MESSAGE", infoMessage);
1387
+ cbResult.message = cbResult.message + " " + infoMessage.message;
1388
+ if (infoMessage.category === "FAILURE") {
1389
+ cbResult.type = resultType.error;
1390
+ }
1391
+ });
1392
+ }
1393
+
1394
+ if (cbResult.type == resultType.error || !autoSave) {
1395
+ return cbResult;
1396
+ }
1397
+
1398
+ for (var property in data) {
1399
+ if (property === "InfoMessage") {
1400
+ continue;
1401
+ } else {
1402
+ var beArr = data[property];
1403
+ // Clear BE for PULL request.Pull will always be Insert
1404
+ if (reqype == requestType.PULL) {
1405
+ var children = helper.getBeTableNames(property);
1406
+ if (children != null && children.length > 0) {
1407
+ for (var i = 0; i < children.length; i++) {
1408
+ webDb.execute(`DELETE FROM ${children[i].name}`);
1409
+ }
1410
+ }
1411
+ }
1412
+
1413
+ beArr.forEach(function (element) {
1414
+ // Ignore if incoming BE does nont exist in metadata
1415
+ var sMetas = metadata.sMeta.filter(function (e) {
1416
+ return e.beName === property;
1417
+ });
1418
+ if (sMetas.length <= 0) {
1419
+ console.log(`Ignoring processing BE - ${property} as it does not exist in current metadata.`);
1420
+ return;
1421
+ }
1422
+
1423
+ parser.handleEachBE(element, reqype, property, headerLid);
1424
+ });
1425
+ }
1426
+ }
1427
+
1428
+ return cbResult;
1429
+ };
1430
+ parser.handleEachBE = function (be, reqType, beName, headerLid) {
1431
+ //var headerLid = "";
1432
+ if (helper.isEmpty(headerLid))
1433
+ headerLid = helper.guid();
1434
+
1435
+ var isActionDelete = false;
1436
+
1437
+ for (var property in be) {
1438
+ if (be.hasOwnProperty(property)) {
1439
+ var value = be[property];
1440
+ //Item
1441
+ if (value.constructor === Array) {
1442
+ value.forEach(function (item) {
1443
+ item["FID"] = headerLid;
1444
+ var structureInDB = reqType === requestType.PULL ? null : webDb.getBasedOnGidOrLid(property, item);
1445
+ if (structureInDB == null) {
1446
+ item.FID = headerLid;
1447
+ webDb.insert(property, item);
1448
+ } else {
1449
+ item["LID"] = structureInDB["LID"]
1450
+ item = helper.copyProperty(item, structureInDB);
1451
+ item["OBJECT_STATUS"] = 0;
1452
+ item["SYNC_STATUS"] = 0;
1453
+ webDb.updateStructure(property, item);
1454
+ }
1455
+ });
1456
+
1457
+ //Header
1458
+ } else if (value.constructor === Object) {
1459
+ value["LID"] = headerLid; //helper.guid();
1460
+ //headerLid = value.LID;
1461
+
1462
+ //Handle action delete
1463
+ if (isActionDelete) {
1464
+ webDb.deleteRecordStructure(property, value);
1465
+ return;
1466
+ }
1467
+ var structureInDB = reqType === requestType.PULL ? null : webDb.getBasedOnGidOrLid(property, value);
1468
+
1469
+ //Browser does not support reconciliation so delete BE if exists and copy over existing header field values
1470
+ // Otherwise items not present in server will remain on client db
1471
+ if (reqType === requestType.RQST) {
1472
+ if (structureInDB && structureInDB != null) {
1473
+ var children = helper.getBeChildrenNames(property);
1474
+ if (children != null && children.length > 0) {
1475
+ for (var i = 0; i < children.length; i++) {
1476
+ webDb.deleteRecord(children[i]["name"], `FID='${structureInDB.LID}'`);
1477
+ }
1478
+ }
1479
+ }
1480
+ }
1481
+ if (structureInDB == null) {
1482
+ value.LID = headerLid; //helper.guid();
1483
+ webDb.insert(property, value);
1484
+ } else {
1485
+
1486
+ switch (reqType) {
1487
+ case requestType.PULL:
1488
+ case requestType.QUERY:
1489
+ case requestType.PUSH:
1490
+
1491
+ /**
1492
+ * If the object status is 0, then it means that the object is in sync with the server.
1493
+ * Otherwise, it means it has local changes.
1494
+ * We do not want to override the local changes with the server changes.
1495
+ */
1496
+ if (structureInDB["OBJECT_STATUS"] == 0) {
1497
+ value["LID"] = structureInDB["LID"]
1498
+ value = helper.copyProperty(value, structureInDB);
1499
+ value["OBJECT_STATUS"] = 0;
1500
+ value["SYNC_STATUS"] = 0;
1501
+ webDb.updateStructure(property, value);
1502
+ }
1503
+ break;
1504
+
1505
+ case requestType.RQST:
1506
+
1507
+ /**
1508
+ * For RQST type, we want to override the local changes with the server changes.
1509
+ */
1510
+ value["LID"] = structureInDB["LID"]
1511
+ value = helper.copyProperty(value, structureInDB);
1512
+ value["OBJECT_STATUS"] = 0;
1513
+ value["SYNC_STATUS"] = 0;
1514
+ webDb.updateStructure(property, value);
1515
+
1516
+ break;
1517
+
1518
+ }
1519
+ }
1520
+
1521
+ //headerLid = value.LID;
1522
+ } else {
1523
+ //Handle Action D - Delete Header and children
1524
+ isActionDelete = "D" == value;
1525
+ }
1526
+ }
1527
+ }
1528
+ };
1529
+ return parser;
1530
+ })();
1531
+
1532
+ // metadataParser - parse metadata.json, create BusinessEntityMeta, StructureMeta and FieldMeta and save.
1533
+ var metadataParser = /** @class */ (function () {
1534
+ function metadataParser() { }
1535
+ metadataParser.initialize = function () {
1536
+ if (loginParameters.metadataPath.length > 0) {
1537
+ metadataParser.loadJSON(metadataParser.parse);
1538
+ } else if (loginParameters.metadataJSON.length > 0) {
1539
+ metadataParser.parse(loginParameters.metadataJSON);
1540
+ } else {
1541
+ console.log("ERROR: " + "metadataJSON is empty. Set the JSON to loginParameters.metadataJSON");
1542
+ }
1543
+ };
1544
+ metadataParser.loadJSON = function (callback) {
1545
+ var xobj = new XMLHttpRequest();
1546
+ xobj.overrideMimeType("application/json");
1547
+ var metadataPath = helper.isEmpty(loginParameters.metadataPath) ? "metadata.json" : loginParameters.metadataPath;
1548
+ xobj.open("GET", metadataPath, true);
1549
+ xobj.onreadystatechange = function () {
1550
+ if (xobj.readyState == 4 && xobj.status == 200) {
1551
+ callback(xobj.responseText);
1552
+ }
1553
+ };
1554
+ xobj.send(null);
1555
+ };
1556
+ metadataParser.parse = function (json) {
1557
+ if (helper.isEmpty(json)) return;
1558
+ //Parse metadata.json and hold it in metadata in localstorage
1559
+ // Clearing all parsed array to avoid duplicating on multiple metadata parse call from app. e.g. calling login apis will trigger parse metadata again
1560
+ metadata.sMeta = [];
1561
+ metadata.fMeta = [];
1562
+ metadata.bMeta = [];
1563
+ var data = JSON.parse(json);
1564
+ for (var property in data) {
1565
+ if (data.hasOwnProperty(property)) {
1566
+ var value = data[property];
1567
+ if (value.constructor === Object) {
1568
+ metadataParser.parseEachBE(value, property);
1569
+ }
1570
+ }
1571
+ }
1572
+ // Add InfoMessage to metadata be,s and fmeta
1573
+
1574
+ var beMeta = {};
1575
+ beMeta.attachment = false;
1576
+ beMeta.onConflict = "SERVER_WINS";
1577
+ beMeta.save = true;
1578
+ beMeta.name = "INFO_MESSAGE";
1579
+ metadata.bMeta.push(beMeta);
1580
+
1581
+ var infoSMeta = {
1582
+ beName: "INFO_MESSAGE",
1583
+ isheader: true,
1584
+ name: "INFO_MESSAGE",
1585
+ };
1586
+ metadata.sMeta.push(infoSMeta);
1587
+
1588
+ var uniqueKeys = ["LID"];
1589
+ var columnNames = [
1590
+ "LID",
1591
+ "TIMESTAMP",
1592
+ "TYPE",
1593
+ "SUB_TYPE",
1594
+ "CATEGORY",
1595
+ "MESSAGE",
1596
+ "BE_NAME",
1597
+ "BE_LID",
1598
+ "MESSAGE_BLOB",
1599
+ ];
1600
+ var columnTypes = ["TEXT", "INTEGER", "TEXT", "TEXT", "TEXT", "TEXT", "TEXT", "TEXT", "BLOB"];
1601
+ columnNames.forEach(function (cName) {
1602
+ let fMeta = {
1603
+ beName: "INFO_MESSAGE",
1604
+ sName: "INFO_MESSAGE",
1605
+ name: cName,
1606
+ isGid: uniqueKeys.indexOf(cName) !== -1,
1607
+ isMandatory: false,
1608
+ sqlType: columnTypes[columnNames.indexOf(cName)],
1609
+ };
1610
+ metadata.fMeta.push(fMeta);
1611
+ });
1612
+ };
1613
+ metadataParser.parseEachBE = function (be, name) {
1614
+ var beMeta = {};
1615
+ beMeta.attachment = helper.isEmpty(be.attachments) ? false : be.attachments;
1616
+ beMeta.onConflict = helper.isEmpty(be.onConflict) ? conflictRule.SERVER_WINS : be.onConflict;
1617
+ beMeta.save = helper.isEmpty(be.save) ? true : be.save;
1618
+ beMeta.name = name;
1619
+ metadata.bMeta.push(beMeta);
1620
+ for (var property in be) {
1621
+ if (be.hasOwnProperty(property)) {
1622
+ var value = be[property];
1623
+ if (value.constructor === Object) {
1624
+ var sMeta = {};
1625
+ sMeta.beName = beMeta.name;
1626
+ sMeta.isheader = property.indexOf("_HEADER") > -1 || property.indexOf("_HDR") > -1 ? true : false;
1627
+ sMeta.name = property;
1628
+ metadata.sMeta.push(sMeta);
1629
+ var fields = value.field;
1630
+ if (fields != null && fields.length > 0) {
1631
+ fields.forEach(function (f) {
1632
+ var fMeta = {};
1633
+ fMeta.beName = beMeta.name;
1634
+ fMeta.sName = sMeta.name;
1635
+ fMeta.name = f.name;
1636
+ fMeta.isGid = f.isGid;
1637
+ fMeta.isMandatory = f.mandatory;
1638
+ fMeta.sqlType = f.sqlType;
1639
+ metadata.fMeta.push(fMeta);
1640
+ });
1641
+ }
1642
+ }
1643
+ }
1644
+ }
1645
+ };
1646
+ return metadataParser;
1647
+ })();
1648
+
1649
+ //#endregion
1650
+
1651
+ //#region WebDb Module
1652
+ var webDb = /** @class */ (function () {
1653
+ function webDb() { }
1654
+
1655
+ webDb.initialize = function (callback) {
1656
+ var initSqlJs = window.initSqlJs;
1657
+ config = {
1658
+ locateFile: (filename) => "assets/js/sql-wasm.wasm",
1659
+ };
1660
+ initSqlJs(config).then(function (SQL) {
1661
+ if (webDb.appDb == null) {
1662
+ webDb.appDb = new SQL.Database();
1663
+ webDb.createApplicationTables();
1664
+ webDb.createInfoMessageTable();
1665
+ if (loginParameters.cacheWebData) {
1666
+ webDb.populateWebDb(SQL, function () {
1667
+ callback()
1668
+ });
1669
+ }
1670
+ else {
1671
+ callback();
1672
+ }
1673
+ } else {
1674
+ callback();
1675
+ }
1676
+ });
1677
+ };
1678
+ webDb.insert = function (name, structure) {
1679
+ if (helper.isEmpty(structure.LID)) {
1680
+ structure.LID = helper.guid();
1681
+ }
1682
+ if (helper.isEmpty(structure.TIMESTAMP)) {
1683
+ structure.TIMESTAMP = helper.currentDateTime();
1684
+ }
1685
+ var columnIndex = 0;
1686
+ var columnNames = [];
1687
+ var columnValues = [];
1688
+ var sFieldMeta = helper.getStructureFields(name);
1689
+ sFieldMeta.forEach(function (fMeta) {
1690
+ if (structure.hasOwnProperty(fMeta.name)) {
1691
+ if (!structure[fMeta.name]) return;
1692
+ columnNames[columnIndex] = fMeta.name;
1693
+ columnValues[columnIndex] = structure[fMeta.name];
1694
+ columnIndex++;
1695
+ }
1696
+ });
1697
+ var query = webDb.prepareInsertBindQuery(name, columnNames);
1698
+ webDb.executeBindQuery(query, columnValues);
1699
+ };
1700
+ webDb.insertOrUpdateBasedOnGid = function (tableName, structure) {
1701
+ if (helper.isEmpty(structure.LID)) {
1702
+ structure.LID = helper.guid();
1703
+ }
1704
+ var columnIndex = 0;
1705
+ var columnNames = [];
1706
+ var columnValues = [];
1707
+ var sFieldMeta = helper.getStructureFields(tableName);
1708
+ sFieldMeta.forEach(function (fMeta) {
1709
+ if (structure.hasOwnProperty(fMeta.name)) {
1710
+ if (helper.isEmpty(structure[fMeta.name])) return;
1711
+ columnNames[columnIndex] = fMeta.name;
1712
+ columnValues[columnIndex] = structure[fMeta.name];
1713
+ columnIndex++;
1714
+ }
1715
+ });
1716
+ var query = webDb.prepareReplaceBindQuery(tableName, columnNames);
1717
+ webDb.executeBindQuery(query, columnValues);
1718
+ };
1719
+ webDb.select = function (tableName, whereClause, orderByFields) {
1720
+ whereClause = whereClause;
1721
+ var query = webDb.prepareSelectQuery(tableName, whereClause, orderByFields);
1722
+ return webDb.executeQuery(query);
1723
+ };
1724
+ webDb.updateStructure = function (tableName, structure, whereClause) {
1725
+ var columnIndex = 0;
1726
+ var columnNames = [];
1727
+ var columnValues = [];
1728
+ var sFieldMeta = helper.getStructureFields(tableName);
1729
+ sFieldMeta.forEach(function (fMeta) {
1730
+ if (structure.hasOwnProperty(fMeta.name)) {
1731
+ if (helper.isEmpty(structure[fMeta.name])) return;
1732
+ columnNames[columnIndex] = fMeta.name;
1733
+ columnValues[columnIndex] = structure[fMeta.name];
1734
+ columnIndex++;
1735
+ }
1736
+ });
1737
+ whereClause = helper.isEmpty(whereClause) ? `LID = '${structure.LID}'` : whereClause;
1738
+ var query = webDb.prepareReplaceBindQuery(tableName, columnNames);
1739
+ webDb.executeBindQuery(query, columnValues);
1740
+ webDb.update(tableName, columnNames, columnValues, whereClause);
1741
+ };
1742
+ webDb.update = function (tableName, columnNames, columnValues, whereClause) {
1743
+ var query = webDb.prepareUpdateBindQuery(tableName, columnNames, whereClause);
1744
+ webDb.executeBindQuery(query, columnValues);
1745
+ };
1746
+ webDb.deleteRecordStructure = function (tableName, structure) {
1747
+ var structureInDB = webDb.getBasedOnGid(tableName, structure);
1748
+ if (structureInDB && structureInDB != null) {
1749
+ webDb.deleteRecord(tableName, `LID = '${structureInDB.LID}'`);
1750
+ }
1751
+ };
1752
+ webDb.deleteRecord = function (tableName, whereClause) {
1753
+ var query = webDb.prepareDeleteQuery(tableName, whereClause);
1754
+ webDb.execute(query);
1755
+ };
1756
+ webDb.saveAppMeta = function (appMeta) {
1757
+ metadata.appMeta = appMeta;
1758
+ localStorage.setItem(loginParameters.appName, JSON.stringify(appMeta));
1759
+ // webDb.insert("appMeta", appMeta, true);
1760
+ };
1761
+ webDb.getAppMeta = function () {
1762
+ metadata.appMeta.authorization = "Bearer:" + localStorage.getItem("token");
1763
+ return metadata.appMeta;
1764
+ };
1765
+ webDb.reloadAppMeta = function (callback) {
1766
+ var token = localStorage.getItem("token");
1767
+ if (!token) return callback(false);
1768
+
1769
+ var appMeta = localStorage.getItem(loginParameters.appName);
1770
+ if (appMeta) {
1771
+ metadata.appMeta = JSON.parse(appMeta);
1772
+ restUtil.appMeta.authorization = "Bearer:" + token;
1773
+ } else {
1774
+ if (!loginParameters.appName) {
1775
+ console.log("App name is not provided. Current session token will be ignored and forced user to login");
1776
+ return callback(false);
1777
+ }
1778
+
1779
+ url = localStorage.getItem("UMP_url");
1780
+ if (!url) {
1781
+ url = loginParameters.url;
1782
+ }
1783
+ // Append /UMP if not there.
1784
+ if (url && !url.endsWith("/UMP") && !url.endsWith("/UMP/")) {
1785
+ if (!url.endsWith("/")) {
1786
+ url += "/";
1787
+ }
1788
+ url += "UMP";
1789
+ }
1790
+
1791
+ restUtil.appMeta = {};
1792
+ restUtil.appMeta.frontEnd = loginParameters.feUserId;
1793
+ restUtil.appMeta.appName = loginParameters.appName;
1794
+ restUtil.appMeta.url = url;
1795
+ restUtil.appMeta.company = localStorage.getItem("company");
1796
+ restUtil.appMeta.username = localStorage.getItem("email"); // This field holds the username for all login types.
1797
+ restUtil.appMeta.loginType = localStorage.getItem("login_type");
1798
+ restUtil.appMeta.domain = localStorage.getItem("domain"); // Required for ADS login.
1799
+ webDb.saveAppMeta(restUtil.appMeta);
1800
+ restUtil.appMeta.authorization = "Bearer:" + token;
1801
+ }
1802
+ webDb.initialize(function () {
1803
+ callback(true);
1804
+ });
1805
+ };
1806
+
1807
+ // Considering structure name is unique.(Not handling same structure across multiple BusinessEntity)
1808
+ webDb.getBasedOnGid = function (tableName, structure) {
1809
+ if (helper.isEmpty(tableName)) return null;
1810
+ var sMeta = metadata.sMeta.find(function (e) {
1811
+ return e.name === tableName;
1812
+ });
1813
+
1814
+ if (sMeta == null || sMeta.length <= 0) return null;
1815
+
1816
+ var sBeMeta = metadata.bMeta.find((b) => b.name === sMeta.beName);
1817
+ if (!sBeMeta.save) return;
1818
+
1819
+ var gidColumns = metadata.fMeta.filter(function (e) {
1820
+ return e.sName === tableName && e.isGid === true;
1821
+ });
1822
+ if (gidColumns == null || gidColumns.length <= 0) return null;
1823
+ var gidValues = [];
1824
+ var columnIndex = 0;
1825
+ gidColumns.forEach(function (gid) {
1826
+ gidColumns[columnIndex] = gid.name;
1827
+ gidValues[columnIndex] = helper.isEmpty(structure[gid.name]) ? null : structure[gid.name];
1828
+ columnIndex++;
1829
+ });
1830
+
1831
+ var whereClauseForDuplicate = "";
1832
+ for (var i = 0; i < gidColumns.length; i++) {
1833
+ if (i == gidColumns.length - 1)
1834
+ whereClauseForDuplicate =
1835
+ whereClauseForDuplicate +
1836
+ " " +
1837
+ gidColumns[i] +
1838
+ " = " +
1839
+ "'" +
1840
+ gidValues[i].toString().replace(/'/g, "''") +
1841
+ "'";
1842
+ else
1843
+ whereClauseForDuplicate =
1844
+ whereClauseForDuplicate +
1845
+ " " +
1846
+ gidColumns[i] +
1847
+ " = " +
1848
+ "'" +
1849
+ gidValues[i].toString().replace(/'/g, "''") +
1850
+ "'" +
1851
+ " AND ";
1852
+ }
1853
+
1854
+ var duplicateDataStructures = webDb.select(tableName, whereClauseForDuplicate);
1855
+ if (duplicateDataStructures != null && duplicateDataStructures.length > 0) {
1856
+ return duplicateDataStructures[0];
1857
+ }
1858
+ return null;
1859
+ };
1860
+ webDb.getBasedOnLid = function (tableName, structure) {
1861
+ if (helper.isEmpty(tableName)) return null;
1862
+ var whereClauseForDuplicate = `LID = '${structure.LID}'`;
1863
+ var duplicateDataStructures = webDb.select(tableName, whereClauseForDuplicate);
1864
+ if (duplicateDataStructures != null && duplicateDataStructures.length > 0) {
1865
+ return duplicateDataStructures[0];
1866
+ }
1867
+ return null;
1868
+ };
1869
+ webDb.getBasedOnGidOrLid = function (tableName, structure) {
1870
+ if (helper.isEmpty(tableName)) return null;
1871
+ var gidStructure = webDb.getBasedOnGid(tableName, structure);
1872
+ return gidStructure != null ? gidStructure : webDb.getBasedOnLid(tableName, structure);
1873
+ };
1874
+ //TODO
1875
+ webDb.reCreateAppDb = function () {
1876
+ console.log("reCreateAppDb: Api not implemented!");
1877
+ };
1878
+ webDb.createApplicationTables = function () {
1879
+ var foreignKeysForItemStructure = ["FID"];
1880
+ var parentsForForeignKeysInHeaderStructure = ["LID"];
1881
+
1882
+ metadata.sMeta.forEach(function (s) {
1883
+ if (s.beName.indexOf("INFO_MESSAGE") != -1) return;
1884
+ var sFieldMeta = metadata.fMeta.filter((f) => f.beName == s.beName && f.sName == s.name);
1885
+ var sBeMeta = metadata.bMeta.find((b) => b.name === s.beName);
1886
+ // Do not create table if BE Save property is false
1887
+ if (!sBeMeta.save) return;
1888
+
1889
+ var columnIndex = 0;
1890
+ var columnNames = [];
1891
+ var columnTypes = [];
1892
+ var mandatoryFields = [];
1893
+ var primaryKeys = ["LID"];
1894
+ var uniqueKeys = [];
1895
+
1896
+ if (s.isheader) {
1897
+ columnNames[0] = "LID";
1898
+ columnTypes[0] = "TEXT";
1899
+ mandatoryFields[0] = true;
1900
+
1901
+ columnNames[1] = "TIMESTAMP";
1902
+ columnTypes[1] = "INTEGER";
1903
+ mandatoryFields[1] = false;
1904
+
1905
+ columnNames[2] = "OBJECT_STATUS";
1906
+ columnTypes[2] = "INTEGER DEFAULT 0";
1907
+ mandatoryFields[2] = false;
1908
+
1909
+ columnNames[3] = "SYNC_STATUS";
1910
+ columnTypes[3] = "INTEGER DEFAULT 0";
1911
+ mandatoryFields[3] = false;
1912
+
1913
+ columnIndex = 4;
1914
+ } else {
1915
+ if (s.name.toLowerCase().endsWith("_attachment")) {
1916
+ return;
1917
+ }
1918
+
1919
+ columnNames[0] = "LID";
1920
+ columnTypes[0] = "TEXT";
1921
+ mandatoryFields[0] = true;
1922
+
1923
+ columnNames[1] = "FID";
1924
+ columnTypes[1] = "TEXT";
1925
+ mandatoryFields[1] = false;
1926
+
1927
+ columnNames[2] = "TIMESTAMP";
1928
+ columnTypes[2] = "INTEGER";
1929
+ mandatoryFields[2] = false;
1930
+
1931
+ columnNames[3] = "OBJECT_STATUS";
1932
+ columnTypes[3] = "INTEGER DEFAULT 0";
1933
+ mandatoryFields[3] = false;
1934
+
1935
+ columnNames[4] = "SYNC_STATUS";
1936
+ columnTypes[4] = "INTEGER DEFAULT 0";
1937
+ mandatoryFields[4] = false;
1938
+
1939
+ columnIndex = 5;
1940
+ }
1941
+
1942
+ sFieldMeta.forEach(function (fMeta) {
1943
+ columnNames[columnIndex] = fMeta.name;
1944
+ columnTypes[columnIndex] = fMeta.sqlType;
1945
+ if (fMeta.isGid) {
1946
+ uniqueKeys.push(fMeta.name);
1947
+ }
1948
+ mandatoryFields[columnIndex] = fMeta.isMandatory;
1949
+ columnIndex++;
1950
+ });
1951
+
1952
+ if (s.isheader) {
1953
+ webDb.createTable(s.name, columnNames, columnTypes, primaryKeys, uniqueKeys, mandatoryFields, null, null, null);
1954
+
1955
+ // If BE support attachment then create BEName_Attachement tabel and add StructureMeta and FieldMeta entry to metadata
1956
+ if (sBeMeta.attachment) {
1957
+ webDb.createAttachmentTable(sBeMeta.name, s.name);
1958
+ }
1959
+ } else {
1960
+ var headerName = helper.getBeHeaderName(s.beName);
1961
+ webDb.createTable(
1962
+ s.name,
1963
+ columnNames,
1964
+ columnTypes,
1965
+ primaryKeys,
1966
+ uniqueKeys,
1967
+ mandatoryFields,
1968
+ foreignKeysForItemStructure,
1969
+ headerName,
1970
+ parentsForForeignKeysInHeaderStructure
1971
+ );
1972
+ }
1973
+ });
1974
+ };
1975
+ webDb.createTable = function (
1976
+ tableName,
1977
+ columnNames,
1978
+ columnTypes,
1979
+ primaryKeys,
1980
+ uniqueKeys,
1981
+ mandatoryFields,
1982
+ foreignKeys,
1983
+ foreignKeyTableName,
1984
+ foreignKeyTableKeys
1985
+ ) {
1986
+ var query = webDb.prepareCreateQuery(
1987
+ tableName,
1988
+ columnNames,
1989
+ columnTypes,
1990
+ primaryKeys,
1991
+ uniqueKeys,
1992
+ mandatoryFields,
1993
+ foreignKeys,
1994
+ foreignKeyTableName,
1995
+ foreignKeyTableKeys
1996
+ );
1997
+ webDb.execute(query);
1998
+ };
1999
+ webDb.createAttachmentTable = function (beName, headerName) {
2000
+ var attchPrimaryKeys = ["LID"];
2001
+ var foreignKeysForItemStructure = ["FID"];
2002
+ var attchUniqueKeys = ["UID"];
2003
+ var parentsForForeignKeysInHeaderStructure = ["LID"];
2004
+ var attchColumnNames = [
2005
+ "LID",
2006
+ "FID",
2007
+ "TIMESTAMP",
2008
+ "OBJECT_STATUS",
2009
+ "SYNC_STATUS",
2010
+ "UID",
2011
+ "MIME_TYPE",
2012
+ "FILE_NAME",
2013
+ "DESCRIPTION",
2014
+ "URL",
2015
+ "EXTERNAL_URL",
2016
+ "URL_REQUIRES_AUTH",
2017
+ "LOCAL_PATH",
2018
+ "NO_CACHE",
2019
+ "AUTO_DOWNLOAD",
2020
+ "ATTACHMENT_STATUS",
2021
+ "CUSTOM_FIELD_1",
2022
+ "CUSTOM_FIELD_2",
2023
+ "TAG1",
2024
+ "TAG2",
2025
+ "TAG3",
2026
+ "TAG4",
2027
+ "TAG5",
2028
+ "DATA",
2029
+ ];
2030
+ var attchColumnTypes = [
2031
+ "TEXT",
2032
+ "TEXT",
2033
+ "INTEGER",
2034
+ "INTEGER DEFAULT 0",
2035
+ "INTEGER DEFAULT 0",
2036
+ "TEXT",
2037
+ "TEXT",
2038
+ "TEXT",
2039
+ "TEXT",
2040
+ "TEXT",
2041
+ "TEXT",
2042
+ "TEXT",
2043
+ "TEXT",
2044
+ "TEXT",
2045
+ "TEXT",
2046
+ "INTEGER",
2047
+ "TEXT",
2048
+ "TEXT",
2049
+ "TEXT",
2050
+ "TEXT",
2051
+ "TEXT",
2052
+ "TEXT",
2053
+ "TEXT",
2054
+ "TEXT",
2055
+ ];
2056
+ var attchMandatoryFields = [
2057
+ true,
2058
+ true,
2059
+ false,
2060
+ false,
2061
+ false,
2062
+ false,
2063
+ false,
2064
+ false,
2065
+ false,
2066
+ false,
2067
+ false,
2068
+ false,
2069
+ false,
2070
+ false,
2071
+ false,
2072
+ false,
2073
+ false,
2074
+ false,
2075
+ false,
2076
+ false,
2077
+ false,
2078
+ false,
2079
+ false,
2080
+ false,
2081
+ ];
2082
+
2083
+ webDb.createTable(
2084
+ `${beName}_ATTACHMENT`,
2085
+ attchColumnNames,
2086
+ attchColumnTypes,
2087
+ attchPrimaryKeys,
2088
+ attchUniqueKeys,
2089
+ attchMandatoryFields,
2090
+ foreignKeysForItemStructure,
2091
+ headerName,
2092
+ parentsForForeignKeysInHeaderStructure
2093
+ );
2094
+
2095
+ var attchSMeta = {
2096
+ beName: beName,
2097
+ isheader: false,
2098
+ name: `${beName}_ATTACHMENT`,
2099
+ };
2100
+ metadata.sMeta.push(attchSMeta);
2101
+
2102
+ attchColumnNames.forEach(function (cName) {
2103
+ let fMeta = {
2104
+ beName: beName,
2105
+ sName: `${beName}_ATTACHMENT`,
2106
+ name: cName,
2107
+ isGid: attchUniqueKeys.indexOf(cName) !== -1,
2108
+ isMandatory: attchMandatoryFields[attchColumnNames.indexOf(cName)],
2109
+ sqlType: attchColumnTypes[attchColumnNames.indexOf(cName)],
2110
+ };
2111
+ metadata.fMeta.push(fMeta);
2112
+ });
2113
+ };
2114
+ webDb.createInfoMessageTable = function () {
2115
+ var primaryKeys = ["LID"];
2116
+ var uniqueKeys = ["LID"];
2117
+ var columnNames = [
2118
+ "LID",
2119
+ "TIMESTAMP",
2120
+ "TYPE",
2121
+ "SUB_TYPE",
2122
+ "CATEGORY",
2123
+ "MESSAGE",
2124
+ "BE_NAME",
2125
+ "BE_LID",
2126
+ "MESSAGE_BLOB",
2127
+ ];
2128
+ var columnTypes = ["TEXT", "INTEGER", "TEXT", "TEXT", "TEXT", "TEXT", "TEXT", "TEXT", "BLOB"];
2129
+ webDb.createTable("INFO_MESSAGE", columnNames, columnTypes, primaryKeys, uniqueKeys);
2130
+
2131
+ var attchSMeta = {
2132
+ beName: "INFO_MESSAGE",
2133
+ isheader: true,
2134
+ name: "INFO_MESSAGE",
2135
+ };
2136
+ metadata.sMeta.push(attchSMeta);
2137
+
2138
+ columnNames.forEach(function (cName) {
2139
+ let fMeta = {
2140
+ beName: "INFO_MESSAGE",
2141
+ sName: "INFO_MESSAGE",
2142
+ name: cName,
2143
+ isGid: uniqueKeys.indexOf(cName) !== -1,
2144
+ isMandatory: false,
2145
+ sqlType: columnTypes[columnNames.indexOf(cName)],
2146
+ };
2147
+ metadata.fMeta.push(fMeta);
2148
+ });
2149
+ };
2150
+ // Execute query without return result
2151
+ webDb.execute = function (query) {
2152
+ webDb.appDb.run(query);
2153
+ };
2154
+ //Execute query and return results
2155
+ webDb.executeQuery = function (query) {
2156
+ var rows = [];
2157
+ if (!webDb.appDb) {
2158
+ console.log('App DB not initialized yet. Call this api after sometime.')
2159
+ return rows
2160
+ }
2161
+
2162
+ var stmt = webDb.appDb.prepare(query);
2163
+ while (stmt.step()) {
2164
+ var row = stmt.getAsObject();
2165
+ rows.push(row);
2166
+ }
2167
+ return rows;
2168
+ };
2169
+ //Execute bind query without return result
2170
+ webDb.executeBindQuery = function (query, value) {
2171
+ webDb.appDb.run(query, value);
2172
+ };
2173
+ webDb.prepareCreateQuery = function (
2174
+ tableName,
2175
+ tableColumnNames,
2176
+ tableColumnTypes,
2177
+ primaryKeys,
2178
+ uniqueKeys,
2179
+ mandatoryFields,
2180
+ foreignKeys,
2181
+ foreignKeyTableName,
2182
+ foreignKeyTableKeys
2183
+ ) {
2184
+ var query = "";
2185
+ var primaryKey = "";
2186
+ var uniqueKey = "";
2187
+ var foreignKey = "";
2188
+ var foreignKeyTableKey = "";
2189
+
2190
+ if (primaryKeys != null) {
2191
+ for (var i = 0; i < primaryKeys.length; i++) {
2192
+ if (i == 0) {
2193
+ primaryKey += primaryKeys[i];
2194
+ } else {
2195
+ primaryKey += ", " + primaryKeys[i];
2196
+ }
2197
+ }
2198
+ }
2199
+
2200
+ if (uniqueKeys != null) {
2201
+ for (var i = 0; i < uniqueKeys.length; i++) {
2202
+ if (i == 0) {
2203
+ uniqueKey += uniqueKeys[i];
2204
+ } else {
2205
+ uniqueKey += ", " + uniqueKeys[i];
2206
+ }
2207
+ }
2208
+ }
2209
+
2210
+ if (foreignKeyTableName != null) {
2211
+ for (var i = 0; i < foreignKeys.length; i++) {
2212
+ if (i == 0) {
2213
+ foreignKey += foreignKeys[i];
2214
+ } else {
2215
+ foreignKey += ", " + foreignKeys[i];
2216
+ }
2217
+ }
2218
+
2219
+ for (var i = 0; i < foreignKeyTableKeys.length; i++) {
2220
+ if (i == 0) {
2221
+ foreignKeyTableKey += foreignKeyTableKeys[i];
2222
+ } else {
2223
+ foreignKeyTableKey += ", " + foreignKeyTableKeys[i];
2224
+ }
2225
+ }
2226
+ }
2227
+
2228
+ var noOfColumns = 0;
2229
+
2230
+ if (tableColumnNames != null) noOfColumns = tableColumnNames.length;
2231
+
2232
+ query = "CREATE TABLE '" + tableName + "' (";
2233
+
2234
+ for (var i = 0; i < noOfColumns; i++) {
2235
+ if (i == 0) query += "'" + tableColumnNames[i] + "' ";
2236
+ else query += ", '" + tableColumnNames[i] + "' ";
2237
+
2238
+ if (tableColumnTypes != null) {
2239
+ try {
2240
+ query += tableColumnTypes[i];
2241
+ } catch (error) {
2242
+ console.error(`Error occured in preparing create query. ${error}`);
2243
+ }
2244
+ }
2245
+
2246
+ if (mandatoryFields != null) {
2247
+ var isMandatory = mandatoryFields[i];
2248
+ if (isMandatory) {
2249
+ query += " NOT NULL";
2250
+ }
2251
+ }
2252
+ }
2253
+
2254
+ if (!helper.isEmpty(primaryKey)) {
2255
+ query += ", " + "PRIMARY KEY(" + primaryKey + ")";
2256
+ }
2257
+
2258
+ if (!helper.isEmpty(uniqueKey)) {
2259
+ query += ", " + "UNIQUE(" + uniqueKey + ")";
2260
+ }
2261
+
2262
+ if (!helper.isEmpty(foreignKeyTableName)) {
2263
+ query +=
2264
+ ", FOREIGN KEY(" +
2265
+ foreignKey +
2266
+ ") REFERENCES " +
2267
+ foreignKeyTableName +
2268
+ "(" +
2269
+ foreignKeyTableKey +
2270
+ ")" +
2271
+ "ON UPDATE CASCADE ON DELETE CASCADE";
2272
+ }
2273
+
2274
+ query = query + ")";
2275
+
2276
+ return query;
2277
+ };
2278
+ webDb.prepareInsertBindQuery = function (tableName, tableColumnNames) {
2279
+ var query = "";
2280
+ var noOfColumns = tableColumnNames.length;
2281
+
2282
+ query = "INSERT INTO " + tableName + " (";
2283
+
2284
+ for (let i = 0; i < noOfColumns; i++) {
2285
+ var key = tableColumnNames[i];
2286
+ query = query + key + ",";
2287
+ }
2288
+
2289
+ query = query.slice(0, -1);
2290
+ query += ")";
2291
+ query = query + " VALUES (";
2292
+
2293
+ var value = "";
2294
+ for (var i = 0; i < noOfColumns; i++) {
2295
+ value = value == "" ? value + "?" : value + ", " + "?";
2296
+ }
2297
+ query = query + value + ")";
2298
+ return query;
2299
+ };
2300
+ webDb.prepareSelectQuery = function (tableName, whereClause, orderByFields) {
2301
+ var query = "SELECT * FROM " + tableName + " ";
2302
+ if (!helper.isEmpty(whereClause)) query = query + "WHERE " + whereClause;
2303
+
2304
+ if (orderByFields && orderByFields != null && orderByFields.length > 0) {
2305
+ query = query + " ORDER BY ";
2306
+ for (var i = 0; i < orderByFields.length; i++) {
2307
+ if (i == orderByFields.length - 1) query = query + orderByFields[i];
2308
+ else query = query + orderByFields[i] + ", ";
2309
+ }
2310
+ query = query + " COLLATE NOCASE ASC ";
2311
+ }
2312
+ return query;
2313
+ };
2314
+ webDb.prepareReplaceBindQuery = function (tableName, tableColumnNames) {
2315
+ var noOfColumns = tableColumnNames.length;
2316
+ var query = "REPLACE INTO " + tableName + " (";
2317
+ for (let i = 0; i < noOfColumns; i++) {
2318
+ var key = tableColumnNames[i];
2319
+ query = query + key + ",";
2320
+ }
2321
+ query = query.slice(0, -1);
2322
+ query += ")";
2323
+ query = query + " VALUES (";
2324
+
2325
+ var value = "";
2326
+
2327
+ for (let i = 0; i < noOfColumns; i++) {
2328
+ value = value == "" ? value + "?" : value + ", " + "?";
2329
+ }
2330
+ query = query + value + ")";
2331
+ return query;
2332
+ };
2333
+ webDb.prepareDeleteQuery = function (tableName, whereClause) {
2334
+ var query = "DELETE FROM " + tableName + " ";
2335
+ if (!helper.isEmpty(whereClause)) query = query + "WHERE " + whereClause;
2336
+ return query;
2337
+ };
2338
+ webDb.prepareUpdateBindQuery = function (tableName, tableColumnNames, whereClause) {
2339
+ var query = "";
2340
+ var noOfColumns = tableColumnNames.length;
2341
+ query = "UPDATE " + tableName + " SET ";
2342
+ for (var i = 0; i < noOfColumns; i++) {
2343
+ query = i == 0 ? query + tableColumnNames[i] + " = ? " : query + " , " + tableColumnNames[i] + " = ? ";
2344
+ }
2345
+ if (!helper.isEmpty(whereClause)) query = query + " WHERE " + whereClause;
2346
+ return query;
2347
+ };
2348
+ webDb.exportWebDb = function () {
2349
+ //Download sqlite db
2350
+ var arraybuff = webDb.appDb.export();
2351
+ var blob = new Blob([arraybuff]);
2352
+ var a = document.createElement("a");
2353
+ document.body.appendChild(a);
2354
+ a.href = window.URL.createObjectURL(blob);
2355
+ a.download = "sql.db";
2356
+ a.onclick = function () {
2357
+ setTimeout(function () {
2358
+ window.URL.revokeObjectURL(a.href);
2359
+ }, 1500);
2360
+ };
2361
+ a.click();
2362
+ };
2363
+
2364
+ webDb.saveWebDb = async function () {
2365
+ if (window.unvired_db_worker) {
2366
+ await window.unvired_db_worker.saveWebDb(loginParameters.appName || "UNVIRED_DB", webDb.appDb.export());
2367
+ }
2368
+ else {
2369
+ console.error('Could not save the data in indexedDB because the script: unvired_db_worker is not loaded. Please make sure that this script is loaded in your application.')
2370
+ }
2371
+ };
2372
+
2373
+ webDb.populateWebDb = function (SQL, cb) {
2374
+ var db;
2375
+ var request = window.indexedDB.open(loginParameters.appName || "UNVIRED_DB");
2376
+ request.onupgradeneeded = function (event) {
2377
+ db = event.target.result;
2378
+ db.createObjectStore("appData", { keyPath: "id" });
2379
+ cb()
2380
+ };
2381
+ request.onerror = function (event) {
2382
+ console.log("The database failed to open: " + event);
2383
+ cb()
2384
+ };
2385
+ request.onsuccess = function (event) {
2386
+ db = request.result;
2387
+ if (!db.objectStoreNames.contains("appData")) {
2388
+ cb()
2389
+ return;
2390
+ }
2391
+
2392
+ db.onversionchange = function() {
2393
+ console.log('Unvired Plugin Proxy: Received version change event, we would also this receive event when an attempt is made to delete the database. Closing the database connection in order to facilitate the process.')
2394
+ db.close()
2395
+ }
2396
+
2397
+ var transaction = db.transaction(["appData"]);
2398
+ var objectStore = transaction.objectStore("appData");
2399
+ var dataRequest = objectStore.get(1);
2400
+
2401
+ dataRequest.onerror = function (event) {
2402
+ console.log("Unable to read appData index DB table");
2403
+ cb()
2404
+ };
2405
+ dataRequest.onsuccess = function (event) {
2406
+ if (dataRequest.result) {
2407
+ webDb.appDb = new SQL.Database(dataRequest.result.data);
2408
+ } else {
2409
+ console.log("Error while populatig web db - no db found in index DB");
2410
+ }
2411
+ cb()
2412
+ };
2413
+ };
2414
+ };
2415
+
2416
+ webDb.appDb = null;
2417
+ return webDb;
2418
+ })();
2419
+
2420
+ //#endregion
2421
+
2422
+ //#region exported modules
2423
+ require("cordova/exec/proxy").add("LoginPlugin", module.exports);
2424
+ require("cordova/exec/proxy").add("LoggerPlugin", module.exports);
2425
+ require("cordova/exec/proxy").add("SyncEnginePlugin", module.exports);
2426
+ require("cordova/exec/proxy").add("AttachmentPlugin", module.exports);
2427
+ require("cordova/exec/proxy").add("SettingsPlugin", module.exports);
2428
+ require("cordova/exec/proxy").add("DatabasePlugin", module.exports);
2429
+ //#endregion
2430
+