· 4 years ago · Sep 03, 2021, 12:38 PM
1const conn = require('../public/customrDB')
2const nodemailer = require('nodemailer')
3const axios = require('axios')
4var commonSettings = require('../public/commonSetting')
5var curl = require('curlrequest')
6
7
8//Uppercase first letter of a word
9const jsUcfirstEachWord = string => {
10 var splitStr = string.toLowerCase().split(' ');
11 for (var i = 0; i < splitStr.length; i++) {
12 // You do not need to check if i is larger than splitStr length, as your for does that for you
13 // Assign it back to the array
14 splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
15 }
16 // Directly return the joined string
17 return splitStr.join(' ');
18}
19
20//Query for return single object
21const getSingleObjectFromMysql = async (table, where, field = '*') => {
22 /*
23 First Value = Table Name
24 Second Value = Where Condition
25 Third Value = Fields
26 */
27 const [rows, fields] = await conn.promise().query(`SELECT ${field} from ${table} WHERE ${where} `)
28 const data = JSON.parse(JSON.stringify(rows))
29 const returnData = data.length == 0 ? null : data[0]
30 return returnData
31}
32
33//Query for return single object By Given Whole Query(with or w/o inner join)
34const getDataFromMysqlByGivenQuery = async (query, returnType) => {
35 /*
36 First Value = Query
37 Second Value = Return Type
38 this means return type is array or object 0 as object and 1 as array
39 */
40 const [rows, fields] = await conn.promise().query(query)
41 const data = JSON.parse(JSON.stringify(rows))
42 if (returnType == 0) {
43 $responseData = data[0]
44 } else {
45 $responseData = data
46 }
47 const returnData = data.length == 0 ? null : $responseData
48 return returnData
49}
50
51//Convert date into DD-MM-YYYY
52const toShortFormatDate = date => {
53 const getDay = date.getDate()
54 const getMonth = date.toLocaleString('default', { month: 'long' })
55 const getYear = date.getFullYear()
56 const fullDate = `${getDay} ${getMonth} ${getYear}`
57 return fullDate
58}
59
60//Convert date into YYYY-MM-DD
61const shortDateWithHyphen = date => {
62 const getDay = ("0" + date.getDate()).slice(-2)
63 const getMonth = ("0" + (date.getMonth() + 1)).slice(-2)
64 const getYear = date.getFullYear()
65 const fullDate = `${getYear}-${getMonth}-${getDay}`
66 return fullDate
67}
68
69
70
71const insertQuery = async (table, fields, values) => {
72 const query = `INSERT INTO ${table} (${fields}) VALUES (${values})`
73 const rows = await conn.promise().query(query)
74 const data = JSON.parse(JSON.stringify(rows))
75 if (data[0].affectedRows == 1) {
76 return true
77 }
78 return false
79}
80
81
82
83const bulkInsertQuery = async (table, fields, values) => {
84 const query = `INSERT INTO ${table} (${fields}) VALUES ?`
85 const rows = await conn.promise().query(query, [values])
86 const data = JSON.parse(JSON.stringify(rows))
87 if (data[0].affectedRows == values.length) {
88 return true
89 }
90 return false
91}
92
93const deleteQuery = async (table, key, value) => {
94 const query = `DELETE FROM ${table} WHERE ${key} = ${value}`;
95 const rows = await conn.promise().query(query)
96 const data = JSON.parse(JSON.stringify(rows))
97 if (data[0].affectedRows == 1) {
98 return true
99 }
100 return false
101}
102
103const updateQuery = async (table, key, value, whereKey, whereVal) => {
104 const query = `UPDATE ${table} SET ${key} = ${value} WHERE ${whereKey} = ${whereVal}`
105 const rows = await conn.promise().query(query)
106 const data = JSON.parse(JSON.stringify(rows))
107 if (data[0].affectedRows == 1) {
108 return true
109 }
110 return false
111}
112
113const updateByQuery = async (query) => {
114 const rows = await conn.promise().query(query)
115 const data = JSON.parse(JSON.stringify(rows))
116 if (data[0].affectedRows == 1) {
117 return true
118 }
119 return false
120}
121
122const saveUserActivityLog = async (leadId, status) => {
123
124 const userLogParamsName = 'lead_id,status_id';
125 const userLogParamsValue = `${leadId}, ${status}`;
126 const userLog = await insertQuery('rr_ob_users_status_log', userLogParamsName, userLogParamsValue);
127 // console.log(userLog);
128}
129
130const updateObUserCurrStatus = async (leadId, statusVal) => {
131
132 const query = `UPDATE rr_ob_users SET current_status = ${statusVal} WHERE lead_id = ${leadId}`;
133 const rows = await conn.promise().query(query)
134 const data = JSON.parse(JSON.stringify(rows))
135 if (data[0].affectedRows == 1) {
136 return true
137 }
138 return false
139}
140
141
142
143//Get user variable details
144const getVariableKeyDataByUser = async (table, userId, key) => {
145 const [rows, fields] = await conn.promise().query(`SELECT value from ${table} WHERE user_id = ${userId} AND data_key = '${key}'`)
146 const variable = JSON.parse(JSON.stringify(rows))
147 const returnvalue = variable.length == 0 ? null : variable[0].value
148 return returnvalue
149}
150
151const getRandomString = async (type, len) => {
152 var a = Math.floor(100000 + Math.random() * 900000);
153 a = String(a);
154 a = a.substring(0, len);
155 return a;
156}
157
158//const
159const leadDetailsUpdate = async (type, leadId, key) => {
160 var bodyJson = '';
161 var request = require('request')
162 const query = `SELECT customer_email_id, lead_id, current_status, customer_phone_no FROM rr_ob_users WHERE lead_id = '${leadId}'`
163 const users = await getDataFromMysqlByGivenQuery(query, 0)
164 if (type == "phone") {
165 bodyJson = JSON.stringify([{ "Attribute": "EmailAddress", "Value": users['customer_email_id'] }, { "Attribute": "Phone", "Value": key }])
166 } else if (type == "pan") {
167 bodyJson = JSON.stringify([{ "Attribute": "EmailAddress", "Value": users['customer_email_id'] }, { "Attribute": "mx_PAN_Number", "Value": key }])
168 }else if(type == "otpverify"){
169 bodyJson = JSON.stringify([{ "Attribute": "EmailAddress", "Value": users['customer_email_id'] }, { "Attribute": "mx_Onboard_OTP_Verified", "Value": key }])
170 }
171 var options = {
172 'method': 'POST',
173 'url': 'https://api.leadsquared.com/v2/LeadManagement.svc/Lead.CreateOrUpdate?postUpdatedLead=false&accessKey=' + commonSettings.LeadSquared_AccessKey + '&secretKey=' + commonSettings.LeadSquared_SecreteKey,
174 'headers': {
175 'Content-Type': 'application/json'
176 },
177 body: bodyJson
178 };
179 request(options, function (error, response) {
180 // console.log('test', options)
181 // console.log(JSON.stringify(options.body))
182 // console.log(response.body)
183 if (error) {
184 return error
185 }
186 return users
187 });
188}
189
190const sendSMS = async (phone, otp, res) => {
191 var request = require('request');
192 var userMobile = phone;
193 var path = commonSettings.smsconfig.path;
194 var apiKey = commonSettings.smsconfig.api_key;
195 var sender = commonSettings.smsconfig.sender;
196 var method = commonSettings.smsconfig.method;
197 var verification = 'Your one-time verification code to register your mobile number on Research and Ranking is ' + otp;
198 var sendurl = path + '/v4/?api_key=' + apiKey + '&method=' + method + '&message=' + encodeURIComponent(verification) + '&to=' + (userMobile) + '&sender=' + sender;
199 var options = { url: sendurl, include: true }
200 curl.request(options, function (error, response, body) {
201 if (error) {
202
203 return {
204 response_code: commonSettings.response.success,
205 message: "SMS not sent."
206 }
207
208 // return res.status(200).json({
209 // status:true,
210 // response_code:constants.response.success,
211 // message:"SMS not sent."
212 // })
213 }
214 return {
215 // status: true,
216 response_code: commonSettings.response.success,
217 message: "SMS sent."
218 }
219
220 // return res.status(200).json({
221 // status: true,
222 // response_code: constants.response.success,
223 // message: "SMS sent."
224 // })
225
226
227 });
228}
229
230const sendSMS_OTP = async (phone, verificationText, res) => {
231 var request = require('request');
232 var userMobile = phone;
233 var path = commonSettings.smsconfig.path;
234 var apiKey = commonSettings.smsconfig.api_key;
235 var sender = commonSettings.smsconfig.sender;
236 var method = commonSettings.smsconfig.method;
237 //var verification = 'Your one-time verification code for agreement on Research and Ranking is ' + otp;
238 var sendurl = path + '/v4/?api_key=' + apiKey + '&method=' + method + '&message=' + encodeURIComponent(verificationText) + '&to=' + (userMobile) + '&sender=' + sender;
239 var options = { url: sendurl, include: true }
240 curl.request(options, function (error, response, body) {
241 if (error) {
242 return {
243 response_code: commonSettings.response.success,
244 message: "SMS not sent."
245 }
246 }
247 return {
248 // status: true,
249 response_code: commonSettings.response.success,
250 message: "SMS sent."
251 }
252 });
253}
254
255const getSmsConfig = async (key = false) => {
256 const arr = {
257 'apikey': 'Aaab7d3d28064841ab6569f81cc54335d',
258 'sender': 'RESRAN',
259 'url': 'http://alerts.solutionsinfini.com/api/v3/index.php',
260 'verification': 'Your one-time verification code to register your mobile number on Research and Ranking is %s',
261 'change_password_verification_code': 'Dear %s, Your one time verification code to change your password on Research & Ranking is %s',
262 'login_with_otp_code': 'Dear %s, Your one time verification code for Research & Ranking is %s',
263 'verification_code_change_password': 'Your one-time verification code is %s',
264 'membership': 'Dear %s, We have received an online payment of Rs %s towards your purchase of %s R&R subscription%s. Please login to www.researchandranking.com to access all the features from your dashboard. Team Research and Ranking',
265 'reports': 'Dear %s, We have received an online payment of Rs %s towards your purchase of %s Customized Research Reports. Please login to www.researchandranking.com to access all the features from your dashboard. Team Research and Ranking',
266 'expiry': 'Dear %s, We value your patronage and appreciate your confidence in us! Your subscription is about to expire in %s days. To continue to enjoy all the benefits, please visit our website www.researchandranking.com to renew your subscription today.Team Research and Ranking',
267
268 'digital_campaign1_otp': '%s is the one time password (OTP) for your mobile number verification.',
269 'digital_campaign2_admin_alert': 'Received one new stock query (%s) from landing page. Check your mail box for more details.',
270 'digital_campaign1_smsdemo': 'Buy %s in the range of %s with %s allocation with the potential targets of %s. Buy %s in the range of %s with %s allocation with the potential targets of %s. Visit the below mentioned link to download the reports of these companies: http://www.researchandranking.com/sample-reports Team Research and Ranking (www.researchandranking.com)',
271 }
272}
273
274function panAuthenticate() {
275
276 return new Promise((resolve, reject) => {
277 var config = {
278 method: 'post',
279 url: 'https://api.quicko.com/authenticate',
280 headers: {
281 'x-api-key': 'key_live_U2TkwpOSyXsxGxgAsLLx2972paSHWhPw',
282 'x-api-secret': 'secret_live_EWOqYnYW4xnvsciZvkqNNj3ygHh9rfQW',
283 'x-api-version': '3.3'
284 }
285 };
286
287 axios(config)
288 .then(function (response) {
289 // next JSON.stringify(response.data);
290
291 // console.log(JSON.stringify(response.data));
292 resolve(response.data);
293 })
294
295 })
296}
297
298const sendOnboardingLinkOnSMS = async (phone, link, res) => {
299 var userMobile = phone;
300 var path = commonSettings.smsconfig.path;
301 var apiKey = commonSettings.smsconfig.api_key;
302 var sender = commonSettings.smsconfig.sender;
303 var method = commonSettings.smsconfig.method;
304 let baseURL = commonSettings.onBoardingStageURL;
305 var verification = 'Hello, You have been invited to eSign and complete your eKyc Document from Research and Ranking. Please click on the link below to proceed ' + baseURL + "?uid=" + link;
306 var sendurl = path + '/v4/?api_key=' + apiKey + '&method=' + method + '&message=' + encodeURIComponent(verification) + '&to=' + (userMobile) + '&sender=' + sender;
307 var options = { url: sendurl, include: true }
308 curl.request(options, function (error, response, body) {
309 if (error) {
310 return {
311 response_code: commonSettings.response.success,
312 message: "SMS not sent."
313 }
314 }
315 return {
316 response_code: commonSettings.response.success,
317 message: "SMS sent."
318 }
319 });
320}
321
322const updateBodyInLeadSq = async (bodyJson) => {
323
324 var request = require('request');
325 var options = {
326 'method': 'POST',
327 'url': 'https://api.leadsquared.com/v2/LeadManagement.svc/Lead.CreateOrUpdate?postUpdatedLead=false&accessKey=' + commonSettings.LeadSquared_AccessKey + '&secretKey=' + commonSettings.LeadSquared_SecreteKey,
328 'headers': {
329 'Content-Type': 'application/json'
330 },
331 body: bodyJson
332 };
333 request(options, function (error, response) {
334 //console.log('test', options);
335 console.log('test 2', error);
336
337 console.log('test 3: '+JSON.stringify(options.body))
338 console.log(response.body)
339 if (error) {
340 // console.log(error)
341
342 return error
343 }
344 return true;
345 });
346}
347
348const isCurrentStatusCorrect = async (leadId, nextStatus) => {
349 try {
350 const userQry = `SELECT current_status, customer_email_id FROM rr_ob_users
351 WHERE lead_id = ${leadId}`;
352 const usrData = await getDataFromMysqlByGivenQuery(userQry, 0)
353 if (usrData == null) {
354 return false;
355 }
356 let preStatus = nextStatus-1;
357 // console.log(preStatus, usrData.current_status)
358 if(preStatus == usrData.current_status){
359 return true;
360 }
361 return false
362 } catch (error) {
363 console.log("Error in isCurrentStatusCorrect()", error.message)
364 return false;
365 }
366}
367
368
369
370module.exports = {
371 jsUcfirstEachWord,
372 getSingleObjectFromMysql,
373 getDataFromMysqlByGivenQuery,
374 toShortFormatDate,
375 insertQuery,
376 deleteQuery,
377 shortDateWithHyphen,
378 getVariableKeyDataByUser,
379 bulkInsertQuery,
380 getRandomString,
381 panAuthenticate,
382 getSmsConfig,
383 sendSMS,
384 updateQuery,
385 sendOnboardingLinkOnSMS,
386 leadDetailsUpdate,
387 updateBodyInLeadSq,
388 saveUserActivityLog,
389 updateObUserCurrStatus,
390 isCurrentStatusCorrect,
391 updateByQuery,
392 sendSMS_OTP
393}
394