zocrmsdkmiblu 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # BLUELABEL PROGRAMERS SDK ZOHOCRM
2
+
3
+ Please Install
4
+
5
+ npm i zocrmsdk
6
+
7
+ GET RECORD CRM V4
8
+
9
+ await zcrm.initialize({
10
+ client_id: "",
11
+ client_secret: "",
12
+ user_identifier: "",
13
+ redirect_url: "",
14
+ mysql_username: "",
15
+ mysql_password: ""
16
+ })
17
+
18
+ var response = await zcrm.API.MODULES.get({ module: "", id: "" })
19
+
@@ -0,0 +1,66 @@
1
+
2
+ var config = null;
3
+ var qs = require('querystring');
4
+ var httpclient = require('request');
5
+
6
+ var actionvsurl = {
7
+
8
+ generate_token:'/oauth/v2/token'
9
+ }
10
+
11
+ var mand_configurations = {
12
+
13
+ generate_token : ['client_id','client_secret','redirect_uri','code','grant_type'],
14
+ refresh_access_token : ['client_id','client_secret','grant_type','refresh_token']
15
+ }
16
+
17
+
18
+ var OAuth = function (configuration,action) {
19
+ if (!configuration)
20
+ throw new Error('Missing configuration for Zoho OAuth2 service');
21
+ assertConfigAttributesAreSet(configuration, mand_configurations[action]);
22
+ config = configuration;
23
+ };
24
+
25
+
26
+ function assertConfigAttributesAreSet(configuration, attributes) {
27
+ attributes.forEach(function (attribute) {
28
+ if (!configuration[attribute])
29
+ throw new Error('Missing configuration for Zoho OAuth service: '+ attribute);
30
+ });
31
+ }
32
+
33
+ OAuth.constructurl=function(action){
34
+
35
+ var crmclient = require('./ZCRMRestClient');
36
+ var url = "https://"+crmclient.getIAMUrl()+actionvsurl[action]+'?' + qs.stringify(config);
37
+ return url;
38
+
39
+ }
40
+
41
+ OAuth.generateTokens=function(url){
42
+ return new Promise(function(resolve,reject){
43
+
44
+ httpclient.post(url,{
45
+
46
+ },function (err, response) {
47
+
48
+ var resultObj = {};
49
+
50
+ if(err){
51
+
52
+ resolve(err);
53
+ }
54
+ resolve(response);
55
+
56
+ });
57
+ })
58
+ }
59
+
60
+
61
+ module.exports = OAuth;
62
+
63
+
64
+
65
+
66
+
@@ -0,0 +1,88 @@
1
+ var util = require('../util');
2
+
3
+ var modules = function modules()
4
+ {
5
+
6
+ return {
7
+ get : function(input)
8
+ {
9
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}", HTTP_METHODS.GET, false));//No I18N
10
+ },
11
+ getRelated : function(input)
12
+ {
13
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}/"+input.related_module, HTTP_METHODS.GET, false));//No I18N
14
+ },
15
+ post : function(input)
16
+ {
17
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}", HTTP_METHODS.POST, false));//No I18N
18
+ },
19
+ put : function(input)
20
+ {
21
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}", HTTP_METHODS.PUT, false));//No I18N
22
+ },
23
+ delete : function (input)
24
+ {
25
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}", HTTP_METHODS.DELETE, false));//No I18N
26
+ },
27
+ getAllDeletedRecords : function (input)
28
+ {
29
+ if (input.params)
30
+ {
31
+ input.params.type = "all";
32
+ }
33
+ else
34
+ {
35
+ input.params = {
36
+ "type" : "all"//No I18N
37
+ };
38
+ }
39
+
40
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/deleted", HTTP_METHODS.GET, false));//No I18N
41
+ },
42
+ getRecycleBinRecords : function (input)
43
+ {
44
+ if (input.params)
45
+ {
46
+ input.type = "recycle";
47
+ }
48
+ else
49
+ {
50
+ input.params = {
51
+ "type" : "recycle"//No I18N
52
+ };
53
+ }
54
+
55
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/deleted", HTTP_METHODS.GET, false));//No I18N
56
+ },
57
+ getPermanentlyDeletedRecords : function (input)
58
+ {
59
+ if (input.params)
60
+ {
61
+ input.type = "permanent";
62
+ }
63
+ else
64
+ {
65
+ input.params = {
66
+ "type" : "permanent"//No I18N
67
+ };
68
+ }
69
+
70
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/deleted", HTTP_METHODS.GET, false));//No I18N
71
+ },
72
+ search : function (input)
73
+ {
74
+ var query = util.convertToCOQLQuery(input.params.criteria,'id',input.module,input.params.page || 0,input.params.per_page || 200)
75
+ input.body = {select_query:query}
76
+ console.log(input)
77
+ //return util.promiseResponse(util.constructRequestDetails(input, input.module + "/search", HTTP_METHODS.GET, false));//No I18N
78
+
79
+ return this.coql(input)
80
+ },
81
+ coql: function(input) {
82
+ input.api_name = 'coql';
83
+ return util.promiseResponse(util.constructRequestDetails(input, input.api_name, HTTP_METHODS.POST, false));//No I18N
84
+ }
85
+ }
86
+ }
87
+
88
+ module.exports = modules;
@@ -0,0 +1,31 @@
1
+ var util = require("../util");
2
+
3
+ var actions = function actions()
4
+ {
5
+ return {
6
+ convert : function (input)
7
+ {
8
+
9
+ return util.promiseResponse(util.constructRequestDetails(input, "Leads/{id}/actions/convert", HTTP_METHODS.POST, false));//No I18N
10
+ },
11
+ blueprint : function (input)
12
+ {
13
+
14
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+"/{id}/actions/blueprint", HTTP_METHODS.PUT, false));//No I18N
15
+ },
16
+ getblueprint : function (input)
17
+ {
18
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+"/{id}/actions/blueprint", HTTP_METHODS.GET, false));//No I18N
19
+ },
20
+ sendemail : function (input)
21
+ {
22
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+"/{id}/actions/send_mail", HTTP_METHODS.POST, false));//No I18N
23
+ },
24
+ emailAttchDownload : function (input)
25
+ {
26
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+"/{id}/Emails/actions/download_attachments", HTTP_METHODS.GET, false));//No I18N
27
+ },
28
+ }
29
+ }
30
+
31
+ module.exports = actions;
@@ -0,0 +1,44 @@
1
+
2
+ var util = require('../util');
3
+ var attachments = function attachments()
4
+ {
5
+
6
+ return {
7
+ uploadFile : function (input)
8
+ {
9
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+ "/{id}/Attachments", HTTP_METHODS.POST, false));//No I18N
10
+ },
11
+ deleteFile : function (input)
12
+ {
13
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+ "/{id}/Attachments/"+input.relatedId, HTTP_METHODS.DELETE, false));//No I18N
14
+ },
15
+ downloadFile : function (input)
16
+ {
17
+ input.download_file = true;
18
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+ "/{id}/Attachments/"+input.relatedId, HTTP_METHODS.GET, false));//No I18N
19
+ },
20
+ uploadLink : function (input)
21
+ {
22
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+ "/{id}/Attachments", HTTP_METHODS.POST, false));//No I18N
23
+ },
24
+ uploadPhoto : function (input)
25
+ {
26
+ return util.promiseResponse(util.constructRequestDetails(input, input.module+ "/{id}/photo", HTTP_METHODS.POST, false));//No I18N
27
+ },
28
+ downloadPhoto : function (input)
29
+ {
30
+ input.download_file = true;
31
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}/photo", HTTP_METHODS.GET, false));//No I18N
32
+ },
33
+ deletePhoto : function (input)
34
+ {
35
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}/photo", HTTP_METHODS.DELETE, false));//No I18N
36
+ },
37
+ getAllAttachments : function (input)
38
+ {
39
+ return util.promiseResponse(util.constructRequestDetails(input, input.module + "/{id}/attachments", HTTP_METHODS.GET, false));//No I18N
40
+ }
41
+ }
42
+ }
43
+
44
+ module.exports = attachments;
@@ -0,0 +1,22 @@
1
+ var util = require('../util');
2
+ var url = "functions/{api_name}/actions/execute";
3
+
4
+ var functions = function functions(){
5
+
6
+ return{
7
+
8
+ executeFunctionsInGet :function(input){
9
+
10
+
11
+ return util.promiseResponse(util.constructRequestDetails(input, url , HTTP_METHODS.GET, true));//No I18N
12
+ },
13
+
14
+ executeFunctionsInPost :function(input){
15
+
16
+ return util.promiseResponse(util.constructRequestDetails(input, url , HTTP_METHODS.POST, true));//No I18N
17
+ }
18
+ }
19
+
20
+ }
21
+
22
+ module.exports = functions;
@@ -0,0 +1,18 @@
1
+
2
+ var util = require('../util');
3
+
4
+ var org = function org()
5
+ {
6
+ return {
7
+ get : function (input)
8
+ {
9
+ return util.promiseResponse(util.constructRequestDetails(input, "org", HTTP_METHODS.GET, true));//No I18N
10
+ },
11
+ authoken:function(isInvalid=false)
12
+ {
13
+ return util.getAuthToken(isInvalid)
14
+ }
15
+ }
16
+ }
17
+
18
+ module.exports = org;
@@ -0,0 +1,46 @@
1
+ var util = require('../util');
2
+
3
+ var settings = function settings()
4
+ {
5
+
6
+ return {
7
+ getFields : function (input)
8
+ {
9
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/fields/{id}", HTTP_METHODS.GET, true));//No I18N
10
+ },
11
+ getLayouts : function (input)
12
+ {
13
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/layouts/{id}", HTTP_METHODS.GET, true));//No I18N
14
+ },
15
+ getCustomViews : function (input)
16
+ {
17
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/custom_views/{id}", HTTP_METHODS.GET, true));//No I18N
18
+ },
19
+ updateCustomViews : function (input)
20
+ {
21
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/custom_views/{id}", HTTP_METHODS.PUT, true));//No I18N
22
+ },
23
+ getModules : function (input)
24
+ {
25
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/modules" + ((input && input.module) ? "/" + input.module : ""), HTTP_METHODS.GET, false));//No I18N
26
+ },
27
+ getRoles : function (input)
28
+ {
29
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/roles/{id}", HTTP_METHODS.GET, true));//No I18N
30
+ },
31
+ getProfiles : function (input)
32
+ {
33
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/profiles/{id}", HTTP_METHODS.GET, true));//No I18N
34
+ },
35
+ getRelatedLists : function (input)
36
+ {
37
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/related_lists/{id}", HTTP_METHODS.GET, true));//No I18N
38
+ },
39
+ getInventoryTemplates : function (input)
40
+ {
41
+ return util.promiseResponse(util.constructRequestDetails(input, "settings/inventory_templates/{id}", HTTP_METHODS.GET, false));//No I18N
42
+ }
43
+ }
44
+ }
45
+
46
+ module.exports = settings;
@@ -0,0 +1,19 @@
1
+ var util = require('../util');
2
+
3
+ var users = function users()
4
+ {
5
+
6
+ return {
7
+ get : function (input)
8
+ {
9
+ return util.promiseResponse(util.constructRequestDetails(input, "users/{id}", HTTP_METHODS.GET, true));//No I18N
10
+ },
11
+ getUsersType : function (input)
12
+ {
13
+ return util.promiseResponse(util.constructRequestDetails(input, "users", HTTP_METHODS.GET, true));//No I18N
14
+ },
15
+ }
16
+ }
17
+
18
+
19
+ module.exports = users;
@@ -0,0 +1,341 @@
1
+
2
+ var OAuth = require('./OAuth');
3
+ var path = require("path");
4
+
5
+
6
+
7
+ var persistenceModule = path.dirname(__filename) + "/mysql/mysql_util";
8
+ var iamurl = "accounts.zoho.com";
9
+ var baseURL = "www.zohoapis.com";
10
+ var version = "v2.1";
11
+ var mysql_username = process.env.MYSQL_USER;
12
+ var mysql_password = process.env.MYSQL_PASSWORD;
13
+ var default_user_identifier = "zcrm_default_user";
14
+
15
+ var client_id = process.env.CLIENT_ID;
16
+ var client_secret = process.env.CLIENT_SECRET;
17
+ var redirect_url = process.env.REDIRECT_URL;
18
+ var user_identifier = process.env.USER_IDENTIFIER;
19
+
20
+ var ZCRMRestClient = function () { };
21
+
22
+ ZCRMRestClient.initialize = function (configJSON) {
23
+
24
+
25
+ return new Promise(function (resolve, reject) {
26
+
27
+ if (configJSON) {
28
+
29
+ ZCRMRestClient.initializeWithValues(configJSON);
30
+ resolve();
31
+
32
+ }
33
+
34
+ var PropertiesReader = require('properties-reader');
35
+ var properties = PropertiesReader('resources/oauth_configuration.properties');
36
+ var client_id = properties.get('zoho.crm.clientid');
37
+ var client_secret = properties.get('zoho.crm.clientsecret');
38
+ var redirect_url = properties.get('zoho.crm.redirecturl');
39
+ var iam_url = properties.get('zoho.crm.iamurl') ? properties.get('zoho.crm.iamurl') : iamurl;
40
+
41
+ var config_properties = PropertiesReader('resources/configuration.properties');
42
+
43
+ persistenceModule = config_properties.get('crm.api.tokenmanagement') ? config_properties.get('crm.api.tokenmanagement') : persistenceModule;
44
+
45
+ baseURL = config_properties.get('crm.api.url') ? config_properties.get('crm.api.url') : baseURL;
46
+
47
+ mysql_username = config_properties.get('mysql.username') ? config_properties.get('mysql.username') : mysql_username;
48
+
49
+ mysql_password = config_properties.get('mysql.password') ? config_properties.get('mysql.password') : mysql_password;
50
+
51
+
52
+ if (config_properties.get('crm.api.user_identifier')) {
53
+
54
+ ZCRMRestClient.setUserIdentifier(config_properties.get('crm.api.user_identifier'));
55
+ }
56
+ else {
57
+
58
+ ZCRMRestClient.setUserIdentifier(default_user_identifier);
59
+ }
60
+
61
+ if (!client_id || !client_secret || !redirect_url) {
62
+
63
+ throw new Error("Populate the oauth_configuration.properties file");
64
+
65
+ }
66
+
67
+ ZCRMRestClient.setClientId(client_id);
68
+ ZCRMRestClient.setClientSecret(client_secret);
69
+ ZCRMRestClient.setRedirectURL(redirect_url);
70
+ ZCRMRestClient.setIAMUrl(iam_url);
71
+
72
+
73
+ resolve();
74
+
75
+ })
76
+ }
77
+
78
+ ZCRMRestClient.initializeWithValues = function (configJSON) {
79
+
80
+ var mandatory_values = ['client_id', 'client_secret', 'redirect_url']
81
+ mandatory_values.forEach(function (key) {
82
+ if (!configJSON[key]) {
83
+ throw new Error('Missing configuration for Zoho OAuth service: ' + key);
84
+ }
85
+ })
86
+ var client_id = configJSON.client_id;
87
+ var client_secret = configJSON.client_secret;
88
+ var redirect_url = configJSON.redirect_url;
89
+ var iam_url = configJSON.iamurl ? configJSON.iamurl : iamurl;
90
+ var useridentifier = configJSON.user_identifier ? configJSON.user_identifier : default_user_identifier;
91
+
92
+ mysql_username = configJSON.mysql_username ? configJSON.mysql_username : mysql_username;
93
+ mysql_password = configJSON.mysql_password ? configJSON.mysql_password : mysql_password;
94
+ baseURL = configJSON.base_url ? configJSON.base_url : baseURL;
95
+ version = configJSON.version ? configJSON.version : version;
96
+ persistenceModule = configJSON.tokenmanagement ? configJSON.tokenmanagement : persistenceModule;
97
+
98
+ ZCRMRestClient.setClientId(client_id);
99
+ ZCRMRestClient.setClientSecret(client_secret);
100
+ ZCRMRestClient.setRedirectURL(redirect_url);
101
+ ZCRMRestClient.setIAMUrl(iam_url);
102
+ ZCRMRestClient.setUserIdentifier(useridentifier);
103
+
104
+ }
105
+
106
+ ZCRMRestClient.generateAuthTokens = function (user_identifier, grant_token) {
107
+
108
+ return new Promise(function (resolve, reject) {
109
+
110
+ if (!user_identifier) {
111
+
112
+ user_identifier = ZCRMRestClient.getUserIdentifier();
113
+ }
114
+
115
+ var config = ZCRMRestClient.getConfig(grant_token);
116
+ new OAuth(config, "generate_token");
117
+ var api_url = OAuth.constructurl("generate_token");
118
+
119
+ OAuth.generateTokens(api_url).then(function (response) {
120
+
121
+ if (response.statusCode != 200) {
122
+
123
+ throw new Error("Problem occured while generating access token from grant token. Response : " + JSON.stringify(response));
124
+
125
+ }
126
+
127
+ var persistence_module = require(persistenceModule);
128
+ var resultObj = ZCRMRestClient.parseAndConstructObject(response);
129
+ resultObj.user_identifier = user_identifier;
130
+
131
+ if (resultObj.access_token) {
132
+
133
+ persistence_module.saveOAuthTokens(resultObj).then(function (save_resp) {
134
+
135
+ ZCRMRestClient.setUserIdentifier(user_identifier),
136
+
137
+ resolve(resultObj)
138
+
139
+ }
140
+
141
+ );
142
+ }
143
+ else {
144
+
145
+ throw new Error("Problem occured while generating access token and refresh token from grant token.Response : " + JSON.stringify(response));
146
+ }
147
+ })
148
+ })
149
+ }
150
+
151
+
152
+ ZCRMRestClient.generateAuthTokenfromRefreshToken = function (user_identifier, refresh_token) {
153
+
154
+ return new Promise(function (resolve, reject) {
155
+
156
+ if (!user_identifier) {
157
+
158
+ user_identifier = ZCRMRestClient.getUserIdentifier();
159
+ }
160
+
161
+ var config = ZCRMRestClient.getConfig_refresh(refresh_token);
162
+ new OAuth(config, "refresh_access_token");
163
+ var api_url = OAuth.constructurl("generate_token");
164
+
165
+ OAuth.generateTokens(api_url).then(function (response) {
166
+
167
+ if (response.statusCode != 200) {
168
+
169
+ throw new Error("Problem occured while generating access token from refresh token . Response : " + JSON.stringify(response));
170
+
171
+ }
172
+ var persistence_module = require(persistenceModule);
173
+ var resultObj = ZCRMRestClient.parseAndConstructObject(response);
174
+
175
+ resultObj.user_identifier = user_identifier;
176
+ resultObj.refresh_token = refresh_token;
177
+
178
+ if (resultObj.access_token) {
179
+
180
+ persistence_module.saveOAuthTokens(resultObj).then(function (save_response) {
181
+
182
+ ZCRMRestClient.setUserIdentifier(user_identifier),
183
+ resolve(resultObj)
184
+
185
+ }
186
+
187
+ );
188
+ }
189
+ else {
190
+ throw new Error("Problem occured while generating access token from refresh token. Response : " + JSON.stringify(response));
191
+
192
+ }
193
+
194
+
195
+ })
196
+ })
197
+ };
198
+
199
+
200
+ ZCRMRestClient.getConfig = function (grant_token) {
201
+
202
+ var config = {};
203
+
204
+ config.client_id = ZCRMRestClient.getClientId();
205
+ config.client_secret = ZCRMRestClient.getClientSecret();
206
+ config.code = grant_token;
207
+ config.redirect_uri = ZCRMRestClient.getRedirectURL();
208
+ config.grant_type = "authorization_code";
209
+
210
+ return config;
211
+
212
+ };
213
+
214
+ ZCRMRestClient.getConfig_refresh = function (refresh_token) {
215
+
216
+ var config = {};
217
+
218
+ config.client_id = ZCRMRestClient.getClientId();
219
+ config.client_secret = ZCRMRestClient.getClientSecret();
220
+ config.refresh_token = refresh_token;
221
+ config.grant_type = "refresh_token";
222
+
223
+ return config;
224
+
225
+ }
226
+
227
+ ZCRMRestClient.setClientId = function (clientid) {
228
+
229
+ client_id = clientid;
230
+ }
231
+
232
+ ZCRMRestClient.setClientSecret = function (clientsecret) {
233
+
234
+ client_secret = clientsecret;
235
+
236
+ }
237
+
238
+ ZCRMRestClient.setRedirectURL = function (redirecturl) {
239
+
240
+ redirect_url = redirecturl;
241
+ }
242
+
243
+ ZCRMRestClient.setUserIdentifier = function (useridentifier) {
244
+
245
+ user_identifier = useridentifier;
246
+
247
+ }
248
+
249
+ ZCRMRestClient.setIAMUrl = function (iam_url) {
250
+
251
+ iamurl = iam_url;
252
+ }
253
+
254
+ ZCRMRestClient.setBaseURL = function (baseurl) {
255
+
256
+ baseURL = baseurl;
257
+ }
258
+
259
+ ZCRMRestClient.getClientId = function () {
260
+
261
+ return client_id;
262
+
263
+ }
264
+
265
+ ZCRMRestClient.getClientSecret = function () {
266
+
267
+ return client_secret;
268
+
269
+ }
270
+
271
+ ZCRMRestClient.getRedirectURL = function () {
272
+
273
+ return redirect_url;
274
+ }
275
+
276
+ ZCRMRestClient.getUserIdentifier = function () {
277
+
278
+ if (!user_identifier) {
279
+
280
+ return default_user_identifier;
281
+ }
282
+ return user_identifier;
283
+ }
284
+
285
+ ZCRMRestClient.getPersistenceModule = function () {
286
+
287
+ return persistenceModule;
288
+ }
289
+
290
+ ZCRMRestClient.getAPIURL = function () {
291
+
292
+ return baseURL;
293
+ }
294
+
295
+ ZCRMRestClient.getVersion = function (allrecord) {
296
+
297
+ return version;
298
+ }
299
+ ZCRMRestClient.getIAMUrl = function () {
300
+
301
+ return iamurl;
302
+ }
303
+ ZCRMRestClient.getMySQLUserName = function () {
304
+
305
+ return mysql_username;
306
+ }
307
+ ZCRMRestClient.getMYSQLPassword = function () {
308
+
309
+ return mysql_password;
310
+
311
+ }
312
+ ZCRMRestClient.parseAndConstructObject = function (response) {
313
+
314
+ var body = response["body"];
315
+ body = JSON.parse(body);
316
+
317
+ var date = new Date();
318
+ var current_time = date.getTime();
319
+
320
+ var resultObj = {};
321
+
322
+ if (body.access_token) {
323
+
324
+ resultObj.access_token = body.access_token;
325
+
326
+ if (body.refresh_token) {
327
+
328
+ resultObj.refresh_token = body.refresh_token;
329
+ }
330
+ if (!body.expires_in_sec) {
331
+ body.expires_in = body.expires_in * 1000;
332
+ }
333
+ resultObj.expires_in = body.expires_in + current_time;
334
+ }
335
+ return resultObj;
336
+
337
+ }
338
+
339
+ ZCRMRestClient.API = require('./crmapi');
340
+
341
+ module.exports = ZCRMRestClient;
@@ -0,0 +1,33 @@
1
+
2
+ var modules = require('./REST_API/Records');
3
+ var settings = require('./REST_API/settings');
4
+ var actions = require('./REST_API/actions');
5
+ var users = require('./REST_API/users');
6
+ var org = require('./REST_API/org');
7
+ var attachments = require('./REST_API/attachments');
8
+ var functions = require('./REST_API/functions');
9
+
10
+ global.HTTP_METHODS
11
+
12
+ global.HTTP_METHODS = {
13
+ GET : "GET",//No I18N
14
+ POST : "POST",//No I18N
15
+ PUT : "PUT",//No I18N
16
+ DELETE : "DELETE"//No I18N
17
+ };
18
+
19
+ var API = (function (argument) {
20
+ return {
21
+
22
+ MODULES : new modules(),
23
+ SETTINGS : new settings(),
24
+ ACTIONS : new actions(),
25
+ USERS : new users(),
26
+ ORG : new org(),
27
+ ATTACHMENTS : new attachments(),
28
+ FUNCTIONS :new functions()
29
+ }
30
+
31
+ })(this)
32
+
33
+ module.exports = API;
@@ -0,0 +1,162 @@
1
+
2
+ var mysql_util = {};
3
+ var mysql = require('mysql');
4
+
5
+ mysql_util.saveOAuthTokens = function(config_obj){
6
+
7
+ return new Promise(function(resolve,reject){
8
+
9
+ var con = getConnection();
10
+
11
+ var sql = "INSERT INTO oauthtokens (useridentifier, accesstoken,refreshtoken,expirytime) VALUES ('"+config_obj.user_identifier+"','"+config_obj.access_token+"','"+config_obj.refresh_token+"',"+config_obj.expires_in+")";
12
+
13
+ mysql_util.deleteOAuthTokens().then(function(){
14
+
15
+ con.connect(function(err){
16
+
17
+ if(err){
18
+ throw new Error(err);
19
+ }
20
+
21
+ con.query(sql,function(err,result){
22
+
23
+ if (err) {
24
+ throw new Error(err);
25
+ con.end();
26
+ }
27
+
28
+ con.end();
29
+
30
+ resolve();
31
+
32
+ })
33
+
34
+
35
+ })
36
+
37
+ })
38
+
39
+ })
40
+ }
41
+
42
+ mysql_util.getOAuthTokens = function(){
43
+
44
+ return new Promise(function(resolve,reject){
45
+
46
+ var con = getConnection();
47
+
48
+ var crmclient = require('../ZCRMRestClient');
49
+ con.connect(function(err){
50
+
51
+ if(err) throw err;
52
+
53
+ var sql = "Select * from oauthtokens where useridentifier = '"+crmclient.getUserIdentifier()+"'";
54
+
55
+ con.query(sql,function(err,result){
56
+
57
+ if(err) {
58
+ throw new Error(err);
59
+ con.end();
60
+ }
61
+
62
+ con.end();
63
+
64
+ if(result != undefined && result.length != 0)
65
+ {
66
+ var modified_result ={};
67
+ modified_result["access_token"] = result[0].accesstoken;
68
+ modified_result["refresh_token"] = result[0].refreshtoken;
69
+ modified_result["expires_in"] = result[0].expirytime;
70
+ modified_result["user_identifier"] = result[0].useridentifier;
71
+ resolve(modified_result);
72
+ }
73
+ resolve(result);
74
+ });
75
+
76
+ });
77
+ })
78
+
79
+ }
80
+
81
+ mysql_util.updateOAuthTokens = function(config_obj){
82
+
83
+
84
+ return new Promise(function(resolve,reject){
85
+
86
+ var con = getConnection();
87
+ var crmclient = require('../ZCRMRestClient');
88
+ con.connect(function(err){
89
+
90
+ if(err) throw err;
91
+
92
+ var sql = `
93
+ update oauthtokens
94
+ set accesstoken = '${config_obj.access_token}',
95
+ expirytime=${config_obj.expires_in}
96
+ where useridentifier = '${crmclient.getUserIdentifier()}'`;
97
+
98
+ con.query(sql,function(err,result){
99
+
100
+ if(err) {
101
+ throw new Error(err);
102
+ con.end();
103
+ }
104
+
105
+ con.end();
106
+
107
+ resolve(result);
108
+
109
+ })
110
+ })
111
+ });
112
+ }
113
+
114
+ mysql_util.deleteOAuthTokens = function(){
115
+
116
+ return new Promise(function(resolve,reject){
117
+
118
+ var con = getConnection();
119
+
120
+ var crmclient = require('../ZCRMRestClient');
121
+
122
+ var sql = "delete from oauthtokens where useridentifier='"+crmclient.getUserIdentifier()+"'";
123
+
124
+ con.connect(function(err){
125
+
126
+ if(err) throw err;
127
+
128
+ con.query(sql,function(err,result){
129
+
130
+ if(err) {
131
+ throw new Error(err);
132
+ }
133
+
134
+ con.end();
135
+
136
+ resolve(result);
137
+ })
138
+
139
+
140
+ })
141
+ })
142
+
143
+ }
144
+
145
+
146
+ function getConnection(){
147
+
148
+ var crmclient = require('../ZCRMRestClient');
149
+ var con = mysql.createConnection({
150
+
151
+ host: process.env.MYSQL_IP||"35.239.104.86",
152
+ user: crmclient.getMySQLUserName(),
153
+ password: crmclient.getMYSQLPassword(),
154
+ database: "zohooauth"
155
+
156
+ });
157
+
158
+ return con;
159
+
160
+ }
161
+
162
+ module.exports = mysql_util;
package/lib/js/util.js ADDED
@@ -0,0 +1,327 @@
1
+
2
+ function promiseResponse(request) {
3
+
4
+ var crmclient = require('./ZCRMRestClient');
5
+ var OAuth = require('./OAuth');
6
+
7
+ return new Promise(function (resolve, reject) {
8
+ var persistenceModule = require(crmclient.getPersistenceModule());
9
+ getAuthToken().then(resp=>{
10
+ makeapicall(request).then(function (response) {
11
+
12
+ try {
13
+ var isExpire = JSON.parse(response.body);
14
+ if (isExpire.code == 'INVALID_TOKEN') {
15
+ //Update Token
16
+
17
+ getAuthToken(true).then(resp=>{
18
+ makeapicall(request).then(function (response) {
19
+
20
+ resolve(response);
21
+
22
+ })
23
+ })
24
+ }else{
25
+ resolve(response);
26
+ }
27
+ } catch (error) {
28
+ resolve(response);
29
+ }
30
+
31
+ })
32
+ })
33
+
34
+ })
35
+ }
36
+
37
+
38
+ function makeapicall(request) {
39
+
40
+ return new Promise(function (resolve, reject) {
41
+
42
+ var crmclient = require('./ZCRMRestClient');
43
+ var httpclient = require('request');
44
+ var OAuth = require('./OAuth');
45
+ var persistenceModule = require(crmclient.getPersistenceModule());
46
+ var qs = require('querystring');
47
+
48
+ persistenceModule.getOAuthTokens(crmclient.getUserIdentifier()).then(function (result_obj) {
49
+ var access_token = result_obj.access_token;
50
+ var allrecords = request.all || null
51
+ var baseUrl = "https://" + crmclient.getAPIURL() + "/crm/" + crmclient.getVersion(allrecords) + "/" + request.url;
52
+ if (request.params) {
53
+ baseUrl = baseUrl + '?' + request.params;
54
+ }
55
+
56
+ var api_headers = {};
57
+ var encoding = "utf8";
58
+ var req_body = null;
59
+ var formData = null;
60
+
61
+ if (request.download_file) {
62
+ encoding = "binary";//No I18N
63
+ }
64
+
65
+ var form_Data = null;
66
+
67
+ if (request.x_file_content) {
68
+ var FormData = require('form-data');
69
+ form_Data = new FormData();
70
+ form_Data.append('file', request.x_file_content);//No I18N
71
+ req_body = form_Data;
72
+ api_headers = form_Data.getHeaders();
73
+ }
74
+ else {
75
+ req_body = request.body || null;
76
+ }
77
+
78
+ if (request.headers) {
79
+ var header_keys = Object.keys(request.headers);
80
+ for (i in header_keys) {
81
+ api_headers[header_keys[i]] = request.headers[header_keys[i]];
82
+ }
83
+ }
84
+
85
+ api_headers.Authorization = 'Zoho-oauthtoken ' + access_token;
86
+ api_headers["User-Agent"] = 'Zoho CRM Node SDK';
87
+
88
+ /* console.log({
89
+
90
+ uri: baseUrl,
91
+ method: request.type,
92
+ headers: api_headers,
93
+ body: req_body,
94
+ encoding: encoding
95
+
96
+ },crmclient.getVersion(allrecords)); */
97
+ httpclient({
98
+
99
+ uri: baseUrl,
100
+ method: request.type,
101
+ headers: api_headers,
102
+ body: req_body,
103
+ encoding: encoding
104
+
105
+ }, function (error, response, body) {
106
+
107
+ if (error) {
108
+ resolve(error);
109
+ }
110
+ else if (response.statusCode == 204) {
111
+
112
+ var respObj = {
113
+ "message": "no data", //No I18N
114
+ "status_code": "204" //No I18N
115
+ }
116
+ resolve(JSON.stringify(respObj));
117
+
118
+ } else {
119
+ if (request.download_file) {
120
+
121
+ var filename;
122
+ var disposition = response.headers["content-disposition"];//No I18N
123
+ if (disposition && disposition.indexOf('attachment') !== -1) {
124
+ var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
125
+ var matches = filenameRegex.exec(disposition);
126
+ if (matches != null && matches[1]) {
127
+ filename = matches[1].replace(/['"]/g, '');
128
+ filename = filename.replace('UTF-8', '');
129
+ }
130
+ }
131
+ response.filename = filename;
132
+ resolve(response);
133
+ }
134
+ else {
135
+ resolve(response);
136
+ }
137
+ }
138
+ });
139
+ })
140
+ })
141
+ }
142
+ function getAuthToken(isInvalid) {
143
+
144
+ var crmclient = require('./ZCRMRestClient');
145
+ var OAuth = require('./OAuth');
146
+
147
+
148
+ return new Promise(function (resolve, reject) {
149
+
150
+ var persistenceModule = require(crmclient.getPersistenceModule());
151
+
152
+ persistenceModule.getOAuthTokens(crmclient.getUserIdentifier()).then(function (response) {
153
+
154
+ var date = new Date();
155
+ var current_time = date.getTime();
156
+ var access_token = response.access_token;
157
+ var expires_in = response.expires_in;
158
+ var refresh_token = response.refresh_token;
159
+ var result_obj = (response);
160
+
161
+ if ((current_time > expires_in) || isInvalid) {
162
+ if(isInvalid)console.info("============== REGENERATE TOKEN BY INVALID =============");
163
+ if(!isInvalid)console.info("============== REGENERATE TOKEN BY TIME =============");
164
+
165
+ var config = crmclient.getConfig_refresh(refresh_token)
166
+ new OAuth(config, 'refresh_access_token');
167
+ var url = OAuth.constructurl('generate_token');
168
+ OAuth.generateTokens(url).then(function (response) {
169
+
170
+ result_obj = crmclient.parseAndConstructObject(response);
171
+
172
+ persistenceModule.updateOAuthTokens(result_obj).then(function (response) {
173
+ resolve(result_obj);
174
+ });
175
+ })
176
+ }
177
+
178
+
179
+ else {
180
+ //console.info("============== TOKEN NO EXPIRADO =============")
181
+ resolve(result_obj);
182
+ }
183
+ })
184
+ })
185
+ }
186
+
187
+ function createParams(parameters) {
188
+
189
+ var params, key;
190
+ for (key in parameters) {
191
+ if (parameters.hasOwnProperty(key)) {
192
+ if (params) {
193
+ params = params + key + '=' + parameters[key] + '&';
194
+ }
195
+ else {
196
+ params = key + '=' + parameters[key] + '&';
197
+ }
198
+ }
199
+ }
200
+
201
+ return params;
202
+ }
203
+
204
+ function constructRequestDetails(input, url, type, isModuleParam) {
205
+
206
+ var requestDetails = {};
207
+
208
+ requestDetails.type = type;
209
+
210
+ if (input != undefined) {
211
+ if (input.id) {
212
+ url = url.replace("{id}", input.id);
213
+ }
214
+ else {
215
+ url = url.replace("/{id}", "");
216
+ }
217
+ if (input.api_name) {
218
+
219
+ url = url.replace("{api_name}", input.api_name);
220
+
221
+
222
+ var params = {};
223
+ if (input.params) {
224
+
225
+ params = input.params;
226
+ }
227
+ params.auth_type = "apikey";
228
+ input.params = params;
229
+ }
230
+ else {
231
+
232
+ url = url.replace("/{api_name}", "");
233
+
234
+ }
235
+ if (input.params) {
236
+ requestDetails.params = createParams(input.params) + (input.module && isModuleParam ? "module=" + input.module : "");//No I18N
237
+ }
238
+ if (!requestDetails.params && isModuleParam) {
239
+ requestDetails.params = "module=" + input.module;//No I18N
240
+ }
241
+ if (input.body && (type == HTTP_METHODS.POST || type == HTTP_METHODS.PUT)) {
242
+ requestDetails.body = JSON.stringify(input.body);
243
+ }
244
+ if (input.x_file_content) {
245
+ requestDetails.x_file_content = input.x_file_content;
246
+ }
247
+ if (input.download_file) {
248
+ requestDetails.download_file = input.download_file;
249
+ }
250
+ if (input.headers) {
251
+
252
+ requestDetails.headers = input.headers;
253
+ }
254
+ }
255
+
256
+ requestDetails.url = url;
257
+
258
+ return requestDetails;
259
+
260
+
261
+ }
262
+ function convertToCOQLQuery(inputText, fields, module,page,per_page) {
263
+ const conditions = inputText.split(/\b(and|or)\b/i);
264
+
265
+ const queryParts = [];
266
+ let operator = 'AND'; // Operador predeterminado
267
+ const operatorsWithGrouping = ['equals', 'starts_with', 'in', '>='];
268
+ let currentEqualsLikeGroup = [];
269
+ let currentBetweenGroup = [];
270
+
271
+ conditions.forEach(condition => {
272
+ const cleanCondition = condition.trim();
273
+ if (cleanCondition.match(/^(and|or)$/i)) {
274
+ operator = cleanCondition.toLowerCase();
275
+ } else {
276
+ const [field, op, value] = cleanCondition
277
+ .replace(/\(|\)/g, '') // Eliminar paréntesis
278
+ .split(':');
279
+
280
+ if (op === 'between') {
281
+ const [start, end] = value.split(',');
282
+ currentBetweenGroup.push(`${field} between '${start}' and '${end}'`);
283
+ }
284
+ else if (op === 'in') {
285
+ const elements = value.split(',');
286
+ currentEqualsLikeGroup.push(`${field} in (${elements.map(el => `'${el.trim()}'`).join(', ')})`);
287
+ }
288
+ else if (op === 'is not null') {
289
+
290
+ currentBetweenGroup.push(`(${field} is not null)`);
291
+ }
292
+ else if (operatorsWithGrouping.includes(op)) {
293
+ currentEqualsLikeGroup.push(`(${field} ${op === 'equals' ? '=' : op} '${value}')`);
294
+ } else {
295
+ queryParts.push(currentEqualsLikeGroup.join(` ${operator} `));
296
+ currentEqualsLikeGroup = [];
297
+ }
298
+ }
299
+ });
300
+ if (currentEqualsLikeGroup.length > 0) {
301
+ queryParts.push(`(${currentEqualsLikeGroup.join(` ${operator} `)})`);
302
+ }
303
+ if (currentBetweenGroup.length > 0) {
304
+ queryParts.push(`(${currentBetweenGroup.join(` AND `)})`);
305
+ }
306
+
307
+ const finalQuery = `SELECT ${fields} FROM ${module} WHERE ${queryParts.join(` ${operator} `)} LIMIT ${[page*per_page,per_page]}`;
308
+
309
+ return finalQuery;
310
+ }
311
+ function calculateLimit(pageNumber, resultsPerPage) {
312
+ if (pageNumber < 0) {
313
+ throw new Error('El número de página debe ser mayor o igual a 0.');
314
+ }
315
+
316
+ const lowerLimit = pageNumber * resultsPerPage;
317
+ const upperLimit = (pageNumber + 1) * resultsPerPage;
318
+
319
+ return [pageNumber, resultsPerPage];
320
+ }
321
+ module.exports = {
322
+
323
+ constructRequestDetails: constructRequestDetails,
324
+ promiseResponse: promiseResponse,
325
+ getAuthToken: getAuthToken,
326
+ convertToCOQLQuery: convertToCOQLQuery
327
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "zocrmsdkmiblu",
3
+ "version": "0.2.4",
4
+ "author": "IT Team",
5
+ "license": "MIT",
6
+ "dependencies": {
7
+ "fs": "0.0.1-security",
8
+ "mysql": "^2.18.1",
9
+ "properties-reader": "0.0.16",
10
+ "querystring": "^0.2.0",
11
+ "request": "^2.88.2",
12
+ "typescript": "^5.0.4"
13
+ },
14
+ "description": "Node SDK for Zoho CRM BY JB",
15
+ "keywords": [
16
+ "zoho crm",
17
+ "sdk zoho"
18
+ ],
19
+ "main": "lib/js/ZCRMRestClient",
20
+ "scripts": {
21
+ "test": "mocha --timeout 5000 test/dev.test.js"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^20.1.2",
25
+ "@types/request": "^2.48.8",
26
+ "mocha": "^10.2.0"
27
+ }
28
+ }