· 6 years ago · Feb 10, 2020, 02:08 PM
1var Promise = require('bluebird');
2var express = require('express');
3var router = express.Router();
4var config = require('../config').config();
5var request = require('request');
6var Cloudant = require('@cloudant/cloudant');
7var username = config.username;
8var password = config.password;
9var moment = require('moment');
10var _ = require("underscore");
11var BoxSDK = require('box-node-sdk');
12//var FileSaver = require('file-saver');
13var fileDownload = require('js-file-download');
14// var userarray=[];
15// var cloudant = Cloudant({ account: username, password: password, plugins: 'promises' });
16// const couchbackup = require('@cloudant/couchbackup');
17 var fs = require('file-system');
18// var prejolt=[];
19// var postjolt=[];
20// import Moment from 'moment';
21var h=0;
22var p=0;
23var Cloudant = require('cloudant');
24var username;
25var password;
26var cloudant;
27function getDbCredentials(){
28
29 if (process.env.VCAP_SERVICES) {
30 // Running on Bluemix. Parse the port and host that we've been assigned.
31 var env = JSON.parse(process.env.VCAP_SERVICES);
32 var credentials = env['cloudantNoSQLDB'][0]['credentials'];
33 config.username=credentials.username;
34 config.password=credentials.password;
35 username = credentials.username;
36 password = credentials.password;
37
38 } else{
39 username=config.username;
40 password=config.password;
41 }
42 cloudant = Cloudant({ account: username, password: password, plugins: 'promises' });
43 }
44
45getDbCredentials();
46
47/**********code for uploading*********/
48
49var multer = require('multer');
50var xlstojson = require("xls-to-json-lc");
51var xlsxtojson = require("xlsx-to-json-lc");
52var fs = require('fs');
53var cradle = require('cradle');
54
55///******/
56var event_cache = {};
57var superUserData = [];
58var iotData = [];
59var superLogsData = [];
60
61
62
63
64/******* to get all the account data from lapDB , npsDB, accountinfo, actionplan, stickinessdb ***********/
65function getAllData(db, record) {
66 return new Promise(function (resolve, reject) {
67 db.list({ include_docs: true }, function (err, data) {
68 if (!err) {
69 resolve(data);
70 // console.log("Actionplan data db",data);
71 }
72 else {
73 resolve(err);
74 }
75 });
76 });
77}
78// function notifyAllData(db, record) {
79// return new Promise(function (resolve, reject) {
80// db.insert({ include_docs: true }, function (err, data) {
81// if (!err) {
82// resolve(data);
83// }
84// else {
85// resolve(err);
86// }
87// });
88// });
89
90// }
91// function saveNotify(db, record) {
92// return new Promise(function (resolve, reject) {
93// db.insert(record, function (err, data) {
94// if (!err) {
95// resolve(data);
96// }
97// else {
98// resolve(err);
99// }
100// });
101// });
102// }
103
104
105router.get('/api/v1/getConfig/all', function (req, res) {
106
107 var accountId = req.params.accountId;
108 lapdb = cloudant.db.use('lapdatabase')
109 newlapdb = cloudant.db.use('newlapdatabase')
110 npsdb = cloudant.db.use('nps123');
111 //notifydb= cloudant.db.use('notification');
112 accountdb = cloudant.db.use('accounts');
113 accountsummarydb = cloudant.db.use('accountsummary');
114 accountinfodb = cloudant.db.use('accountinfo');
115 actionPlandb = cloudant.db.use('actionplan');
116 stickinessdb = cloudant.db.use('stickinessdbnew');
117
118 // var record = req.body;
119 // saveNotify(db, record).then(function (myData)
120 // {
121 // console.log("save data",myData);
122 // res.json(myData);
123 // console.log(record);
124 // });
125
126 dbquerries = [getAllData(lapdb), getAllData(npsdb), getAllData(accountdb), getAllData(accountsummarydb), getAllData(accountinfodb), getAllData(actionPlandb), getAllData(stickinessdb), getAllData(newlapdb)]
127 Promise.all(dbquerries).then(function (data) {
128 // console.log(JSON.stringify(data[2].rows[0].doc.accountName_AP));
129 var config = {};
130 config.lap = [];
131 config.newlap = [];
132 config.nps = [];
133 config.account = [];
134 config.tableSummary = [];
135 config.accountsummary = [];
136 config.accountInfo = [];
137 config.actionPlanStatus = [];
138 config.stickiness = [];
139 config.quater = [];
140 for (var i = 0; i < data[0].rows.length; i++) {
141 if (data[0].rows[i].id == "lapConfig") {
142 config.lapconfig = data[0].rows[i].doc;
143 }
144 }
145
146 for (var j = 0; j < data[1].rows.length; j++) {
147 if (data[1].rows[j].id == "npsConfig") {
148 config.npsconfig = data[1].rows[j].doc;
149 }
150 }
151 var account_summary_config = data[3].rows[0].doc;
152
153
154 for (var j = 0; j < data[4].rows.length; j++) {
155 // console.log("account Data------------------"+JSON.stringify(data[4].rows[j]));
156 if (data[4].rows[j].id == "accountInfoConfig") {
157 var account_info = data[4].rows[j].doc;
158 }
159 }
160 for (var i = 0; i < data[7].rows.length; i++) {
161 if (data[7].rows[i].id == "newlapconfig") {
162 config.newlapconfig = data[7].rows[i].doc;
163 }
164 }
165
166 var action_plan_data = data[5].rows;
167 var stickiness_data = data[6].rows;
168 const calc = calculation(stickiness_data);
169 config.stickiness = calc;
170 for (var i = 0; i < data[7].rows.length; i++) {
171 var newlapAccount = [];
172 var Chart1 = [];
173 var chart2 = [];
174 var chart3 = [];
175 var chart4 = [];
176 var chart5 = [];
177 if (data[7].rows[i].id != "newlapconfig") {
178 if (data[7].rows[i].doc["Account Type"] == "ER") {
179 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Comments.length; k++) {
180 var query = config.newlapconfig.AccountType_ER[0].Comments[k];
181 var json = {
182 "question": query,
183 "ans": data[7].rows[i].doc[query]
184 };
185 newlapAccount.push(json);
186 }
187 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Chart1.length; k++) {
188 var query = config.newlapconfig.AccountType_ER[0].Chart1[k];
189 var ans;
190 if (data[7].rows[i].doc[query] == 0) {
191 ans = 3;
192 }
193 else if (data[7].rows[i].doc[query] >= 40) {
194 ans = 1;
195 }
196 else if (1 <= data[7].rows[i].doc[query] <= 39) {
197 ans = 2;
198 }
199 var json = {
200 "name": query,
201 "value": ans
202 };
203 Chart1.push(json);
204
205 }
206 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Chart2.length; k++) {
207 var query = config.newlapconfig.AccountType_ER[0].Chart2[k];
208 var str = query.split("-");
209 var newstr = str[1].trim();
210 var name = newstr.replace('[', '').replace(']', '').replace('*', '');
211 var json = {
212 "name": name,
213 "value": parseInt(data[7].rows[i].doc[query])
214
215 };
216 chart2.push(json);
217 }
218 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Chart3.length; k++) {
219 var query = config.newlapconfig.AccountType_ER[0].Chart3[k];
220 var str = query.split("-");
221 var json = {
222 "name": str[1].trim(),
223 "value": parseInt(data[7].rows[i].doc[query])
224
225 };
226 chart3.push(json);
227 }
228 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Chart4.length; k++) {
229 var query = config.newlapconfig.AccountType_ER[0].Chart4[k];
230 var str = query.replace('1', '');
231
232 var json = {
233 "name": str,
234 "value": data[7].rows[i].doc[query]
235
236 };
237 chart4.push(json);
238 }
239 for (var k = 0; k < config.newlapconfig.AccountType_ER[0].Chart5.length; k++) {
240 var query = config.newlapconfig.AccountType_ER[0].Chart5[k];
241
242 var json = {
243 "name": query,
244 "value": data[7].rows[i].doc[query]
245
246 };
247 chart5.push(json);
248 }
249 var finaljson = {
250
251 "AccountInfo": [],
252 //"AccountBasic":[],
253 "Comments": [],
254 "chart1": [],
255 "Chart2": [],
256 "Chart3": [],
257 "Chart4": [],
258 "Chart5": [],
259 "IOT": data[7].rows[i].doc["IOT"],
260 "Account Type": data[7].rows[i].doc["Account Type"]
261 };
262 var accName = data[7].rows[i].doc["_id"].split("_");
263 accName = accName[0].trim();
264 finaljson.AccountInfo.push(
265 {
266
267 "title": "Account Name:",
268 "value": accName
269 },
270 {
271 "title": "Sector:",
272 "value": data[7].rows[i].doc["Sector"]
273
274 },
275 {
276 "title": "Survey Taken By:",
277 "value": data[7].rows[i].doc["First name"] + " " + data[7].rows[i].doc["Last name"],
278 },
279 {
280 "title": "Role:",
281 "value": data[7].rows[i].doc[((config.newlapconfig.AccountType_ER[0].Table1[0].Role))],
282 },
283 {
284 "title": "completed:",
285 "value": data[7].rows[i].doc[((config.newlapconfig.AccountType_ER[0].Table1[0].Completed))],
286 });
287 finaljson.Comments = newlapAccount;
288 finaljson.chart1 = Chart1;
289 finaljson.Chart2 = chart2;
290 finaljson.Chart3 = chart3;
291 finaljson.Chart4 = chart4;
292 finaljson.Chart5 = chart5;
293 config.newlap.push(finaljson);
294 }
295 else if (data[7].rows[i].doc["Account Type"] == "E") {
296 for (var k = 0; k < config.newlapconfig.AccountType_E[0].Comments.length; k++) {
297 var query = config.newlapconfig.AccountType_E[0].Comments[k];
298 var json = {
299 "question": query,
300 "ans": data[7].rows[i].doc[query]
301 };
302 newlapAccount.push(json);
303 }
304 for (var k = 0; k < config.newlapconfig.AccountType_E[0].Chart1.length; k++) {
305 var query = config.newlapconfig.AccountType_E[0].Chart1[k];
306
307 var ans;
308 if (data[7].rows[i].doc[query] == 0) {
309 ans = 3;
310 }
311 else if (data[7].rows[i].doc[query] >= 40) {
312 ans = 1;
313 }
314 else if (1 <= data[7].rows[i].doc[query] <= 39) {
315 ans = 2;
316 }
317 var json = {
318 "name": query,
319 "value": ans
320 };
321
322 Chart1.push(json);
323 }
324 for (var k = 0; k < config.newlapconfig.AccountType_E[0].Chart2.length; k++) {
325 var query = config.newlapconfig.AccountType_E[0].Chart2[k];
326 var str = query.split("-");
327 var newstr = str[1].trim();
328 var name = newstr.replace('[', '').replace(']', '');
329 var json = {
330 "name": name,
331 "value": parseInt(data[7].rows[i].doc[query])
332
333 };
334 chart2.push(json);
335 }
336 for (var k = 0; k < config.newlapconfig.AccountType_E[0].Chart3.length; k++) {
337 var query = config.newlapconfig.AccountType_E[0].Chart3[k];
338 var str = query.split("-");
339 var json = {
340 "name": str[1].trim(),
341 "value": data[7].rows[i].doc[query]
342
343 };
344 chart3.push(json);
345 }
346 for (var k = 0; k < config.newlapconfig.AccountType_E[0].Chart4.length; k++) {
347 var query = config.newlapconfig.AccountType_E[0].Chart4[k];
348 var str = query.replace('1', '');
349
350 var json = {
351 "name": str,
352 "value": data[7].rows[i].doc[query]
353
354 };
355 chart4.push(json);
356 }
357 var finaljson = {
358
359 "AccountInfo": [],
360 //"AccountBasic":[],
361 "Comments": [],
362 "chart1": [],
363 "Chart2": [],
364 "Chart3": [],
365 "Chart4": [],
366 "IOT": data[7].rows[i].doc["IOT"],
367 "Account Type": data[7].rows[i].doc["Account Type"]
368 };
369 var accName = data[7].rows[i].doc["_id"].split("_");
370 accName = accName[0].trim();
371
372 finaljson.AccountInfo.push(
373 {
374
375 "title": "Account Name:",
376 "value": accName
377 },
378 {
379 "title": "Sector:",
380 "value": data[7].rows[i].doc["Sector"]
381
382 },
383 {
384 "title": "Survey Taken By:",
385 "value": data[7].rows[i].doc["First name"] + " " + data[7].rows[i].doc["Last name"],
386 },
387 {
388 "title": "Role:",
389 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_E[0].Table1[0].Role)],
390 },
391 {
392 "title": "completed:",
393 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_E[0].Table1[0].Completed)],
394 });
395 finaljson.Comments = newlapAccount;
396 finaljson.chart1 = Chart1;
397 finaljson.Chart2 = chart2;
398 finaljson.Chart3 = chart3;
399 finaljson.Chart4 = chart4;
400 config.newlap.push(finaljson);
401 }
402 else if (data[7].rows[i].doc["Account Type"] == "G") {
403
404
405 for (var k = 0; k < config.newlapconfig.AccountType_G[0].Comments.length; k++) {
406 var query = config.newlapconfig.AccountType_G[0].Comments[k];
407 var json = {
408 "question": query,
409 "ans": data[7].rows[i].doc[query]
410 };
411 newlapAccount.push(json);
412 }
413 for (var k = 0; k < config.newlapconfig.AccountType_G[0].Chart1.length; k++) {
414 var query = config.newlapconfig.AccountType_G[0].Chart1[k];
415
416 var json = {
417 "name": query,
418 "value": data[7].rows[i].doc[query]
419 };
420 Chart1.push(json);
421 }
422 for (var k = 0; k < config.newlapconfig.AccountType_G[0].Chart2.length; k++) {
423 var query = config.newlapconfig.AccountType_G[0].Chart2[k];
424 var str = query.split("-");
425 var newstr = str[1].trim();
426 var name = newstr.replace('[', '').replace(']', '').replace('*', '');
427 var json = {
428 "name": name,
429 "value": parseInt(data[7].rows[i].doc[query])
430
431 };
432 chart2.push(json);
433 }
434 for (var k = 0; k < config.newlapconfig.AccountType_G[0].Chart3.length; k++) {
435 var query = config.newlapconfig.AccountType_G[0].Chart3[k];
436
437 var json = {
438 "name": query,
439 "value": data[7].rows[i].doc[query]
440
441 };
442 chart3.push(json);
443 }
444 var finaljson = {
445
446 "AccountInfo": [],
447 //"AccountBasic":[],
448 "Comments": [],
449 "chart1": [],
450 "Chart2": [],
451 "Chart3": [],
452 "IOT": data[7].rows[i].doc["IOT"],
453 "Account Type": data[7].rows[i].doc["Account Type"]
454 };
455
456 var accName = data[7].rows[i].doc["_id"].split("_");
457 accName = accName[0].trim();
458 finaljson.AccountInfo.push(
459 {
460
461 "title": "Account Name:",
462 "value": accName
463 },
464 {
465 "title": "Sector:",
466 "value": data[7].rows[i].doc["Sector"]
467
468 },
469 {
470 "title": "Survey Taken By:",
471 "value": data[7].rows[i].doc["First name"] + " " + data[7].rows[i].doc["Last name"],
472 },
473 {
474 "title": "Role:",
475 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_G[0].Table1[0].Role)],
476 },
477 {
478 "title": "completed:",
479 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_G[0].Table1[0].Completed)],
480 });
481 finaljson.Comments = newlapAccount;
482 finaljson.chart1 = Chart1;
483 finaljson.Chart2 = chart2;
484 finaljson.Chart3 = chart3;
485 config.newlap.push(finaljson);
486 }
487
488 else if (data[7].rows[i].doc["Account Type"] == "GR") {
489
490
491 for (var k = 0; k < config.newlapconfig.AccountType_GR[0].Comments.length; k++) {
492 var query = config.newlapconfig.AccountType_GR[0].Comments[k];
493 var json = {
494 "question": query,
495 "ans": data[7].rows[i].doc[query]
496 };
497 newlapAccount.push(json);
498 }
499 for (var k = 0; k < config.newlapconfig.AccountType_GR[0].Chart1.length; k++) {
500 var query = config.newlapconfig.AccountType_GR[0].Chart1[k];
501
502
503 var json = {
504 "name": query,
505 "value": data[7].rows[i].doc[query]
506 };
507 Chart1.push(json);
508 }
509 for (var k = 0; k < config.newlapconfig.AccountType_GR[0].Chart2.length; k++) {
510 var query = config.newlapconfig.AccountType_GR[0].Chart2[k];
511 var str = query.split("-");
512
513 var newstr = str[1].trim();
514 var name = newstr.replace('[', '').replace(']', '').replace('*', '');
515 var json = {
516 "name": name,
517 "value": parseInt(data[7].rows[i].doc[query])
518
519 };
520 chart2.push(json);
521 }
522 for (var k = 0; k < config.newlapconfig.AccountType_GR[0].Chart3.length; k++) {
523 var query = config.newlapconfig.AccountType_GR[0].Chart3[k];
524
525 var json = {
526 "name": query,
527 "value": data[7].rows[i].doc[query]
528
529 };
530 chart3.push(json);
531 }
532 for (var k = 0; k < config.newlapconfig.AccountType_GR[0].Chart4.length; k++) {
533 var query = config.newlapconfig.AccountType_GR[0].Chart4[k];
534
535 var json = {
536 "name": query,
537 "value": data[7].rows[i].doc[query]
538
539 };
540 chart4.push(json);
541 }
542 var finaljson = {
543
544 "AccountInfo": [],
545 //"AccountBasic":[],
546 "Comments": [],
547 "chart1": [],
548 "Chart2": [],
549 "Chart3": [],
550 "Chart4": [],
551 "IOT": data[7].rows[i].doc["IOT"],
552 "Account Type": data[7].rows[i].doc["Account Type"]
553 };
554 var accName = data[7].rows[i].doc["_id"].split("_");
555 accName = accName[0].trim();
556 finaljson.AccountInfo.push(
557 {
558
559 "title": "Account Name:",
560 "value": accName
561 },
562 {
563 "title": "Sector:",
564 "value": data[7].rows[i].doc["Sector"]
565
566 },
567 {
568 "title": "Survey Taken By:",
569 "value": data[7].rows[i].doc["First name"] + " " + data[7].rows[i].doc["Last name"],
570 },
571 {
572 "title": "Role:",
573 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_GR[0].Table1[0].Role)],
574 },
575 {
576 "title": "completed:",
577 "value": data[7].rows[i].doc[(config.newlapconfig.AccountType_GR[0].Table1[0].Completed)],
578 });
579 finaljson.Comments = newlapAccount;
580 finaljson.chart1 = Chart1;
581 finaljson.Chart2 = chart2;
582 finaljson.Chart3 = chart3;
583 finaljson.Chart4 = chart4;
584 config.newlap.push(finaljson);
585 }
586 // console.log(config.newlap);
587 }
588
589 }
590
591
592 for (var i = 0; i < data[0].rows.length; i++) {
593 var lapAccount = [];
594 var pieChart1 = [];
595 var pieChart2 = [];
596 var radarChart = [];
597 if (data[0].rows[i].id != "lapConfig") {
598
599 for (var k = 0; k < config.lapconfig.Comments.length; k++) {
600 var query = config.lapconfig.Comments[k];
601 var json = {
602 "question": query,
603 "ans": data[0].rows[i].doc[query]
604 };
605 lapAccount.push(json);
606 }
607 for (var k = 0; k < config.lapconfig.PieChart1.length; k++) {
608 var query = config.lapconfig.PieChart1[k];
609 var str = query.split("-");
610
611 var json = {
612 "name": str[1].trim(),
613 "value": parseInt(data[0].rows[i].doc[query])
614 };
615 pieChart1.push(json);
616 }
617 for (var k = 0; k < config.lapconfig.PieChart2.length; k++) {
618 var query = config.lapconfig.PieChart2[k];
619 var str = query.split("-");
620 var json = {
621 "name": str[1].trim(),
622 "value": parseInt(data[0].rows[i].doc[query])
623
624 };
625 pieChart2.push(json);
626 }
627 for (var k = 0; k < config.lapconfig.radarChart.length; k++) {
628 var query = config.lapconfig.radarChart[k];
629 var ans;
630 if (data[0].rows[i].doc[query] == 0) {
631 ans = 3;
632 }
633 else if (data[0].rows[i].doc[query] >= 40) {
634 ans = 1;
635 }
636 else if (1 <= data[0].rows[i].doc[query] <= 39) {
637 ans = 2;
638 }
639 var json = {
640 "question": query,
641 "ans": ans
642 };
643 radarChart.push(json);
644 }
645
646 var finaljson = {
647
648 "AccountInfo": [],
649 //"AccountBasic":[],
650 "Comments": [],
651 "PieChart1": [],
652 "PieChart2": [],
653 "RadarChart": [],
654 "IOT": data[0].rows[i].doc["IOT"]
655 };
656 var accName = data[0].rows[i].doc["_id"].split("_");
657 accName = accName[0].trim();
658 finaljson.AccountInfo.push(
659 {
660
661 "title": "Account Name:",
662 "value": accName
663 },
664 {
665 "title": "Sector:",
666 "value": data[0].rows[i].doc["Sector"]
667
668 },
669 {
670 "title": "Survey Taken By:",
671 "value": data[0].rows[i].doc["First name"] + " " + data[0].rows[i].doc["Last name"],
672 },
673 {
674 "title": "Role:",
675 "value": data[0].rows[i].doc[(config.lapconfig.role)],
676 },
677 {
678 "title": "completed:",
679 "value": data[0].rows[i].doc[(config.lapconfig.completed)],
680 });
681 finaljson.Comments = lapAccount;
682 finaljson.PieChart1 = pieChart1;
683 finaljson.PieChart2 = pieChart2;
684 finaljson.RadarChart = radarChart;
685
686 config.lap.push(finaljson);
687 }
688 }
689
690 config.account.push({ "accountName_EU": data[2].rows[0].doc.accountName_EU },
691 { "accountName_NA": data[2].rows[0].doc.accountName_NA },
692 { "accountName_AP": data[2].rows[0].doc.accountName_AP },
693 { "accountName_LA": data[2].rows[0].doc.accountName_LA },
694 { "accountName_GCG": data[2].rows[0].doc.accountName_GCG},
695 { "accountName_JP": data[2].rows[0].doc.accountName_JP },
696 { "accountName_MEA": data[2].rows[0].doc.accountName_MEA }
697 );
698 config.quater = data[2].rows[0].doc.quater;
699 // console.log(config.account);
700 for (var j = 0; j < data[1].rows.length; j++) {
701 // console.log("hello");
702 // console.log(data[1].rows[j].doc);
703 if (data[1].rows[j].id != "npsConfig") {
704 var result = NPSdivison(data[1].rows[j].doc, config);
705 // console.log("HELLO NPS");
706 // console.log(JSON.stringify(result));
707 config.nps.push(result);
708 }
709 }
710 for (var j = 0; j < data[4].rows.length; j++) {
711 if (data[4].rows[j].id != "accountInfoConfig") {
712 var result = processAccountInfoSummary(data[4].rows[j].doc, account_info);
713 config.accountInfo.push(result);
714 }
715 }
716
717 for (var m = 0; m < config.account.length; m++) {
718 processAccountlevelSummary(m, config, action_plan_data, account_summary_config);
719 }
720 /*for(var m=0; m<config.account[0].accountName_EU.length;m++){
721 var item=config.account[0].accountName_EU[m];
722 var nps="";
723 var lap=processLAPData(item.name,config);
724 if(item.DNS=="true"){
725 nps="DNS";
726 }
727 else{
728 nps=processNPSData(item.name,config);
729 }
730 var accInfo=processAccInterview(item.name, config.accountInfo);
731 //var stickinessStatus=processStickinessData(item.name,scoreDoc);
732 var tableData={
733 "accountName":item.name,
734 "sector":item.sector,
735 "joltwave":item.wave,
736 "lap":lap,
737 "nps":nps,
738 "stickiness":"",
739 "accountInterview":accInfo
740 }
741 config.tableSummary.push(tableData);
742 var summary=processAccountSummary(item.name,config,account_summary_config,nps,lap);
743 var acc_summary={
744 "accountName":item.name,
745 "dimension":summary
746 }
747 config.accountsummary.push(acc_summary);
748 actionPlanStatus=processActionPlanData(item.name,item.sector,action_plan_data,"EU");
749 config.actionPlanStatus.push(actionPlanStatus);
750
751 }
752 for(var m=0; m<config.account[1].accountName_NA.length;m++){
753 var item=config.account[1].accountName_NA[m];
754 actionPlanStatus=processActionPlanData(item.name,item.sector,action_plan_data,"NA");
755 config.actionPlanStatus.push(actionPlanStatus);
756 }*/
757 res.json(config);
758 }, function (err) {
759 console.log(err);
760 });
761});
762function processAccountlevelSummary(ind, config, action_plan_data, account_summary_config) {
763 console.log(ind,"give it");
764 if (ind == 0) {
765 var accountList = config.account[0].accountName_EU;
766 iot = "EU";
767 }
768 else if (ind == 1) {
769 var accountList = config.account[1].accountName_NA;
770 iot = "NA";
771 }
772 else if (ind == 2) {
773 console.log("Inside AP");
774 var accountList = config.account[2].accountName_AP;
775 iot = "AP";
776 }
777 else if(ind ==3){
778 console.log("LA");
779 var accountList=config.account[3].accountName_LA;
780 iot="LA";
781 }
782 else if(ind ==4){
783 console.log("GCG");
784 var accountList=config.account[4].accountName_GCG;
785 iot="GCG";
786 }
787 else if(ind ==5){
788 console.log("JP");
789 var accountList=config.account[5].accountName_JP;
790 iot="JP";
791 }
792 else if(ind ==6){
793 console.log("MEA");
794 var accountList=config.account[6].accountName_MEA;
795 iot="MEA";
796 }
797 for (var m = 0; m < accountList.length; m++) {
798 var item = accountList[m];
799 var nps = "";
800 var lap = processLAPData(item.name, iot, config);
801 if (item.DNS == "true") {
802 nps = "DNS";
803 }
804 else {
805 nps = processNPSData(item.name, iot, config);
806 }
807 var accInfo = processAccInterview(item.name, iot, config.accountInfo);
808 var clientInterview = processClientInterviewStatus(item.name, iot, config.accountInfo);
809 var stickinessStatus = processStickinessData(item.name, iot, config.stickiness);
810 var tableData = {
811 "accountName": item.name,
812 "sector": item.sector,
813 "joltwave": item.wave,
814 "lap": lap,
815 "nps": nps,
816 "stickiness": stickinessStatus,
817 "accountInterview": accInfo,
818 "iot": iot,
819 "clientInterview": clientInterview
820 }
821 config.tableSummary.push(tableData);
822 var summary = processAccountSummary(item.name, config, account_summary_config, nps, lap, iot, stickinessStatus);
823 var acc_summary = {
824 "accountName": item.name,
825 "dimension": summary,
826 "iot": iot
827
828 }
829 config.accountsummary.push(acc_summary);
830 actionPlanStatus = processActionPlanData(item.name, item.sector, action_plan_data, iot);
831 config.actionPlanStatus.push(actionPlanStatus);
832
833 }
834
835}
836function processAccInterview(name, iot, accountInfo) {
837
838 for (var c = 0; c < accountInfo.length; c++) {
839 if (accountInfo[c]["accountName"] == name && accountInfo[c]["iot"] == iot) {
840 var result = "Y";
841 break;
842 }
843 else result = "N";
844 }
845 return result;
846}
847function processClientInterviewStatus(name, iot, accountInfo) {
848 for (var c = 0; c < accountInfo.length; c++) {
849 if (accountInfo[c]["accountName"] == name && accountInfo[c]["iot"] == iot) {
850 var data = accountInfo[c]["surveyInterview"];
851 var clientInterview = data[5];
852 if (clientInterview["title"] == "Client Interview" && clientInterview["value"] != "") {
853 var result = "Y";
854 break;
855 }
856 else {
857 result = "N";
858 }
859
860 }
861
862 }
863 return result;
864
865}
866/************ to check if data is submitted for Stickiness Survey**************/
867function processStickinessData(accName, iot, stickinessDoc) {
868 var result = "";
869 for (var c = 0; c < stickinessDoc.length; c++) {
870 if (stickinessDoc[c]["account_name"] == accName && stickinessDoc[c]["IOT"] == iot) {
871 result = "Y";
872 break;
873 }
874 else { result = "N"; }
875 }
876 return result;
877}
878/******end of code**********/
879/***** function to process the action plan data submission status account wise******/
880function processActionPlanData(name, sector, actionDoc, iot) {
881
882 for (var c = 0; c < actionDoc.length; c++) {
883 if (actionDoc[c].doc["accountName"] == name && actionDoc[c].doc["iot"] == iot) {
884 actionPlan = actionDoc[c].doc.actionPlan == true ? "Y" : "N";
885 walletShare = actionDoc[c].doc.walletShare == true ? "Y" : "N";
886 innovationCulture = actionDoc[c].doc.innovationCulture == true ? "Y" : "N";
887 innovationInitiatives = actionDoc[c].doc.innovationInitiatives == true ? "Y" : "N";
888 pipeline = actionDoc[c].doc.pipeline == true ? "Y" : "N";
889 var result = {
890 "account_Name": name,
891 "sector": sector,
892 "action_Plan": actionPlan,
893 "walletshare": walletShare,
894 "intervention_status": innovationInitiatives,
895 "culture_assessment": innovationCulture,
896 "pipeline": pipeline,
897 "iot": iot
898 };
899 break;
900 }
901 else {
902 var result = {
903 "account_Name": name,
904 "sector": sector,
905 "action_Plan": "N",
906 "walletshare": "N",
907 "intervention_status": "N",
908 "culture_assessment": "N",
909 "pipeline": "N",
910 "iot": iot
911 };
912 }
913 }
914 return result;
915
916}
917/***********/
918
919function processAccountSummary(name, config, account_summary_config, isNPS, isLAP, iot, isStickiness) {
920 var finalSummary = [];
921 for (var i = 0; i < account_summary_config.dimension.length; i++) {
922 var item = account_summary_config.dimension[i];
923 var dimension = {
924 "title": item.title,
925 "list": []
926 };
927 for (var k = 0; k < item.list.length; k++) {
928 var array1 = [];
929 //console.log("itemlist");
930 // console.log(item.list[k].nps +" "+ isNPS);
931 //console.log("nps data+++");
932 // console.log(config.nps[0]);
933 //console.log(config.nps[0].prejolt.account_Name);
934 //console.log(config.nps.length);
935 if (item.list[k].nps == "Y") {
936 if (isNPS == "Y") {
937 for (var m = 0; m < config.nps.length; m++) {
938 //console.log(config.nps[m].prejolt);
939 // console.log("inside nps >>");
940 if(config.nps[m].prejolt)
941 {
942
943 if (config.nps[m].prejolt.account_Name == name && config.nps[m].prejolt.iot == iot) {
944 var npsdata = config.nps[m].prejolt.scroing;
945
946 for (var n = 0; n < npsdata.length; n++) {
947 if (item.list[k].name == npsdata[n].title) {
948 var val = npsdata[n].value;
949 if (val == "") {
950 var ans = "";
951 }
952 else if (0 == val || val <= 6) {
953 var ans = "Low";
954 }
955 else if (7 == val || val == 8) {
956 var ans = "Medium";
957 }
958 else if (9 == val || val == 10) {
959 var ans = "High";
960 }
961 var json = {
962 "id": item.list[k].id,
963 "name": item.list[k].name,
964 "nps": ans,
965 "lap": "",
966 "stickiness": "",
967 "account_info": ""
968 }
969 array1 = json;
970 }
971 }
972 }
973 }
974 }
975 dimension.list[k] = array1;
976 }
977 else {
978 var json = {
979 "id": item.list[k].id,
980 "name": item.list[k].name,
981 "nps": "",
982 "lap": "",
983 "stickiness": "",
984 "account_info": ""
985 }
986 array1 = json;
987 dimension.list[k] = json;
988
989 }
990 }
991 if (item.list[k].lap == "Y") {
992 if (isLAP == "Y") {
993 for (var m = 0; m < config.lap.length; m++) {
994 if (config.lap[m].AccountInfo[0].value == name && config.lap[m].IOT == iot) {
995 var lapdata = config.lap[m];
996 // if (item.list[k].name == "Client Relationship" || item.list[k].name == "Innovation") {
997 // for (var a = 0; a < lapdata.PieChart1.length; a++) {
998 // if (item.list[k].name == lapdata.PieChart1[a].name) {
999 // var val = lapdata.PieChart1[a].value;
1000 // if(val== ""){
1001 // var ans="";
1002 // }
1003 // else if (val == 1) {
1004 // var ans = "Low";
1005 // }
1006 // else if (val == 2) {
1007 // var ans = "Medium";
1008 // }
1009 // else if (val == 3) {
1010 // var ans = "High";
1011 // }
1012 // var json = {
1013 // "id": item.list[k].id,
1014 // "name": item.list[k].name,
1015 // "nps": "",
1016 // "lap": ans,
1017 // "stickiness": "",
1018 // "account_info": ""
1019 // }
1020 // array1 = json;
1021 // }
1022 // }
1023 // }
1024 if (item.list[k].name == "Resource Availability or Capability" || item.list[k].name == "Delivery Quality" || item.list[k].name == "Competition provided better value" || item.list[k].name == "Planned Contract Contraction" || item.list[k].name == "Client Relationship" || item.list[k].name == "Innovation") {
1025 for (var b = 0; b < lapdata.RadarChart.length; b++) {
1026 if (item.list[k].name == lapdata.RadarChart[b].question) {
1027 var val = lapdata.RadarChart[b].ans;
1028 if (val == "") {
1029 var ans = "";
1030 }
1031 else if (val == 1) {
1032 var ans = "Low";
1033 }
1034 else if (val == 2) {
1035 var ans = "Medium";
1036 }
1037 else if (val == 3) {
1038 var ans = "High";
1039 }
1040 var json = {
1041 "id": item.list[k].id,
1042 "name": item.list[k].name,
1043 "nps": "",
1044 "lap": ans,
1045 "stickiness": "",
1046 "account_info": ""
1047 }
1048 array1 = json;
1049 }
1050 if (item.list[k].name == "Innovation") {
1051 var val = lapdata.RadarChart[3].ans;
1052 if (val == "") {
1053 var ans = "";
1054 }
1055 else if (val == 1) {
1056 var ans = "Low";
1057 }
1058 else if (val == 2) {
1059 var ans = "Medium";
1060 }
1061 else if (val == 3) {
1062 var ans = "High";
1063 }
1064 var json = {
1065 "id": item.list[k].id,
1066 "name": item.list[k].name,
1067 "nps": "",
1068 "lap": ans,
1069 "stickiness": "",
1070 "account_info": ""
1071 }
1072 array1 = json;
1073 }
1074
1075 }
1076 }
1077 }
1078 }
1079 dimension.list[k] = json;
1080 }
1081 else {
1082 var json = {
1083 "id": item.list[k].id,
1084 "name": item.list[k].name,
1085 "nps": "",
1086 "lap": "",
1087 "stickiness": "",
1088 "account_info": ""
1089 }
1090 array1 = json;
1091 dimension.list[k] = json;
1092 }
1093 }
1094 if (item.list[k].account_interview == "Y") {
1095 for (var m = 0; m < config.accountInfo.length; m++) {
1096 if (config.accountInfo[m].account[0].value == name && config.accountInfo[m].iot == iot) {
1097 var accdata = config.accountInfo[m].radar_chart;
1098
1099 for (var n = 0; n < accdata.length; n++) {
1100 if (item.list[k].name == accdata[n].title) {
1101 var val = accdata[n].value;
1102 if (val == 1) {
1103 var ans = "Low";
1104 }
1105 else if (val == 2) {
1106 var ans = "Medium";
1107 }
1108 else if (val == 3) {
1109 var ans = "High";
1110 }
1111 dimension.list[k].account_info = ans;
1112 }
1113 }
1114 }
1115 }
1116 }
1117 if (item.list[k].stickiness == "Y") {
1118 if (isStickiness == "Y") {
1119 for (var m = 0; m < config.stickiness.length; m++) {
1120 if (config.stickiness[m].account_name == name && config.stickiness[m].IOT == iot) {
1121 var ans = "";
1122 var accdata = config.stickiness[m];
1123
1124 if (item.list[k].name == "Strategic Partnership / Collaboration") {
1125 ans = config.stickiness[m]["radar_data"]["Client Relationship"];
1126 }
1127 else if (item.list[k].name == "Deliver Methods(Agile, DevOps, Cloud)") {
1128 ans = config.stickiness[m]["radar_data"]["Delivery Quality"];
1129 }
1130 else if (item.list[k].name == "Deployment of Innovation") {
1131 ans = config.stickiness[m]["radar_data"]["Innovation"];
1132 }
1133 else if (item.list[k].name == "Capability") {
1134 ans = config.stickiness[m]["radar_data"]["Resource Availability and Capability"];
1135 }
1136 if (ans == 1) {
1137 var val = "Low";
1138 }
1139 else if (ans == 2) {
1140 var val = "Medium";
1141 }
1142 else if (ans == 3) {
1143 var val = "High";
1144 }
1145 var json = {
1146 "id": item.list[k].id,
1147 "name": item.list[k].name,
1148 "nps": "",
1149 "lap": "",
1150 "stickiness": val,
1151 "account_info": ""
1152 }
1153
1154 dimension.list[k] = json;
1155 }
1156 }
1157 } else {
1158 var json = {
1159 "id": item.list[k].id,
1160 "name": item.list[k].name,
1161 "nps": "",
1162 "lap": "",
1163 "stickiness": "",
1164 "account_info": ""
1165 }
1166
1167 dimension.list[k] = json;
1168 }
1169 }
1170 }
1171 finalSummary.push(dimension);
1172 }
1173 return finalSummary;
1174};
1175/********************** */
1176
1177function processNPSData(accountName, iot, config) {
1178 var result = "";
1179 for (var c = 0; c < config.nps.length; c++) {
1180 if(config.nps[c].prejolt){
1181 if (config.nps[c].prejolt.account_Name == accountName && config.nps[c].prejolt.iot == iot) {
1182 result = "Y";
1183 break;
1184 }
1185
1186 else { result = "N"; }
1187 }
1188 else { result = "N"; }
1189 }
1190 return result;
1191};
1192function processLAPData(accountName, iot, config) {
1193 var result = "";
1194 for (var c = 0; c < config.lap.length; c++) {
1195 if (config.lap[c]["AccountInfo"][0].value == accountName && config.lap[c]["IOT"] == iot) {
1196 result = "Y";
1197 break;
1198 }
1199 else { result = "N"; }
1200 }
1201 return result;
1202};
1203function processAccountInfoSummary(infoItem, config) {
1204 const account = [];
1205 const team = [];
1206 const financial_data = [];
1207 const survey_interview = [];
1208 const radar_chart = [];
1209 for (var k = 0; k < config.account.length; k++) {
1210 var query = config.account[k];
1211 var json = {
1212 "title": query,
1213 "value": infoItem[query]
1214 };
1215 account.push(json);
1216 }
1217 for (var k = 0; k < config.team.length; k++) {
1218 var query = config.team[k];
1219 // if (query === "Sector GM or Market Owner") {
1220 // var json = {
1221 // "title": "Sector / Market GM ",
1222 // "value": infoItem["Sector GM or Market Owner"]
1223 // };
1224 // }
1225 // else if (query === "LAP") {
1226 // var json = {
1227 // "title": "GLAP / LAP ",
1228 // "value": infoItem["LAP"]
1229 // };
1230 // }
1231 // else {
1232
1233 var json = {
1234 "title": query,
1235 "value": infoItem[query]
1236 };
1237 // }
1238 team.push(json);
1239 }
1240 for (var k = 0; k < config.financial_data.length; k++) {
1241 var query = config.financial_data[k];
1242 var json = {
1243 "title": query,
1244 "value": infoItem[query]
1245 };
1246 financial_data.push(json);
1247 }
1248 for (var k = 0; k < config.survey_interview.length; k++) {
1249 var query = config.survey_interview[k];
1250 if (query == "Account Interview Date") {
1251 var json = {
1252 "title": "Account Interview",
1253 "value": infoItem[query]
1254 };
1255 }
1256 else {
1257 var json = {
1258 "title": query,
1259 "value": infoItem[query]
1260 }; }
1261 survey_interview.push(json);
1262 }
1263 for (var k = 0; k < config.radar_chart.length; k++) {
1264 var query = config.radar_chart[k];
1265 var json = {
1266 "title": query,
1267 "value": parseInt(infoItem[query])
1268 };
1269 radar_chart.push(json);
1270 }
1271 var accName = infoItem["_id"].split("_");
1272 accName = accName[0].trim();
1273 finaljson = {
1274 "account": account,
1275 "team": team,
1276 "financialData": financial_data,
1277 "surveyInterview": survey_interview,
1278 "radar_chart": radar_chart,
1279 "_id": infoItem["_id"],
1280 "_rev": infoItem["_rev"],
1281 "Market": infoItem["Market"],
1282 "Coverage": infoItem["Coverage"],
1283 "Sector GM or Market Owner": infoItem["Sector GM or Market Owner"],
1284 "accountName": accName,
1285 "iot": infoItem["IOT"]
1286
1287 };
1288 return finaljson;
1289}
1290
1291
1292function NPSdivison(item,config)
1293{
1294 var prejolt=[];
1295var postjolt=[];
1296var account_Name="";
1297//console.log("wave");
1298//console.log(wave);
1299
1300// console.log(item.data.length);
1301
1302
1303 if(item.IOT=='AP')
1304 {
1305 for(let i=0;i<item.data.length;i++)
1306 {
1307 var date=item.data[i]["Response Date"].split(' ')[0];
1308 var date1= new Date(date);
1309 var date2= new Date('March 7,2018');
1310 account_Name=item.data[i].Unit;
1311 if(date1>date2)
1312 {
1313 postjolt.push(item.data[i]);
1314 }
1315 else
1316 {
1317 prejolt.push(item.data[i]);
1318 }
1319
1320
1321 }
1322
1323}
1324else if(item.IOT=='EU')
1325{
1326 for(let i=0;i<item.data.length;i++)
1327 {
1328 var date=item.data[i]["Response Date"].split(' ')[0];
1329 var date1= new Date(date);
1330 var date2=new Date('January 4,2018');
1331 account_Name=item.data[i].Unit;
1332 if(date1>date2)
1333 {
1334 postjolt.push(item.data[i]);
1335 }
1336 else
1337 {
1338 prejolt.push(item.data[i]);
1339 }
1340 }
1341}
1342
1343else if(item.IOT=='NA')
1344{
1345 if(item.Wave=="1")
1346 {
1347 for(let i=0;i<item.data.length;i++)
1348 {
1349 var date=item.data[i]["Response Date"].split(' ')[0];
1350 var date1=new Date(date);
1351 var date2= new Date('November 1,2017');
1352 account_Name=item.data[i].Unit;
1353 if(date1>date2)
1354 {
1355 postjolt.push(item.data[i]);
1356 }
1357 else
1358 {
1359 prejolt.push(item.data[i]);
1360 }
1361
1362
1363 }
1364}
1365else if(item.Wave=="2")
1366{
1367 for(let i=0;i<item.data.length;i++)
1368 {
1369 var date=item.data[i]["Response Date"].split(' ')[0];
1370 var date1=new Date(date);
1371 var date2= new Date('May 3,2018');
1372 account_Name=item.data[i].Unit;
1373 if(date1>date2)
1374 {
1375 postjolt.push(item.data[i]);
1376 }
1377 else
1378 {
1379 prejolt.push(item.data[i]);
1380 }
1381
1382
1383 }
1384}
1385
1386}
1387// if(prejolt.length>0)
1388// {
1389var json={
1390 "IOT":item.IOT,
1391 "group":item.group,
1392 "data":prejolt
1393}
1394// }
1395// else if(postjolt.length>0)
1396// {
1397var json2={
1398 "IOT":item.IOT,
1399 "group":item.group,
1400 "data":postjolt
1401
1402}
1403 // }
1404
1405 if(prejolt.length>0)
1406 {
1407 var prejoltnps=processNPSSummary(json,config);
1408 }
1409 if(postjolt.length>0)
1410 {
1411 var postjoltnps=processNPSSummary(json2,config);
1412 }
1413 // console.log("hiiiiiii");
1414 // console.log(prejolt);
1415 // console.log(postjolt);
1416 var finalNPSjson2 = {
1417 "prejolt":prejoltnps,
1418 "postjolt":postjoltnps,
1419 "account_Name":account_Name,
1420 "IOT":item.IOT
1421 };
1422
1423 return finalNPSjson2;
1424
1425}
1426function processNPSSummary(item, config) {
1427 var totalRecord = item.data.length;
1428
1429 var configItem = config.npsconfig;
1430// console.log("HELLO ITEM");
1431// console.log(item);
1432// if(item.IOT=='AP')
1433// {
1434// for(let i=0;i<item.data.length;i++)
1435// {
1436// var date=item.data[i]["Response Date"].split(' ')[0];
1437// if(date>7th March)
1438// {
1439// function npsprejolt(item,config)
1440// {
1441// var totalRecord = item.data.length;
1442// var configItem = config.npsconfig;
1443// const scoring = [];
1444// var surveyType_run = [];
1445// var surveyType_project = [];
1446// configItem.Scoring.forEach((items) => {
1447// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1448// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1449// const score = {
1450// title: items,
1451// value: avg
1452// };
1453// scoring.push(score);
1454
1455// });
1456// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1457// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1458// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1459// surveyType_run = surveyType.filter(value => value === 'Run').length;
1460// surveyType_project = surveyType.filter(value => value === "Project").length;
1461// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1462// var finalNPSprejolt = {
1463// "account_Name": item.data[0][configItem.AccountName],
1464// "sector": sectorName,
1465// "iot": item.IOT,
1466// "additional_comments": comments,
1467// "reason_for_scoring": reason_for_score_comment,
1468// "no_respondents": totalRecord,
1469// "scroing": scoring
1470
1471// };
1472// if (surveyType_run > 0) {
1473// finainalNPSprejolt.run = surveyType_run;
1474// }
1475// if (surveyType_project > 0) {
1476// finalNPSprejolt.project = surveyType_project;
1477// }
1478// return finalNPSprejolt;
1479// }
1480// }
1481
1482// else if(date<7th March)
1483// {
1484// function npspostjolt(item,config)
1485// {
1486// var totalRecord = item.data.length;
1487// var configItem = config.npsconfig;
1488// const scoring = [];
1489// var surveyType_run = [];
1490// var surveyType_project = [];
1491// configItem.Scoring.forEach((items) => {
1492// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1493// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1494// const score = {
1495// title: items,
1496// value: avg
1497// };
1498// scoring.push(score);
1499
1500// });
1501// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1502// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1503// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1504// surveyType_run = surveyType.filter(value => value === 'Run').length;
1505// surveyType_project = surveyType.filter(value => value === "Project").length;
1506// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1507// var finalNPSpostjolt = {
1508// "account_Name": item.data[0][configItem.AccountName],
1509// "sector": sectorName,
1510// "iot": item.IOT,
1511// "additional_comments": comments,
1512// "reason_for_scoring": reason_for_score_comment,
1513// "no_respondents": totalRecord,
1514// "scroing": scoring
1515
1516// };
1517// if (surveyType_run > 0) {
1518// finainalNPSpostjolt.run = surveyType_run;
1519// }
1520// if (surveyType_project > 0) {
1521// finalNPSpostjolt.project = surveyType_project;
1522// }
1523// return finalNPSpostjolt;
1524// }
1525// }
1526
1527
1528
1529
1530// }
1531
1532// }
1533// else if(item.IOT=='EU')
1534// {
1535// for(let i=0;i<item.data.length;i++)
1536// {
1537// var date=item.data[i]["Response Date"].split(' ')[0];
1538// if(date>14th Jan)
1539// {
1540// function npsprejolt(item,config)
1541// {
1542// var totalRecord = item.data.length;
1543// var configItem = config.npsconfig;
1544// const scoring = [];
1545// var surveyType_run = [];
1546// var surveyType_project = [];
1547// configItem.Scoring.forEach((items) => {
1548// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1549// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1550// const score = {
1551// title: items,
1552// value: avg
1553// };
1554// scoring.push(score);
1555
1556// });
1557// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1558// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1559// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1560// surveyType_run = surveyType.filter(value => value === 'Run').length;
1561// surveyType_project = surveyType.filter(value => value === "Project").length;
1562// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1563// var finalNPSprejolt = {
1564// "account_Name": item.data[0][configItem.AccountName],
1565// "sector": sectorName,
1566// "iot": item.IOT,
1567// "additional_comments": comments,
1568// "reason_for_scoring": reason_for_score_comment,
1569// "no_respondents": totalRecord,
1570// "scroing": scoring
1571
1572// };
1573// if (surveyType_run > 0) {
1574// finainalNPSprejolt.run = surveyType_run;
1575// }
1576// if (surveyType_project > 0) {
1577// finalNPSprejolt.project = surveyType_project;
1578// }
1579// return finalNPSprejolt;
1580// }
1581// }
1582
1583// else if(date<14th Jan)
1584// {
1585// function npspostjolt(item,config)
1586// {
1587// var totalRecord = item.data.length;
1588// var configItem = config.npsconfig;
1589// const scoring = [];
1590// var surveyType_run = [];
1591// var surveyType_project = [];
1592// configItem.Scoring.forEach((items) => {
1593// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1594// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1595// const score = {
1596// title: items,
1597// value: avg
1598// };
1599// scoring.push(score);
1600
1601// });
1602// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1603// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1604// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1605// surveyType_run = surveyType.filter(value => value === 'Run').length;
1606// surveyType_project = surveyType.filter(value => value === "Project").length;
1607// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1608// var finalNPSpostjolt = {
1609// "account_Name": item.data[0][configItem.AccountName],
1610// "sector": sectorName,
1611// "iot": item.IOT,
1612// "additional_comments": comments,
1613// "reason_for_scoring": reason_for_score_comment,
1614// "no_respondents": totalRecord,
1615// "scroing": scoring
1616
1617// };
1618// if (surveyType_run > 0) {
1619// finainalNPSpostjolt.run = surveyType_run;
1620// }
1621// if (surveyType_project > 0) {
1622// finalNPSpostjolt.project = surveyType_project;
1623// }
1624// return finalNPSpostjolt;
1625// }
1626// }
1627
1628
1629
1630
1631// }
1632
1633// }
1634// else if(item.IOT=='NA')
1635// {
1636
1637// for(let i=0;i<item.data.length;i++)
1638// {
1639// var date=item.data[i]["Response Date"].split(' ')[0];
1640// if(date>3rd May)
1641// {
1642// function npsprejolt(item,config)
1643// {
1644// var totalRecord = item.data.length;
1645// var configItem = config.npsconfig;
1646// const scoring = [];
1647// var surveyType_run = [];
1648// var surveyType_project = [];
1649// configItem.Scoring.forEach((items) => {
1650// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1651// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1652// const score = {
1653// title: items,
1654// value: avg
1655// };
1656// scoring.push(score);
1657
1658// });
1659// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1660// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1661// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1662// surveyType_run = surveyType.filter(value => value === 'Run').length;
1663// surveyType_project = surveyType.filter(value => value === "Project").length;
1664// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1665// var finalNPSprejolt = {
1666// "account_Name": item.data[0][configItem.AccountName],
1667// "sector": sectorName,
1668// "iot": item.IOT,
1669// "additional_comments": comments,
1670// "reason_for_scoring": reason_for_score_comment,
1671// "no_respondents": totalRecord,
1672// "scroing": scoring
1673
1674// };
1675// if (surveyType_run > 0) {
1676// finainalNPSprejolt.run = surveyType_run;
1677// }
1678// if (surveyType_project > 0) {
1679// finalNPSprejolt.project = surveyType_project;
1680// }
1681// return finalNPSprejolt;
1682// }
1683// }
1684
1685// else if(date<14th Jan)
1686// {
1687// function npspostjolt(item,config)
1688// {
1689// var totalRecord = item.data.length;
1690// var configItem = config.npsconfig;
1691// const scoring = [];
1692// var surveyType_run = [];
1693// var surveyType_project = [];
1694// configItem.Scoring.forEach((items) => {
1695// const data = item.data[i].map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1696// const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1697// const score = {
1698// title: items,
1699// value: avg
1700// };
1701// scoring.push(score);
1702
1703// });
1704// const comments = item.data[i].map(value => value[configItem.AdditionalComments]).filter(value => value);
1705// const reason_for_score_comment = item.data[i].map(value => value[configItem.ReasonforScores]).filter(value => value);
1706// const surveyType = item.data[i].map(value => value[configItem.surveyType]);
1707// surveyType_run = surveyType.filter(value => value === 'Run').length;
1708// surveyType_project = surveyType.filter(value => value === "Project").length;
1709// var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1710// var finalNPSpostjolt = {
1711// "account_Name": item.data[0][configItem.AccountName],
1712// "sector": sectorName,
1713// "iot": item.IOT,
1714// "additional_comments": comments,
1715// "reason_for_scoring": reason_for_score_comment,
1716// "no_respondents": totalRecord,
1717// "scroing": scoring
1718
1719// };
1720// if (surveyType_run > 0) {
1721// finainalNPSpostjolt.run = surveyType_run;
1722// }
1723// if (surveyType_project > 0) {
1724// finalNPSpostjolt.project = surveyType_project;
1725// }
1726// return finalNPSpostjolt;
1727// }
1728// }
1729// }
1730
1731// }
1732// var finalNPSjson = {
1733// "prejolt":finalNPSprejolt,
1734// "postjolt":finalNPSpostjolt
1735// };
1736// return finalNPSjson;
1737
1738
1739
1740 const scoring = [];
1741 var surveyType_run = [];
1742 var surveyType_project = [];
1743 configItem.Scoring.forEach((items) => {
1744 const data = item.data.map(value => value[items]).filter(value => value).map(n => parseInt(n, 10));
1745 const avg = data.length === 0 ? "" : Math.round(data.reduce((a, b) => a + b) / data.length);
1746 const score = {
1747 title: items,
1748 value: avg
1749 };
1750 scoring.push(score);
1751
1752 });
1753
1754 const comments = item.data.map(value => value[configItem.AdditionalComments]).filter(value => value);
1755 const reason_for_score_comment = item.data.map(value => value[configItem.ReasonforScores]).filter(value => value);
1756 const surveyType = item.data.map(value => value[configItem.surveyType]);
1757 surveyType_run = surveyType.filter(value => value === 'Run').length;
1758 surveyType_project = surveyType.filter(value => value === "Project").length;
1759 var sectorName = findSector(item.data[0][configItem.AccountName], config.account, item.IOT);
1760 var finalNPSjson = {
1761 // "account_Nameee": item.data,
1762 "account_Name":item.data[0].Unit,
1763 "sector":sectorName ,
1764 // "account":1,
1765 "iot": item.IOT,
1766 "additional_comments": comments,
1767 "reason_for_scoring": reason_for_score_comment,
1768 "no_respondents": totalRecord,
1769 "scroing": scoring
1770
1771 };
1772 if (surveyType_run > 0) {
1773 finalNPSjson.run = surveyType_run;
1774 }
1775 if (surveyType_project > 0) {
1776 finalNPSjson.project = surveyType_project;
1777 }
1778 return finalNPSjson;
1779
1780};
1781
1782function findSector(accountName, accountList, iot) {
1783 if (iot == "EU") {
1784 var accountArray = accountList[0].accountName_EU;
1785 }
1786 else if (iot == "NA") {
1787 var accountArray = accountList[1].accountName_NA;
1788 }
1789 else if (iot == "AP") {
1790 var accountArray = accountList[2].accountName_AP;
1791 }
1792 else if (iot == "LA") {
1793 var accountArray = accountList[3].accountName_LA;
1794 }
1795 else if (iot == "GCG") {
1796 var accountArray = accountList[4].accountName_GCG;
1797 }
1798 else if (iot == "JP") {
1799 var accountArray = accountList[5].accountName_JP;
1800 }
1801 else if (iot == "MEA") {
1802 var accountArray = accountList[6].accountName_MEA;
1803 }
1804 // console.log(accountArray);
1805 // console.log(iot);
1806 for (var k = 0; k < accountArray.length; k++) {
1807 if (accountName == accountArray[k].name) {
1808 // var ind=accountArray.indexOf(accountName);
1809 var sector = accountArray[k].sector;
1810 }
1811 }
1812
1813 return sector;
1814};
1815/**********end of all account data************/
1816
1817/************ to check super user access***********/
1818function checkRole(db, record) {
1819 console.log("inside find");
1820 console.log(record);
1821 return new Promise(function (resolve, reject) {
1822 db.find(record, function (err, data) {
1823 if (!err) {
1824 resolve(data);
1825 }
1826 else {
1827 resolve(err);
1828 }
1829 });
1830 });
1831}
1832// router.post('/api/v1/findUser', function (req, res) {
1833// var record = { "selector": { "email": req.body.userId } };
1834// db = cloudant.db.use('audit_logs');
1835// checkRole(db, record).then(function (result) {
1836// superLogsData = result.docs[0];
1837// console.log("SUPER USER AUDIT DATA");
1838// console.log(superLogsData);
1839// res.json(superLogsData.email);
1840// // if (result.docs.length > 0) {
1841// // }
1842// })
1843// })
1844router.post('/api/v1/findSuperUser', function (req, res) {
1845 // var record = { "selector": { "user": req.body.userId } };
1846 var record = { "selector": { "user":{ "$regex": "^(?i)"+req.body.userId+"$"}} };
1847 // "email": {
1848 // "$regex": "^(?i)" + Username + "$"
1849 // }
1850 db = cloudant.db.use('userlist_backup');
1851 checkRole(db, record).then(function (result) {
1852 superUserData = result.docs[0];
1853 // console.log("---------------------------------------------------",superUserData);
1854 if (result.docs.length > 0) {
1855 var accountId = req.params.accountId;
1856 iotdb = cloudant.db.use('listofiot');
1857 actionplandb = cloudant.db.use('actionplanconfigfiles');
1858 dbquerries = [getAllIOT(iotdb), getAllIOT(actionplandb)]
1859 Promise.all(dbquerries).then(function (data) {
1860 var response = {
1861 "iot": data[0].rows[0].doc.iot_data,
1862 "sector_EU": data[0].rows[0].doc.sector_data_EU,
1863 "sector_NA": data[0].rows[0].doc.sector_data_NA,
1864 "sector_AP": data[0].rows[0].doc.sector_data_AP,
1865 "sector_GCG":data[0].rows[0].doc.sector_data_GCG,
1866 "sector_LA":data[0].rows[0].doc.sector_data_LA,
1867 "sector_JP":data[0].rows[0].doc.sector_data_JP,
1868 "sector_MEA":data[0].rows[0].doc.sector_data_MEA,
1869 "actionPlanCultureAssessment": {
1870 "title": data[1].rows[0].doc.title,
1871 "data": data[1].rows[0].doc.data
1872 },
1873 "actionPlanInterventionStatus": {
1874 "title": data[1].rows[1].doc.title,
1875 "data": data[1].rows[1].doc.data
1876 }
1877 }
1878
1879 iotData.push(response);
1880 console.log(JSON.stringify(iotData));
1881 finalJsonArray = {
1882 "role": superUserData.data,
1883 "iotData": iotData,
1884 "notify":superUserData.notify,
1885 "pmo":superUserData.pmo
1886 }
1887 res.json(finalJsonArray);
1888 console.log("Response Data is :",finalJsonArray);
1889 }, function (err) {
1890 console.log(err);
1891 });
1892 superUserData.role = null;
1893 iotData = [];
1894 // });
1895 // res.json(iotData)
1896 } else {
1897 res.json({ "message": "Sorry you are not authorized.", "role": [] });
1898 }
1899 });
1900});/*********** to get account level data for lap and nps******************/
1901function getData(db, record) {
1902 return new Promise(function (resolve, reject) {
1903 db.get(record, function (err, data) {
1904 if (!err) {
1905 resolve(data);
1906 }
1907 else {
1908 resolve(err);
1909 }
1910
1911 });
1912 });
1913}
1914
1915router.get('/api/v1/getConfig/:accountId', function (req, res) {
1916
1917 var accountId = req.params.accountId;
1918 lapdb = cloudant.db.use('lapdatabase')
1919 npsdb = cloudant.db.use('nps123');
1920 console.log(accountId);
1921 dbquerries = [getData(lapdb, "lapConfig"), getData(npsdb, "npsConfig"), getData(lapdb, accountId), getData(npsdb, accountId)]
1922 Promise.all(dbquerries).then(function (data) {
1923 console.log("response");
1924 console.log("dean");
1925
1926 var response = {};
1927 response.lapConfig = data[0];
1928 response.npsConfig = data[1];
1929 response.nps = {};
1930 response.lap = {}
1931 if (data[3].hasOwnProperty('_id')) {
1932 response.nps = data[3];
1933 }
1934 if (data[2].hasOwnProperty('_id')) {
1935
1936 response.lap = data[2];
1937 }
1938 res.json(response);
1939 }, function (err) {
1940 console.log(err);
1941 });
1942});
1943/******** end of account level data *************/
1944
1945/******** Get pipeline data *************/
1946router.get('/api/v1/getPipelineData/:accountId', function (req, res) {
1947
1948 var accountId = req.params.accountId;
1949 pipelinedb = cloudant.db.use('pipeline')
1950 salesdb = cloudant.db.use('salesconnect');
1951 console.log(accountId);
1952 dbquerries = [getData(pipelinedb, accountId), getData(salesdb, accountId)]
1953 Promise.all(dbquerries).then(function (data) {
1954 console.log("response");
1955
1956 var response = {};
1957 response.salesConnect = {};
1958 response.pipeline = {};
1959
1960 if (data[0].hasOwnProperty('_id')) {
1961 response.pipeline = data[0];
1962 }
1963 if (data[1].hasOwnProperty('_id')) {
1964
1965 response.salesConnect = data[1];
1966 }
1967 res.json(response);
1968 }, function (err) {
1969 console.log(err);
1970 });
1971});
1972/**************End of getPipeline function************/
1973
1974/*********To store notification data in DB ********/
1975
1976
1977router.post('/api/v1/notify', function (req, res) {
1978 var record = req.body;
1979 console.log(record);
1980 db = cloudant.db.use('notifydb');
1981 saveNotify(db, record).then(function (myData) {
1982 console.log("save data",myData);
1983 res.json(myData);
1984 });
1985});
1986function saveNotify(db, record) {
1987 return new Promise(function (resolve, reject) {
1988 db.insert(record, function (err, data) {
1989 if (!err) {
1990 resolve(data);
1991 }
1992 else {
1993 resolve(err);
1994 }
1995 });
1996 });
1997}
1998/**Backing up database */
1999// function backupData(){
2000// couchbackup.backup(
2001// 'https://51a88e11-63df-49a2-b340-19b1a379f8c5-bluemix.cloudant.com/accountinfo',
2002// fs.createWriteStream('backup.txt'),
2003// {parallelism: 2},
2004// function(err, data) {
2005// if (err) {
2006// console.error("Failed! " + err);
2007// } else {
2008// console.error("Success! " + data);
2009// }
2010// });
2011// }
2012 /** ................. */
2013/**************get all iot names ************/
2014function getAllIOT(db, record) {
2015 return new Promise(function (resolve, reject) {
2016 db.list({ include_docs: true }, function (err, data) {
2017 if (!err) {
2018 resolve(data);
2019 }
2020 else {
2021 resolve(err);
2022 }
2023 });
2024 });
2025}
2026router.get('/api/v1/getIOTList', function (req, res) {
2027
2028 var accountId = req.params.accountId;
2029 iotdb = cloudant.db.use('listofiot');
2030 actionplandb = cloudant.db.use('actionplanconfigfiles');
2031 dbquerries = [getAllIOT(iotdb), getAllIOT(actionplandb)]
2032 Promise.all(dbquerries).then(function (data) {
2033 var response = {
2034 "iot": data[0].rows[0].doc.iot_data,
2035 "sector_EU": data[0].rows[0].doc.sector_data_EU,
2036 "sector_NA": data[0].rows[0].doc.sector_data_NA,
2037 "sector_AP": data[0].rows[0].doc.sector_data_AP,
2038 "sector_LA":data[0].rows[0].doc.sector_data_LA,
2039 "sector_GCG":data[0].rows[0].doc.sector_data_GCG,
2040 "sector_JP":data[0].rows[0].doc.sector_data_JP,
2041 "sector_MEA":data[0].rows[0].doc.sector_data_MEA,
2042 "actionPlanCultureAssessment": {
2043 "title": data[1].rows[0].doc.title,
2044 "data": data[1].rows[0].doc.data
2045 },
2046 "actionPlanInterventionStatus": {
2047 "title": data[1].rows[1].doc.title,
2048 "data": data[1].rows[1].doc.data
2049 }
2050 }
2051 res.json(response);
2052 }, function (err) {
2053 console.log(err);
2054 });
2055});
2056/********* end of code for getting iot list******/
2057/*********get pipeline vs opportunity data*******/
2058// router.get('/api/v1/getPipelineOpportunity',function(req,res){
2059// var accountId = req.params.accountId;
2060// pipelineDb = cloudant.db.use('pipeline');
2061// salesDb = cloudant.db.use('salesconnect');
2062// dbquerries = [getData(pipelinedb, accountId), getData(salesdb, accountId)]
2063
2064
2065// })
2066/********End of code for getting pipeline vs opportunity data*****/
2067/********************* get action plan config files***********/
2068function getActionplanConfig(db, record) {
2069 return new Promise(function (resolve, reject) {
2070 db.list({ include_docs: true }, function (err, data) {
2071 if (!err) {
2072 resolve(data);
2073 }
2074 else {
2075 resolve(err);
2076 }
2077 });
2078 });
2079}
2080router.get('/api/v1/getActionPlanConfig', function (req, res) {
2081
2082 var accountId = req.params.accountId;
2083 actionplandb = cloudant.db.use('actionplanconfigfiles');
2084 dbquerries = [getActionplanConfig(actionplandb)]
2085 Promise.all(dbquerries).then(function (data) {
2086 var response = {
2087 "actionPlanCultureAssessment": {
2088 "title": data[0].rows[0].doc.title,
2089 "data": data[0].rows[0].doc.data
2090 },
2091 "actionPlanInterventionStatus": {
2092 "title": data[0].rows[1].doc.title,
2093 "data": data[0].rows[1].doc.data
2094 }
2095
2096 }
2097 res.json(response);
2098 }, function (err) {
2099 console.log(err);
2100 });
2101});
2102/******end of code**********/
2103/************ to add new data to DB************/
2104
2105function saveData(db, record) {
2106 return new Promise(function (resolve, reject) {
2107 db.insert(record, function (err, data) {
2108 if (!err) {
2109 resolve(data);
2110 }
2111 else {
2112 resolve(err);
2113 }
2114 });
2115 });
2116}
2117router.post('/api/v1/add', function (req, res) {
2118 var record = req.body;
2119 console.log(record);
2120 db = cloudant.db.use('actionplan');
2121 saveData(db, record).then(function (myData) {
2122 res.json(myData);
2123 });
2124
2125});
2126
2127/*********** Update Account info values for radar chart*************/
2128
2129function updateAccountInfo(db, record) {
2130 return new Promise(function (resolve, reject) {
2131 db.insert(record, function (err, data) {
2132 if (!err) {
2133 resolve(data);
2134 }
2135 else {
2136 resolve(err);
2137 }
2138 });
2139 });
2140}
2141router.post('/api/v1/updateAccountInfo', function (req, res) {
2142 var record = req.body;
2143 //console.log(record);
2144 db = cloudant.db.use('accountinfo');
2145 updateAccountInfo(db, record).then(function (myData) {
2146 //console.log("reposne")
2147 //console.log(myData);
2148 res.json(myData);
2149 });
2150});
2151/**********end of code**********/
2152/******* code for loading all the users from the userlist database**********/
2153function getAllUsers(db, record) {
2154 return new Promise(function (resolve, reject) {
2155 db.list({ include_docs: true }, function (err, data) {
2156 if (!err) {
2157 resolve(data);
2158 }
2159 else {
2160 resolve(err);
2161 }
2162 });
2163 });
2164}
2165router.get('/api/v1/getUserList', function (req, res) {
2166
2167 var accountId = req.params.accountId;
2168 userdb = cloudant.db.use('userlist_backup');
2169 dbquerries = [getAllUsers(userdb)]
2170 Promise.all(dbquerries).then(function (data) {
2171 var response = {
2172 "userlist": [],
2173 // "userDetails":[]
2174 };
2175 for (let i = 0; i < data[0].rows.length; i++) {
2176 response.userlist.push(data[0].rows[i].doc);
2177 // var json={
2178 // "_id":data[0].rows[i].doc["_id"],
2179 // "_rev":data[0].rows[i].doc["_rev"]
2180
2181 // }
2182 // response.userDetails.push(json);
2183 }
2184 res.json(response);
2185 }, function (err) {
2186 console.log(err);
2187 });
2188});
2189/******end of code************/
2190
2191/********to get notification data from db */
2192 router.get('/api/v1/getNotify', function (req, res) {
2193
2194 notifydb = cloudant.db.use('notifydb');
2195 dbquerries = [getnotify(notifydb)]
2196 Promise.all(dbquerries).then(function (data) {
2197 var response = {
2198 "notifylist": [],
2199 };
2200 for (let i = 0; i < data[0].rows.length; i++)
2201 {
2202 {
2203 response.notifylist.push(data[0].rows[i].doc);
2204 }
2205 }
2206 res.json(response);
2207 }, function (err) {
2208 console.log(err);
2209 });
2210});
2211function getnotify(db, record) {
2212 return new Promise(function (resolve, reject) {
2213 db.list({ include_docs: true }, function (err, data) {
2214 if (!err) {
2215 resolve(data);
2216 }
2217 else {
2218 resolve(err);
2219 }
2220 });
2221 });
2222}
2223/*****Backup data */
2224router.get('/api/v1/getBackup', function (req, res) {
2225
2226 notifydb = cloudant.db.use('notifydb');
2227 actiondb=cloudant.db.use('actionplan');
2228 accountinfodb=cloudant.db.use('accountinfo')
2229 console.log("------------------------------------------------->",accountinfodb);
2230 lap1db=cloudant.db.use('lapdatabase')
2231 lap2db=cloudant.db.use('newlapdatabase')
2232 npsdb=cloudant.db.use('nps123')
2233 salesdb=cloudant.db.use('salesconnect')
2234 pipelinedb=cloudant.db.use('pipeline')
2235 dbquerries = [getBackup(notifydb),getBackup(actiondb),getBackup(accountinfodb),getBackup(lap1db),getBackup(lap2db),getBackup(npsdb),getBackup(salesdb),getBackup(pipelinedb)]
2236 Promise.all(dbquerries).then(function (data) {
2237 var response = {
2238 "notifylist": [],
2239 "actionlist":[],
2240 "accountinfo":[],
2241 "lap":[],
2242 "newlap":[],
2243 "nps":[],
2244 "sales":[],
2245 "pipeline":[]
2246 };
2247
2248 for (let i = 0; i < data[0].rows.length; i++)
2249
2250 {
2251 response.notifylist.push(data[0].rows[i].doc);
2252
2253 }
2254 for (let i = 0; i < data[1].rows.length; i++)
2255
2256 {
2257 response.actionlist.push(data[1].rows[i].doc);
2258
2259 }
2260 for (let i = 0; i < data[2].rows.length; i++)
2261
2262 {
2263 response.accountinfo.push(data[2].rows[i].doc);
2264
2265 }
2266 for (let i = 0; i < data[3].rows.length; i++)
2267
2268 {
2269 response.lap.push(data[3].rows[i].doc);
2270
2271 }
2272 for (let i = 0; i < data[4].rows.length; i++)
2273
2274 {
2275 response.newlap.push(data[4].rows[i].doc);
2276
2277 }
2278 for (let i = 0; i < data[5].rows.length; i++)
2279
2280 {
2281 response.nps.push(data[5].rows[i].doc);
2282
2283 }
2284 for (let i = 0; i < data[6].rows.length; i++)
2285
2286 {
2287 response.sales.push(data[6].rows[i].doc);
2288
2289 }
2290 for (let i = 0; i < data[7].rows.length; i++)
2291
2292 {
2293 response.pipeline.push(data[7].rows[i].doc);
2294
2295 }
2296 res.json(response);
2297 var fs = require('fs');
2298 let dd=moment(new Date()).format('MM-DD-YYYY');
2299 console.log(dd);
2300 var wstream1 = fs.createWriteStream("noti2.txt");
2301 wstream1.write(JSON.stringify(response.notifylist));
2302 var wstream2 = fs.createWriteStream('actionplanbackup'+dd+'.txt');
2303 wstream2.write(JSON.stringify(response.actionlist));
2304 var wstream3 = fs.createWriteStream('accountbackup'+dd+'.txt');
2305 wstream3.write(JSON.stringify(response.accountinfo));
2306 var wstream4 = fs.createWriteStream('lapbackup'+dd+'.txt');
2307 wstream4.write(JSON.stringify(response.lap));
2308 var wstream5 = fs.createWriteStream('lapwave2'+dd+'.txt');
2309 wstream5.write(JSON.stringify(response.newlap));
2310 var wstream6 = fs.createWriteStream('nps'+dd+'.txt');
2311 wstream6.write(JSON.stringify(response.nps));
2312 var wstream7 = fs.createWriteStream('sales'+dd+'.txt');
2313 wstream7.write(JSON.stringify(response.sales));
2314 var wstream8 = fs.createWriteStream('pipeline'+dd+'.txt');
2315 wstream8.write(JSON.stringify(response.pipeline));
2316
2317
2318
2319
2320// var fileContent = "Hello World!";
2321
2322
2323// var filepath = "mynewfile.txt";
2324
2325// fs.writeFile(filepath, fileContent, (err) => {
2326// if (err) throw err;
2327
2328// console.log("The file was succesfully saved!");
2329// });
2330
2331//fileDownload(wstream8, 'filename.csv');
2332 // boxbackup();
2333
2334
2335
2336
2337 // res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':attachment, filename={Backup}.txt});
2338 // res.end(response);
2339
2340
2341 }, function (err) {
2342 console.log(err);
2343 });
2344});
2345function getBackup(db, record) {
2346 return new Promise(function (resolve, reject) {
2347 db.list({ include_docs: true }, function (err, data) {
2348 if (!err) {
2349
2350
2351 resolve(data);
2352 }
2353 else {
2354 resolve(err);
2355 }
2356 });
2357 });
2358}
2359/********../ save to box*/
2360// function boxbackup(){
2361
2362
2363
2364
2365// var sdk = new BoxSDK({
2366// clientID: '3xi89eutdjlewxjfu43now61e5aipma7',
2367// clientSecret: 'zM4cFWJBmRiDBp94QjqPND69JMfPOFST',
2368// appAuth: {
2369// keyID: '5okenis2',
2370// privateKey: '-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI3vPWQGMBgqwCAggA\nMBQGCCqGSIb3DQMHBAg5lvXMVrX2uASCBMi6pARrEQUapHpy6uJ8rjGBhw8pKh5+\npsv+EMn6BmR3xC4Va7tEGarV9AJUOV3QmJEMsIfNphHxz3jVW2n9Ng3t98p5oN+a\n5Mj0vbSCwCYr0wP9Sk08us0uGil22tu4laRD+hLDG4fac2XyJYB2poY8aQfAdd4p\nCx2Yu1KXrfHyhtzKm3WZ1ciFI54p0PGYxL22aewSrG94C6Dbllpcas1JrOavWcjv\nNC7fYmlFiVMS4sXqCPH0mAJ865Kj2XUASGYTHFFbEXx6WbqSzmaBAYtYbkusVffT\na40ykZBicJcnec6WZDlaETUzbV0mVssKAKjBZZw0KVpEqAreUI+lESzrkA3D4biB\nKcpxhxyub2T96r2pcNzF0fzxDq2QSnA8h5KRYFZojxTeD/iWncVgANt+7qz1Q6Q9\nsGJFsP44alRcNmOTP3fTokNzuTonkttb23pLol3YcHO1VLT9khj5UVpLDw77oaSl\nszM9YGq4EaooiDZfpe8bCiywRj3RWBeA7oXD6FOW/ptVN4eY2hpjNRjaooZ8I/7H\nSn32/8i/d1d5LdBVvFv94aVGaZq+jPwNLXlCob9dRcLHTvedk/hXNziSQANnB7g3\n0qHCFakB+09d2/Bb01IhasiQULtZaLPW+goa3OsoJ79QBBBYj5Ptcp4mk9/qP4A5\ndtp/3ZuDagUGIsRSS1Ip18XXE9UDnCFwZQFGee4OYyqGFruLtoj/YacNOugCJntp\nDln4yd5oiRHawnI78SG8dRLFVOjngm3w5H+4B3nWuYj+c3hCoh2/xWFItRuYmUyn\nCQhmHNBsntiz+8M6f3KL/BhqbWJZ9L58QUJiqWaNscnf+/Z54m41BbOV9dTsZ45l\nKLeSrw8iBsRhqmCzJGp2elhUbF9u+P4xXRng8R7xzn/efmPoXy33VGG25CP+vvPi\nX7WKPbzds22EpLnSrkDvRrvnZ2/8JEjpJwvJw9xKrAzGugsTt/1SEFVBMaTXhHY6\nVV1TU6zEkxbTdEQdYPorefOgqyC1uX1Y9HOW9gmCIt8tjdtX5KX6Il/cCg2PLMBu\nDuEugvpW5fEzudIYUGflIDmntz0WlrNy750g20/qSCx0XYWwnMP4EMBkBNPuc/jS\n/jE8DsxAYiRmHSfOYFpJXbkJMzbRbfAmEsoqmNLgrudt8CXhbEjl5dsgFTwQcZBJ\nNh8BHPph8bgB1P1VC5jTLens+VCR7rQU7Juy9JNxAmNz0tzVrQTGoDFu0qa6iOX4\nb1wilACJS34l1RunBQhYiJiLVoTd01gza6L76oBaLvsJLUZN/Ibs0zSQWPXvQg/c\nXwhX3awOYnyzJNKbGYqq/1fOfvJnijiX4wMHM9rqzFMnCwYQ6JPTBLqLTsUh3tzp\nQWhbaoAUMa4UfOKztX7vUty8VWKLJjg056azk9q2J2IDFfaqm6ft71jlF0fbpGf+\noao7qcN4Qcc+2KLL2ouVfATwOMExplYtH2f4wyYuBxGwgOOw/DXPKnAvwn+a8O6P\n4hYA13vDXD+gb1dk74tDNB0Cbl2RDG95zEE4K5bN77ha49HbO7VVDh3TPXL8hC8o\nhUV+V54974Z1LbGRrKJ5kkrlMmlnbuU93F39aWIeeYhQH0KmuPjqIpF/33lOqJJE\nltk=\n-----END ENCRYPTED PRIVATE KEY-----\n',
2371// passphrase: '7ef94bb8a15ca2ef226f92a882560ea1'
2372// }
2373// });
2374// var client = sdk.getAppAuthClient('enterprise', '455328');
2375// console.log(client);
2376// var appUserClient = sdk.getAppAuthClient('user', '4022030180');
2377
2378// //var fileData = browfs.createReadStream('C:\Users\BodhisatwaDas\Desktop\JOLT_1\joltapi\actionplanbackup09-24-2018.txt');
2379
2380
2381// console.log("Inside save to box ");
2382
2383// appUserClient.users.get('4022030180', null, function (err, currentUser) {
2384// if (err) throw err;
2385// console.log('get data, ' + currentUser.name + '!');
2386// });
2387
2388// appUserClient.files.uploadFile('0', 'calendar.json', fileData, function(err, file) {
2389// if(err){
2390// console.log("saving error"+err)
2391// }else{
2392// console.log("saved to box")
2393// }
2394// });
2395
2396// client.users.get('4022030180', null, function(err, currentUser) {
2397// if(err) throw err; console.log('Hello, ' + currentUser.name + '!');
2398// });
2399// }
2400
2401/*********************************** */
2402function getnotifyv(db, record) {
2403 return new Promise(function (resolve, reject) {
2404 db.list({ include_docs: true }, function (err, data) {
2405 if (!err) {
2406 resolve(data);
2407 }
2408 else {
2409 resolve(err);
2410 }
2411 });
2412 });
2413}
2414
2415router.get('/api/v1/getNotifyV', function (req, res) {
2416
2417 notifydb = cloudant.db.use('userlist_backup');
2418 dbquerries = [getnotify(notifydb)]
2419 Promise.all(dbquerries).then(function (data) {
2420 var response = {
2421 "notifylist": [],
2422 };
2423 for (let i = 0; i < data[0].rows.length; i++)
2424 {
2425 {
2426 response.notifylist.push(data[0].rows[i].doc);
2427 }
2428 }
2429 res.json(response);
2430 }, function (err) {
2431 console.log(err);
2432 });
2433});
2434
2435/******* Code to add a new user in userlist Db ********/
2436function saveUser(db, record) {
2437 return new Promise(function (resolve, reject) {
2438 db.insert(record, function (err, data) {
2439 if (!err) {
2440 resolve(data);
2441 }
2442 else {
2443 resolve(err);
2444 }
2445 });
2446 });
2447}
2448router.post('/api/v1/addNewUser', function (req, res) {
2449 var record = req.body._id;
2450 console.log("req.body",record);
2451 var newrecord = { "selector": { "_id": record } };
2452 db = cloudant.db.use('userlist_backup');
2453 checkRole(db,newrecord).then(function(data){
2454 console.log("data",data);
2455 if(data.docs.length>0){
2456 console.log("reqrev",req.body._rev);
2457 console.log("dbrev",data.docs[0]._rev);
2458 req.body._rev=data.docs[0]._rev
2459 // for(var i=0;i<data.docs.length;i++){
2460
2461 // }
2462 updateUserRecord(db, req.body).then(function (myData) {
2463 console.log("myData",myData)
2464 res.json(myData);
2465 });
2466 }
2467 else{
2468 saveUser(db, req.body).then(function (myData) {
2469 res.json(myData);
2470 });
2471 }
2472 })
2473
2474 // saveUser(db, record).then(function (myData) {
2475 // res.json(myData);
2476 // });
2477});
2478router.post('/api/v1/addNewUserLogs', function (req, res) {
2479 var record = req.body;
2480 console.log(record);
2481 db = cloudant.db.use('audit_logs');
2482 saveUser(db, record).then(function (myData) {
2483 res.json(myData);
2484 });
2485
2486});
2487/*******end of code ************/
2488
2489/******* code for updating an existing user data********/
2490function updateUserRecord(db, record) {
2491 return new Promise(function (resolve, reject) {
2492 db.insert(record, function (err, data) {
2493 if (!err) {
2494 resolve(data);
2495 }
2496 else {
2497 resolve(err);
2498 }
2499 });
2500 });
2501}
2502router.post('/api/v1/updateUserDetails', function (req, res) {
2503 var record = req.body;
2504 //console.log(record);
2505 db = cloudant.db.use('userlist_backup');
2506 updateUserRecord(db, record).then(function (myData) {
2507 res.json(myData);
2508 });
2509});
2510
2511
2512/******end of code *********/
2513
2514/******* code for updating an existing GTM data********/
2515function updateGtmRecord(db, record) {
2516 return new Promise(function (resolve, reject) {
2517 db.insert(record, function (err, data) {
2518 if (!err) {
2519 resolve(data);
2520 }
2521 else {
2522 resolve(err);
2523 }
2524 });
2525 });
2526}
2527router.post('/api/v1/updateGTMDetails', function (req, res) {
2528 var record = req.body;
2529 console.log(record);
2530 db = cloudant.db.use('deals_addinfo');
2531 updateUserRecord(db, record).then(function (myData) {
2532 res.json(myData);
2533 });
2534});
2535
2536
2537/******end of code *********/
2538/****For Mobile GTM Update */
2539
2540function updateGtmRecord(db, record) {
2541 return new Promise(function (resolve, reject) {
2542 db.insert(record, function (err, data) {
2543 if (!err) {
2544 resolve(data);
2545 }
2546 else {
2547 resolve(err);
2548 }
2549 });
2550 });
2551}
2552router.post('/api/v1/updateGTMDetailsMobile', function (req, res) {
2553 var record = req.body;
2554 console.log(record);
2555 db = cloudant.db.use('deals_addinfo');
2556 updateUserRecord(db, record).then(function (myData) {
2557 res.json(myData);
2558 });
2559});
2560
2561router.post('/api/v1/updateNotifyDB', function (req, res) {
2562 var record = req.body;
2563 console.log(record);
2564 db = cloudant.db.use('notifydb');
2565 updateUserRecord(db, record).then(function (myData) {
2566 res.json(myData);
2567 });
2568});
2569
2570
2571
2572
2573
2574/***** */
2575
2576
2577
2578/******* code for Deleting an existing user *******/
2579function deleteUser(db, record) {
2580 return new Promise(function (resolve, reject) {
2581 var docUniqueId = record._id;
2582 var docRevNum = record._rev;
2583 db.destroy(docUniqueId, docRevNum, function (err, data) {
2584 if (!err) {
2585 resolve(data);
2586 }
2587 else {
2588 resolve(err);
2589 }
2590 });
2591 });
2592}
2593
2594router.post('/api/v1/deleteUser', function (req, res) {
2595 var record = req.body;
2596 db = cloudant.db.use('userlist_backup');
2597 deleteUser(db, record).then(function (myData) {
2598 res.json(myData);
2599 });
2600});
2601
2602/********end os code*************/
2603
2604/*************** API to find an exisiting record**********/
2605
2606function findData(db, record) {
2607 return new Promise(function (resolve, reject) {
2608 db.find(record, function (err, data) {
2609 if (!err) {
2610 resolve(data);
2611 }
2612 else {
2613 resolve(err);
2614 }
2615 });
2616 });
2617}
2618
2619router.post('/api/v1/find/accountId', function (req, res) {
2620 var accountId = { "selector": { "_id": req.body.accountId } };
2621 db = cloudant.db.use('actionplan');
2622 findData(db, accountId).then(function (myData) {
2623 res.json(myData);
2624 });
2625});
2626
2627/********************* code to calculate stickiness scores************/
2628function getStickinessRecord(db, record) {
2629 return new Promise(function (resolve, reject) {
2630 db.list({ include_docs: true }, function (err, data) {
2631 if (!err) {
2632 resolve(data);
2633 }
2634 else {
2635 resolve(err);
2636 }
2637 });
2638 });
2639}
2640router.get('/api/v1/stickinessData', function (req, res) {
2641
2642 var accountId = req.params.accountId;
2643 actionplandb = cloudant.db.use('stickinessdb');
2644 dbquerries = [getStickinessRecord(actionplandb)]
2645 Promise.all(dbquerries).then(function (data) {
2646 /*for(var i=0; i<data[0].rows.length;i++){
2647 if(data[0].rows[i].id == "stickinessconfig"){
2648 //var doc =data[0].rows[i].doc;
2649 }
2650
2651 } */
2652 var doc = data[0].rows;
2653 const calc = calculation(doc);
2654 res.json(calc);
2655 }, function (err) {
2656 console.log(err);
2657 });
2658});
2659/**************************/
2660const indexs = ["Generic Index", "CUSTOM AMS ADM", "DIGITAL", "SAP", "TESTING", "ORACLE", "CLOUD", "MS"];
2661const newDimesions = ["Overall account info", "Client Relationship", "Resource Availability and Capability", "Delivery Quality", "Innovation"]
2662
2663const calulationDimensions = newDimesions;
2664//const accountArray= data[0].rows;
2665calulationDimensions.shift();
2666
2667function calculateforEachAccount(account) {
2668 const accountCalculation = {};
2669 indexs.forEach(item => {
2670
2671 if (account[item]) {
2672 accountCalculation[item] = {};
2673 calulationDimensions.forEach(dimension => {
2674 const act = account[item][dimension];
2675 const valuesArray = [];
2676 const keysArray = Object.keys(act);
2677 keysArray.forEach(key => valuesArray.push(act[key]));
2678 const yesCount = valuesArray.filter(n => n.toLowerCase() === 'yes').length;
2679 const noCount = valuesArray.filter(n => n.toLowerCase() === 'no').length;
2680 accountCalculation[item][dimension] = calculateScore(yesCount, noCount);
2681 });
2682 }
2683 });
2684
2685 return calulateFinalScore(accountCalculation);
2686}
2687
2688
2689function calculateScore(yesCount, noCount) {
2690 if (yesCount == 0 && noCount == 0) {
2691 return 0;
2692 }
2693 if (noCount == 0) {
2694 return yesCount;
2695 }
2696
2697 return yesCount / noCount;
2698}
2699
2700//const calc = calculation();
2701//this will give all acoount calculation
2702//console.log(JSON.stringify(calc));
2703function calculation(accountArray) {
2704 const statsJSON = [];
2705 accountArray.forEach(account => {
2706 const statsObj = {};
2707 const stats = calculateforEachAccount(account.doc);
2708 var accName = account.doc._id.split("_");
2709 accName = accName[0].trim();
2710
2711 statsObj["radar_data"] = stats;
2712 statsObj["account_name"] = accName;
2713 statsObj["IOT"] = account.doc.IOT;
2714 if (account.doc.hasOwnProperty("Generic Index")) {
2715 statsObj["Generic Index"] = account.doc["Generic Index"];
2716 }
2717 if (account.doc.hasOwnProperty("SAP")) {
2718 statsObj["SAP"] = account.doc["SAP"];
2719 }
2720 if (account.doc.hasOwnProperty("CUSTOM AMS ADM")) {
2721 statsObj["CUSTOM AMS ADM"] = account.doc["CUSTOM AMS ADM"];
2722 }
2723 if (account.doc.hasOwnProperty("DIGITAL")) {
2724 statsObj["DIGITAL"] = account.doc["DIGITAL"];
2725 }
2726 if (account.doc.hasOwnProperty("TESTING")) {
2727 statsObj["TESTING"] = account.doc["TESTING"];
2728 }
2729 if (account.doc.hasOwnProperty("ORACLE")) {
2730 statsObj["ORACLE"] = account.doc["ORACLE"];
2731 }
2732 if (account.doc.hasOwnProperty("CLOUD")) {
2733 statsObj["CLOUD"] = account.doc["CLOUD"];
2734 }
2735 if (account.doc.hasOwnProperty("MS")) {
2736 statsObj["MS"] = account.doc["MS"];
2737 }
2738 statsJSON.push(statsObj);
2739 });
2740 return statsJSON;
2741}
2742
2743function calulateFinalScore(accountCalculation) {
2744 const keys = Object.keys(accountCalculation);
2745 const generic = keys.shift();
2746 const genericObject = accountCalculation[generic];
2747 const valueArray = {
2748 "Client Relationship": [],
2749 "Resource Availability and Capability": [],
2750 "Delivery Quality": [],
2751 "Innovation": []
2752 };
2753 keys.forEach(key => {
2754 const obj = accountCalculation[key];
2755 const items = Object.keys(obj);
2756 items.forEach(item => {
2757 valueArray[item].push(obj[item]);
2758 });
2759 });
2760 // console.log(JSON.stringify(valueArray));
2761 const finalScoreArray = {
2762 "Client Relationship": 0,
2763 "Resource Availability and Capability": 0,
2764 "Delivery Quality": 0,
2765 "Innovation": 0
2766 };
2767 const rcNames = Object.keys(finalScoreArray);
2768 const finalArray = []
2769 rcNames.forEach(key => {
2770 const services = valueArray[key];
2771 //console.log(JSON.stringify(key + services));
2772 // console.log(genericObject[key]/2 +" "+ services.reduce((a,b)=> a+b ,0)/services.length);
2773 finalScoreArray[key] = getRadarIndex(genericObject[key] / 2 + services.reduce((a, b) => a + b, 0) / services.length);
2774 // const radarObject={};
2775 // radarObject[key] = getRadarIndex(genericObject[key]/2+ services.reduce((a,b)=> a+b ,0)/services.length);
2776 // finalArray.push(radarObject);
2777 });
2778 return finalScoreArray;
2779
2780}
2781
2782function getRadarIndex(value) {
2783 var index = 1;
2784 if (value > 1.5) {
2785 index = 3;
2786 } else if (value >= 1.2 && value <= 1.5) {
2787 index = 2;
2788 }
2789 return index;
2790
2791}
2792
2793
2794
2795
2796
2797
2798
2799
2800/******** to upload stickiness Data********/
2801
2802// const objectData=[
2803// ["Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","Generic Index","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","CUSTOM AMS ADM","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","DIGITAL","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","SAP","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","TESTING","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","ORACLE","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","CLOUD","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS","MS" ],
2804// ["Dimensions","Overall account info","Overall account info","Overall account info","Overall account info","Overall account info","Overall account info","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Leveraging Assets & Tools","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Strategic Partnership","Strategic Partnership","Strategic Partnership","Strategic Partnership","Capability for the Future","Capability for the Future","Capability for the Future","Capability for the Future","Effective, Optimum Delivery model","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Consulting for Growth","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools","Leveraging Assets & Tools" ],
2805// ["Questions","Highest wallet share","Type of engagement","Financial Benefits","Level of knowledge","GBS revenue >5M per year","GBS Revenue growth","Customer Business Planning","Metrics/outcomes - Customer Business Planning","Integrated IBM presence in client portfolio","CXO-level connects","Customer Relationship","Strategic Advisory","Key relationship differentiators","Showcased IBM's capabilities","Functional/technical/enterprise architects","Architects ability to influence the client ","Showcasing the team's capabilities","Automation Capabilities","DevOps engineers / consultants","Agile PM / coaches","GBS 5+1 priorities","Offshore delivery model","Agile methodologies","Cloud services for PaaS work","DevOps methodologies and tools","Co participation -Client's business","Virtual collaboration & Remote Delivery","Articulated IBM's transformation vision/ POV","GBS suite of oferings","Hybrid Agile/ Agile@Maintenance","AMS specific DevOps practices and tools","Industry best practices - Agile, DevOps","Mobile at Scale","Automation/acceleration tools","Test Automation","Cost savings through automation","Automate minimum 80% test cases","Leveraging remote collaboration tools","Architectural assessment of your client's portfolio","Cloud Affinity assessment","Application Portfolio Assessment","Automation solutions like COG1, COG3, RPA, Database upgrade etc.","DevOps transformation program","Delivery quality enhancing tools like CAST, Sonar, APM, NewRelic etc.","Security Vulnerability assessment","Agile / Distributed Agile /KANBAN","Application IMPACT Method for Custom Application Development / Maintenance","Agile based Service transition","Secure Engineering practices","Digitize knowledge repository and Cognitive enabled Knowledge Transfe","Application Portfolio Modernization/ Microservices & API/ Cloud Adoption (e.g. YAMOC)","Security Testing","Maturity & Advisory assessments","Digital Consultancy through PoV's and PoC's","Subscription-based single Development Platform with integrated toolchain","IBM's automation and Cognitive solutions","IBM as a strong partner for Digital Transformation","Digital-Reinvention assessment","IBM as Digital Agencies of Record","Helping client adopt one or more of the latest capabilities of various digital platforms","Using rapid POC using Garage (Mobile, CBS, Bluemix)","Positioned apple-ibm partnership and differentiated our capabilities to build enterprise mobile apps","Joint plan to review and redefining the IT/ digital strategy","Conducted the IBM Design Thinking workshop and IBM Garage-based co-creation","Providing services to Chief Marketing Office","Legacy system of records with Front end applications","Digital platforms for client","Maturity assessment to evaluate digital readiness","Digital architects","Digital platforms capabilities","Digital strategy capabilities","Garage Model of delivery of application services","Garage Model of delivery of digital platforms","Remote Collaboration tools","Embeded design thinking in delivery model","Agile for digital delivery","Devops for digital delivery","Used analytics generate create measurable efficiencies","Mobile at Scale","Assessments and strategy engagements as a value proposition ","Garage model of development for building services","Digital platforms for client","Client engaged with any of IBM's design studios","Helping client improve their customer journeys","IBM salesforce capabilities","IBM Watson Commerce capabilities","IBM Mobile@scale capabilities","Introduced IBM Marketing Platform capabilities","Adopted rapid POC using Garage","Leveraging Remote Collaboration tools","Adopting Design thinking framework","Using Digital Industry solutions","Command Center / OCC setup","Aligned with SAP Account Executive","Hana Roadmap Strategy","SAP Testing CoE","Engaged with client on SAP Garage","Garner/Forester reference customer list","SAP Marketing event - Sapphire/regional event","Using IBM Hana Migration Center","SAP Digital transformation niche area","SAP landscape on IBM Cloud ","Modularization Approach for Rapid Deployment","SAP Advanced Delivery Management Model","Using Outcome based models","YoY productivity","Access to customers SAP Adoption Roadmap","IBM SAP Digital Transformation Partnership LSS Demos","IBM Solman Cloud SaaS Demo","Advanced SAP tools like RDM, Solman 7.2, BCPA Demo","PoV on how SAP HANA and Cloud offering will delivery business value","De-customization","Complete Suite of IBM development tools/ templates","IBM Localisation accelerator","Ascend methodology for Hana projects","IBM Industry IMPACT Solutions","Worksoft Process mapping & test Automation & CTD for optimisation","Leverage IBM COG tools","value realisation through IBM Tools (IMPACT Template, Localization tool kit, HANA Cookbook, SAP OCC, TAC, Test Automation)","Evaluated Location Agnostic strategy for Testing","Roadmap for Agile and Continuous testing","IBM's partnership with Worksoft for SAP / package Testing Automation","Structured optimisation techniques for test design","Cognitive defect prevention methodology","Production defect efficiency below 95%","Test automation efforts reducing test efforts and time to market by around 30%","Maturity assessment for the Test Service ","UAT support","Performance/ Security Testing","Digital testing initiatives","Current applications tested for performance and security","High degree of client trust and commercial enablement","Testing service as a 'managed' service","IGNITE Cognitive assets (Classify, Predict, Defect analytics)","Applicability of an IBM Cloud enabled infrastructure for functional Testing","Industry assets (Banking & Retail avlbl currently)","IBM's CTD- Cucumber- Selenium- Appium - Perfecto based OTFA Asset pilot","Discuss New emerging areas - on Blockchain, Big Data, Microservices, SFDC and EA Testing","Testing as a service model leveraging IBM Cloud enabled infrastructure","IBM's CTD (Combinatorial Test Design) Focus Tool ","Service Virtualization to perform end to end Testing","IBM's SteF Framework for rapid Test Automation using HP UFT/ QTP","Automation to manage API Testing","IBM IGNITE Platform consisting of Combinatorial Test Design, Optimised test Automation and Cognitive assets (Classify, Predict, Defect analytics)","Structured Test data management tools","IBM's partnership with Oracle on collaboration strategy","Oracle Command Center Leaders for business process and technical monitoring","Oracle Cloud and PaaS offerings","Leverage our Cloud Elite and Diamond partner status with Oracle and the global leadership connect with Oracle to expedite any critical issue","IGNITE Oracle Cloud Agile Method & Oracle IMPACT Application Development Method","Oracle in EA or EA ADM to accelerate their Digital Transformation journey","IBM Cloud Migration Services","IBM Core ERP Upgrade Lab Solutions","IBM Oracle Command Center Solution","IBM Shared Services Solution for DBA/Administration tasks","Oracle Revenue & Management Billing","IBM Cloud Garage Assets & Solutions","IBM Oracle Cloud SaaS AMS Solution","IBM Oracle PaaS on SaaS","New Oracle Cloud Garage delivery framework","New Methods on Cloud Agile and Cloud AD","Roadmap with Oracle clients to move them towards an Agile & DevOps","IBM Oracle HR Process Services with Core ERP/Cloud","Oracle Industry Solutions on cloud","IBM Oracle Database Cloud Services Solution","IBM Oracle PaaS + DevOps Automation Solution","Strategy to move client's HR, Finance/SCM and CRM application to the Oracle's HCM, ERP, Cx Cloud","Oracle & IBM's new PaaS offerings","IBM Oracle Cloud & Cognitive transformation Roadmap Study/Assessment","IBM Oracle Cloud/ Cloud SAAS/ Digital/ Cognitive/ Mobile ransformation Roadmap Study/ Assessment","IBM Oracle Fusion Middleware & Cross Product Integration Solution with Oracle PaaS","IBM Oracle OUM Methodology","IBM's Oracle Cloud Garage assets on SaaS & PaaS","IBM's EA Automation Services Framework","Shaping client's Cloud Strategy","Application portfolio Modernization, Rationalization and Transformation strategy","Shaping client's Data Strategy","Microservices strategy","Client's application portfolio running on n-3 or older versions of system software/databases/middleware","IBM's capability to create a business case for cloud transformation","(a) Cloud Migration (b) Run & Manage - AppOpps (c) Microservices (d) Security and Privacy (e) Cloud Native Development (f) Big Data Services?","Run or proposed a POC / POV in any of the above 6 areas","IBM's Hybrid Cloud strategy leveraging BlueMix, AWS and Azure","IBM's AppOpp capabilities or Middleware Manages Services capabilities","IBM's Cloud Innovate methodology","DevOps methodology and Toolchain","IBM's Migration Factory based delivery model","Cloud Affinity Assessment for client's portfolio","Application Assessment Questionnaire","IBM's Security & Privacy offering","Application Workload Discovery","Solution Operations Center offering","Demo of IBM's Cloud Toolkit","ADDI (Application Discovery and Analysis Insight)","Capability of IBM's automated data migration tool - Xenobridge","IBM's partnership with Microsoft on Strategic Partnership strategy","Microsoft Solutions like MS Surface Garage, IBM Banking/Retail industry solutions","on-prem to Office 365 Strategic Partnership migration strategy","migration to Dynamics 365 strategy","Microsoft Custom, Strategic Partnership, ERP, CRM and Analytics","Microsoft Hybrid Cloud migration/Integration Assessment Solution","Microsoft Cloud/Azure Cognitive Solution","IBM Microsoft Azure PaaS + DevOps Automation Solution","Integration of IBM Cloud Enterprise Application Managed Services with Microsoft Dynamics","Next Gen Field Services","IBM Advanced Social Solutions","Accelerated Omni-Channel Retail Solution","Industry - Accelerated MS CRM Solution","Microsoft Dynamics/AX with Surface Device/Mobility & Digitization platform","Social Enterprise Insight","Azure Streaming Analytics","Operations intelligence Services","IBM Microsoft Azure Cloud Assessment strategy" ],
2806// ["TYSON FOODS INC","No","FP","Yes","High","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","Yes","Yes","Yes","No","Yes","Yes","No","Yes","Yes","Yes","Yes","No","No","Yes","Yes","Yes","Yes","Yes","No","Yes","No","Yes","No","No","No","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Yes","No","Yes","No","No","No","No","Yes","Yes","Yes","No","No","No","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","No","No","No","Yes","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ],
2807// ["ANTHEM","Yes","T&M/Co-Source","Yes","High","Yes","Yes","No","No","Yes","Yes","Yes","No","Yes","Yes","Yes","No","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","Yes","Yes","Yes","No","Yes","Yes","No","No","Yes","No","No","Yes","Yes","Yes","No","No","Yes","Yes","No","No","No","Yes","No","Yes","No","Yes","Yes","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ],
2808// ["PRIME THERAPEUTICS","No","T&M/Co-Source","No","Medium","No","Yes","No","No","Yes","No","No","No","Yes","Yes","No","No","Yes","Yes","No","Yes","Yes","Yes","No","No","No","No","No","Yes","Yes","No","No","No","Yes","Yes","No","No","No","No","No","Yes","Yes","No","No","No","No","No","No","No","No","No","Yes","No","Yes","No","No","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","","" ],
2809// ["CBRE GROUP, INC","No","FP","No","High","No","Yes","No","N.A.","No","No","No","No","No","Yes","No","N.A.","Yes","Yes","Yes","Yes","Yes","Yes","No","No","No","No","Yes","N.A.","Yes","No","N.A.","Yes","No","N.A.","N.A.","No","N.A.","Yes","No","No","Yes","Yes","N.A.","No","N.A.","No","No","N.A.","Yes","Yes","No","No","No","No","N.A.","Yes","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ],
2810// ["PITNEY BOWES","Yes","FP","No","Medium","N.A.","N.A.","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","N.A.","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","Yes","N.A.","No","N.A.","Yes","No","No","No","Yes","N.A.","Yes","N.A.","Yes","No","N.A.","No","Yes","Yes","N.A.","Yes","Yes","Yes","Yes","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","No","Yes","Yes","No","No","No","Yes","No","Yes","No","No","No","No","N.A.","Yes","No","Yes","Yes","No","Yes","No","No","N.A.","N.A.","Yes","Yes","Yes","","","","","","","","","","","","","","","","","","","","","","","","","","","Yes","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","No","N.A.","No","No","No","No","No","No","No","No","No","No","No","","","","","","","","","","","","","","","","","","","","","","No","No","N.A.","No","Yes","No","No","No","N.A.","No","No","No","No","No","No","No","No","No","","" ],
2811// ["STATE FARM","No","Staff Aug","No","Medium","No","No","Yes","No","N.A.","Yes","No","No","Yes","Yes","Yes","No","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","N.A.","Yes","Yes","Yes","Yes","Yes","No","Yes","Yes","No","No","Yes","No","Yes","Yes","N.A.","Yes","N.A.","N.A.","Yes","Yes","Yes","Yes","Yes","No","N.A.","Yes","Yes","Yes","No","Yes","No","Yes","Yes","No","Yes","No","Yes","No","No","Yes","No","Yes","Yes","Yes","No","No","Yes","Yes","Yes","Yes","No","No","Yes","Yes","Yes","No","Yes","Yes","Yes","Yes","No","No","Yes","Yes","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","No","Yes","N.A.","No","No","No","Yes","No","No","No","Yes","Yes","N.A.","No","No","Yes","No","N.A.","Yes","No","No","No","No","Yes","No","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ],
2812// ["PRUDENTIAL FINANCIAL","Yes","Staff Aug","No","High","Yes","Yes","N.A.","N.A.","No","Yes","Yes","Yes","Yes","Yes","Yes","N.A.","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","Yes","Yes","N.A.","Yes","Yes","No","Yes","Yes","No","Yes","Yes","N.A.","No","Yes","Yes","N.A.","N.A.","N.A.","Yes","Yes","N.A.","Yes","N.A.","Yes","Yes","No","N.A.","N.A.","Yes","Yes","Yes","No","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","No","Yes","N.A.","N.A.","No","Yes","Yes","N.A.","No","N.A.","Yes","No","No","No","No","No","No","Yes","Yes","N.A.","N.A.","N.A.","N.A.","N.A.","No","Yes","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Yes","No","N.A.","No","No","N.A.","No","No","No","No","N.A.","N.A.","N.A.","No","No","No","No","No","","" ]
2813// ]
2814// const indexs = ["Generic Index", "CUSTOM AMS ADM", "DIGITAL", "SAP", "TESTING", "ORACLE", "CLOUD","MS"];
2815// const newDimesions = ["Overall account info", "Client Relationship", "Resource Availability and Capability","Delivery Quality","Innovation"]
2816// const dimensionsObject = {
2817// "Overall account info": "Overall account info",
2818// "Strategic Partnership": "Client Relationship",
2819// "Capability for the Future": "Resource Availability and Capability",
2820// "Effective, Optimum Delivery model": "Delivery Quality",
2821// "Consulting for Growth": "Innovation",
2822// "Leveraging Assets & Tools": "Innovation"
2823// };
2824// const finalObject = {};
2825// for(let k = 3; k < objectData.length; k++ ){
2826// finalObject[objectData[k][0]] = indexObject();
2827// }
2828// const groupArray = objectData[0];
2829// const dimensionArray = [];
2830// for(let m =1 ; m<objectData[1].length;m++){
2831// dimensionArray.push(dimensionsObject[objectData[1][m]]);
2832// }
2833// console.log(dimensionArray.length)
2834// const questions = objectData[2];
2835// for(let j = 1; j < objectData[0].length; j++) {
2836// for(let i = 3; i < objectData.length; i++ ) {
2837// finalObject[objectData[i][0]][groupArray[j]][dimensionArray[j-1]][questions[j]] = objectData[i][j];
2838// }
2839// }
2840// function createDimensionObject(){
2841// return {"Overall account info":{},
2842// "Client Relationship" :{},
2843// "Resource Availability and Capability": {},
2844// "Delivery Quality": {},
2845// "Innovation":{}
2846// };
2847// }
2848// function indexObject(){
2849// return {
2850// "Generic Index": createDimensionObject(),
2851// "CUSTOM AMS ADM": createDimensionObject(),
2852// "DIGITAL": createDimensionObject(),
2853// "SAP": createDimensionObject(),
2854// "TESTING": createDimensionObject(),
2855// "ORACLE": createDimensionObject(),
2856// "CLOUD": createDimensionObject(),
2857// "MS":createDimensionObject()
2858// };
2859// }
2860// const calulationTechnologies = indexs;
2861// const dimensionsArray = newDimesions;
2862// const accountJSON = getTheAccountArray();
2863
2864// function getTheAccountArray(){
2865// const accountJSON ={};
2866// for (let y =3; y < objectData.length; y++){
2867// accountJSON[objectData[y][0]] =cleanUptheAccount(finalObject[objectData[y][0]]);
2868// }
2869// return accountJSON;
2870// }
2871// function cleanUptheAccount(account) {
2872// indexs.forEach((item)=>{
2873// dimensionsArray.forEach(dimension =>{
2874// const act = account[item][dimension];
2875// const valuesArray = [];
2876// const keysArray = Object.keys(act);
2877// keysArray.forEach(key => valuesArray.push(act[key]));
2878// const acutalValueArray = valuesArray.filter(n =>n);
2879// if(acutalValueArray == 0){
2880// delete account[item][dimension];
2881// }
2882// });
2883// const act = account[item];
2884// const keysArray = Object.keys(act);
2885
2886// if(Object.keys(act).length ===0){
2887
2888// delete account[item];
2889// }
2890
2891// });
2892// return account;
2893// }
2894
2895// const docArray = { "docs": uploadDocs() };
2896// // this will give you the final json object for uploading
2897// console.log(JSON.stringify(docArray));
2898
2899// function uploadDocs() {
2900// const accountArray = Object.keys(accountJSON);
2901// const statsJSON ={};
2902// const docsArray =[];
2903// accountArray.forEach(account => {
2904// const doc = accountJSON[account];
2905// doc._id = account;
2906// docsArray.push(doc);
2907// });
2908// return docsArray;
2909// }
2910 /************/
2911/**************/
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927/**************/
2928
2929var dbCredentials = {
2930 dbName: 'nps123',
2931 dbuse: 'lap_bck',
2932 dbAccount: 'accountinfo',
2933 dbAction: 'actionplan_back',
2934 dbPipeline: 'pipeline_bck',
2935 dbSales: 'salesconnect_bck',
2936 dbNewlap: 'newlap_bck',
2937 dbDeals : 'deals'
2938};
2939/***************function for uploading***********/
2940var storage = multer.diskStorage({ //multers disk storage settings
2941 destination: function (req, file, cb) {
2942 cb(null, './uploads/')
2943 },
2944 filename: function (req, file, cb) {
2945 var datetimestamp = Date.now();
2946 cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
2947 }
2948});
2949
2950var upload = multer({ //multer settings
2951 storage: storage,
2952 fileFilter: function (req, file, callback) { //file filter
2953 if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length - 1]) === -1) {
2954 return callback(new Error('Wrong extension type'));
2955 }
2956 console.log("DADSDA");
2957 callback(null, true);
2958 }
2959}).single('file');
2960
2961
2962function addData(db, record) {
2963 var data1 = record;
2964 console.log(data1);
2965
2966 //console.log(arr);
2967
2968 return new Promise(function (resolve, reject) {
2969 db.bulk({ docs: data1 }, function (err, body) {
2970 if (!err) {
2971 resolve(body);
2972 }
2973 else {
2974 resolve(err);
2975 }
2976 });
2977 });
2978}
2979
2980
2981function addDataLap(db, record) {
2982 var dataLap = record;
2983 console.log(dataLap);
2984
2985 //console.log(arr);
2986
2987 return new Promise(function (resolve, reject) {
2988 db.bulk({ docs: dataLap }, function (err, body) {
2989 if (!err) {
2990 resolve(body);
2991 }
2992 else {
2993 resolve(err);
2994 }
2995 });
2996 });
2997}
2998
2999function addAccountInfo(db, record) {
3000 var accountData = record;
3001 console.log(accountData);
3002
3003 //console.log(arr);
3004
3005 return new Promise(function (resolve, reject) {
3006 db.bulk({ docs: accountData }, function (err, body) {
3007 if (!err) {
3008 resolve(body);
3009 }
3010 else {
3011 resolve(err);
3012 }
3013 });
3014 });
3015}
3016
3017
3018function addActionPlanData(db, record) {
3019 var actionData = record;
3020 console.log(actionData);
3021
3022 //console.log(arr);
3023
3024 return new Promise(function (resolve, reject) {
3025 db.bulk({ docs: actionData }, function (err, body) {
3026 if (!err) {
3027 resolve(body);
3028 }
3029 else {
3030 resolve(err);
3031 }
3032 });
3033 });
3034}
3035
3036
3037function addDataPipeline(db, record) {
3038 var dataPipe = record;
3039
3040
3041 return new Promise(function (resolve, reject) {
3042 db.bulk({ docs: dataPipe }, function (err, body) {
3043 if (!err) {
3044 console.log(body);
3045 resolve(body);
3046 }
3047 else {
3048 console.log(err);
3049 resolve(err);
3050 }
3051 });
3052 });
3053}
3054
3055function addDataSales(db, record) {
3056 var dataSales = record;
3057 // console.log(dataSales);
3058
3059 //console.log(arr);
3060
3061 return new Promise(function (resolve, reject) {
3062 db.bulk({ docs: dataSales }, function (err, body) {
3063 if (!err) {
3064 resolve(body);
3065 }
3066 else {
3067 resolve(err);
3068 }
3069 });
3070 });
3071}
3072
3073
3074/** API path that will upload the nps files */
3075router.post('/upload', function (req, res) {
3076 var exceltojson;
3077 upload(req, res, function (err) {
3078
3079 if (err) {
3080 res.json({ error_code: 1, err_desc: err });
3081 return;
3082 }
3083 /** Multer gives us file info in req.file object */
3084 if (!req.file) {
3085 res.json({ error_code: 1, err_desc: "No file passed" });
3086 return;
3087 }
3088 /** Check the extension of the incoming file and
3089 * use the appropriate module
3090 */
3091 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
3092 exceltojson = xlsxtojson;
3093 } else {
3094 exceltojson = xlstojson;
3095
3096 }
3097 console.log(req.file.path);
3098 try {
3099 exceltojson({
3100 input: req.file.path,
3101 output: null, //since we don't need output.json
3102 lowerCaseHeaders: true
3103 }, function (err, result) {
3104 if (err) {
3105 return res.json({ error_code: 1, err_desc: err, data: null });
3106 }
3107 db = cloudant.db.use(dbCredentials.dbName);
3108 var data11 = result;
3109 //var str = "abc's test#s";
3110 //alert(str.replace(/[^a-zA-Z ]/g, ""));
3111 //var data = JSON.parse(JSON.stringify(data11).replace(/[^a-zA-Z ]/g, ""));
3112 //var data = JSON.parse(JSON.stringify(data11).replace(/\s+?/g, ""));
3113 //var data1=JSON.parse(JSON.stringify(data).replace(/\s(?=\w+":)/g, ""));
3114 //var data2=JSON.parse(JSON.stringify(data1).replace(/\s(?=\w+":)/g, ""));
3115 //data=data2;
3116 //var data = JSON.parse(JSON.stringify(result));
3117 //res.json(data);
3118
3119
3120 data11.forEach(function (e, i) {
3121 // Iterate over the keys of object
3122 Object.keys(e).forEach(function (key) {
3123
3124 // Copy the value
3125 var val = e[key],
3126 newKey = key.replace(/\s+/g, "");
3127
3128 // Remove key-value from object
3129 delete data11[i][key];
3130
3131 // Add value with new key
3132 data11[i][newKey] = val;
3133 });
3134 });
3135 //res.json(data11);
3136
3137 groups = Object.create(null),
3138 grouped = [];
3139
3140 data11.forEach(function (o) {
3141 if (!groups[o.unit]) {
3142 groups[o.unit] = [];
3143 grouped.push({ group: o.accountname, "_id": o.unit + '_' + o.iot, "IOT": o.iot, "Wave": o.wave, data: groups[o.unit] });
3144 }
3145 //groups[o.accountname].push({Country:o.country,Unit:o.unit,"Response Date":o.responsedate,"Unique ID":o.uniqueid,surveytype:o.surveytype,surveylanguage:o.surveylanguage,language:o.language,companyname:o.companyname,issuingcountrynumber:o.issuingcountrynumber,ibmcustomernumber:o.ibmcustomernumber,sapid:o.sapid,gbgid:o.gbgid,gbgname:o.gbgname,dunsumber:o.dunsumber,securityid:o.securityid,sandsector:o.sanddsector,GBSSector:o.gbssector,industry:o.industry,cers:o.cers,countrydescription:o.countrydescription,regionid:o.regionid,regiondescription:o.regiondescription,imt:o.imt,"IOT":o.iot,iotdescription:o.iotdescription,salutation:o.salutation,account:o.account,clientrole:o.clientrole,clientjobtitle:o.clientjobtitle,customernumber:o.customernumber,businessunit:o.businessunit,subbrand:o.subbrand,surveyeligibledate:o.surveyeligibledate,projectname:o.projectname,rundescription:o.rundescription,sourcetype:o.sourcetype,projectcompletiondate:o.projectcompletiondate,projectstage:o.projectstage,servicesline:o.servicesline,project:o.project,gtssegment1:o.gtssegment1,gtssegment2:o.gtssegment2,gbssegment1:o.gbssegment1,gbssegment2:o.gbssegment2,chqsegment:o.chqsegment,labsystemssvcsegment:o.labsystemssvcsegment,offering:o.offering,gbtlevel10:o.gbtlevel10,gbtlevel10description:o.gbtlevel10description,gbtlevel20:o.gbtlevel20,gbtlevel20description:o.gbtlevel20description,gbtlevel30:o.gbtlevel30,gbtlevel30description:o.gbtlevel30description,gbtlevel40:o.gbtlevel40,gbtlevel40description:o.gbtlevel40description,gbtlevel17:o.gbtlevel17,gbtlevel17description:o.gbtlevel17description,"Likelihood to Recommend Services":o.likelihoodtorecommendservices, "Likelihood to Choose Services":o.likelihoodtochooseservices, "Services Overall Satisfaction":o.servicesoverallsatisfaction,"Reasons for Scores":o.reasonsforscores,translationtoenglishforreasonsforscores: o.translationtoenglishforreasonsforscores, "Value": o.value, "Innovation": o.innovation, "Partnership": o.partnership, "Responsiveness": o.responsiveness,"Industry Expertise":o.industryexpertise, "Quality": o.quality, "Timeliness": o.timeliness, "Staffing": o.staffing, "Technical Expertise": o.technicalexpertise, "Expertise": o.expertise, "Communication": o.communication, "Proactivity": o.proactivity, "Additional Comments": o.additionalcomments,delivery:o.delivery});
3146 groups[o.unit].push({ "Response Date": o.responsedate, "Unique ID": o.uniqueid, "surveytype": o.surveytype, "Country": o.country, "Survey language": o.surveylanguage, "Language": o.language, "Unit": o.unit, "Company Name": o.companyname, "Issuing Country Number": o.issuingcountrynumber, "IBM Customer Number": o.ibmcustomernumber, "SAP ID": o.sapid, "GBG ID": o.gbgid, "GBG Name": o.gbgname, "Account Name": o.accountname, "DUNS Number": o.dunsnumber, "Security ID": o.securityid, "S&D Sector": o.sanddsector, "GBS Sector": o.gbssector, "Industry": o.industry, "CERS": o.cers, "Country Description": o.countrydescription, "Region ID": o.regionid, "Region Description": o.regiondescription, "IMT": o.imt, "IOT": o.iot, "IOT Description": o.iotdescription, "Salutation": o.salutation, "Account": o.account, "Client Role": o.clientrole, "Client Job Title": o.clientjobtitle, "Customer Number": o.customernumber, "Business Unit": o.businessunit, "Sub Brand": o.subbrand, "Survey eligible date": o.surveyeligibledate, "Project Name": o.projectname, "Run Description": o.rundescription, "Source Type": o.sourcetype, "Project Completion Date": o.projectcompletiondate, "Project Stage": o.projectstage, "Services Line": o.servicesline, "Project": o.project, "GTS Segment 1": o.gtssegment1, "GTS Segment 2": o.gtssegment2, "GBS Segment 1": o.gbssegment1, "GBS Segment 2": o.gbssegment2, "CHQ Segment": o.chqsegment, "Lab Systems SVC Segment": o.labsystemssvcsegment, "Offering": o.offering, "GBT Level 10": o.gbtlevel10, "GBT Level 10 Description": o.gbtlevel10description, "GBT Level 20": o.gbtlevel20, "GBT Level 20 Description": o.gbtlevel20description, "GBT Level 30": o.gbtlevel30, "GBT Level 30 Description": o.gbtlevel30description, "GBT Level 40": o.gbtlevel40, "GBT Level 40 Description": o.gbtlevel40description, "GBT Level 17": o.gbtlevel17, "GBT Level 17 Description": o.gbtlevel17description, "Likelihood to Recommend Services": o.likelihoodtorecommendservices, "Likelihood to Choose Services": o.likelihoodtochooseservices, "Services Overall Satisfaction": o.servicesoverallsatisfaction, "Reasons for Scores": o.reasonsforscores, "Translation to English for Reasons for Scores": o.translationtoenglishforreasonsforscores, "Value": o.value, "Innovation": o.innovation, "Partnership": o.partnership, "Responsiveness": o.responsiveness, "Industry Expertise": o.industryexpertise, "Quality": o.quality, "Timeliness": o.timeliness, "Staffing": o.staffing, "Technical Expertise": o.technicalexpertise, "Expertise": o.expertise, "Communication": o.communication, "Proactivity": o.proactivity, "Additional Comments": o.additionalcomments, "Translation to English for Additional Comments": o.translationtoenglishforadditionalcomments, "Contact Made?": o.contactmade, "Client Satisfied with Resolution? (If no, please provide comments)": o.clientsatisfiedwithresolution, "Action Underway": o.actionunderway, "Additional Details / Comments": o.additionaldetailscomments, "Client Relationship or Governance": o.clientrelationshiporgovernance, "Contract or Solution": o.contractorsolution, "Delivery": o.delivery, "Other": o.other });
3147 });
3148 });
3149 var response=[] ;
3150 var updateData=[];
3151dealsAddInfo = cloudant.db.use('nps123');
3152dbquerries = [dealsData(dealsAddInfo)];
3153Promise.all(dbquerries).then(function (data)
3154{
3155 // console.log(JSON.stringify(data));
3156 for(let j = 0; j < grouped.length;j++){
3157 for(let i = 0; i < data[0].rows.length; i++){
3158
3159 response.push(data[0].rows[i].doc);
3160
3161
3162 if(grouped[j]._id===response[i]._id){
3163
3164 grouped[j]._rev=response[i]._rev;
3165
3166 updateData.push(grouped[j]);
3167
3168
3169
3170 }
3171
3172}}
3173 console.log(grouped);
3174 //res.json(grouped);
3175 addData(db, updateData).then(function (myData) {
3176 res.json(myData);
3177 });
3178 //res.json(grouped);
3179 });
3180 } catch (e) {
3181 res.json({ error_code: 1, err_desc: "Corrupted excel file" });
3182 }
3183 })
3184
3185});
3186
3187
3188/////
3189
3190/** API path that will upload lap the files */
3191router.post('/uploadlap', function (req, res) {
3192 var exceltojson;
3193 upload(req, res, function (err) {
3194 if (err) {
3195 console.log(err);
3196 res.json({ error_code: 1, err_desc: err });
3197 return;
3198 }
3199 console.log("das");
3200 /** Multer gives us file info in req.file object */
3201 if (!req.file) {
3202 res.json({ error_code: 1, err_desc: "No file passed" });
3203 return;
3204 }
3205 /** Check the extension of the incoming file and
3206 * use the appropriate module
3207 */
3208 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
3209 console.log("gddgfdgd");
3210 exceltojson = xlsxtojson;
3211
3212 } else {
3213 exceltojson = xlstojson;
3214
3215 }
3216 console.log(req.file.path);
3217 try {
3218 exceltojson({
3219 input: req.file.path,
3220 output: null, //since we don't need output.json
3221 lowerCaseHeaders: true
3222 }, function (err, result) {
3223 if (err) {
3224 return res.json({ error_code: 1, err_desc: err, data: null });
3225 }
3226 db = cloudant.db.use(dbCredentials.dbuse);
3227 console.log(result);
3228 var datalap = result;
3229
3230 datalap.forEach(function (e, i) {
3231 // Iterate over the keys of object
3232 Object.keys(e).forEach(function (key) {
3233
3234 // Copy the value
3235 var val = e[key],
3236 newKey = key.replace(/\s+/g, "");
3237 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
3238 // [^a-zA-Z0-9]\s/g
3239
3240 // Remove key-value from object
3241 delete datalap[i][key];
3242
3243 // Add value with new key
3244 datalap[i][newKey1] = val;
3245 });
3246
3247 });
3248
3249
3250 //res.json(datalap);
3251
3252 grouped1 = [];
3253
3254 datalap.forEach(function (o) {
3255 o._id = o.accountname + '_' + o.iot;
3256
3257 grouped1.push({ "_id": o._id, "Account Name": o.accountname, "IOT": o.iot, "Completed": o.completed, "Last page": o.lastpage, "Start language": o.startlanguage, "Token": o.token, "Date started": o.datestarted, "Date last action": o.datelastaction, "Are you the current LAP on the account-": o.areyouthecurrentlapontheaccount_, "Do you know the current LAP on the account-": o.doyouknowthecurrentlapontheaccount_, "Please provide the name and email of the LAP currently on the account. First Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_firstname, "Please provide the name and email of the LAP currently on the account. Last Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_lastname, "Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_ibmintranetemailaddress, "Planned Contract Contraction": o.plannedcontractcontraction, "Client Relationship": o.clientrelationship, "Delivery Quality": o.deliveryquality, "Lack of Innovation": o.lackofinnovation, "Resource Availability or Capability": o.resourceavailabilityorcapability, "Competition provided better value": o.competitionprovidedbettervalue, "Others": o.others, "You have identified that percentage of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root cause.": o.youhaveidentifiedthat_ofyourytderosionof_septytderosion_misduetoplannedcontractcontraction_pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause_, "What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)": o.whatistheplannedrevenuedeclineinthecontractduetoproductivity_ytd2017_m_, "What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)": o.whatistheactualrevenuedeclineinthecontractduetoproductivity_ytd2017_m_, "What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)": o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction_ytd2017_m_, "What is the New revenue in YTD 2017 (€M)": o.whatisthenewrevenueinytd2017_m_, "Is your clients IT application budget growing-": o.isyourclientsitapplicationbudgetgrowing_, "If yes, what is the % growth -(approx)": o.ifyes_whatisthe_growth_approx_, "What is the overall CX score for the account- NPS Score": o.whatistheoverallcxscorefortheaccount_npsscore, "Is the client referenceable-": o.istheclientreferenceable_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_technicalexpertise_areaofimpact_yorn_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_technicalexpertise_npsscore_ifavailable_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_industryexpertise_areaofimpact_yorn_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_industryexpertise_npsscore_ifavailable_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_quality_areaofimpact_yorn_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_quality_npsscore_ifavailable_, "If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)": o.ifnpsislessthan7_whatisarethekeyareasofimprovement_theirnpsscores_ifany_staffing_areaofimpact_yorn_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_staffing_npsscore_ifavailable_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_timeliness_areaofimpact_yorn_, "If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)": o.ifnpsislessthan7_whatarethekeyareasofimprovement_theirnpsscores_ifany_timeliness_npsscore_ifavailable_, "I have regular meetings with CxO on topics outside of current IBM scope. CEO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_ceo, "I have regular meetings with CxO on topics outside of current IBM scope. CIO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cio, "I have regular meetings with CxO on topics outside of current IBM scope. CTO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cto, "I have regular meetings with CxO on topics outside of current IBM scope. CMO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cmo, "I have regular meetings with CxO on topics outside of current IBM scope. CPO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cpo, "I have regular meetings with CxO on topics outside of current IBM scope. CHRO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_chro, "I have regular meetings with CxO on topics outside of current IBM scope. CFO": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cfo, "I have regular meetings with CxO on topics outside of current IBM scope. Others": o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_others, "Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)": o.hastheibmwalletsharedeclinedattheaccount_1h2017vs1h2016_, "Please name the key competitors and their approx wallet share- 1 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1competitor, "Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1approxwalletshare_, "Please name the key competitors and their approx wallet share- 2 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2competitor, "Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2approxwalletshare_, "Please name the key competitors and their approx wallet share- 3 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3competitor, "Please name the key competitors and their approx wallet share- 3 Approx Wallet Share %": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3approxwalletshare_, "Please name the key competitors and their approx wallet share- 4 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4competitor, "Please name the key competitors and their approx wallet share- 4 Approx Wallet Share %": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4approxwalletshare_, "Please name the key competitors and their approx wallet share- 5 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5competitor, "Please name the key competitors and their approx wallet share- 5 Approx Wallet Share %": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5approxwalletshare_, "In your view, which competitor is perceived as the most trusted partner & why-": o.inyourview_whichcompetitorisperceivedasthemosttrustedpartner_why_, "In your view, why is IBM not considered as the most trusted partner-": o.inyourview_whyisibmnotconsideredasthemosttrustedpartner_, "What are the key areas where competition is winning against IBM-": o.whatarethekeyareaswherecompetitioniswinningagainstibm_, "In this client, what do we need to do differently to better position ourselves competitively- Differentiated offering": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_differentiatedoffering, "In this client, what do we need to do differently to better position ourselves competitively- Pricing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_pricing, "In this client, what do we need to do differently to better position ourselves competitively- Client Relationship": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_clientrelationship, "In this client, what do we need to do differently to better position ourselves competitively- Innovation": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_innovation, "In this client, what do we need to do differently to better position ourselves competitively- Account Marketing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_accountmarketing, "In this client, what do we need to do differently to better position ourselves competitively- Others": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_others, "What are the top reasons hindering pipeline generation for the account- Demand visibility": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_demandvisibility, "What are the top reasons hindering pipeline generation for the account- IBM Offerings vs Client need": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_ibmofferingsvsclientneed, "What are the top reasons hindering pipeline generation for the account- Delivery issues": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_deliveryissues, "What are the top reasons hindering pipeline generation for the account- Relationship with buyers": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_relationshipwithbuyers, "What are the top reasons hindering pipeline generation for the account- Inadequate coverage": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequatecoverage, "What are the top reasons hindering pipeline generation for the account- Inadequate awareness of CAI offerings": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequateawarenessofcaiofferings, "What are the top reasons hindering pipeline generation for the account- Others": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_others, "Do you have what you need from the CAI (ADMI, CAMS or EA) team to drive growth at the account-": o.doyouhavewhatyouneedfromthecai_admi_camsorea_teamtodrivegrowthattheaccount_, "What support do you need from CAI (ADMI, CAMS or EA) team to generate pipeline-": o.whatsupportdoyouneedfromcai_admi_camsorea_teamtogeneratepipeline_, "Did you have an account planning session in 2017 for the account-": o.didyouhaveanaccountplanningsessionin2017fortheaccount_, "Have you completed an account planning session for 2018 for the account-": o.haveyoucompletedanaccountplanningsessionfor2018fortheaccount_, "Is there a contract ending greater than $500K in the account in 2018-": o.isthereacontractendinggreaterthan_500kintheaccountin2018_, "Is there a risk of ELA audit-": o.isthereariskofelaaudit_, "When was the ELA audit done or when is it expected -": o.whenwastheelaauditdoneorwhenisitexpected_, "Before we end this survey, are there any additional comments you want to add that would provide insight to growing CAI in the account-": o.beforeweendthissurvey_arethereanyadditionalcommentsyouwanttoaddthatwouldprovideinsighttogrowingcaiintheaccount_, "Please describe the role you play on the account.": o.pleasedescribetheroleyouplayontheaccount_, "Please describe the role you play on the account. Other": o.pleasedescribetheroleyouplayontheaccount_other, "First name": o.firstname, "Last name": o.lastname, "Email address": o.emailaddress, "Sector": o.sector, "Type": o.type, "Market": o.market });
3258 // grouped1.push({"Account Name":o.accountname,"IOT":o.iot,"Completed":o.completed,"Last page":o.lastpage,"Start language":o.startlanguage,"Token":o.token,"Date started":o.datestarted,"Date last action":o.datelastaction,"Are you the current LAP on the account-":o.areyouthecurrentlapontheaccount,"Do you know the current LAP on the account-":o.doyouknowthecurrentlapontheaccount,"Please provide the name and email of the LAP currently on the account. First Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.firstname,"Please provide the name and email of the LAP currently on the account. Last Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.lastname,"Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.ibmintranetemailaddress,"Planned Contract Contraction":o.plannedcontractcontraction,"Client Relationship":o.clientrelationship,"Delivery Quality":o.deliveryquality,"Lack of Innovation":o.lackofinnovation,"Resource Availability or Capability":o.resourceavailabilityorcapability,"Competition provided better value":o.competitionprovidedbettervalue,"Others":o.others, [@@@"You have identified that % of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root ":o.youhaveidentifiedthat%ofyourytderosionof€(septytderosion)misduetoplannedcontractcontraction.pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause.,"What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)":o.whatistheplannedrevenuedeclineinthecontractduetoproductivity(ytd2017)-(€m),"What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)":o.whatistheactualrevenuedeclineinthecontractduetoproductivity-(ytd2017)(€m),"What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)":o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction-(ytd2017)-(€m),"What is the New revenue in YTD 2017 (€M)":o.whatisthenewrevenueinytd2017(€m), @@@] "Is your clients IT application budget growing-":o.isyourclientsitapplicationbudgetgrowing-,"If yes, what is the % growth -(approx)":o.ifyes,whatisthe%growth-(approx), "What is the overall CX score for the account- NPS Score":o.whatistheoverallcxscorefortheaccount-npsscore,"Is the client referenceable-":o.istheclientreferenceable-,"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)npsscore(ifavailable),"If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)":o.ifnpsislessthan7,whatisarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)npsscore(ifavailable),"I have regular meetings with CxO on topics outside of current IBM scope. CEO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.ceo,"I have regular meetings with CxO on topics outside of current IBM scope. CIO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cio,"I have regular meetings with CxO on topics outside of current IBM scope. CTO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cto,"I have regular meetings with CxO on topics outside of current IBM scope. CMO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cmo,"I have regular meetings with CxO on topics outside of current IBM scope. CPO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cpo,"I have regular meetings with CxO on topics outside of current IBM scope. CHRO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.chro,"I have regular meetings with CxO on topics outside of current IBM scope. CFO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cfo,"I have regular meetings with CxO on topics outside of current IBM scope. Others":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.others,"Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)":o.hastheibmwalletsharedeclinedattheaccount-(1h2017vs1h2016),"Please name the key competitors and their approx wallet share- 1 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1competitor,"Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1approxwalletshare%,"Please name the key competitors and their approx wallet share- 2 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2competitor,"Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2approxwalletshare%});
3259
3260 });
3261 });
3262
3263 console.log(grouped1);
3264
3265 //res.json(grouped1);
3266 var response=[] ;
3267 var updateData=[];
3268 dealsAddInfo = cloudant.db.use('lap_bck');
3269 dbquerries = [dealsData(dealsAddInfo)];
3270 Promise.all(dbquerries).then(function (data)
3271 {
3272 // console.log(JSON.stringify(data));
3273 for(let j = 0; j < grouped1.length;j++){
3274 for(let i = 0; i < data[0].rows.length; i++){
3275
3276 response.push(data[0].rows[i].doc);
3277
3278
3279 if(grouped1[j]._id===response[i]._id){
3280
3281 grouped1[j]._rev=response[i]._rev;
3282
3283 updateData.push(grouped1[j]);
3284
3285
3286
3287 }
3288
3289 }}
3290
3291 addDataLap(db, grouped1).then(function (myLapData) {
3292 res.json(myLapData);
3293 });
3294 // res.json(data1);
3295 });
3296 } catch (e) {
3297 res.json({ error_code: 1, err_desc: "Corupted excel file" });
3298 }
3299 })
3300
3301});
3302
3303
3304///////////////////
3305
3306/** API path that will upload the accountinfo files */
3307router.post('/uploadAccountInfo', function (req, res) {
3308 var exceltojson;
3309 upload(req, res, function (err) {
3310
3311 if (err) {
3312 res.json({ error_code: 1, err_desc: err });
3313 return;
3314 }
3315 /** Multer gives us file info in req.file object */
3316 if (!req.file) {
3317 res.json({ error_code: 1, err_desc: "No file passed" });
3318 return;
3319 }
3320 /** Check the extension of the incoming file and
3321 * use the appropriate module
3322 */
3323 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
3324 exceltojson = xlsxtojson;
3325 //
3326 } else {
3327 exceltojson = xlstojson;
3328
3329 }
3330 console.log(req.file.path);
3331 try {
3332 exceltojson({
3333 input: req.file.path,
3334 output: null, //since we don't need output.json
3335 lowerCaseHeaders: true
3336 }, function (err, result) {
3337 if (err) {
3338 return res.json({ error_code: 1, err_desc: err, data: null });
3339 }
3340 db = cloudant.db.use(dbCredentials.dbAccount);
3341
3342 var response = result;
3343
3344 response.forEach(function (e, i) {
3345 // Iterate over the keys of object
3346 Object.keys(e).forEach(function (key) {
3347
3348 // Copy the value
3349 var val = e[key],
3350 newKey = key.replace(/\s+/g, "");
3351
3352 // Remove key-value from object
3353 delete response[i][key];
3354
3355 // Add value with new key
3356 response[i][newKey] = val;
3357 });
3358 });
3359
3360 groupedRes = [];
3361
3362 response.forEach(function (i) {
3363 i._id = i.account + '_' + i.iot;
3364
3365 groupedRes.push({ "_id": i._id, "IOT": i.iot, "Account": i.account, "Sector": i.sector, "Category / Cluster": i.categoryorcluster, "Total CAI Erosion": i.totalcaierosion, "Planned Contract Erosion": i.plannedcontracterosion, "Pipeline": i.pipeline, "Signings FY": i.signingsfy, "Revenue FY": i.revenuefy, "Planned Contract Contraction": i.plannedcontractcontraction, "Client Relationship": i.clientrelationship, "Delivery Quality": i.deliveryquality, "Innovation": i.innovation, "Resource Availability or Capability": i.resourceavailabilityorcapability, "Competition provided better value": i.competitionprovidedbettervalue, "LAP Survey": i.lapsurvey, "NPS Survey": i.npssurvey, "Stickiness Survey": i.stickinesssurvey, "Employee Engagement": i.employeeengagement, "Account Interview Date": i.accountinterviewdate, "Client Interview": i.clientinterview, "GLAP / LAP": i.lap, "DPE": i.dpe, "Sector / Market GM": i.sectorgmormarketowner, "CAI Coach": i.caicoach, "CAI Support Coach": i.caisupportcoach, "PEP / SSAE Executive": i.pepexecutive, "Coverage": i.coverage, "Market": i.market, "GBG ID": i.gbgid, "Wave": i.wave, "Jolt Classification": i.joltclassification })
3366
3367
3368 });
3369
3370 addDataDealsAdd(db, groupedRes).then(function (myLapData) {
3371 res.json(myLapData);
3372 });
3373 });
3374 } catch (e) {
3375 res.json({ error_code: 1, err_desc: "Corupted excel file" });
3376 }
3377 })
3378
3379 });
3380
3381function addDataDealsAdd(db, record) {
3382 var dataLap = record;
3383 console.log(dataLap);
3384 return new Promise(function (resolve, reject) {
3385 db.bulk({ docs: dataLap }, function (err, body) {
3386 if (!err) {
3387 resolve(body);
3388 }
3389 else {
3390 resolve(err);
3391 }
3392 });
3393 });
3394}
3395
3396
3397/** API path that will upload the action plan files */
3398router.post('/uploadActionPlan', function (req, res) {
3399 var exceltojson;
3400 upload(req, res, function (err) {
3401
3402 if (err) {
3403 res.json({ error_code: 1, err_desc: err });
3404 return;
3405 }
3406 /** Multer gives us file info in req.file object */
3407 if (!req.file) {
3408 res.json({ error_code: 1, err_desc: "No file passed" });
3409 return;
3410 }
3411 /** Check the extension of the incoming file and
3412 * use the appropriate module
3413 */
3414 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
3415 exceltojson = xlsxtojson;
3416 } else {
3417 exceltojson = xlstojson;
3418
3419 }
3420 console.log(req.file.path);
3421 try {
3422 exceltojson({
3423 input: req.file.path,
3424 output: null, //since we don't need output.json
3425 lowerCaseHeaders: true
3426 }, function (err, result) {
3427 if (err) {
3428 return res.json({ error_code: 1, err_desc: err, data: null });
3429 }
3430 db = cloudant.db.use(dbCredentials.dbAction);
3431 var dataaction = result;
3432 //var data = JSON.parse(JSON.stringify(data11).replace(/[^a-zA-Z ]/g, ""));
3433 //var data = JSON.parse(JSON.stringify(data11).replace(/\s+?/g, ""));
3434 //var data1=JSON.parse(JSON.stringify(data).replace(/\s(?=\w+":)/g, ""));
3435 //var data2=JSON.parse(JSON.stringify(data1).replace(/\s(?=\w+":)/g, ""));
3436 //data=data2;
3437 //var data = JSON.parse(JSON.stringify(result));
3438 //res.json(data);
3439
3440 //res.json(dataaction);
3441
3442 items = Object.create(null),
3443 itemed = [];
3444 cultureArray = [
3445 {
3446 "title": "Framework",
3447 "list": [
3448 {
3449 "name": "Do you have an Innovation plan set collaboratively with your customer?",
3450 "yes": "",
3451 "comments": "",
3452 "edit": ""
3453 },
3454 {
3455 "name": "Is there an Innovation focal point/lead on your account?",
3456 "yes": "",
3457 "comments": "",
3458 "edit": ""
3459 },
3460 {
3461 "name": "Does your plan incorporate client insights, imperatives and business drivers?",
3462 "yes": "",
3463 "comments": "",
3464 "edit": ""
3465 },
3466 {
3467 "name": "Is there an Innovation steering committee - including the client?",
3468 "yes": "",
3469 "comments": "",
3470 "edit": ""
3471 },
3472 {
3473 "name": "Does the plan include governance (tasks, actions, dates, tracking)?",
3474 "yes": "",
3475 "comments": "",
3476 "edit": ""
3477 },
3478 {
3479 "name": "Are there means to recognize and reward innovation with client?",
3480 "yes": "",
3481 "comments": "",
3482 "edit": ""
3483 },
3484 {
3485 "name": "Are measures of success established?",
3486 "yes": "",
3487 "comments": "",
3488 "edit": ""
3489 }
3490 ]
3491 },
3492 {
3493 "title": "Communications & Stakeholder Alignment",
3494 "list": [
3495 {
3496 "name": "Have you established your key stakeholders for sharing innovation outcome with?",
3497 "yes": "",
3498 "comments": "",
3499 "edit": ""
3500 },
3501 {
3502 "name": "Is the ideation process tracked and reported to the client (all correct stakeholders)?",
3503 "yes": "",
3504 "comments": "",
3505 "edit": ""
3506 },
3507 {
3508 "name": "Is it clear what successful Innovation looks like with these stakeholders?",
3509 "yes": "",
3510 "comments": "",
3511 "edit": ""
3512 }
3513 ]
3514 },
3515 {
3516 "title": "Ideation",
3517 "list": [
3518 {
3519 "name": "Does your account have an Ideation platform?",
3520 "yes": "",
3521 "comments": "",
3522 "edit": ""
3523 },
3524 {
3525 "name": "Is your ideation platform used continually?",
3526 "yes": "",
3527 "comments": "",
3528 "edit": ""
3529 },
3530 {
3531 "name": "Do you have a defined process to review and vet ideas?",
3532 "yes": "",
3533 "comments": "",
3534 "edit": ""
3535 }
3536 ]
3537 },
3538 {
3539 "title": "Enablement",
3540 "list": [
3541 {
3542 "name": "Does innovation plan lead to POC's & demonstration of innovation?",
3543 "yes": "",
3544 "comments": "",
3545 "edit": ""
3546 },
3547 {
3548 "name": "Do you use IBM Design Thinking to elaborate ideas?",
3549 "yes": "",
3550 "comments": "",
3551 "edit": ""
3552 },
3553 {
3554 "name": "Do you use the IBM Garage Method or Garages to prototype or provide proof of concepts?",
3555 "yes": "",
3556 "comments": "",
3557 "edit": ""
3558 }
3559 ]
3560 }
3561 ];
3562 initiativeArray = [
3563 {
3564 "title": "IBM Automation",
3565 "list": [
3566 {
3567 "name": "Have you conducted a CEA Maturity Assessment with your client?",
3568 "yes": "",
3569 "comments": "",
3570 "edit": ""
3571 },
3572 {
3573 "name": "Have you proposed CEA Advisory Services?",
3574 "yes": "",
3575 "comments": "",
3576 "edit": ""
3577 },
3578 {
3579 "name": "Have you deployed Cognitive capabilities as part of your existing AMS Delivery?",
3580 "yes": "",
3581 "comments": "",
3582 "edit": ""
3583 },
3584 {
3585 "name": "Have you deployed RPA capabilities (robots) as part of your existing AMS delivery?",
3586 "yes": "",
3587 "comments": "",
3588 "edit": ""
3589 }
3590 ]
3591 },
3592 {
3593 "title": "Cloud Innovate",
3594 "list": [
3595 {
3596 "name": "Have you done a Cloud Affinity Assessment with your client?",
3597 "yes": "",
3598 "comments": "",
3599 "edit": ""
3600 },
3601 {
3602 "name": "Have you discussed Cloud Advisory and Strategy services?",
3603 "yes": "",
3604 "comments": "",
3605 "edit": ""
3606 },
3607 {
3608 "name": "Have you discussed Rationalization for Cloud services?",
3609 "yes": "",
3610 "comments": "",
3611 "edit": ""
3612 },
3613 {
3614 "name": "Have you discussed Cloud Modernization services?",
3615 "yes": "",
3616 "comments": "",
3617 "edit": ""
3618 },
3619 {
3620 "name": "Have you discussed AMS to Cloud services?",
3621 "yes": "",
3622 "comments": "",
3623 "edit": ""
3624 },
3625 {
3626 "name": "Have you discussed Cloud Operations services?",
3627 "yes": "",
3628 "comments": "",
3629 "edit": ""
3630 }
3631 ]
3632 },
3633 {
3634 "title": "Testing",
3635 "list": [
3636 {
3637 "name": "Have you engaged in a Test CoE discussion?",
3638 "yes": "",
3639 "comments": "",
3640 "edit": ""
3641 },
3642 {
3643 "name": "Are you using Ignite Assets - e.g. CTD?",
3644 "yes": "",
3645 "comments": "",
3646 "edit": ""
3647 }
3648 ]
3649 },
3650 {
3651 "title": "Application Development",
3652 "list": [
3653 {
3654 "name": "Have you introduced a Microservices proposal to your client?",
3655 "yes": "",
3656 "comments": "",
3657 "edit": ""
3658 },
3659 {
3660 "name": "Have you implemented elements of DevOps?",
3661 "yes": "",
3662 "comments": "",
3663 "edit": ""
3664 }
3665 ]
3666 },
3667 {
3668 "title": "Agile",
3669 "list": [
3670 {
3671 "name": "Have you held an Account Clinic?",
3672 "yes": "",
3673 "comments": "",
3674 "edit": ""
3675 },
3676 {
3677 "name": "Have you offered Strategy Services?",
3678 "yes": "",
3679 "comments": "",
3680 "edit": ""
3681 },
3682 {
3683 "name": "Have you implemented Lean2 Agile (L2A)?",
3684 "yes": "",
3685 "comments": "",
3686 "edit": ""
3687 }
3688 ]
3689 },
3690 {
3691 "title": "Enterprise Applications",
3692 "list": [
3693 {
3694 "name": "Have you done an S4Hana assessment with your client?",
3695 "yes": "",
3696 "comments": "",
3697 "edit": ""
3698 }
3699 ]
3700 }
3701 ];
3702 gbsArray = [
3703 {
3704 "title": "Microservices & Cloud migration",
3705 "yes": ""
3706 },
3707 {
3708 "title": "Next Generation Cloud EA(viz.Hana S4)",
3709 "yes": ""
3710 },
3711 {
3712 "title": "Cognitive Enterprise Automation",
3713 "yes": ""
3714 },
3715 {
3716 "title": "Cognified & Automated BPO for cost takeout",
3717 "yes": ""
3718 },
3719 {
3720 "title": "Watson Process Reengineering",
3721 "yes": ""
3722 },
3723 {
3724 "title": "Digital Reinvention for Growth",
3725 "yes": ""
3726 }
3727 ];
3728 walletArray = [
3729 {
3730 "title": "Rev",
3731 "list": [
3732 {
3733 "name": "Annual Rev (CAI)",
3734 "h1": "",
3735 "h2": "",
3736 "q1": "",
3737 "q2": ""
3738 }
3739 ]
3740 },
3741 {
3742 "title": "Wallet Share",
3743 "list": [
3744 {
3745 "name": "IBM",
3746 "h1": "",
3747 "h2": "",
3748 "q1": "",
3749 "q2": ""
3750 },
3751 {
3752 "name": "Competitor",
3753 "h1": "",
3754 "h2": "",
3755 "q1": "",
3756 "q2": ""
3757 }
3758 ]
3759 }
3760 ];
3761 actionPlanConfigDataArray = [];
3762 var updatedData=[];
3763 var mainrecord = [];
3764 dataaction.forEach(function (i) {
3765 if (mainrecord.length === 0) {
3766 i._id = (i.account + '_' + i.iot);
3767
3768 mainrecord.push({ "_id": i._id, "iot": i.iot, "accountName": i.account, "sector": i.sector, "innovationCulture": false, "innovationInitiatives": false, "walletShare": false, "actionPlan": true, "pipeline": false, actionPlanConfigData: [], approach: [], pipelineConfigData: [], cultureConfigData: cultureArray, initiativesConfigData: initiativeArray, gbsHorizon: gbsArray, walletShareConfigData: walletArray });
3769 mainrecord[0].actionPlanConfigData.push({ "id": i.id, "name": i.name, "Action": i.action, "oppAreas": [i.oppareas], "Owner": i.owner, "Account": i.account, "LAP": i.lap, "rootcausecategory": i.rootcausecategory, currentStatus: i.currentstatus, "targetDate": i.targetdate, "dateraised": i.dateraised, "ORIGStatus": i.origtatus, "Odds": i.odds, "opptVal": i.opptval, "sales": i.sales.replace('\r\n', ','), "rev": i.revimp, 'q1': i.q1, 'q2': i.q2, 'q3': i.q3, 'q4': i.q4, "comment": i.comment, "lastUpdatedBy": i.lastupdatedby, "lastUpdatedDate": i.lastupdateddate });
3770 }
3771 // .replace('\r\n',',')
3772 else {
3773 var index = _.findIndex(mainrecord, { accountName: i.account });
3774 if (index === -1) {
3775 actionplan = [];
3776 i._id = (i.account + '_' + i.iot)
3777 actionplan.push({ "id": i.id, "name": i.name, "Action": i.action, "oppAreas": [i.oppareas], "Owner": i.owner, "Account": i.account, "LAP": i.lap, "rootcausecategory": i.rootcausecategory, currentStatus: i.currentstatus, "targetDate": i.targetdate, "dateraised": i.dateraised, "ORIGStatus": i.origtatus, "Odds": i.odds, "opptVal": i.opptval, "sales": i.sales.replace('\r\n', ','), "rev": i.revimp, 'q1': i.q1, 'q2': i.q2, 'q3': i.q3, 'q4': i.q4, "comment": i.comment, "lastUpdatedBy": i.lastupdatedby, "lastUpdatedDate": i.lastupdateddate });
3778 mainrecord.push({ "_id": i._id, "iot": i.iot, "accountName": i.account, "sector": i.sector, "innovationCulture": false, "innovationInitiatives": false, "walletShare": false, "actionPlan": true, "pipeline": false, actionPlanConfigData: actionplan, approach: [], pipelineConfigData: [], cultureConfigData: cultureArray, initiativesConfigData: initiativeArray, gbsHorizon: gbsArray, walletShareConfigData: walletArray });
3779
3780 } else {
3781 mainrecord[index].actionPlanConfigData.push({ "id": i.id, "name": i.name, "Action": i.action, "oppAreas": [i.oppareas], "Owner": i.owner, "Account": i.account, "LAP": i.lap, "rootcausecategory": i.rootcausecategory, currentStatus: i.currentstatus, "targetDate": i.targetdate, "dateraised": i.dateraised, "ORIGStatus": i.origtatus, "Odds": i.odds, "opptVal": i.opptval, "sales": i.sales.replace('\r\n', ','), "rev": i.revimp, 'q1': i.q1, 'q2': i.q2, 'q3': i.q3, 'q4': i.q4, "comment": i.comment, "lastUpdatedBy": i.lastupdatedby, "lastUpdatedDate": i.lastupdateddate });
3782
3783 }
3784 }
3785 // console.log("deannn");
3786
3787 // console.log(mainrecord[0].actionPlanConfigData);
3788
3789 // if (!items[i.account]) {
3790 // items[i.account] = [];
3791 // var id = "";
3792 // //itemedData=[];
3793
3794 // //actionPlanConfigDataArray.push({"accountName":i.account, data:items[i.account]});
3795 // actionPlanConfigDataArray = items[i.account];
3796 // //id=i.account+'_'+i.iot;
3797 // i._id = i.account + '_' + i.iot;
3798 // itemed.push({ "_id":i._id,"iot": i.iot, "accountName": i.account, "sector": i.sector, "innovationCulture": false, "innovationInitiatives": false, "walletShare": false, "actionPlan": true, "pipeline": false, actionPlanConfigData: actionPlanConfigDataArray, approach: [], pipelineConfigData: [], cultureConfigData: cultureArray, initiativesConfigData: initiativeArray, gbsHorizon: gbsArray, walletShareConfigData: walletArray });
3799
3800 // }
3801
3802 // items[i.account].push({ "id":i.id,"name": i.name, "Action": i.action, "oppAreas": [], "Owner": i.owner, "Account": i.account, "LAP": i.lap, "rootcausecategory": i.rootcausecategory, currentStatus: i.currentstatus, "targetDate": i.targetdate, "dateraised": i.dateraised, "ORIGStatus": i.origtatus, "Odds": i.odds, "opptVal": i.opptval, "comment": i.comment, "lastUpdatedBy": i.lastupdatedby, "lastUpdatedDate": i.lastupdateddate });
3803 //items[i.account].push({"id":i.id,"name":i.name,"Action":i.action,"Owner":i.owner,"Account":i.account,"LAP":i.lap,"rootcausecategory":i.rootcausecategory,currentStatus:i.currentstatus,"targetDate":i.targetdate,"dateraised":i.dateraised,"ORIGStatus":i.origtatus,"Odds":i.odds,"opptVal":i.opptval,"sales":i.sales,"revImp":i.revimp,"q1":i.q1,"q2":i.q2,"q3":i.q3,"q4":i.q4,"comment":i.comment,"lastUpdatedBy":i.lastupdatedby,"lastUpdatedDate":i.lastupdateddate});
3804 //items[i.account].push(grouped);
3805 //itemedData.push({"_id":i.account+'_'+i.iot,"iot":i.iot,"accountName":i.account,"sector":i.sector,"imt":i.imt, "innovationCulture": false,"innovationInitiatives": false,"walletShare": false, "actionPlan": true, "pipeline": false, actionPlanConfigData: itemed,approach: [],pipelineConfigData:[],cultureConfigData:cultureArray,initiativesConfigData:initiativeArray,gbsHorizon:gbsArray,walletShareConfigData:walletArray});
3806 });
3807 // console.log(mainrecord[0].actionPlanConfigData);
3808
3809
3810
3811 var response=[] ;
3812 var updateData=[];
3813 dealsAddInfo = cloudant.db.use('actionplan_back');
3814 dbquerries = [dealsData(dealsAddInfo)];
3815 Promise.all(dbquerries).then(function (data) {
3816 // console.log("aaaaaaaaaaaaaa");
3817 // console.log(data);
3818 for(let j = 0; j < mainrecord.length;j++)
3819 {
3820 for(let i = 0; i < data[0].rows.length; i++)
3821 {
3822 // console.log("hahaha");
3823 // console.log(data[0].rows.length);
3824
3825 response.push(data[0].rows[i].doc);
3826
3827 // console.log(mainrecord[j].actionPlanConfigData);
3828 // console.log(response[i].actionPlanConfigData);
3829 // console.log("sammm");
3830 // console.log(response[i].actionPlanConfigData);
3831 // console.log("break");
3832 // console.log(mainrecord[j].actionPlanConfigData);
3833 // console.log(mainrecord[j].actionPlanConfigData[0]);
3834 // console.log(mainrecord[j].actionPlanConfigData.length);
3835 // updatedData.push(mainrecord[j].act)
3836 // for(var r=0;r<mainrecord[j].actionPlanConfigData.length;r++){
3837 if(mainrecord[j]._id===response[i]._id){
3838 // mainrecord[j]._rev=response[i]._rev;
3839 // // updatedData.push(mainrecord[j].actionPlanConfigData);
3840 // // console.log(updatedData);
3841 // // console.log("HELLO RECORD");
3842 // for(var k=0;k<response[i].actionPlanConfigData.length;k++){
3843 for(var k=0;k<mainrecord[j].actionPlanConfigData.length;k++){
3844
3845 // console.log("ozil");
3846 // console.log(response[i].actionPlanConfigData.length);
3847 // console.log(mainrecord[j].actionPlanConfigData);
3848 // console.log(response[i].actionPlanConfigData[k]);
3849 // mainrecord[j].actionPlanConfigData.push(response[i].actionPlanConfigData[k]);
3850 response[i].actionPlanConfigData.push(mainrecord[j].actionPlanConfigData[k]);
3851 updateData.push(response[i]);
3852 }
3853 // updateData=response;
3854 // console.log("RESPONSE");
3855 // console.log(responses[i]);
3856 // var uploadDataItem=response[i];
3857 // addDataPipeline(db, updateData).then(function (myData) {
3858 // res.json(myData);
3859
3860 // });
3861 }
3862
3863 // }
3864
3865
3866 }}
3867 // updateData=response;
3868
3869
3870 // console.log("deansam");
3871 // console.log(data[0].rows[3].doc);
3872
3873 // console.log("RESPONSE");
3874 // console.log(JSON.stringify(reponse));
3875 addDataPipeline(db, updateData).then(function (myData) {
3876 res.json(myData);
3877
3878 });
3879 })
3880
3881
3882
3883// addDataPipeline(db, response).then(function (myData) {
3884// res.json(myData);
3885// });
3886 });
3887
3888 //console.log(grouped);
3889 //res.json(itemed);
3890 // var response=[] ;
3891 // var updateData=[];
3892 // dealsAddInfo = cloudant.db.use('actionplan_back');
3893 // dbquerries = [dealsData(dealsAddInfo)];
3894 // Promise.all(dbquerries).then(function (data) {
3895 // for(let j = 0; j < mainrecord.length;j++){
3896 // for(let i = 0; i < data[0].rows.length; i++){
3897
3898 // response.push(data[0].rows[i].doc);
3899
3900 // // updateData=response;
3901 // if(mainrecord[j]._id===response[i]._id){
3902
3903 // console.log(mainrecord[j].actionPlanConfigData);
3904 // console.log(response[i].actionPlanConfigData);
3905 // mainrecord[j]._rev=response[i]._rev;
3906 // mainrecord[j].actionPlanConfigData.push(response[i].actionPlanConfigData);
3907
3908
3909 // // updateData.push(mainrecord[j].actionPlanConfigData);
3910
3911
3912
3913 // }
3914
3915 // }}
3916
3917 // res.json(grouped);
3918 // });
3919 } catch (e) {
3920 res.json({ error_code: 1, err_desc: "Corupted excel file" });
3921 }
3922 })
3923});
3924
3925/*********/
3926
3927/** API path that will upload pipeline files */
3928router.post('/uploadPipeline', function (req, res) {
3929 var exceltojson;
3930 upload(req, res, function (err) {
3931
3932 if (err) {
3933 res.json({ error_code: 1, err_desc: err });
3934 return;
3935 }
3936 /** Multer gives us file info in req.file object */
3937 if (!req.file) {
3938 res.json({ error_code: 1, err_desc: "No file passed" });
3939 return;
3940 }
3941 /** Check the extension of the incoming file and
3942 * use the appropriate module
3943 */
3944 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
3945 exceltojson = xlsxtojson;
3946
3947 } else {
3948 exceltojson = xlstojson;
3949
3950 }
3951 console.log(req.file.path);
3952 try {
3953 exceltojson({
3954 input: req.file.path,
3955 output: null, //since we don't need output.json
3956 lowerCaseHeaders: true
3957 }, function (err, result) {
3958 if (err) {
3959 return res.json({ error_code: 1, err_desc: err, data: null });
3960 }
3961 db = cloudant.db.use(dbCredentials.dbPipeline);
3962
3963 var datapipeline = result;
3964
3965 datapipeline.forEach(function (e, i) {
3966 // Iterate over the keys of object
3967 Object.keys(e).forEach(function (key) {
3968
3969 // Copy the value
3970 var val = e[key],
3971 newKey = key.replace(/\s+/g, "");
3972 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
3973 // [^a-zA-Z0-9]\s/g
3974
3975 // Remove key-value from object
3976 delete datapipeline[i][key];
3977
3978 // Add value with new key
3979 datapipeline[i][newKey1] = val;
3980 });
3981
3982 });
3983
3984
3985 //res.json(datalap);
3986 pipeGrp = Object.create(null),
3987 groupedpipe = [];
3988 datapipeline.forEach(function (p) {
3989
3990 if (!pipeGrp[p.accountname]) {
3991 pipeGrp[p.accountname] = [];
3992 p._id = p.accountname + '_' + p.iot;
3993 groupedpipe.push({ "_id": p._id, data: pipeGrp[p.accountname] })
3994 }
3995
3996 pipeGrp[p.accountname].push({ "_id": p._id, "accountname": p.accountname, "gbgid": p.gbgid, "IOT": p.iot, "Sector": p.sector, "Identified Pipeline": p.identifiedpipeline, "IBM Automation": p.ibmautomation, "V_Total": p.v_total, "V_AMS/Testing": p.v_ams_testing, "V_Cloud": p.v_cloud, "V_Nextgenea": p.v_nextgenea, "wins": p._10mwins, "totalWins": p.totalwins, "P_Total": p.p_total, "P_AMS/Testing": p.p_ams_testing, "P_Cloud": p.p_cloud, "P_Nextgenea": p.p_nextgenea })
3997 // push({"Account Name":p.accountname,"GBG ID":p.gbgid,"IOT":p.iot,"Sector":p.sector,"Account Type":p.accounttype,"Total":p.total,"AMS/Testing":p.ams_testing,"Cloud":p.cloud,"Next Gen EA":p.nextgenea,"<$10M Wins":p._10mwins,"Total Wins":p.totalwins,"Total":p.total,"AMS/Testing":p.ams_testing,"Cloud":p.cloud,"Next Gen EA":p.nextgenea})
3998 // pipeGrp[p.accountname].push({"Account Name":p.accountname,"GBG ID":p.gbgid,"IOT":p.iot,"Sector":p.sector,"Account Type":p.accounttype,"V_Total":p.v_total,"V_AMS/Testing":p.v_ams_testing,"V_Cloud":p.v_cloud,"V_Next Gen EA":p.v_nextgenea,"<$10M Wins":p._10mwins,"Total Wins":p.totalwins,"P_Total":p.p_total,"P_AMS/Testing":p.p_ams_testing,"P_Cloud":p.p_cloud,"P_Next Gen EA":p.p_nextgenea})
3999
4000
4001
4002 });
4003 });
4004
4005 // console.log("Res"+JSON.stringify(groupedpipe));
4006 // res.json(groupedpipe);
4007 var response=[] ;
4008 var updateData=[];
4009 dealsAddInfo = cloudant.db.use('pipeline_bck');
4010 dbquerries = [dealsData(dealsAddInfo)];
4011 Promise.all(dbquerries).then(function (data) {
4012 // console.log(JSON.stringify(data));
4013 for(let j = 0; j < groupedpipe.length;j++){
4014 for(let i = 0; i < data[0].rows.length; i++){
4015
4016 response.push(data[0].rows[i].doc);
4017
4018
4019 if(groupedpipe[j]._id===response[i]._id){
4020
4021 groupedpipe[j]._rev=response[i]._rev;
4022
4023 updateData.push(groupedpipe[j]);
4024
4025
4026
4027 }
4028
4029 }}
4030
4031 addDataPipeline(db,updateData).then(function (myPipelineData) {
4032 res.json(myPipelineData);
4033 });
4034 // res.json(data1);
4035 });
4036 } catch (e) {
4037 res.json({ error_code: 1, err_desc: "Corrupted excel file" });
4038 }
4039 })
4040
4041});
4042
4043/*******/
4044
4045/** API path that will upload salesconnect files */
4046router.post('/uploadSales', function (req, res) {
4047 var exceltojson;
4048 upload(req, res, function (err) {
4049
4050 if (err) {
4051 res.json({ error_code: 1, err_desc: err });
4052 return;
4053 }
4054 /** Multer gives us file info in req.file object */
4055 if (!req.file) {
4056 res.json({ error_code: 1, err_desc: "No file passed" });
4057 return;
4058 }
4059 /** Check the extension of the incoming file and
4060 * use the appropriate module
4061 */
4062 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
4063 exceltojson = xlsxtojson;
4064
4065 } else {
4066 exceltojson = xlstojson;
4067
4068 }
4069 console.log(req.file.path);
4070 try {
4071 exceltojson({
4072 input: req.file.path,
4073 output: null, //since we don't need output.json
4074 lowerCaseHeaders: true
4075 }, function (err, result) {
4076 if (err) {
4077 return res.json({ error_code: 1, err_desc: err, data: null });
4078 }
4079 db = cloudant.db.use(dbCredentials.dbSales);
4080
4081 var datasales = result;
4082
4083 datasales.forEach(function (e, i) {
4084 // Iterate over the keys of object
4085 Object.keys(e).forEach(function (key) {
4086
4087 // Copy the value
4088 var val = e[key],
4089 newKey = key.replace(/\s+/g, "");
4090 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
4091 // [^a-zA-Z0-9]\s/g
4092
4093 // Remove key-value from object
4094 delete datasales[i][key];
4095
4096 // Add value with new key
4097 datasales[i][newKey1] = val;
4098 });
4099
4100 });
4101
4102
4103 //res.json(datalap);
4104 groups = Object.create(null),
4105 groupedsales = [];
4106 // console.log("ds"+JSON.stringify(datasales))
4107 datasales.forEach(function (s) {
4108 if (!groups[s.customer]) {
4109 groups[s.customer] = [];
4110 groupedsales.push({ group: s.customer, "_id": s.customer + '_' + s.geo, "IOT": s.geo, data: groups[s.customer] });
4111 }
4112
4113 groups[s.customer].push({ "_id": s._id, "accountname": s.customer, "gbgid": s.gbgid, "IOT": s.geo, "Sector": s.sector, "account_type": s.accounttype, "Oppno": s.oppno, "level17": s.level17, "level30description": s.level30description, "sales_stage_name": s.salesstagename, "rev_signings": s.rev_signingsvalue_m_, "quater": s.fcst_decperiod })
4114 // groups[s.customer].push({ "_id": s._id, "Account Name": s.customer, "GBG ID": s.gbgid, "IOT": s.geo, "Sector": s.sector, "Account Type": s.accounttype, "Opp No": s.oppno, "Level 17": s.level17, "Level 30 Description": s.level30description, "Sales Stage Name": s.salesstagename, "Rev/Signings Value [$M]": s.rev_signingsvalue_m_, "Fcst/Dec Period": s.fcst_decperiod })
4115
4116 });
4117 });
4118
4119 // console.log("grp"+JSON.stringify(groupedsales));
4120
4121 //res.json(grouped1);
4122 var response=[] ;
4123 var updateData=[];
4124 dealsAddInfo = cloudant.db.use('salesconnect_bck');
4125 dbquerries = [dealsData(dealsAddInfo)];
4126 Promise.all(dbquerries).then(function (data) {
4127 // console.log(JSON.stringify(data));
4128 for(let j = 0; j < groupedsales.length;j++){
4129 for(let i = 0; i < data[0].rows.length; i++){
4130
4131 response.push(data[0].rows[i].doc);
4132
4133
4134 if(groupedsales[j]._id===response[i]._id){
4135
4136 groupedsales[j]._rev=response[i]._rev;
4137
4138 updateData.push(groupedsales[j]);
4139
4140
4141 // for(var k=0;k<groupedsales[j].data.length;k++){
4142
4143 // console.log("ozil");
4144 // console.log(response[i].actionPlanConfigData.length);
4145 // console.log(mainrecord[j].actionPlanConfigData);
4146 // console.log(response[i].actionPlanConfigData[k]);
4147 // mainrecord[j].actionPlanConfigData.push(response[i].actionPlanConfigData[k]);
4148 // response[i].data.push(mainrecord[j].data[k]);
4149 // }
4150
4151
4152 }
4153
4154 }}
4155
4156
4157 addDataSales(db, updateData).then(function (mySalesData) {
4158 res.json(mySalesData);
4159 });
4160 // res.json(data1);
4161 });
4162 } catch (e) {
4163 res.json({ error_code: 1, err_desc: "Corrupted excel file" });
4164 }
4165 })
4166
4167});
4168
4169
4170
4171/********/
4172/****************** Opportunity vs pipeline**********************/
4173function oppVsPipeline(db, record) {
4174
4175 return new Promise(function (resolve, reject) {
4176 db.list({ include_docs: true }, function (err, data) {
4177 if (!err) {
4178 resolve(data);
4179 }
4180 else {
4181 resolve(err);
4182 }
4183 });
4184 });
4185}
4186
4187router.post('/api/v1/getOppAreas', function (req, res) {
4188 var iot = req.body.IOT;
4189 pipelinedb = cloudant.db.use('pipeline');
4190 // salesconnectdb = cloudant.db.use('salesconnect');
4191 actiondb = cloudant.db.use('actionplan');
4192 accountdb = cloudant.db.use('accounts');
4193
4194 dbquerries = [oppVsPipeline(actiondb), oppVsPipeline(pipelinedb), oppVsPipeline(accountdb)]
4195 Promise.all(dbquerries).then(function (data) {
4196 console.log(data);
4197 var response = {
4198 "action": [],
4199 "actionPlan": [],
4200 "OpportunityCount":[]
4201 }
4202 let action = [];
4203 let pipeline = [];
4204 var selectedIot = "accountName_" + iot;
4205 let accountList = data[2].rows[0].doc[selectedIot];
4206 for (let i = 0; i < data[0].rows.length; i++) {
4207 if (data[0].rows[i].doc["iot"] === iot) {
4208 response.actionPlan.push(data[0].rows[i].doc)
4209 let oppvalue = [];
4210 let group = data[0].rows[i].doc.actionPlanConfigData.map(function (obj) {
4211 if (obj.oppAreas.length > 0) {
4212 obj.oppAreas.forEach(function (element) {
4213 oppvalue.push(element);
4214 });
4215 }
4216 });
4217 grp = oppvalue.filter(value => value != [])
4218 grp = grp.sort().filter((x, i, a) => !i || x != a[i - 1])
4219 let accJson = {
4220 "account": data[0].rows[i].doc["_id"],
4221 "data": grp
4222 }
4223 action.push(accJson);
4224 }
4225 }
4226 for (let i = 0; i < data[1].rows.length; i++) {
4227 if (data[1].rows[i].doc.data[0]["IOT"] === iot) {
4228 let accJson = {
4229 "account": data[1].rows[i].doc["_id"],
4230 "data": data[1].rows[i].doc
4231
4232 }
4233 pipeline.push(accJson);
4234 }
4235 }
4236 pipelineKey = {
4237 "AMS / Testing": "V_AMS/Testing",
4238 "Cloud": "V_Cloud",
4239 "Next Gen EA": "V_Nextgenea",
4240 "Digital, CPT, Analytics": "",
4241 "Captive": "",
4242 "IBM Automation": "IBM Automation"
4243
4244 };
4245 for (let j = 0; j < accountList.length; j++) {
4246 accountName = accountList[j].name;
4247 console.log(accountName);
4248 let actionExist = false;
4249 let pipelineExist = false;
4250 let finalArr = [];
4251 let pipelineArr = [];
4252 for (let j = 0; j < action.length; j++) {
4253 var actionAccount = action[j].account.split("_");
4254 actionAccount = actionAccount[0].trim();
4255 if (accountName == actionAccount) {
4256 console.log("action exist");
4257 actionExist = true;
4258 var accountObj = action[j];
4259 }
4260 }
4261 for (let k = 0; k < pipeline.length; k++) {
4262 console.log(pipeline[k].account);
4263 var pipelineAccount = pipeline[k].account.split("_");
4264 pipelineAccount = pipelineAccount[0].trim();
4265 if (accountName == pipelineAccount) {
4266 console.log("pipe exist");
4267 pipelineExist = true;
4268 var pipeData = pipeline[k].data.data[0];
4269 console.log(pipeData);
4270 pipelineArr = pipeline[k].data.data[0];
4271 }
4272 }
4273 if (actionExist && pipelineExist) {
4274 finalArr = [];
4275 console.log(pipeData);
4276 Object.entries(pipelineKey).forEach(([key, value]) => {
4277 let oppoVal = {};
4278 if (accountObj.data.length == 0) {
4279
4280 oppoVal = {
4281 "key": key,
4282 "opportunity": "",
4283 "pipeline": (pipeData[value] != undefined ? pipeData[value] : "")
4284 };
4285 }
4286 else {
4287 oppoVal = {
4288 "key": key,
4289 "opportunity": (accountObj.data.indexOf(key) != -1 ? "present" : ""),
4290 "pipeline": (pipeData[value] != undefined ? pipeData[value] : "")
4291 };
4292 }
4293 finalArr.push(oppoVal);
4294 });
4295
4296
4297 response.action.push({
4298 "account": accountObj.account,
4299 "data": finalArr,
4300 "Sector": pipelineArr.Sector,
4301 "gbgid": pipelineArr.gbgid,
4302 "V_Total": pipelineArr.V_Total,
4303 "P_Total": pipelineArr.P_Total,
4304 "wins": pipelineArr.wins,
4305 "totalWins": pipelineArr.totalWins,
4306 });
4307 }
4308 else if (!actionExist && pipelineExist) {
4309 Object.entries(pipelineKey).forEach(([key, value]) => {
4310 let oppoVal = {};
4311
4312 oppoVal = {
4313 "key": key,
4314 "opportunity": "",
4315 "pipeline": (pipeData[value] != undefined ? pipeData[value] : "")
4316 };
4317
4318 finalArr.push(oppoVal);
4319 });
4320
4321 response.action.push({
4322 "account": accountName + "_" + iot,
4323 "data": finalArr,
4324 "Sector": pipelineArr.Sector,
4325 "gbgid": pipelineArr.gbgid,
4326 "V_Total": pipelineArr.V_Total,
4327 "P_Total": pipelineArr.P_Total,
4328 "wins": pipelineArr.wins,
4329 "totalWins": pipelineArr.totalWins,
4330 });
4331 }
4332 else if (!actionExist && !pipelineExist) {
4333 Object.entries(pipelineKey).forEach(([key, value]) => {
4334 let oppoVal = {};
4335
4336 oppoVal = {
4337 "key": key,
4338 "opportunity": "",
4339 "pipeline": ""
4340 };
4341
4342 finalArr.push(oppoVal);
4343 });
4344
4345 response.action.push({
4346 "account": accountName + "_" + iot,
4347 "data": finalArr,
4348 "Sector": "",
4349 "gbgid": "",
4350 "V_Total": "",
4351 "P_Total": "",
4352 "wins": "",
4353 "totalWins": "",
4354 });
4355
4356 }
4357 else if (actionExist && !pipelineExist) {
4358 console.log("inside action exist");
4359 console.log();
4360 Object.entries(pipelineKey).forEach(([key, value]) => {
4361 let oppoVal = {};
4362 if (accountObj.data.length == 0) {
4363
4364 oppoVal = {
4365 "key": key,
4366 "opportunity": "",
4367 "pipeline": ""
4368 };
4369 }
4370 else {
4371 oppoVal = {
4372 "key": key,
4373 "opportunity": (accountObj.data.indexOf(key) != -1 ? "present" : ""),
4374 "pipeline": ""
4375 };
4376 }
4377 finalArr.push(oppoVal);
4378 });
4379
4380 response.action.push({
4381 "account": accountObj.account,
4382 "data": finalArr,
4383 "Sector": "",
4384 "gbgid": "",
4385 "V_Total": "",
4386 "P_Total": "",
4387 "wins": "",
4388 "totalWins": "",
4389 });
4390 }
4391 }
4392 let OppCountData=[];
4393 let accountIbm = [];
4394 let accountCloud = [];
4395 let accountAms = [];
4396 let accountDigital = [];
4397 let accountNextGen = [];
4398 let accountCaptive = [];
4399
4400
4401 let countIbm = 0;
4402 let countCloud = 0;
4403 let countAms = 0;
4404 let countDigital = 0;
4405 let countNextGen = 0;
4406 let countCaptive = 0;
4407 let total = 0;
4408
4409 for(let j=0;j<response.action.length;j++){
4410 for(let l=0;l<response.action[j].data.length;l++){
4411 if(response.action[j].data[l].key === "Cloud" && response.action[j].data[l].opportunity === 'present'){
4412 countCloud = countCloud+1;
4413 accountCloud.push(response.action[j].account.split("_")[0]);
4414 }
4415
4416 if(response.action[j].data[l].key === "IBM Automation" && response.action[j].data[l].opportunity === 'present'){
4417 countIbm = countIbm+1;
4418 accountIbm.push(response.action[j].account.split("_")[0]);
4419 }
4420
4421 if(response.action[j].data[l].key === "AMS / Testing" && response.action[j].data[l].opportunity === 'present'){
4422 countAms = countAms+1;
4423 accountAms.push(response.action[j].account.split("_")[0]);
4424 }
4425
4426 if(response.action[j].data[l].key === "Digital, CPT, Analytics" && response.action[j].data[l].opportunity === 'present'){
4427 countDigital = countDigital+1;
4428 accountDigital.push(response.action[j].account.split("_")[0]);
4429 }
4430
4431 if(response.action[j].data[l].key === "Next Gen EA" && response.action[j].data[l].opportunity === 'present'){
4432 countNextGen = countNextGen+1;
4433 accountNextGen.push(response.action[j].account.split("_")[0]);
4434 }
4435
4436 if(response.action[j].data[l].key === "Captive" && response.action[j].data[l].opportunity === 'present'){
4437 countCaptive = countCaptive+1;
4438 accountCaptive.push(response.action[j].account.split("_")[0]);
4439 }
4440
4441
4442 }
4443
4444
4445 }
4446 total = countCloud + countIbm + countAms + countDigital + countNextGen + countCaptive;
4447 OppCountData.push({
4448 accountIbm : accountIbm,
4449 accountCloud : accountCloud,
4450 accountAms : accountAms,
4451 accountDigital : accountDigital,
4452 accountNextGen : accountNextGen,
4453 accountCaptive : accountCaptive,
4454 countCloud : countCloud,
4455 countIbm : countIbm,
4456 countAms : countAms,
4457 countDigital : countDigital,
4458 countNextGen : countNextGen,
4459 countCaptive : countCaptive,
4460 totalIotWise : total
4461 })
4462
4463 response.OpportunityCount.push(OppCountData)
4464 res.json(response);
4465
4466 }, function (err) {
4467 console.log(err);
4468
4469 });
4470
4471});
4472
4473/******** Get pipeline data iotwise *************/
4474router.post('/api/v1/getPipelineDataIot', function (req, res) {
4475
4476 var iot = req.body.IOT;
4477 var sector = req.body.IOT;
4478 pipelinedb = cloudant.db.use('pipeline')
4479 salesdb = cloudant.db.use('salesconnect');
4480 dbquerries = [oppVsPipeline(pipelinedb), oppVsPipeline(salesdb)]
4481 Promise.all(dbquerries).then(function (data) {
4482
4483 var response = {};
4484 response.salesConnectiot = [];
4485 response.pipelineiot = [];
4486 for (var i = 0; i < data[0].rows.length; i++) {
4487 if (data[0].rows[i].doc.data[0]["IOT"] === iot) {
4488 response.pipelineiot.push(data[0].rows[i].doc.data[0]);
4489 }
4490 }
4491 for (var j = 0; j < data[1].rows.length; j++) {
4492 if (data[1].rows[j].doc.data[0]["IOT"] === iot) {
4493 response.salesConnectiot.push(data[1].rows[j].doc);
4494 }
4495 }
4496 res.json(response);
4497 }, function (err) {
4498 console.log(err);
4499 });
4500});
4501/**************End of getPipeline function************/
4502
4503
4504/******Action plan progress tracker IOT , sector wise **********/
4505
4506router.post('/api/v1/getProgressTrackerCount', function (req, res) {
4507 var iot = req.body.IOT;
4508 console.log(iot);
4509 actiondb = cloudant.db.use('actionplan');
4510 dbquerries = [oppVsPipeline(actiondb)]
4511 Promise.all(dbquerries).then(function (data) {
4512 // console.log(JSON.stringify(data));
4513
4514 var response = {
4515 "rootCause": [],
4516 "progress" : [],
4517 "gtotal":[],
4518 "gprogresstotal":[]
4519 }
4520 // var clientRelCount = any;
4521 let rootCauseData = [];
4522
4523 let GCR=0;
4524 let GCS=0;
4525 let GCom=0;
4526 let GCC=0;
4527 let GDQ=0;
4528 let GInn=0;
4529 let GJGR=0;
4530 let GPCC=0;
4531 let GRAAC=0;
4532 let GO=0;
4533 let GGT=0;
4534
4535 let GComplete=0;
4536 let GCompleteCDNP=0;
4537 let GCompleteClosed=0;
4538 let GCompleteWon=0;
4539 let GInProgress=0;
4540 let GNotStarted=0;
4541 let GonHold=0;
4542 let GGrandTotal=0;
4543
4544
4545 let progressData = [];
4546
4547 for (let i = 0; i < data[0].rows.length; i++) {
4548
4549 if (data[0].rows[i].doc["iot"] === iot) {
4550 countClient = 0;
4551 countSpend = 0;
4552 countCompetition = 0;
4553 countCost = 0;
4554 countDelivery = 0;
4555 countInnovation = 0;
4556 countJg = 0;
4557 countPlanned = 0;
4558 countResource = 0;
4559 countOthers = 0;
4560 totalRootAccountWise=0;
4561
4562 countComplete = 0;
4563 countCdnp = 0;
4564 countClosed = 0;
4565 countWon = 0;
4566 countProgress = 0;
4567 countNotStarted = 0;
4568 countOnHold = 0;
4569 let lap = "";
4570 let date = "";
4571 totalProgressAccountWise = 0;
4572
4573
4574 for (let k = 0; k < data[0].rows[i].doc.actionPlanConfigData.length; k++) {
4575
4576 if (data[0].rows[i].doc.actionPlanConfigData[k].name === "Client Relationship") {
4577 countClient = countClient + 1;
4578 }
4579
4580 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Client Spend"){
4581 countSpend = countSpend + 1;
4582 }
4583
4584 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Competition"){
4585 countCompetition = countCompetition + 1;
4586 }
4587
4588 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Cost Competitiveness"){
4589 countCost = countCost + 1;
4590 }
4591
4592 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Delivery Quality"){
4593 countDelivery = countDelivery + 1;
4594 }
4595
4596 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Innovation"){
4597 countInnovation = countInnovation + 1;
4598 }
4599
4600 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "JG Review"){
4601 countJg = countJg + 1;
4602 }
4603
4604 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Planned Contract Contraction"){
4605 countPlanned = countPlanned + 1;
4606 }
4607
4608 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Resource Availability and Capability"){
4609 countResource = countResource + 1;
4610 }
4611
4612 if(data[0].rows[i].doc.actionPlanConfigData[k].name === "Others"){
4613 countOthers = countOthers + 1;
4614 }
4615 totalRootAccountWise = countClient + countSpend + countCompetition + countCost + countDelivery + countInnovation + countJg + countPlanned + countResource + countOthers;
4616
4617 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "Complete"){
4618 countComplete = countComplete + 1;
4619 }
4620
4621 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "Complete-CDNP"){
4622 countCdnp = countCdnp + 1;
4623 }
4624
4625 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "Complete-Closed"){
4626 countClosed = countClosed + 1;
4627 }
4628
4629 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "Complete-Won"){
4630 countWon = countWon + 1;
4631 }
4632
4633 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "In Progress"){
4634 countProgress = countProgress + 1;
4635 }
4636
4637 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "Not Started"){
4638 countNotStarted = countNotStarted + 1;
4639 }
4640
4641 if(data[0].rows[i].doc.actionPlanConfigData[k].currentStatus === "On Hold"){
4642 countOnHold = countOnHold + 1;
4643 }
4644
4645 totalProgressAccountWise = countComplete + countCdnp + countClosed + countWon + countProgress + countNotStarted + countOnHold;
4646 lap = data[0].rows[i].doc.actionPlanConfigData[k]["LAP"];
4647 date = data[0].rows[i].doc.actionPlanConfigData[k].lastUpdatedDate;
4648
4649
4650
4651 }
4652
4653 GCR=GCR+countClient;
4654 GCS=GCS+countSpend;
4655 GCom=GCom+countCompetition;
4656 GCC=GCC+countCost;
4657 GDQ=GDQ+countDelivery;
4658 GInn=GInn+countInnovation;
4659 GJGR=GJGR+countJg;
4660 GPCC=GPCC+countPlanned;
4661 GRAAC=GRAAC+countResource;
4662 GO=GO+countOthers;
4663 GGT=GGT+totalRootAccountWise;
4664
4665
4666
4667 GComplete=GComplete+countComplete;
4668 GCompleteCDNP=GCompleteCDNP+countCdnp;
4669 GCompleteClosed=GCompleteClosed+countClosed;
4670 GCompleteWon=GCompleteWon+countWon;
4671 GInProgress=GInProgress+countProgress;
4672 GNotStarted=GNotStarted+countNotStarted;
4673 GonHold=GonHold+countOnHold;
4674 GGrandTotal=GGrandTotal+totalProgressAccountWise;
4675
4676 rootCauseData.push({
4677 account: data[0].rows[i].doc.accountName,
4678 sector: data[0].rows[i].doc.sector,
4679 clientRelationship: countClient,
4680 clientSpend:countSpend,
4681 competition:countCompetition,
4682 costCompetitive:countCost,
4683 deliveryQuality:countDelivery,
4684 innovation:countInnovation,
4685 jgReview:countJg,
4686 planned:countPlanned,
4687 resource:countResource,
4688 others:countOthers,
4689 accountWiseRootTotal : totalRootAccountWise,
4690
4691 });
4692
4693
4694 progressData.push({
4695 account: data[0].rows[i].doc.accountName,
4696 sector: data[0].rows[i].doc.sector,
4697 lap:lap,
4698 lastUpdatedDate:date,
4699 complete : countComplete,
4700 cdnp : countCdnp,
4701 closed : countClosed,
4702 won : countWon,
4703 inProgress : countProgress,
4704 notStarted : countNotStarted,
4705 onHold : countOnHold,
4706 accountWiseProgressTotal : totalProgressAccountWise
4707 });
4708
4709 }
4710 }
4711 response.rootCause.push(rootCauseData);
4712 response.progress.push(progressData);
4713 response.gtotal.push({gclientRelationship:GCR,
4714 gclientSpend:GCS,
4715 gcompetition:GCom,
4716 gcostCompetitive:GCC,
4717 gdeliveryQuality:GDQ,
4718 ginnovation:GInn,
4719 gjgReview:GJGR,
4720 gplanned:GPCC,
4721 gresource:GRAAC,
4722 gothers:GO,
4723 gaccountWiseRootTotal:GGT}
4724 );
4725 response.gprogresstotal.push({
4726 gcomplete:GComplete,
4727 gcompletecdnp:GCompleteCDNP,
4728 gcompleteclosed:GCompleteClosed,
4729 gcompletewon:GCompleteWon,
4730 ginprogress:GInProgress,
4731 gnotstarted:GNotStarted,
4732 gonhold:GonHold,
4733 ggrandtotal:GGrandTotal,
4734
4735 })
4736 res.json(response);
4737
4738 }, function (err) {
4739 console.log(err);
4740
4741 });
4742
4743});
4744/****************End of the function **********/
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765/** API path that will upload newlap E_ACCOUNTthe files */
4766router.post('/uploadnewlapE', function (req, res) {
4767 var exceltojson;
4768 upload(req, res, function (err) {
4769 if (err) {
4770 console.log(err);
4771 res.json({ error_code: 1, err_desc: err });
4772 return;
4773 }
4774 console.log("das");
4775 /** Multer gives us file info in req.file object */
4776 if (!req.file) {
4777 res.json({ error_code: 1, err_desc: "No file passed" });
4778 return;
4779 }
4780 /** Check the extension of the incoming file and
4781 * use the appropriate module
4782 */
4783 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
4784 console.log("gddgfdgd");
4785 exceltojson = xlsxtojson;
4786
4787 } else {
4788 exceltojson = xlstojson;
4789
4790 }
4791 console.log(req.file.path);
4792 try {
4793 exceltojson({
4794 input: req.file.path,
4795 output: null, //since we don't need output.json
4796 lowerCaseHeaders: true
4797 }, function (err, result) {
4798 if (err) {
4799 return res.json({ error_code: 1, err_desc: err, data: null });
4800 }
4801 db = cloudant.db.use(dbCredentials.dbNewlap);
4802 console.log(result);
4803 var datanewlape = result;
4804
4805 datanewlape.forEach(function (e, i) {
4806 // Iterate over the keys of object
4807 Object.keys(e).forEach(function (key) {
4808
4809 // Copy the value
4810 var val = e[key],
4811 newKey = key.replace(/\s+/g, "");
4812 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
4813 // [^a-zA-Z0-9]\s/g
4814
4815 // Remove key-value from object
4816 delete datanewlape[i][key];
4817
4818 // Add value with new key
4819 datanewlape[i][newKey1] = val;
4820 });
4821
4822 });
4823
4824
4825 //res.json(datalap);
4826
4827 grouped1 = [];
4828
4829 datanewlape.forEach(function (o) {
4830 o._id = o.accountname + '_' + o.iot;
4831
4832 grouped1.push({
4833 "_id": o._id, "id": o.id, "Completed": o.completed, "Last page": o.lastpage, "Start language": o.startlanguage, "Token": o.token, "Date started": o.datestarted, "Date last action": o.datelastaction, "Are you the current LAP on the account-": o.areyouthecurrentlapontheaccount_, "Do you know the current LAP on the account-": o.doyouknowthecurrentlapontheaccount_, "Please provide the name and email of the LAP currently on the account. First Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_firstname, "Please provide the name and email of the LAP currently on the account. Last Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_lastname, "Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_ibmintranetemailaddress, "Planned Contract Contraction": o.plannedcontractcontraction, "Client Relationship": o.clientrelationship, "Delivery Quality": o.deliveryquality, "Innovation": o.innovation, "Resource Availability or Capability": o.resourceavailabilityorcapability, "Cost Competitiveness": o.costcompetitiveness, "Others": o.others, "You have identified that percentage of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root cause.": o.youhaveidentifiedthat_ofyourytderosionof_septytderosion_misduetoplannedcontractcontraction_pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause_, "What was the Planned revenue decline in the contract due to productivity (2017)- ($M)": o.whatwastheplannedrevenuedeclineinthecontractduetoproductivity_2017_m_, "What was the Actual revenue decline in the contract due to productivity- (2017)- ($M)": o.whatwastheactualrevenuedeclineinthecontractduetoproductivity_2017_m_, "What was the revenue decline due to other reasons for planned contract contraction- (2017)- ($M)": o.whatwastherevenuedeclineduetootherreasonsforplannedcontractcontraction_2017_m_, "What was the New revenue in 2017- ($M)": o.whatwasthenewrevenuein2017_m_, "Challenge on Pricing": o.challengeonpricing, "Planned Contract Contraction 1": o.plannedcontractcontraction1, "Client Spend Decline": o.clientspenddecline, "Change in clients’ business / client needs": o.changeinclients_business_clientneeds, "Deferring to next quarter / year": o.deferringtonextquarter_year, "No pipeline": o.nopipeline, "Increased competitor role in account": o.increasedcompetitorroleinaccount, "Delivery Issues": o.deliveryissues, "Resource / Capability Issue": o.resource_capabilityissue, "Other": o.other, "What is your CAI revenue plan for 2018-": o.whatisyourcairevenueplanfor2018_, "What is your CAI revenue forecasted attainment for 2018-": o.whatisyourcairevenueforecastedattainmentfor2018_, "Are there planned CAI revenue declines (e.g. productivity or reduced scope or volumes) or any new revenue (e.g. increased scope or volumes or new scope) expected in 2018-": o.arethereplannedcairevenuedeclines_e_g_productivityorreducedscopeorvolumesoranynewrevenue_e_g_increasedscopeorvolumesornewscope_expectedin2018_, "Please provide a quick summary of the expected amounts and causes of the revenue changes": o.pleaseprovideaquicksummaryoftheexpectedamountsandcausesoftherevenuechanges, "Is your client's IT application budget growing-": o.isyourclient_sitapplicationbudgetgrowing_, "If yes, what is the % growth -(approx)": o.ifyes_whatisthe_growth_approx_, "From your account NPS survey, what is the Services Overall Satisfaction score for the account": o.fromyouraccountnpssurvey_whatistheservicesoverallsatisfactionscorefortheaccount, "Is the client referenceable-": o.istheclientreferenceable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_Areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(NPS Score (if available))": o.fromyouraccountnpssurveyifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_npsscore_ifavailable_,
4834 "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_npsscore_ifavailable_, "Do you have regular meetings with CxO on topics outside of current IBM scope- CEO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_ceo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CIO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cio, "Do you have regular meetings with CxO on topics outside of current IBM scope- CTO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cto, "Do you have regular meetings with CxO on topics outside of current IBM scope- CMO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cmo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CPO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cpo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CHRO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_chro, "Do you have regular meetings with CxO on topics outside of current IBM scope- CFO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cfo, "Do you have regular meetings with CxO on topics outside of current IBM scope- Others": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_others, "How has the client experience been for the contract tenure with respect to contractual benefits for the account-": o.howhastheclientexperiencebeenforthecontracttenurewithrespecttocontractualbenefitsfortheaccount_, "Are there any challenges for IBM with the account currently-": o.arethereanychallengesforibmwiththeaccountcurrently_, "Has the IBM wallet share declined at the account- (2017 vs 2016)": o.hastheibmwalletsharedeclinedattheaccount_2017vs2016_, "Please name the key competitors and their approx wallet share- 1 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1competitor, "Please name the key competitors and their approx wallet share- 1 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1approxwalletshare, "Please name the key competitors and their approx wallet share- 2 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2competitor, "Please name the key competitors and their approx wallet share- 2 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2approxwalletshare, "Please name the key competitors and their approx wallet share- 3 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3competitor, "Please name the key competitors and their approx wallet share- 3 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3approxwalletshare, "Please name the key competitors and their approx wallet share- 4 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4competitor, "Please name the key competitors and their approx wallet share- 4 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4approxwalletshare, "Please name the key competitors and their approx wallet share- 5 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5competitor, "Please name the key competitors and their approx wallet share- 5 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5approxwalletshare, "In your view, who is perceived as the most trusted partner-": o.inyourview_whoisperceivedasthemosttrustedpartner_, "In your view, who is perceived as the most trusted partner- Other": o.inyourview_whoisperceivedasthemosttrustedpartner_other, "In your view, why is IBM not considered as the most trusted partner-": o.inyourview_whyisibmnotconsideredasthemosttrustedpartner_, "What are the key areas where competition is winning against IBM-": o.whatarethekeyareaswherecompetitioniswinningagainstibm_, "In this client, what do we need to do differently to better position ourselves competitively- Differentiated offering": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_differentiatedoffering, "In this client, what do we need to do differently to better position ourselves competitively- Pricing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_pricing, "In this client, what do we need to do differently to better position ourselves competitively- Client Relationship": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_clientrelationship, "In this client, what do we need to do differently to better position ourselves competitively- Innovation": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_innovation, "In this client, what do we need to do differently to better position ourselves competitively- Account Marketing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_accountmarketing, "In this client, what do we need to do differently to better position ourselves competitively- Others": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_others, "What are the top reasons hindering pipeline generation for the account- Demand visibility": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_demandvisibility, "What are the top reasons hindering pipeline generation for the account- IBM Offerings vs Client need": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_ibmofferingsvsclientneed, "What are the top reasons hindering pipeline generation for the account- Delivery issues": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_deliveryissues, "What are the top reasons hindering pipeline generation for the account- Relationship with buyers": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_relationshipwithbuyers, "What are the top reasons hindering pipeline generation for the account- Inadequate coverage": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequatecoverage, "What are the top reasons hindering pipeline generation for the account- Inadequate awareness of CAI offerings": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequateawarenessofcaiofferings, "What are the top reasons hindering pipeline generation for the account- Others": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_others, "Do you have what you need from the CAI (ADMI, CAMS or EA) team to drive growth at the account-": o.doyouhavewhatyouneedfromthecai_admi_camsorea_teamtodrivegrowthattheaccount_, "What support do you need from CAI (ADMI, CAMS or EA) team to generate pipeline-": o.whatsupportdoyouneedfromcai_admi_camsorea_teamtogeneratepipeline_, "Did you have an account planning session in 2018 for the account-": o.didyouhaveanaccountplanningsessionin2018fortheaccount_,
4835 "Is there a contract over $500K in the account that is ending in 2018-": o.isthereacontractover_500Kintheaccountthatisendingin2018_, "Is there a risk of ELA audit-": o.isthereariskofelaaudit_, "When was the ELA audit done or when is it expected -": o.whenwastheelaauditdoneorwhenisitexpected_, "Before we end this survey, are there any additional comments you want to add that would provide insight to growing CAI in the account-": o.beforeweendthissurvey_arethereanyadditionalcommentsyouwanttoaddthatwouldprovideinsighttogrowingcaiintheaccount_, "Please describe the role you play on the account.": o.pleasedescribetheroleyouplayontheaccount_, "Please describe the role you play on the account. Other": o.pleasedescribetheroleyouplayontheaccount_other, "First name": o.firstname, "Last name": o.lastname, "Email address": o.emailaddress, "Account Name": o.accountname, "GBG": o.gbg, "Sector": o.sector, "TA CL": o.tacl, "Cluster": o.cluster, "Dec Backlog YTY %": o.decbacklogyty_, "Dec YTD Rev YTY %": o.decytdrevyty_, "FY17": o.fy17, "BTB": o.btb, "DEC YTD Rev YTY $": o.decytdrevyty_,
4836 "NPS": o.nps, "Account BDE": o.accountbde, "SN": o.sn, "Source": o.source, "Phase": o.phase, "LAP or DPE": o.lapordpe, "Status or Updates": o.statusorupdates, "Contract Detail": o.contractdetail, "FY16": o.fy16, "IOT": o.iot, "Wave": o.wave, "Account Type": o.accounttype
4837 });
4838 // grouped1.push({"Account Name":o.accountname,"IOT":o.iot,"Completed":o.completed,"Last page":o.lastpage,"Start language":o.startlanguage,"Token":o.token,"Date started":o.datestarted,"Date last action":o.datelastaction,"Are you the current LAP on the account-":o.areyouthecurrentlapontheaccount,"Do you know the current LAP on the account-":o.doyouknowthecurrentlapontheaccount,"Please provide the name and email of the LAP currently on the account. First Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.firstname,"Please provide the name and email of the LAP currently on the account. Last Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.lastname,"Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.ibmintranetemailaddress,"Planned Contract Contraction":o.plannedcontractcontraction,"Client Relationship":o.clientrelationship,"Delivery Quality":o.deliveryquality,"Lack of Innovation":o.lackofinnovation,"Resource Availability or Capability":o.resourceavailabilityorcapability,"Competition provided better value":o.competitionprovidedbettervalue,"Others":o.others, [@@@"You have identified that % of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root ":o.youhaveidentifiedthat%ofyourytderosionof€(septytderosion)misduetoplannedcontractcontraction.pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause.,"What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)":o.whatistheplannedrevenuedeclineinthecontractduetoproductivity(ytd2017)-(€m),"What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)":o.whatistheactualrevenuedeclineinthecontractduetoproductivity-(ytd2017)(€m),"What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)":o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction-(ytd2017)-(€m),"What is the New revenue in YTD 2017 (€M)":o.whatisthenewrevenueinytd2017(€m), @@@] "Is your clients IT application budget growing-":o.isyourclientsitapplicationbudgetgrowing-,"If yes, what is the % growth -(approx)":o.ifyes,whatisthe%growth-(approx), "What is the overall CX score for the account- NPS Score":o.whatistheoverallcxscorefortheaccount-npsscore,"Is the client referenceable-":o.istheclientreferenceable-,"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)npsscore(ifavailable),"If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)":o.ifnpsislessthan7,whatisarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)npsscore(ifavailable),"I have regular meetings with CxO on topics outside of current IBM scope. CEO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.ceo,"I have regular meetings with CxO on topics outside of current IBM scope. CIO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cio,"I have regular meetings with CxO on topics outside of current IBM scope. CTO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cto,"I have regular meetings with CxO on topics outside of current IBM scope. CMO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cmo,"I have regular meetings with CxO on topics outside of current IBM scope. CPO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cpo,"I have regular meetings with CxO on topics outside of current IBM scope. CHRO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.chro,"I have regular meetings with CxO on topics outside of current IBM scope. CFO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cfo,"I have regular meetings with CxO on topics outside of current IBM scope. Others":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.others,"Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)":o.hastheibmwalletsharedeclinedattheaccount-(1h2017vs1h2016),"Please name the key competitors and their approx wallet share- 1 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1competitor,"Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1approxwalletshare%,"Please name the key competitors and their approx wallet share- 2 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2competitor,"Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2approxwalletshare%});
4839
4840 });
4841 });
4842
4843
4844 console.log(grouped1);
4845
4846 //res.json(grouped1);
4847 var response=[] ;
4848 var updateData=[];
4849 dealsAddInfo = cloudant.db.use('newlap_bck');
4850 dbquerries = [dealsData(dealsAddInfo)];
4851 Promise.all(dbquerries).then(function (data) {
4852 // console.log(JSON.stringify(data));
4853 for(let j = 0; j < grouped1.length;j++){
4854 for(let i = 0; i < data[0].rows.length; i++){
4855
4856 response.push(data[0].rows[i].doc);
4857
4858
4859 if(grouped1[j]._id===response[i]._id){
4860
4861 grouped1[j]._rev=response[i]._rev;
4862
4863 updateData.push(grouped1[j]);
4864
4865
4866
4867 }
4868
4869 }}
4870
4871 addDataLap(db, updateData).then(function (myLapData) {
4872 res.json(myLapData);
4873 });
4874 // res.json(data1);
4875 });
4876 } catch (e) {
4877 res.json({ error_code: 1, err_desc: "Corupted excel file" });
4878 }
4879 })
4880
4881});
4882
4883/** API path that will upload newlap ER_ACCOUNTthe files */
4884router.post('/uploadnewlapER', function (req, res) {
4885 var exceltojson;
4886 upload(req, res, function (err) {
4887 if (err) {
4888 console.log(err);
4889 res.json({ error_code: 1, err_desc: err });
4890 return;
4891 }
4892 console.log("das");
4893 /** Multer gives us file info in req.file object */
4894 if (!req.file) {
4895 res.json({ error_code: 1, err_desc: "No file passed" });
4896 return;
4897 }
4898 /** Check the extension of the incoming file and
4899 * use the appropriate module
4900 */
4901 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
4902 console.log("gddgfdgd");
4903 exceltojson = xlsxtojson;
4904
4905 } else {
4906 exceltojson = xlstojson;
4907
4908 }
4909 console.log(req.file.path);
4910 try {
4911 exceltojson({
4912 input: req.file.path,
4913 output: null, //since we don't need output.json
4914 lowerCaseHeaders: true
4915 }, function (err, result) {
4916 if (err) {
4917 return res.json({ error_code: 1, err_desc: err, data: null });
4918 }
4919 db = cloudant.db.use(dbCredentials.dbNewlap);
4920 console.log(result);
4921 var datanewlaper = result;
4922
4923 datanewlaper.forEach(function (e, i) {
4924 // Iterate over the keys of object
4925 Object.keys(e).forEach(function (key) {
4926
4927 // Copy the value
4928 var val = e[key],
4929 newKey = key.replace(/\s+/g, "");
4930 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
4931 // [^a-zA-Z0-9]\s/g
4932
4933 // Remove key-value from object
4934 delete datanewlaper[i][key];
4935
4936 // Add value with new key
4937 datanewlaper[i][newKey1] = val;
4938 });
4939
4940 });
4941
4942
4943 //res.json(datalap);
4944
4945 grouped1 = [];
4946
4947 datanewlaper.forEach(function (o) {
4948 o._id = o.accountname + '_' + o.iot;
4949
4950 grouped1.push({
4951 "_id": o._id, "id": o.id, "Completed": o.completed, "Last page": o.lastpage, "Start language": o.startlanguage, "Token": o.token, "Date started": o.datestarted, "Date last action": o.datelastaction, "Are you the current LAP on the account-": o.areyouthecurrentlapontheaccount_, "Do you know the current LAP on the account-": o.doyouknowthecurrentlapontheaccount_, "Please provide the name and email of the LAP currently on the account. First Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_firstname, "Please provide the name and email of the LAP currently on the account. Last Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_lastname, "Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_ibmintranetemailaddress, "Planned Contract Contraction": o.plannedcontractcontraction, "Client Relationship": o.clientrelationship, "Delivery Quality": o.deliveryquality, "Innovation": o.innovation, "Resource Availability or Capability": o.resourceavailabilityorcapability, "Cost Competitiveness": o.costcompetitiveness, "Others": o.others, "You have identified that percentage of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root cause.": o.youhaveidentifiedthat_ofyourytderosionof_septytderosion_misduetoplannedcontractcontraction_pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause_, "What was the Planned revenue decline in the contract due to productivity (2017)- ($M)": o.whatwastheplannedrevenuedeclineinthecontractduetoproductivity_2017_m_, "What was the Actual revenue decline in the contract due to productivity- (2017)- ($M)": o.whatwastheactualrevenuedeclineinthecontractduetoproductivity_2017_m_, "What was the revenue decline due to other reasons for planned contract contraction- (2017)- ($M)": o.whatwastherevenuedeclineduetootherreasonsforplannedcontractcontraction_2017_m_, "What was the New revenue in 2017- ($M)": o.whatwasthenewrevenuein2017_m_, "Challenge on Pricing": o.challengeonpricing, "Planned Contract Contraction 1": o.plannedcontractcontraction1, "Client Spend Decline": o.clientspenddecline, "Change in clients’ business / client needs": o.changeinclients_business_clientneeds, "Deferring to next quarter / year": o.deferringtonextquarter_year, "No pipeline": o.nopipeline, "Increased competitor role in account": o.increasedcompetitorroleinaccount, "Delivery Issues": o.deliveryissues, "Resource / Capability Issue": o.resource_capabilityissue, "Other": o.other, "Is the wallet share improving in the account-": o.isthewalletshareimprovingintheaccount_, "Cost Competitiveness": o.costcompetitiveness, "Capability wrt competition": o.capabilitywrtcompetition, "Vendor Consolidation": o.vendorconsolidation, "Other": o.other,
4952 "What is the expected timing for the renewal of your major contract-": o.whatistheexpectedtimingfortherenewalofyourmajorcontract_, "Is this is a proactive renewal - i.e. are you going in at least 6 months earlier before the scheduled contract end date-": o.isthisisaproactiverenewal_i_e_areyougoinginatleast6monthsearlierbeforethescheduledcontractenddate_, "IBM Offerings vs Client need": o.ibmofferingsvsclientneed, "Delivery issues": o.deliveryissues, "Relationship with buyers": o.relationshipwithbuyers, "Inadequate coverage": o.inadequatecoverage, "Inadequate awareness of CAI offerings": o.inadequateawarenessofcaiofferings, "Value proposition clarity": o.valuepropositionclarity, "Lack of joint vision of the future": o.lackofjointvisionofthefuture, "Cross-brand IBM collaboration": o.cross_brandibmcollaboration, "Lack of co-creation with the client": o.lackofco_creationwiththeclient, "Ongoing governance": o.ongoinggovernance, "Lack of resources for renewal preparation": o.lackofresourcesforrenewalpreparation, "Other": o.other, "What is your CAI revenue plan for 2018-": o.whatisyourcairevenueplanfor2018_, "What is your CAI revenue forecasted attainment for 2018-": o.whatisyourcairevenueforecastedattainmentfor2018_, "Are there planned CAI revenue declines (e.g. productivity or reduced scope or volumes) or any new revenue (e.g. increased scope or volumes or new scope) expected in 2018-": o.arethereplannedcairevenuedeclines_e_g_productivityorreducedscopeorvolumesoranynewrevenue_e_g_increasedscopeorvolumesornewscope_expectedin2018_, "Please provide a quick summary of the expected amounts and causes of the revenue changes": o.pleaseprovideaquicksummaryoftheexpectedamountsandcausesoftherevenuechanges, "Is your client's IT application budget growing-": o.isyourclient_sitapplicationbudgetgrowing_, "If yes, what is the % growth -(approx)": o.ifyes_whatisthe_growth_approx_, "From your account NPS survey, what is the Services Overall Satisfaction score for the account": o.fromyouraccountnpssurvey_whatistheservicesoverallsatisfactionscorefortheaccount, "Is the client referenceable-": o.istheclientreferenceable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_Areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(NPS Score (if available))": o.fromyouraccountnpssurveyifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_npsscore_ifavailable_,
4953 "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_npsscore_ifavailable_, "Do you have regular meetings with CxO on topics outside of current IBM scope- CEO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_ceo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CIO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cio, "Do you have regular meetings with CxO on topics outside of current IBM scope- CTO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cto, "Do you have regular meetings with CxO on topics outside of current IBM scope- CMO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cmo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CPO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cpo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CHRO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_chro, "Do you have regular meetings with CxO on topics outside of current IBM scope- CFO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cfo, "Do you have regular meetings with CxO on topics outside of current IBM scope- Others": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_others, "How has the client experience been for the contract tenure with respect to contractual benefits for the account-": o.howhastheclientexperiencebeenforthecontracttenurewithrespecttocontractualbenefitsfortheaccount_, "Are there any challenges for IBM with the account currently-": o.arethereanychallengesforibmwiththeaccountcurrently_, "Who are the most likely competitors for this renewal- 1": o.whoarethemostlikelycompetitorsforthisrenewal_1, "Who are the most likely competitors for this renewal- 2": o.whoarethemostlikelycompetitorsforthisrenewal_2, "Who are the most likely competitors for this renewal- 3": o.whoarethemostlikelycompetitorsforthisrenewal_3, "In your view, what are the key differentiators of above competitors-": o.inyourview_whatarethekeydifferentiatorsofabovecompetitors_,
4954 "In your view, who is perceived as the most trusted partner-": o.inyourview_whoisperceivedasthemosttrustedpartner_, "In your view, who is perceived as the most trusted partner- Other": o.inyourview_whoisperceivedasthemosttrustedpartner_other, "In your view, why is IBM not considered as the most trusted partner-": o.inyourview_whyisibmnotconsideredasthemosttrustedpartner_, "What are the key areas where competition is winning against IBM-": o.whatarethekeyareaswherecompetitioniswinningagainstibm_, "In this client, what do we need to do differently to better position ourselves competitively- Differentiated offering": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_differentiatedoffering, "In this client, what do we need to do differently to better position ourselves competitively- Pricing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_pricing, "In this client, what do we need to do differently to better position ourselves competitively- Client Relationship": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_clientrelationship, "In this client, what do we need to do differently to better position ourselves competitively- Innovation": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_innovation, "In this client, what do we need to do differently to better position ourselves competitively- Account Marketing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_accountmarketing, "In this client, what do we need to do differently to better position ourselves competitively- Others": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_others, "What are the top reasons hindering pipeline generation for the account- Demand visibility": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_demandvisibility, "What are the top reasons hindering pipeline generation for the account- IBM Offerings vs Client need": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_ibmofferingsvsclientneed, "What are the top reasons hindering pipeline generation for the account- Delivery issues": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_deliveryissues, "What are the top reasons hindering pipeline generation for the account- Relationship with buyers": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_relationshipwithbuyers, "What are the top reasons hindering pipeline generation for the account- Inadequate coverage": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequatecoverage, "What are the top reasons hindering pipeline generation for the account- Inadequate awareness of CAI offerings": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_inadequateawarenessofcaiofferings, "What are the top reasons hindering pipeline generation for the account- Others": o.whatarethetopreasonshinderingpipelinegenerationfortheaccount_others, "Do you have what you need from the CAI (ADMI, CAMS or EA) team to drive growth at the account-": o.doyouhavewhatyouneedfromthecai_admi_camsorea_teamtodrivegrowthattheaccount_, "What support do you need from CAI (ADMI, CAMS or EA) team to generate pipeline-": o.whatsupportdoyouneedfromcai_admi_camsorea_teamtogeneratepipeline_, "Did you have an account planning session in 2018 for the account-": o.didyouhaveanaccountplanningsessionin2018fortheaccount_,
4955 "Is there a contract over $500K in the account that is ending in 2018-": o.isthereacontractover_500Kintheaccountthatisendingin2018_, "Is there a risk of ELA audit-": o.isthereariskofelaaudit_, "When was the ELA audit done or when is it expected -": o.whenwastheelaauditdoneorwhenisitexpected_, "Before we end this survey, are there any additional comments you want to add that would provide insight to growing CAI in the account-": o.beforeweendthissurvey_arethereanyadditionalcommentsyouwanttoaddthatwouldprovideinsighttogrowingcaiintheaccount_, "Please describe the role you play on the account.": o.pleasedescribetheroleyouplayontheaccount_, "Please describe the role you play on the account. Other": o.pleasedescribetheroleyouplayontheaccount_other, "First name": o.firstname, "Last name": o.lastname, "Email address": o.emailaddress, "Account Name": o.accountname, "GBG": o.gbg, "Sector": o.sector, "TA CL": o.tacl, "Cluster": o.cluster, "Dec Backlog YTY %": o.decbacklogyty_, "Dec YTD Rev YTY %": o.decytdrevyty_, "FY17": o.fy17, "BTB": o.btb, "DEC YTD Rev YTY $": o.decytdrevyty_,
4956 "NPS": o.nps, "Account BDE": o.accountbde, "SN": o.sn, "Source": o.source, "Phase": o.phase, "LAP or DPE": o.lapordpe, "Status or Updates": o.statusorupdates, "Contract Detail": o.contractdetail, "FY16": o.fy16, "IOT": o.iot, "Wave": o.wave, "Account Type": o.accounttype
4957 });
4958 // grouped1.push({"Account Name":o.accountname,"IOT":o.iot,"Completed":o.completed,"Last page":o.lastpage,"Start language":o.startlanguage,"Token":o.token,"Date started":o.datestarted,"Date last action":o.datelastaction,"Are you the current LAP on the account-":o.areyouthecurrentlapontheaccount,"Do you know the current LAP on the account-":o.doyouknowthecurrentlapontheaccount,"Please provide the name and email of the LAP currently on the account. First Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.firstname,"Please provide the name and email of the LAP currently on the account. Last Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.lastname,"Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.ibmintranetemailaddress,"Planned Contract Contraction":o.plannedcontractcontraction,"Client Relationship":o.clientrelationship,"Delivery Quality":o.deliveryquality,"Lack of Innovation":o.lackofinnovation,"Resource Availability or Capability":o.resourceavailabilityorcapability,"Competition provided better value":o.competitionprovidedbettervalue,"Others":o.others, [@@@"You have identified that % of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root ":o.youhaveidentifiedthat%ofyourytderosionof€(septytderosion)misduetoplannedcontractcontraction.pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause.,"What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)":o.whatistheplannedrevenuedeclineinthecontractduetoproductivity(ytd2017)-(€m),"What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)":o.whatistheactualrevenuedeclineinthecontractduetoproductivity-(ytd2017)(€m),"What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)":o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction-(ytd2017)-(€m),"What is the New revenue in YTD 2017 (€M)":o.whatisthenewrevenueinytd2017(€m), @@@] "Is your clients IT application budget growing-":o.isyourclientsitapplicationbudgetgrowing-,"If yes, what is the % growth -(approx)":o.ifyes,whatisthe%growth-(approx), "What is the overall CX score for the account- NPS Score":o.whatistheoverallcxscorefortheaccount-npsscore,"Is the client referenceable-":o.istheclientreferenceable-,"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)npsscore(ifavailable),"If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)":o.ifnpsislessthan7,whatisarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)npsscore(ifavailable),"I have regular meetings with CxO on topics outside of current IBM scope. CEO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.ceo,"I have regular meetings with CxO on topics outside of current IBM scope. CIO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cio,"I have regular meetings with CxO on topics outside of current IBM scope. CTO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cto,"I have regular meetings with CxO on topics outside of current IBM scope. CMO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cmo,"I have regular meetings with CxO on topics outside of current IBM scope. CPO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cpo,"I have regular meetings with CxO on topics outside of current IBM scope. CHRO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.chro,"I have regular meetings with CxO on topics outside of current IBM scope. CFO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cfo,"I have regular meetings with CxO on topics outside of current IBM scope. Others":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.others,"Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)":o.hastheibmwalletsharedeclinedattheaccount-(1h2017vs1h2016),"Please name the key competitors and their approx wallet share- 1 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1competitor,"Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1approxwalletshare%,"Please name the key competitors and their approx wallet share- 2 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2competitor,"Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2approxwalletshare%});
4959
4960 });
4961 });
4962
4963 console.log(grouped1);
4964
4965 //res.json(grouped1);
4966 var response=[] ;
4967 var updateData=[];
4968 dealsAddInfo = cloudant.db.use('newlap_bck');
4969 dbquerries = [dealsData(dealsAddInfo)];
4970 Promise.all(dbquerries).then(function (data) {
4971 // console.log(JSON.stringify(data));
4972 for(let j = 0; j < grouped1.length;j++){
4973 for(let i = 0; i < data[0].rows.length; i++){
4974
4975 response.push(data[0].rows[i].doc);
4976
4977
4978 if(grouped1[j]._id===response[i]._id){
4979
4980 grouped1[j]._rev=response[i]._rev;
4981
4982 updateData.push(grouped1[j]);
4983
4984
4985
4986 }
4987
4988 }}
4989
4990 addDataLap(db, updateData).then(function (myLapData) {
4991 res.json(myLapData);
4992 });
4993 // res.json(data1);
4994 });
4995 } catch (e) {
4996 res.json({ error_code: 1, err_desc: "Corupted excel file" });
4997 }
4998 })
4999
5000});
5001
5002///////////////////
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013/** API path that will upload newlap G_ACCOUNTthe files */
5014router.post('/uploadnewlapG', function (req, res) {
5015 var exceltojson;
5016 upload(req, res, function (err) {
5017 if (err) {
5018 console.log(err);
5019 res.json({ error_code: 1, err_desc: err });
5020 return;
5021 }
5022 console.log("das");
5023 /** Multer gives us file info in req.file object */
5024 if (!req.file) {
5025 res.json({ error_code: 1, err_desc: "No file passed" });
5026 return;
5027 }
5028 /** Check the extension of the incoming file and
5029 * use the appropriate module
5030 */
5031 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
5032 console.log("gddgfdgd");
5033 exceltojson = xlsxtojson;
5034
5035 } else {
5036 exceltojson = xlstojson;
5037
5038 }
5039 console.log(req.file.path);
5040 try {
5041 exceltojson({
5042 input: req.file.path,
5043 output: null, //since we don't need output.json
5044 lowerCaseHeaders: true
5045 }, function (err, result) {
5046 if (err) {
5047 return res.json({ error_code: 1, err_desc: err, data: null });
5048 }
5049 db = cloudant.db.use(dbCredentials.dbNewlap);
5050 console.log(result);
5051 var datanewlapg = result;
5052
5053 datanewlapg.forEach(function (e, i) {
5054 // Iterate over the keys of object
5055 Object.keys(e).forEach(function (key) {
5056
5057 // Copy the value
5058 var val = e[key],
5059 newKey = key.replace(/\s+/g, "");
5060 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
5061 // [^a-zA-Z0-9]\s/g
5062
5063 // Remove key-value from object
5064 delete datanewlapg[i][key];
5065
5066 // Add value with new key
5067 datanewlapg[i][newKey1] = val;
5068 });
5069
5070 });
5071
5072
5073 //res.json(datalap);
5074
5075 grouped1 = [];
5076
5077 datanewlapg.forEach(function (o) {
5078 o._id = o.accountname + '_' + o.iot;
5079
5080 grouped1.push({
5081 "_id": o._id, "id": o.id, "Completed": o.completed, "Last page": o.lastpage, "Start language": o.startlanguage, "Token": o.token, "Date started": o.datestarted, "Date last action": o.datelastaction, "Are you the current LAP on the account-": o.areyouthecurrentlapontheaccount_, "Do you know the current LAP on the account-": o.doyouknowthecurrentlapontheaccount_, "Please provide the name and email of the LAP currently on the account. First Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_firstname, "Please provide the name and email of the LAP currently on the account. Last Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_lastname, "Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_ibmintranetemailaddress, "Client Relationship": o.clientrelationship, "Delivery Quality": o.deliveryquality, "Innovation": o.innovation, "Resource Availability or Capability": o.resourceavailabilityorcapability, "Cost Competitiveness": o.costcompetitiveness, "Challenge on Pricing": o.challengeonpricing, "Planned Contract Contraction": o.plannedcontractcontraction, "Client Spend Decline": o.clientspenddecline, "Change in clients’ business / client needs": o.changeinclients_business_clientneeds, "Deferring to next quarter / year": o.deferringtonextquarter_year, "No pipeline": o.nopipeline, "Increased competitor role in account": o.increasedcompetitorroleinaccount, "Delivery Issues": o.deliveryissues, "Resource / Capability Issue": o.resource_capabilityissue, "Other": o.other, "Is the wallet share improving in the account-": o.isthewalletshareimprovingintheaccount_, "Cost Competitiveness": o.costcompetitiveness, "Capability wrt competition": o.capabilitywrtcompetition, "Vendor Consolidation": o.vendorconsolidation, "Other": o.other,
5082 "What is your CAI revenue plan for 2018 ($M)-": o.whatisyourcairevenueplanfor2018_m_, "What is your CAI revenue forecasted attainment for 2018 ($M)-": o.whatisyourcairevenueforecastedattainmentfor2018_m_, "Are there planned CAI revenue declines (e.g. productivity or reduced scope or volumes) or any new revenue (e.g. increased scope or volumes or new scope) expected in 2018-": o.arethereplannedcairevenuedeclines_e_g_productivityorreducedscopeorvolumesoranynewrevenue_e_g_increasedscopeorvolumesornewscope_expectedin2018_, "If yes, please provide a quick summary of the expected amounts and causes of the revenue changes.": o.ifyes_pleaseprovideaquicksummaryoftheexpectedamountsandcausesoftherevenuechanges_, "From your account NPS survey, what is the Services Overall Satisfaction score for the account": o.fromyouraccountnpssurvey_whatistheservicesoverallsatisfactionscorefortheaccount, "Is the client referenceable-": o.istheclientreferenceable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_Areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(NPS Score (if available))": o.fromyouraccountnpssurveyifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_npsscore_ifavailable_,
5083 "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_npsscore_ifavailable_, "Do you have regular meetings with CxO on topics outside of current IBM scope- CEO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_ceo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CIO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cio, "Do you have regular meetings with CxO on topics outside of current IBM scope- CTO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cto, "Do you have regular meetings with CxO on topics outside of current IBM scope- CMO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cmo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CPO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cpo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CHRO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_chro, "Do you have regular meetings with CxO on topics outside of current IBM scope- CFO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cfo, "Do you have regular meetings with CxO on topics outside of current IBM scope- Others": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_others, "How has the client experience been for the contract tenure with respect to contractual benefits for the account-": o.howhastheclientexperiencebeenforthecontracttenurewithrespecttocontractualbenefitsfortheaccount_, "Are there any challenges for IBM with the account currently-": o.arethereanychallengesforibmwiththeaccountcurrently_, "Has the IBM wallet share declined at the account- (2017 vs 2016)": o.hastheibmwalletsharedeclinedattheaccount_2017vs2016_, "Please name the key competitors and their approx wallet share- 1 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1competitor, "Please name the key competitors and their approx wallet share- 1 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_1approxwalletshare, "Please name the key competitors and their approx wallet share- 2 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2competitor, "Please name the key competitors and their approx wallet share- 2 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_2approxwalletshare, "Please name the key competitors and their approx wallet share- 3 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3competitor, "Please name the key competitors and their approx wallet share- 3 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_3approxwalletshare, "Please name the key competitors and their approx wallet share- 4 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4competitor, "Please name the key competitors and their approx wallet share- 4 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_4approxwalletshare, "Please name the key competitors and their approx wallet share- 5 Competitor": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5competitor, "Please name the key competitors and their approx wallet share- 5 Approx Wallet Share": o.pleasenamethekeycompetitorsandtheirapproxwalletshare_5approxwalletshare, "In your view, who is perceived as the most trusted partner-": o.inyourview_whoisperceivedasthemosttrustedpartner_, "In your view, who is perceived as the most trusted partner- Other": o.inyourview_whoisperceivedasthemosttrustedpartner_other, "In your view, why is IBM not considered as the most trusted partner-": o.inyourview_whyisibmnotconsideredasthemosttrustedpartner_, "What are the key areas where competition is winning against IBM-": o.whatarethekeyareaswherecompetitioniswinningagainstibm_, "In this client, what do we need to do differently to better position ourselves competitively- Differentiated offering": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_differentiatedoffering, "In this client, what do we need to do differently to better position ourselves competitively- Pricing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_pricing, "In this client, what do we need to do differently to better position ourselves competitively- Client Relationship": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_clientrelationship, "In this client, what do we need to do differently to better position ourselves competitively- Innovation": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_innovation, "In this client, what do we need to do differently to better position ourselves competitively- Account Marketing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_accountmarketing, "In this client, what do we need to do differently to better position ourselves competitively- Others": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_others,
5084 "Is there a contract over $500K in the account that is ending in 2018-": o.isthereacontractover_500Kintheaccountthatisendingin2018_, "Is there a risk of ELA audit-": o.isthereariskofelaaudit_, "When was the ELA audit done or when is it expected -": o.whenwastheelaauditdoneorwhenisitexpected_, "Before we end this survey, are there any additional comments you want to add that would provide insight to growing CAI in the account-": o.beforeweendthissurvey_arethereanyadditionalcommentsyouwanttoaddthatwouldprovideinsighttogrowingcaiintheaccount_, "Please describe the role you play on the account.": o.pleasedescribetheroleyouplayontheaccount_, "Please describe the role you play on the account. Other": o.pleasedescribetheroleyouplayontheaccount_other, "First name": o.firstname, "Last name": o.lastname, "Email address": o.emailaddress, "Account Name": o.accountname, "GBG": o.gbg, "Sector": o.sector, "TA CL": o.tacl, "Cluster": o.cluster, "Dec Backlog YTY %": o.decbacklogyty_, "Dec YTD Rev YTY %": o.decytdrevyty_, "FY17": o.fy17, "BTB": o.btb, "FY16": o.fy16,
5085 "NPS": o.nps, "Account BDE": o.accountbde, "SN": o.sn, "Source": o.source, "Phase": o.phase, "Type": o.type, "Main Market": o.mainmarket, "Contract Detail": o.contractdetail, "DEC YTD Rev YTY $": o.decytdrevyty_, "IOT": o.iot, "Wave": o.wave, "Account Type": o.accounttype
5086 });
5087 // grouped1.push({"Account Name":o.accountname,"IOT":o.iot,"Completed":o.completed,"Last page":o.lastpage,"Start language":o.startlanguage,"Token":o.token,"Date started":o.datestarted,"Date last action":o.datelastaction,"Are you the current LAP on the account-":o.areyouthecurrentlapontheaccount,"Do you know the current LAP on the account-":o.doyouknowthecurrentlapontheaccount,"Please provide the name and email of the LAP currently on the account. First Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.firstname,"Please provide the name and email of the LAP currently on the account. Last Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.lastname,"Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.ibmintranetemailaddress,"Planned Contract Contraction":o.plannedcontractcontraction,"Client Relationship":o.clientrelationship,"Delivery Quality":o.deliveryquality,"Lack of Innovation":o.lackofinnovation,"Resource Availability or Capability":o.resourceavailabilityorcapability,"Competition provided better value":o.competitionprovidedbettervalue,"Others":o.others, [@@@"You have identified that % of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root ":o.youhaveidentifiedthat%ofyourytderosionof€(septytderosion)misduetoplannedcontractcontraction.pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause.,"What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)":o.whatistheplannedrevenuedeclineinthecontractduetoproductivity(ytd2017)-(€m),"What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)":o.whatistheactualrevenuedeclineinthecontractduetoproductivity-(ytd2017)(€m),"What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)":o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction-(ytd2017)-(€m),"What is the New revenue in YTD 2017 (€M)":o.whatisthenewrevenueinytd2017(€m), @@@] "Is your clients IT application budget growing-":o.isyourclientsitapplicationbudgetgrowing-,"If yes, what is the % growth -(approx)":o.ifyes,whatisthe%growth-(approx), "What is the overall CX score for the account- NPS Score":o.whatistheoverallcxscorefortheaccount-npsscore,"Is the client referenceable-":o.istheclientreferenceable-,"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)npsscore(ifavailable),"If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)":o.ifnpsislessthan7,whatisarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)npsscore(ifavailable),"I have regular meetings with CxO on topics outside of current IBM scope. CEO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.ceo,"I have regular meetings with CxO on topics outside of current IBM scope. CIO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cio,"I have regular meetings with CxO on topics outside of current IBM scope. CTO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cto,"I have regular meetings with CxO on topics outside of current IBM scope. CMO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cmo,"I have regular meetings with CxO on topics outside of current IBM scope. CPO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cpo,"I have regular meetings with CxO on topics outside of current IBM scope. CHRO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.chro,"I have regular meetings with CxO on topics outside of current IBM scope. CFO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cfo,"I have regular meetings with CxO on topics outside of current IBM scope. Others":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.others,"Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)":o.hastheibmwalletsharedeclinedattheaccount-(1h2017vs1h2016),"Please name the key competitors and their approx wallet share- 1 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1competitor,"Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1approxwalletshare%,"Please name the key competitors and their approx wallet share- 2 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2competitor,"Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2approxwalletshare%});
5088
5089 });
5090 });
5091
5092 console.log(grouped1);
5093
5094 //res.json(grouped1);
5095 var response=[] ;
5096 var updateData=[];
5097 dealsAddInfo = cloudant.db.use('newlap_bck');
5098 dbquerries = [dealsData(dealsAddInfo)];
5099 Promise.all(dbquerries).then(function (data) {
5100 // console.log(JSON.stringify(data));
5101 for(let j = 0; j < grouped1.length;j++){
5102 for(let i = 0; i < data[0].rows.length; i++){
5103
5104 response.push(data[0].rows[i].doc);
5105
5106
5107 if(grouped1[j]._id===response[i]._id){
5108
5109 grouped1[j]._rev=response[i]._rev;
5110
5111 updateData.push(grouped1[j]);
5112
5113
5114
5115 }
5116
5117 }}
5118
5119 addDataLap(db, updateData).then(function (myLapData) {
5120 res.json(myLapData);
5121 });
5122 // res.json(data1);
5123 });
5124 } catch (e) {
5125 res.json({ error_code: 1, err_desc: "Corupted excel file" });
5126 }
5127 })
5128
5129});
5130/********/
5131
5132
5133
5134
5135
5136
5137
5138
5139/** API path that will upload newlap GR_ACCOUNTthe files */
5140router.post('/uploadnewlapGR', function (req, res) {
5141 var exceltojson;
5142 upload(req, res, function (err) {
5143 if (err) {
5144 console.log(err);
5145 res.json({ error_code: 1, err_desc: err });
5146 return;
5147 }
5148 console.log("das");
5149 /** Multer gives us file info in req.file object */
5150 if (!req.file) {
5151 res.json({ error_code: 1, err_desc: "No file passed" });
5152 return;
5153 }
5154 /** Check the extension of the incoming file and
5155 * use the appropriate module
5156 */
5157 if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
5158 console.log("gddgfdgd");
5159 exceltojson = xlsxtojson;
5160
5161 } else {
5162 exceltojson = xlstojson;
5163
5164 }
5165 console.log(req.file.path);
5166 try {
5167 exceltojson({
5168 input: req.file.path,
5169 output: null, //since we don't need output.json
5170 lowerCaseHeaders: true
5171 }, function (err, result) {
5172 if (err) {
5173 return res.json({ error_code: 1, err_desc: err, data: null });
5174 }
5175 db = cloudant.db.use(dbCredentials.dbNewlap);
5176 console.log(result);
5177 var datanewlapgr = result;
5178
5179 datanewlapgr.forEach(function (e, i) {
5180 // Iterate over the keys of object
5181 Object.keys(e).forEach(function (key) {
5182
5183 // Copy the value
5184 var val = e[key],
5185 newKey = key.replace(/\s+/g, "");
5186 newKey1 = newKey.replace(/[^a-zA-Z0-9]+/g, '_');
5187 // [^a-zA-Z0-9]\s/g
5188
5189 // Remove key-value from object
5190 delete datanewlapgr[i][key];
5191
5192 // Add value with new key
5193 datanewlapgr[i][newKey1] = val;
5194 });
5195
5196 });
5197
5198
5199 //res.json(datalap);
5200
5201 grouped1 = [];
5202
5203 datanewlapgr.forEach(function (o) {
5204 o._id = o.accountname + '_' + o.iot;
5205
5206 grouped1.push({
5207 "_id": o._id, "id": o.id, "Completed": o.completed, "Last page": o.lastpage, "Start language": o.startlanguage, "Token": o.token, "Date started": o.datestarted, "Date last action": o.datelastaction, "Are you the current LAP on the account-": o.areyouthecurrentlapontheaccount_, "Do you know the current LAP on the account-": o.doyouknowthecurrentlapontheaccount_, "Please provide the name and email of the LAP currently on the account. First Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_firstname, "Please provide the name and email of the LAP currently on the account. Last Name": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_lastname, "Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address": o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount_ibmintranetemailaddress, "Client Relationship": o.clientrelationship, "Delivery Quality": o.deliveryquality, "Innovation": o.innovation, "Resource Availability or Capability": o.resourceavailabilityorcapability, "Cost Competitiveness": o.costcompetitiveness, "Challenge on Pricing": o.challengeonpricing, "Planned Contract Contraction": o.plannedcontractcontraction, "Client Spend Decline": o.clientspenddecline, "Change in clients’ business / client needs": o.changeinclients_business_clientneeds, "Deferring to next quarter / year": o.deferringtonextquarter_year, "No pipeline": o.nopipeline, "Increased competitor role in account": o.increasedcompetitorroleinaccount, "Delivery Issues": o.deliveryissues, "Resource / Capability Issue": o.resource_capabilityissue, "Other": o.other, "Is the wallet share improving in the account-": o.isthewalletshareimprovingintheaccount_, "Cost Competitiveness": o.costcompetitiveness, "Capability wrt competition": o.capabilitywrtcompetition, "Vendor Consolidation": o.vendorconsolidation, "Other": o.other,
5208 "What is the expected timing for the renewal of your major contract-": o.whatistheexpectedtimingfortherenewalofyourmajorcontract_, "Is this is a proactive renewal - i.e. Are you going in at least 6 months earlier before the scheduled contract end date-": o.isthisisaproactiverenewal_i_e_areyougoinginatleast6monthsearlierbeforethescheduledcontractenddate_, "IBM Offerings vs Client need": o.ibmofferingsvsclientneed, "Delivery issues": o.deliveryissues, "Relationship with buyers": o.relationshipwithbuyers, "Inadequate coverage": o.inadequatecoverage, "Inadequate awareness of CAI offerings": o.inadequateawarenessofcaiofferings, "Value proposition clarity": o.valuepropositionclarity, "Lack of joint vision of the future": o.lackofjointvisionofthefuture, "Cross-brand IBM collaboration": o.cross_brandibmcollaboration, "Lack of co-creation with the client": o.lackofco_creationwiththeclient, "Ongoing governance": o.ongoinggovernance, "Lack of resources for renewal preparation": o.lackofresourcesforrenewalpreparation, "Other": o.other,
5209 "What is your CAI revenue plan for 2018 ($M)-": o.whatisyourcairevenueplanfor2018_m_, "What is your CAI revenue forecasted attainment for 2018 ($M)-": o.whatisyourcairevenueforecastedattainmentfor2018_m_, "Are there planned CAI revenue declines (e.g. productivity or reduced scope or volumes) or any new revenue (e.g. increased scope or volumes or new scope) expected in 2018-": o.arethereplannedcairevenuedeclines_e_g_productivityorreducedscopeorvolumesoranynewrevenue_e_g_increasedscopeorvolumesornewscope_expectedin2018_, "If yes, please provide a quick summary of the expected amounts and causes of the revenue changes.": o.ifyes_pleaseprovideaquicksummaryoftheexpectedamountsandcausesoftherevenuechanges_, "From your account NPS survey, what is the Services Overall Satisfaction score for the account": o.fromyouraccountnpssurvey_whatistheservicesoverallsatisfactionscorefortheaccount, "Is the client referenceable-": o.istheclientreferenceable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Communication)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_communication_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_Areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Expertise)(NPS Score (if available))": o.fromyouraccountnpssurveyifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_expertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Industry Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_industryexpertise_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Innovation)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_innovation_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Partnership)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_partnership_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Proactivity)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_proactivity_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Quality)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_quality_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Responsiveness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_responsiveness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Staffing)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_staffing_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Technical Expertise)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_technicalexpertise_npsscore_ifavailable_,
5210 "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Timeliness)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_timeliness_npsscore_ifavailable_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(Area of Impact (Y or N))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_areaofimpact_yorn_, "From your account NPS survey, if Services Overall Satisfaction score is less than 9, what are the key areas of improvement- (Value)(NPS Score (if available))": o.fromyouraccountnpssurvey_ifservicesoverallsatisfactionscoreislessthan9_whatarethekeyareasofimprovement_value_npsscore_ifavailable_, "Do you have regular meetings with CxO on topics outside of current IBM scope- CEO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_ceo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CIO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cio, "Do you have regular meetings with CxO on topics outside of current IBM scope- CTO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cto, "Do you have regular meetings with CxO on topics outside of current IBM scope- CMO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cmo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CPO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cpo, "Do you have regular meetings with CxO on topics outside of current IBM scope- CHRO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_chro, "Do you have regular meetings with CxO on topics outside of current IBM scope- CFO": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_cfo, "Do you have regular meetings with CxO on topics outside of current IBM scope- Others": o.doyouhaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope_others, "How has the client experience been for the contract tenure with respect to contractual benefits for the account-": o.howhastheclientexperiencebeenforthecontracttenurewithrespecttocontractualbenefitsfortheaccount_, "Are there any challenges for IBM with the account currently-": o.arethereanychallengesforibmwiththeaccountcurrently_, "Who are the most likely competitors for this renewal- 1": o.whoarethemostlikelycompetitorsforthisrenewal_1, "Who are the most likely competitors for this renewal- 2": o.whoarethemostlikelycompetitorsforthisrenewal_2, "Who are the most likely competitors for this renewal- 3": o.whoarethemostlikelycompetitorsforthisrenewal_3, "In your view, what are the key differentiators of above competitors-": o.inyourview_whatarethekeydifferentiatorsofabovecompetitors_,
5211 "In your view, who is perceived as the most trusted partner-": o.inyourview_whoisperceivedasthemosttrustedpartner_, "In your view, who is perceived as the most trusted partner- Other": o.inyourview_whoisperceivedasthemosttrustedpartner_other, "In your view, why is IBM not considered as the most trusted partner-": o.inyourview_whyisibmnotconsideredasthemosttrustedpartner_, "What are the key areas where competition is winning against IBM-": o.whatarethekeyareaswherecompetitioniswinningagainstibm_, "In this client, what do we need to do differently to better position ourselves competitively- Differentiated offering": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_differentiatedoffering, "In this client, what do we need to do differently to better position ourselves competitively- Pricing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_pricing, "In this client, what do we need to do differently to better position ourselves competitively- Client Relationship": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_clientrelationship, "In this client, what do we need to do differently to better position ourselves competitively- Innovation": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_innovation, "In this client, what do we need to do differently to better position ourselves competitively- Account Marketing": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_accountmarketing, "In this client, what do we need to do differently to better position ourselves competitively- Others": o.inthisclient_whatdoweneedtododifferentlytobetterpositionourselvescompetitively_others, "Do you have what you need from the CAI (ADMI, CAMS or EA) team to drive growth at the account-": o.doyouhavewhatyouneedfromthecai_admi_camsorea_teamtodrivegrowthattheaccount_, "What support do you need from CAI (ADMI, CAMS or EA) team to generate pipeline-": o.whatsupportdoyouneedfromcai_admi_camsorea_teamtogeneratepipeline_, "Did you complete an account planning session in 2018 for the account-": o.didyoucompleteanaccountplanningsessionin2018fortheaccount_, "Is there a contract over $500K in the account in 2018-": o.isthereacontractover_500Kintheaccountin2018_,
5212 "Is there a risk of ELA audit-": o.isthereariskofelaaudit_, "When was the ELA audit done or when is it expected -": o.whenwastheelaauditdoneorwhenisitexpected_, "Before we end this survey, are there any additional comments you want to add that would provide insight to growing CAI in the account-": o.beforeweendthissurvey_arethereanyadditionalcommentsyouwanttoaddthatwouldprovideinsighttogrowingcaiintheaccount_, "Please describe the role you play on the account.": o.pleasedescribetheroleyouplayontheaccount_, "Please describe the role you play on the account. Other": o.pleasedescribetheroleyouplayontheaccount_other, "First name": o.firstname, "Last name": o.lastname, "Email address": o.emailaddress, "Account Name": o.accountname, "GBG": o.gbg, "Sector": o.sector, "TA CL": o.tacl, "Cluster": o.cluster, "Dec Backlog YTY %": o.decbacklogyty_, "Dec YTD Rev YTY %": o.decytdrevyty_, "FY17": o.fy17, "BTB": o.btb, "FY16": o.fy16,
5213 "NPS": o.nps, "Account BDE": o.accountbde, "SN": o.sn, "Source": o.source, "Phase": o.phase, "Type": o.type, "Main Market": o.mainmarket, "Contract Detail": o.contractdetail, "DEC YTD Rev YTY $": o.decytdrevyty_, "IOT": o.iot, "Wave": o.wave, "Account Type": o.accounttype
5214 });
5215 // grouped1.push({"Account Name":o.accountname,"IOT":o.iot,"Completed":o.completed,"Last page":o.lastpage,"Start language":o.startlanguage,"Token":o.token,"Date started":o.datestarted,"Date last action":o.datelastaction,"Are you the current LAP on the account-":o.areyouthecurrentlapontheaccount,"Do you know the current LAP on the account-":o.doyouknowthecurrentlapontheaccount,"Please provide the name and email of the LAP currently on the account. First Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.firstname,"Please provide the name and email of the LAP currently on the account. Last Name":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.lastname,"Please provide the name and email of the LAP currently on the account. IBM Intranet Email Address":o.pleaseprovidethenameandemailofthelapcurrentlyontheaccount.ibmintranetemailaddress,"Planned Contract Contraction":o.plannedcontractcontraction,"Client Relationship":o.clientrelationship,"Delivery Quality":o.deliveryquality,"Lack of Innovation":o.lackofinnovation,"Resource Availability or Capability":o.resourceavailabilityorcapability,"Competition provided better value":o.competitionprovidedbettervalue,"Others":o.others, [@@@"You have identified that % of your YtD erosion of €(Sept YTD Erosion)M is due to planned contract contraction. Please answer the following questions summarizing all contracts on the account that fall into this root ":o.youhaveidentifiedthat%ofyourytderosionof€(septytderosion)misduetoplannedcontractcontraction.pleaseanswerthefollowingquestionssummarizingallcontractsontheaccountthatfallintothisrootcause.,"What is the Planned revenue decline in the contract due to productivity (YTD 2017)- (€M)":o.whatistheplannedrevenuedeclineinthecontractduetoproductivity(ytd2017)-(€m),"What is the Actual revenue decline in the contract due to productivity- (YTD 2017) (€M)":o.whatistheactualrevenuedeclineinthecontractduetoproductivity-(ytd2017)(€m),"What is the revenue decline due to other reasons for planned contract contraction- (YTD 2017)- (€M)":o.whatistherevenuedeclineduetootherreasonsforplannedcontractcontraction-(ytd2017)-(€m),"What is the New revenue in YTD 2017 (€M)":o.whatisthenewrevenueinytd2017(€m), @@@] "Is your clients IT application budget growing-":o.isyourclientsitapplicationbudgetgrowing-,"If yes, what is the % growth -(approx)":o.ifyes,whatisthe%growth-(approx), "What is the overall CX score for the account- NPS Score":o.whatistheoverallcxscorefortheaccount-npsscore,"Is the client referenceable-":o.istheclientreferenceable-,"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Technical Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(technicalexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Industry Expertise) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(industryexpertise)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Quality) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(quality)npsscore(ifavailable),"If NPS is less than 7, What is are the key areas of improvement - their NPS Scores (if any) (Staffing) Area of Impact (Y or N)":o.ifnpsislessthan7,whatisarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Staffing) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(staffing)npsscore(ifavailable),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) Area of Impact (Y or N)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)areaofimpact(yorn),"If NPS is less than 7, What are the key areas of improvement - their NPS Scores (if any) (Timeliness) NPS Score (if available)":o.ifnpsislessthan7,whatarethekeyareasofimprovement-theirnpsscores(ifany)(timeliness)npsscore(ifavailable),"I have regular meetings with CxO on topics outside of current IBM scope. CEO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.ceo,"I have regular meetings with CxO on topics outside of current IBM scope. CIO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cio,"I have regular meetings with CxO on topics outside of current IBM scope. CTO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cto,"I have regular meetings with CxO on topics outside of current IBM scope. CMO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cmo,"I have regular meetings with CxO on topics outside of current IBM scope. CPO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cpo,"I have regular meetings with CxO on topics outside of current IBM scope. CHRO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.chro,"I have regular meetings with CxO on topics outside of current IBM scope. CFO":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.cfo,"I have regular meetings with CxO on topics outside of current IBM scope. Others":o.ihaveregularmeetingswithcxoontopicsoutsideofcurrentibmscope.others,"Has the IBM wallet share declined at the account- (1H 2017 vs 1H 2016)":o.hastheibmwalletsharedeclinedattheaccount-(1h2017vs1h2016),"Please name the key competitors and their approx wallet share- 1 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1competitor,"Please name the key competitors and their approx wallet share- 1 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-1approxwalletshare%,"Please name the key competitors and their approx wallet share- 2 Competitor":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2competitor,"Please name the key competitors and their approx wallet share- 2 Approx Wallet Share %":o.pleasenamethekeycompetitorsandtheirapproxwalletshare-2approxwalletshare%});
5216
5217 });
5218 });
5219
5220 console.log(grouped1);
5221
5222 //res.json(grouped1);
5223 var response=[] ;
5224 var updateData=[];
5225 dealsAddInfo = cloudant.db.use('newlap_bck');
5226 dbquerries = [dealsData(dealsAddInfo)];
5227 Promise.all(dbquerries).then(function (data) {
5228 // console.log(JSON.stringify(data));
5229 for(let j = 0; j < grouped1.length;j++){
5230 for(let i = 0; i < data[0].rows.length; i++){
5231
5232 response.push(data[0].rows[i].doc);
5233
5234
5235 if(grouped1[j]._id===response[i]._id){
5236
5237 grouped1[j]._rev=response[i]._rev;
5238
5239 updateData.push(grouped1[j]);
5240
5241
5242
5243 }
5244
5245 }}
5246
5247
5248
5249 addDataLap(db, updateData).then(function (myLapData) {
5250 res.json(myLapData);
5251 });
5252 // res.json(data1);
5253 });
5254 } catch (e) {
5255 res.json({ error_code: 1, err_desc: "Corupted excel file" });
5256 }
5257 })
5258
5259});
5260/********/
5261
5262function dealsData(db, record) {
5263
5264 return new Promise(function (resolve, reject) {
5265 db.list({ include_docs: true }, function (err, data) {
5266 if (!err) {
5267 resolve(data);
5268 }
5269 else {
5270 resolve(err);
5271 }
5272 });
5273 });
5274 }
5275/***********get deals data ********/
5276// router.get('/api/v1/getDealsData', function (req, res) {
5277// deals = cloudant.db.use('dbdealsdb');
5278// dbquerries = [dealsData(deals)]
5279// Promise.all(dbquerries).then(function (data) {
5280// // console.log(JSON.stringify(data));
5281// var response = {
5282// "dealsData": "",
5283// // "oppData": ""
5284// }
5285
5286// let dataDeals = [];
5287// let OppInfo = [];
5288// // let dataOpp =[]
5289// for (let i = 0; i < data[0].rows.length; i++) {
5290
5291// OppInfo=[
5292// {
5293// "title" : "Sales Stage Name",
5294// "value" : data[0].rows[i].doc["Sales Stage Name"]
5295// },
5296// {
5297// "title" : "Fcst/Dec period",
5298// "value" : data[0].rows[i].doc["Fcst/Dec Period"]
5299// },
5300// {
5301// "title" : "Industry",
5302// "value" : data[0].rows[i].doc["Industry"]
5303// },
5304// {
5305// "title" : "Level 20",
5306// "value" : data[0].rows[i].doc["Level 20"]
5307// },
5308// {
5309// "title" : "Level 30 Desc",
5310// "value" : data[0].rows[i].doc["Level 30 Desc"]
5311// },
5312// {
5313// "title" : "Opp Owner User Name",
5314// "value" : data[0].rows[i].doc["Opp Owner User Name"]
5315// },
5316// {
5317// "title" : "Deal Size",
5318// "value" : data[0].rows[i].doc["Deal Size"]
5319// },
5320// {
5321// "title" : "Opp Create Date",
5322// "value" : data[0].rows[i].doc["Opp Create Date"]
5323// },
5324// {
5325// "title" : "RM Status",
5326// "value" : data[0].rows[i].doc["RM Status"]
5327// },
5328// {
5329// "title" : "Account Type",
5330// "value" : data[0].rows[i].doc["Account Type"]
5331// },
5332// {
5333// "title" : "Contract Booking",
5334// "value" : data[0].rows[i].doc["Contract Booking"]
5335// },
5336// {
5337// "title" : "Odds",
5338// "value" : data[0].rows[i].doc["Odds"]
5339// },
5340// {
5341// "title" : "Competitor",
5342// "value" : data[0].rows[i].doc["Competitor"]
5343// },
5344// {
5345// "title" : "Exec Sponser Name",
5346// "value" : data[0].rows[i].doc["Exec Sponser Name"]
5347// },
5348// {
5349// "title" : "Steps to close comments from LIO",
5350// "value" : data[0].rows[i].doc["Steps to close comments from LIO"]
5351// },
5352// ]
5353
5354// dataDeals.push({
5355// id: data[0].rows[i].doc._id,
5356// rev: data[0].rows[i].doc._rev,
5357// oppNo: data[0].rows[i].doc["Opp No"],
5358// customer : data[0].rows[i].doc["Customer"],
5359// global_buying_id: data[0].rows[i].doc["Global Buying Group ID"],
5360// market: data[0].rows[i].doc["Market"],
5361// oppname: data[0].rows[i].doc["Opp Name"],
5362// revsigningvalue: data[0].rows[i].doc["Rev/Signings Value ($M)"],
5363// lastupdatedby:data[0].rows[i].doc["LastUpdatedBy"],
5364// isusector: data[0].rows[i].doc["ISU Sector"],
5365// iot: data[0].rows[i].doc["IOT"],
5366// industry : data[0].rows[i].doc["Industry"],
5367// OppInfo:OppInfo,
5368// additionalInfo:data[0].rows[i].doc["addInfoArray"]
5369// })
5370
5371
5372// }
5373// response.dealsData = dataDeals;
5374// res.json(response);
5375// }, function (err) {
5376// console.log(err);
5377
5378// });
5379// })
5380/****************************/
5381
5382/***********get deals data New ********/
5383router.get('/api/v1/getDealsDataNew', function (req, res) {
5384 deals = cloudant.db.use('dealsbackup');
5385 dealsAddInfo = cloudant.db.use('deals_addinfo');
5386 dbquerries = [dealsData(deals),dealsData(dealsAddInfo)];
5387 Promise.all(dbquerries).then(function (data) {
5388 // console.log(JSON.stringify(data));
5389 var response = [];
5390
5391 json={};
5392 // let dataOpp =[]
5393 for (let i = 0; i < data[0].rows.length; i++) {
5394 for(let j=0; j< data[1].rows.length;j++){
5395 if(data[0].rows[i].doc["Detail Key"] === data[1].rows[j].doc["Detail Key"]){
5396 json={
5397 "dataDeals":data[0].rows[i].doc,
5398 "addInfo":data[1].rows[j].doc
5399 }
5400 response.push(json);
5401 }
5402 }
5403 }
5404 res.json(response);
5405 }, function (err) {
5406 console.log(err);
5407
5408 });
5409})
5410/****************************/
5411
5412
5413/***********get GTM iot list*******/
5414function gtmData(db, record) {
5415
5416 return new Promise(function (resolve, reject) {
5417 db.list({ include_docs: true }, function (err, data) {
5418 if (!err) {
5419 resolve(data);
5420 }
5421 else {
5422 resolve(err);
5423 }
5424 });
5425 });
5426 }
5427
5428router.get('/api/v1/getGTMiotList', function (req, res) {
5429
5430 gtmIot = cloudant.db.use('listofdealsiot');
5431 dbquerries = [gtmData(gtmIot)]
5432 Promise.all(dbquerries).then(function (data) {
5433 var response = data[0].rows[0].doc
5434
5435 // var response = {
5436 // "iotgtm": data[0].rows[0].doc.iot_data,
5437 // "sectorgtm" : data[0].rows[0].doc.sector_data,
5438 // }
5439 res.json(response);
5440 }, function (err) {
5441 console.log(err);
5442 });
5443 })
5444/************************* */
5445
5446/***********get deals data for Mobile********/
5447router.get('/api/v1/getDealsDataMobile', function (req, res) {
5448 deals = cloudant.db.use('dbdealsdb');
5449 dbquerries = [dealsData(deals)]
5450 Promise.all(dbquerries).then(function (data) {
5451 // console.log(JSON.stringify(data));
5452 var response = {
5453 "dealsData": "",
5454 // "oppData": ""
5455 }
5456
5457 let dataDeals = [];
5458 let OppInfo = [];
5459 // let dataOpp =[]
5460 for (let i = 0; i < data[0].rows.length; i++) {
5461 dataDeals.push({
5462 id: data[0].rows[i].doc._id,
5463 rev: data[0].rows[i].doc._rev,
5464 "Opp No": data[0].rows[i].doc["Opp No"],
5465 "Customer" : data[0].rows[i].doc["Customer"],
5466 "Global Buying Group ID": data[0].rows[i].doc["Global Buying Group ID"],
5467 "Market": data[0].rows[i].doc["Market"],
5468 "Opp Name": data[0].rows[i].doc["Opp Name"],
5469 "Rev/Signings Value ($M)": data[0].rows[i].doc["Rev/Signings Value ($M)"],
5470 "LastUpdatedBy":data[0].rows[i].doc["LastUpdatedBy"],
5471 "ISU Sector": data[0].rows[i].doc["ISU Sector"],
5472 "IOT": data[0].rows[i].doc["IOT"],
5473 "Industry" : data[0].rows[i].doc["Industry"],
5474 "Sales Stage Name":data[0].rows[i].doc["Sales Stage Name"],
5475 "Fcst/Dec period":data[0].rows[i].doc["Fcst/Dec period"],
5476 "Level 20":data[0].rows[i].doc["Level 20"],
5477 "Level 30 Desc":data[0].rows[i].doc["Level 30 Desc"],
5478 "Opp Owner User Name":data[0].rows[i].doc["Opp Owner User Name"],
5479 "Deal Size":data[0].rows[i].doc["Deal Size"],
5480 "Opp Create Date":data[0].rows[i].doc["Opp Create Date"],
5481 "RM Status":data[0].rows[i].doc["RM Status"],
5482 "Account Type":data[0].rows[i].doc["Account Type"],
5483 "Contract Booking":data[0].rows[i].doc["Contract Booking"],
5484 "Odds":data[0].rows[i].doc["Odds"],
5485 "Competitor":data[0].rows[i].doc["Competitor"],
5486 "Exec Sponser Name":data[0].rows[i].doc["Exec Sponser Name"],
5487 "Steps to close comments from LIO":data[0].rows[i].doc["Steps to close comments from LIO"],
5488 "addInfoArray":data[0].rows[i].doc["addInfoArray"]
5489 })
5490
5491
5492 }
5493 response.dealsData = dataDeals;
5494 res.json(response);
5495 }, function (err) {
5496 console.log(err);
5497
5498 });
5499});
5500
5501
5502/************NPS CALCULATION**********/
5503
5504/****************** Inserting xl record to DB*/
5505var iot=['NA','AP','EU'];
5506var measures=['likelihood to recommend services',
5507'likelihood to choose services',
5508'services overall satisfaction',
5509'value',
5510'innovation',
5511'partnership',
5512'responsiveness',
5513'industry expertise',
5514'quality',
5515'timeliness',
5516'staffing',
5517'technical expertise',
5518'expertise',
5519'communication',
5520'proactivity'
5521];
5522function insertXldata(){
5523 xlsxtojson({
5524 input: "Test.xlsx", // input xls
5525 output: "output.json", // output json
5526 sheet: "Consolidated", // specific sheetname
5527 lowerCaseHeaders:true
5528 }, function(err, result) {
5529 if(err) {
5530 console.error(err);
5531 } else {
5532 console.log(result.length);
5533 var data=result;
5534
5535 frameScores(result);
5536
5537 }
5538 });
5539}
5540
5541
5542function bulkInsertNpsData(result){
5543 var db = cloudant.db.use('nps_xl_data');
5544db.bulk({ docs: result }, function(err) {
5545 if (err) {
5546 throw err;
5547 }
5548
5549 console.log('Inserted all cities');
5550});
5551}
5552function bulkDeleteNpsData(){
5553 var db = cloudant.db.use('nps_xl_data');
5554
5555
5556 db.list({ include_docs: true }, function (err, data) {
5557 if (!err) {
5558 // resolve(data);
5559
5560 nanodb.destroy("3a1cc8c7f955f895131c3289f5144eab","3-3e39e2298f109414cef1310449e0fd5c",function(err, body, header) {
5561 if (err) {
5562 console.log('[db.insert] ', err);
5563 return;
5564 }
5565 console.log('you have inserted the rabbit.')
5566 console.log(body);
5567
5568 });
5569 }
5570 else {
5571 resolve(err);
5572 }
5573 });
5574// db.destroy({}, function(err) {
5575// if (err) {
5576// throw err;
5577// }
5578
5579// console.log('Inserted all cities');
5580// });
5581
5582return new Promise(function (resolve, reject) {
5583
5584
5585 db.destroy({}, function (err) {
5586 if (err) {
5587 reject(err);
5588 }
5589 else {
5590 resolve("Success");
5591 }
5592 });
5593});
5594}
5595
5596
5597function frameScores(result){
5598 for(var i=0;i<result.length;i++){
5599 if(result[i]['iot']=="AM"){
5600 result[i]['iot']="NA";
5601 }
5602 else if(result[i]['iot']=="AS"){
5603 result[i]['iot']="AP";
5604 }
5605 if(result[i]['response date'] !=""){
5606 // console.log("-----------"+moment(result[i]['response date']));
5607 var quarter=parseInt(moment(result[i]['response date']).utc().quarter());
5608
5609 result[i]['quarter']="Q"+quarter+"'"+parseInt(moment(result[i]['response date']).format('YYYY'));
5610 // console.log("-----------"+ result[i]['quarter']);
5611 }
5612
5613 // console.log('measure---'+result[i]['iot']);
5614 for(var j=0;j<measures.length;j++){
5615
5616 var measureScore=result[i][""+measures[j]+""];
5617 // console.log('measure---'+measures[j]);
5618 if(measureScore ==""){
5619 var orig=measureScore;
5620
5621 result[i][measures[j]]={
5622 "number_of_Pretractors":"0",
5623 "number_of_passive":"0",
5624 "number_of_detractor":"0",
5625 "orig_val":measureScore
5626 }
5627 }
5628 else if(measureScore.valueOf() > 8 ){
5629 var orig=measureScore;
5630
5631 result[i][measures[j]]={
5632 "number_of_Pretractors":"1",
5633 "number_of_passive":"0",
5634 "number_of_detractor":"0",
5635 "orig_val":measureScore
5636 }
5637 }
5638 else if(measureScore.valueOf() < 7){
5639 var orig=measureScore;
5640
5641 result[i][measures[j]]={
5642 "number_of_Pretractors":"0",
5643 "number_of_passive":"0",
5644 "number_of_detractor":"1",
5645 "orig_val":measureScore
5646 }
5647 }
5648 else if(measureScore.valueOf() == 8 || measureScore.valueOf() == 7 ){
5649 var orig=measureScore;
5650
5651 result[i][measures[j]]={
5652 "number_of_Pretractors":"0",
5653 "number_of_passive":"1",
5654 "number_of_detractor":"0",
5655 "orig_val":measureScore
5656 }
5657 }
5658 }
5659
5660 // console.log("result-----------"+ JSON.stringify(result[i]));
5661 }
5662
5663 bulkInsertNpsData(result);
5664// bulkDeleteNpsData().then(function (data) {
5665// if(data =="Success"){
5666// console.log("success fullt deleted");
5667// }
5668// });
5669// return result;
5670}
5671
5672
5673function reducer(data,key){
5674
5675
5676return data.reduce((previous, current)=>{
5677 previous[current[key]] && previous[current[key]].length != 0 ? previous[current[key]].push(current) : previous[current[key]] = new Array(current)
5678 return previous;
5679}, {})
5680}
5681
5682function NpsCalculation(data,measure){
5683 //console.log("measure"+data.length);
5684// console.log("--------------"+JSON.stringify(data));
5685var totalVal=data.length;
5686
5687var npsValue=0;
5688var numerator=0;
5689var denominator=0;
5690for(var i=0;i<data.length;i++){
5691 var measuringValue=data[i][measure];
5692 numerator+=parseInt(measuringValue['number_of_Pretractors']);
5693 denominator+=parseInt(measuringValue['number_of_detractor']);
5694 // totalVal+=parseInt(measuringValue['orig_val']);
5695
5696}
5697//console.log("npsValue total---"+totalVal+"-----------"+numerator+"-----------"+denominator);
5698
5699npsValue=Math.round(((numerator/totalVal)-(denominator/totalVal))*100);
5700//console.log("npsValue"+npsValue);
5701return npsValue;
5702}
5703
5704function NpsCalcfiltered(filter,myData){
5705 var obj_quarter={};
5706 var reduced_obj={};
5707 if(filter !="" && filter!=undefined){
5708 reduced_obj= reducer(myData,filter);
5709 Object.keys(reduced_obj).forEach(e => {
5710 // console.log(e);
5711 var obj={};
5712 for(var i=0;i<measures.length;i++){
5713 obj[measures[i]]=NpsCalculation(reduced_obj[e],measures[i]);
5714 }
5715
5716 obj_quarter[e]=obj;
5717 });
5718 }
5719 else{
5720 reduced_obj= myData.docs;
5721 var obj={};
5722 for(var i=0;i<measures.length;i++){
5723 obj[measures[i]]=NpsCalculation(reduced_obj,measures[i]);
5724 }
5725 obj_quarter=obj;
5726 }
5727 finalObj=obj_quarter;
5728return finalObj;
5729}
5730
5731router.post('/api/v1/plotNPSReportDetails', function (req, res) {
5732 console.log("hello");
5733 var filter = req.query.filterValue;
5734//console.log("filter"+JSON.stringify(req.body));
5735 db = cloudant.db.use('nps_xl_data');
5736 let findQuery = req.body;
5737 findData(db,findQuery).then(function (myData) {
5738var finalObj={};
5739var allregions=[];
5740//console.log("myDocs"+JSON.stringify(myData.docs));
5741if(myData!=undefined && myData.docs!=undefined){
5742
5743//}
5744 reduced_obj= reducer(myData.docs,'iot');
5745
5746 Object.keys(reduced_obj).forEach(e => {
5747 var obj={};
5748 obj= NpsCalcfiltered(filter,reduced_obj[e]);
5749 finalObj[e]=(obj);
5750 });
5751
5752
5753
5754 res.json(finalObj);
5755
5756
5757}
5758else{
5759 res.json({});
5760}
5761
5762 });
5763
5764});
5765
5766router.get('/api/v1/actionplan/entiredata',function(req,res){
5767 act=cloudant.db.use('actionplan');
5768 dbquerries=[getBackup(act)]
5769 Promise.all(dbquerries).then(function(data){
5770 res.json(data[0].rows)
5771 },function (err) {
5772 console.log(err);})
5773
5774})
5775router.get('/api/v1/actionplan/userdata',function(req,res){
5776 act=cloudant.db.use('userlist_backup');
5777 dbquerries=[getBackup(act)]
5778 Promise.all(dbquerries).then(function(data){
5779 // for( h=0;h<data[0].rows.length;h++){
5780 // userarray.push(data[0].rows[h].id);
5781 // }
5782 // console.log("data of users",data[0].rows.doc[0]._id);
5783 res.json(data[0].rows)
5784
5785 },function (err) {
5786 console.log(err);})
5787})
5788
5789//my new api for users list
5790// router.get('/api/v1/userrequest', function(req, res) {
5791// var userarray=[],username=[];
5792// users_data=cloudant.db.use('userlist_backup');
5793// dbquerries=[getBackup(users_data)]
5794// Promise.all(dbquerries).then(function(data){
5795// for( h=0;h<data[0].rows.length;h++){
5796// console.log("mai hun response",h);
5797// p=h;
5798// request('https://bluepages.ibm.com/BpHttpApisv3/slaphapi?ibmperson/(mail='+data[0].rows[h].id+')/.list/byjson', function(error,response,body){
5799// // console.log("mai hun response11111111111111111111111",data[0].rows[758]["id"]);
5800// console.log("mai hun responsesssssssssssssss",h);
5801// if(!error){
5802// var req_data = JSON.parse(body);
5803// console.log("requested data is",req_data);
5804// if(req_data.search.return.count==0){
5805// // console.log("data id",JSON.stringify(data[0].rows[h]["id"]));
5806// // userarray.push(data[0].rows[i]);
5807// // j++;
5808// }
5809// else{
5810
5811// console.log("data id",JSON.stringify(data[0].rows[p]["id"]));
5812// // j++;
5813// }
5814
5815// }else{
5816// res.send({isauthenticated:false,message:"failed to get data"});
5817// console.log(error);
5818// }
5819
5820
5821// });
5822// // h++;
5823// }
5824
5825
5826// },function (err) {
5827// console.log(err);})
5828
5829// });
5830var finalUserList=[];
5831
5832router.get('/api/v1/userCheck', function(req, res) {
5833let userarray=[];
5834act=cloudant.db.use('userlist_backup');
5835dbquerries=[getBackup(act)]
5836Promise.all(dbquerries).then(function(data){
5837 for( h=0;h<data[0].rows.length;h++){
5838 userarray.push(data[0].rows[h].id);
5839 }
5840let promises = [];
5841for (let i = 0; i < userarray.length; i++) {
5842 promises.push(apicall(userarray[i]));
5843}
5844
5845Promise.all(promises).then((data) => {
5846 console.log("users final 1",finalUserList);
5847 let result= {users:finalUserList}
5848 console.log("HIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII",result)
5849 res.json(result);
5850 // res.send(result);
5851 finalUserList=[];
5852
5853}).catch(err => {
5854 console.log(err);
5855 res.send({error:"error"});
5856});
5857});
5858})
5859function apicall(id){
5860 return new Promise(function (resolve, reject) {
5861 request('https://bluepages.ibm.com/BpHttpApisv3/slaphapi?ibmperson/(mail='+id+')/.list/byjson', function(error,response,body){
5862 if(!error){
5863
5864 var req_data = JSON.parse(body);
5865 console.log("requested data search",req_data.search);
5866 console.log("Search entry lenght",req_data.search.entry.length);
5867 if(req_data.search.return.count==0){
5868 finalUserList.push(id);
5869 resolve(finalUserList);
5870 }
5871
5872 else{
5873 resolve(finalUserList);
5874 }
5875
5876 }else{
5877 console.log(error);
5878 reject();
5879 }
5880 // console.log("users final 2",finalUserList);
5881 });
5882 });
5883}
5884//insertXldata();
5885function addAboutData(db, record) {
5886
5887 return new Promise(function (resolve, reject) {
5888 db.insert(record, function (err, data) {
5889 if (!err) {
5890 resolve(data);
5891 } else {
5892 resolve(err);
5893 }
5894 });
5895 });
5896}
5897router.get('/api/v1/aboutjolt',function(req,res){
5898 act=cloudant.db.use('about_jolt');
5899 dbquerries=[getBackup(act)]
5900 Promise.all(dbquerries).then(function(data){
5901 console.log("data oggggggggf userssss",data[0].rows[0].doc);
5902
5903 res.json(data[0].rows[0].doc)
5904// console.log(res);
5905 },function (err) {
5906 console.log(err);})
5907})
5908
5909router.post('/api/v1/updatedAboutJolt/', function (req, res) {
5910 db = cloudant.db.use('about_jolt');
5911 console.log(req.body, "DATAA");
5912 // console.log("id", record)
5913 dbquerries = [getAllData(db)];
5914 Promise.all(dbquerries).then(function (data) {
5915 if(req.body.name=="About the Jolt Program"){
5916 console.log("inside the prgm")
5917 data[0].rows[0].doc["About the Jolt Program"]=req.body["About the Jolt Program"]
5918 addAboutData(db, data[0].rows[0].doc).then(function (myData) {
5919
5920 res.json(myData);
5921 });
5922
5923 }
5924 else if(req.body.name=="About the Jolt Bluemix Tool"){
5925 console.log("inside the prgm")
5926 data[0].rows[0].doc["About the Jolt Bluemix Tool"]=req.body["About the Jolt Bluemix Tool"]
5927 addAboutData(db, data[0].rows[0].doc).then(function (myData) {
5928
5929 res.json(myData);
5930 });
5931
5932 }
5933 else if(req.body.name=="For any queries and access related issue, please contact:"){
5934 console.log("inside the prgm")
5935 data[0].rows[0].doc["For any queries and access related issue, please contact:"]=req.body["For any queries and access related issue, please contact:"]
5936 addAboutData(db, data[0].rows[0].doc).then(function (myData) {
5937
5938 res.json(myData);
5939 });
5940
5941 }
5942 else {
5943 res.json({
5944 "message": "Sorry, couldn't update data"
5945 });
5946 }
5947 })
5948})
5949/****************************/
5950module.exports = router;