-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
650 lines (542 loc) · 25.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset="utf-8" />
<style>
th, td {
border:1px solid black;
}
.hide{
display: none;
}
</style>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
<script src="fireship.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/nodemailer.min.js"></script>
<!-- path CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/path.js/0.8.4/path.min.js" integrity="sha512-RTzm9c0aNZYxh3AlthYNipI3HCmUTR/hgKqHkcHR3et5IyUDgGlRdInuW8MuN5TliQMS6+M+x2Gl/2WhmmJ5ew==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://smtpjs.com/v3/smtp.js"></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<!-- Client ID: 604220425519-1igogcpqackps8qtmhl4ijfmgon535j8.apps.googleusercontent.com -->
<!--Add buttons to initiate auth sequence and sign out-->
<!-- <label for="clientID">ClientID</label><input type="text" name="clientid" id="clientID" placeholder="Client ID" value='604220425519-1igogcpqackps8qtmhl4ijfmgon535j8.apps.googleusercontent.com'><br> -->
<div class="container">
<p class='maintitle'>Google Sheets API Quickstart</p>
<label for="spreadsheetID" class='spreadsheetlabel'>SpreadsheetID</label><input class="gsheetinput" type="text" name="spreadsheetid" placeholder="SpreadSheetID" id="spreadsheetid" ><br><br> <!--1CmII0O9SMaLSH7pSmi9nIgr4n54XqHzVNcpukWSqajQ-->
<div class="btns">
<button id="authorize_button" >Authorize</button>
<button id="signout_button" >Sign Out</button><br>
<button id='downloadExcelbtn' class="hide">Download Excel file</button>
</div>
<p class="msg"></p>
<table id="table">
</table>
<div class="sendemailcontainer">
<button type="submit">Send mail</button>
</form>
<button id="authorize_button" style="display: none;">Authorize</button><br><br>
<button id="signout_button" style="display: none;">Sign Out</button>
</div>
<pre id="content" style="white-space: pre-wrap;"></pre>
</div>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '342013205412-n849ga9v6oj5ctnqeod7d6hn897ji9e3.apps.googleusercontent.com'
// var OUR_SPREADSHEET_ID='1CmII0O9SMaLSH7pSmi9nIgr4n54XqHzVNcpukWSqajQ'
var API_KEY = 'AIzaSyDRzu5JiW8javFaxTJjxjCyuqrW0Hw9aE8';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
var msg=document.querySelector('.msg')
let exceljson=[]
// Email
var sendemailcontainer=document.querySelector('.sendemailcontainer')
var myemail='[email protected]'
var tomail='[email protected]'
var mypassword='zjxvigwlatsvcurd'
var downloadExcelBtn=document.querySelector('#downloadExcelbtn')
let table = document.getElementById("table");
sendemailcontainer.classList.add('hider');
// Email Functions
//
// function submitform(e){
// e.preventDefault();
// var password=mypassword
// var msg='Trying to send the mail';
// sendemail(myemail,password,msg)
// document.querySelector('.contact-form').reset()
// }
// function sendemail(email,password,msg){
// Email.send({
// Host:'smtp.gmail.com',
// Username:myemail,
// Password:'zjxvigwlatsvcurd',
// To:'[email protected]',
// From:myemail,
// Subject:'Sending mail',
// Body:msg
// }).then((msg)=>{
// alert('mail successfully sent')
// })
// }
// document.querySelector('.contact-form').addEventListener('submit',submitform)
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
msg.innerHTML='';
msg.style.color='black';
table.innerHTML=''
sendemailcontainer.classList.add('hider');
}
// function sendMessage(reallyEncodedMessage)
// {
// gapi.client.gmail.users.messages.send({
// userId: 'me',
// resource: {
// // same response with any of these
// raw: reallyEncodedMessage
// // raw: encodedMessage
// // raw: message
// }
// }).then(function () { alert('Mail sent successfully')});
// }
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
var myvalues = []
// Function to represent client google sheet
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: document.getElementById('spreadsheetid').value,
range: 'Sheet1',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
console.log("Excel range is "+ range.values.length)
// alert(range.values[0].length)
tablecontainer=""
oursheet_ID=[]
for (let i = 0; i < range.values.length; i++) {
var row = range.values[i];
myvalues.push(row);
if(i!=0){
oursheet_ID.push(row[0])
}
tablecontainer+="<tr>"
for(let j=0;j<range.values[0].length;j++){
tablecontainer+=`<td> ${row[j]} </td>`
}
tablecontainer+="</tr>"
}
table.innerHTML=tablecontainer;
msg.style.color='green'
msg.innerHTML='Data is successfully loaded...'
runtheDatabase(oursheet_ID);
} else {
//appendPre('No data found.');
msg.style.color='red'
msg.innerHTML='No data found'
}
}, function(response) {
//appendPre('Error: ' + response.result.error.message);
msg.style.color='red'
msg.innerHTML=`Error: ${response.result.error.message}<br/>Sign out and AUTHORIZE again`
});
}
//Function to represent our google sheet
/* function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1CmII0O9SMaLSH7pSmi9nIgr4n54XqHzVNcpukWSqajQ',
range: 'Sheet1',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
console.log("Excel range is "+ range.values.length)
oursheet_ID=[]
for (let i=1;i<range.values.length;i++){
var row=range.values[i]
oursheet_ID.push(row[0])
}
runtheDatabase(oursheet_ID);
} else {
appendPre('Our data not found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
*/
function runtheDatabase(array) {
console.log(array)
var db = firebase.firestore();
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(
m,
key,
value
) {
vars[key] = value;
});
return vars;
}
let PROJECT_ID = getUrlVars()["projectid"];
// console.log(PROJECT_ID);
const EXCEL_TYPE=''
db.collection("Projects").where("ProjectNo", "==", PROJECT_ID).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
db.collection("Projects").doc(doc.id).collection("Reports").where("C_STATUS", "==", 10).get().then((querySnapshot) => {
querySnapshot.forEach((reportsDoc) => {
for (let index = 0; index < array.length; index++) {
let clientID = array[index];
let PID = reportsDoc.data().PID;
// console.log(PID)
if(PID == clientID){
// console.log(PID,":",clientID,`${typeof(PID)}:${typeof(clientID)}`)
// console.log("condition is becoming true")
db.collection("Projects").doc(doc.id).collection("Reports").doc(PID).update({
status: "Approved",
}, {merge:true})
.then((docRef) => {
// console.log(reportsDoc.data())
})
.catch((error) => {
console.error("Error adding document: ", error);
msg.style.color='red'
msg.innerHTML='Error adding document';
});
break;
} else{
db.collection("Projects").doc(doc.id).collection("Reports").doc(PID).update({
status: "Rejected",
}, {merge:true})
.then((docRef) => {
// console.log(reportsDoc.data())
})
.catch((error) => {
console.error("Error adding document: ", error);
msg.style.color='red'
msg.innerHTML='Error adding document';
});
}
}
});
});
})});
// Send Email with SMTP js
function sendEmail(url,mid,approvedcount,rejectedcount,totalcount,rejection_rate) {
Email.send({
Host: "smtp.gmail.com",
Username: "[email protected]",
Password: mypassword,
To: '[email protected]',
From: "[email protected]",
Subject: "Sending Email using javascript",
Body: `
<html>
<head>
<style>
table{
border-collapse:collapse;
}
th{
color:white;
background-color:black;
}
</style>
</head>
<body>
<p>Hi ${mid} Team,</p>
<p>Thank you for your support! Client has reviewed the data on this project and shared final IDs for this project. Please check the statistics below.</p>
<p><i>Data File — <a href='${url}'> Click here to access the file. </a> </i> </p>
<table border='1' cellspacing='10px'>
<tr>
<th>Status</th>
<th>N</th>
</tr>
<tr>
<td>Completed #</td>
<td>${totalcount}</td>
</tr>
<tr>
<td>Approved #</td>
<td>${approvedcount}</td>
</tr>
<tr>
<td>Rejected #</td>
<td>${rejectedcount}</td>
</tr>
<tr>
<td>Rejection Rate #</td>
<td>${rejection_rate} % </td>
</tr>
</table>
<p>Thank you very much!</p>
<p>Have a great day!</p>
<p>Thanks</p>
<p>{Project Manager Name}</p><br/>
</body>
</html>
`,
})
.then(function (message) {
console.log(`Mail has been sent successfully `)
});
}
db.collection("Projects").where("ProjectNo", "==", PROJECT_ID).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
db.collection("Projects").doc(doc.id).collection("Reports").where("C_STATUS", "==", 10).get().then((querySnapshot)=>{
querySnapshot.forEach((reportsDoc)=>{
the_data=reportsDoc.data()
exceljson.push(the_data)
})
console.log("Excel Json is ",exceljson)
var AllMID=new Set()
var summaryrejectedcount=0
var summaryapprovedcount=0
var summarytotalcount=0
for(let i=0;i<exceljson.length;i++){
console.log(exceljson[i].MID,typeof(exceljson[i].MID))
if(exceljson[i].MID!=undefined){
AllMID.add(exceljson[i].MID)
summarytotalcount+=1
if(exceljson[i].status=="Approved"){
summaryapprovedcount+=1
}
else{
summaryrejectedcount+=1
}
}
}
console.log("All MID are",AllMID)
console.log("Excel json file is ",exceljson)
create_excelFile=confirm("Do you want to create spreadsheets ") //Confirm Button
if(create_excelFile){
//Summary Excel File
var summaryfileName = `MIRATS${PROJECT_ID}_Summary.xlsx`;
// var myheader=['PID','MID','status']
// var ws = XLSX.utils.json_to_sheet(exceljson,{header:myheader});
// var wb = XLSX.utils.book_new();
// Summary File download
// XLSX.utils.book_append_sheet(wb, ws, 'output');
// XLSX.writeFile(wb, fileName);
gapi.client.sheets.spreadsheets.create({
properties: {
title: summaryfileName
}
}).then((response) => {
let mainarray=[]
// console.log("The actual MID ----------------- ",item)
let SPREADSHEET_ID=response.result.spreadsheetId;
// console.log("The whole data of Google sheet is ",response)
headers=Object.keys(exceljson[0])
mainarray.push(headers)
for (let j = 0; j < exceljson.length; j++) {
innerarray=[]
for (let i in exceljson[0]) {
innerarray.push(exceljson[j][i])
}
mainarray.push(innerarray)
}
// console.log('Result to google sheet is ',mainarray)
let values = mainarray
let body = {
values: values
};
mainarray=[]
// Excel Updating values
gapi.client.sheets.spreadsheets.values.update({
spreadsheetId: SPREADSHEET_ID,
range: 'Sheet1',
valueInputOption: 'USER_ENTERED',
resource: body
}).then((response) => {
var result = response.result;
LINK_FOR_SHARING=`https://docs.google.com/spreadsheets/d/${SPREADSHEET_ID}`
summary_rejection_rate=(summaryrejectedcount*100/summarytotalcount).toFixed(2)
sendEmail(LINK_FOR_SHARING,summaryfileName,summaryapprovedcount,summaryrejectedcount,summarytotalcount,summary_rejection_rate)
console.log(`${result.updatedCells} cells updated for Summary file.`);
});
});
//Excel file according to MID
let allmsgs=''
// for(item of AllMID){ // LMN, LM, JR
AllMID.forEach(item=>{
var excel_data=[]
var rejectedcount=0
var approvedcount=0
var totalcount=0
for(let i=0;i<exceljson.length;i++){
if (exceljson[i].MID==item){ //Segragating with MID
excel_data.push(exceljson[i])
totalcount+=1
//Counting approved and rejected count
if (exceljson[i].status=="Approved"){
approvedcount+=1
}else{
rejectedcount+=1
}
}
}
// console.log("Excel Data is ",excel_data)
console.log(`${item}: Approved count - ${approvedcount}, Rejected count: ${rejectedcount},Total Count: ${totalcount} `)
// console.log('present MID is ', item)
var fileName = `MIRATS${PROJECT_ID}_${item}.xlsx`; // Excel File Name
//Creating google sheets
gapi.client.sheets.spreadsheets.create({
properties: {
title: fileName
}
}).then((response) => {
let mainarray=[]
// console.log("The actual MID ----------------- ",item)
let SPREADSHEET_ID=response.result.spreadsheetId;
// console.log("The whole data of Google sheet is ",response)
headers=Object.keys(excel_data[0])
mainarray.push(headers)
for (let j = 0; j < excel_data.length; j++) {
innerarray=[]
for (let i in excel_data[0]) {
innerarray.push(excel_data[j][i])
}
mainarray.push(innerarray)
}
// console.log('Result to google sheet is ',mainarray)
var values = mainarray
var body = {
values: values
};
mainarray=[]
// Excel Updating values
gapi.client.sheets.spreadsheets.values.update({
spreadsheetId: SPREADSHEET_ID,
range: 'Sheet1',
valueInputOption: 'USER_ENTERED',
resource: body
}).then((response) => {
var result = response.result;
LINK_FOR_SHARING=`https://docs.google.com/spreadsheets/d/${SPREADSHEET_ID}`
rejection_rate=(rejectedcount*100/totalcount).toFixed(2)
sendEmail(LINK_FOR_SHARING,item,approvedcount,rejectedcount,totalcount,rejection_rate)
console.log(`${result.updatedCells} cells updated for ${item}`);
});
});
// Very Important because this code downloads Excel file according to MID
// var myheader=['PID','MID','status']
// var ws = XLSX.utils.json_to_sheet(excel_data,{header:myheader});
// var wb = XLSX.utils.book_new();
// XLSX.utils.book_append_sheet(wb, ws, 'output');
// XLSX.writeFile(wb, fileName,{type: 'buffer', bookType: 'xlsx'});
// var excel_filename=`MID_${item}.xlsx`
msg.style.color='green';
allmsgs+=`Excel File for MID:${item} updated Successfully<br/>`
});
//For loop Ends
msg.innerHTML=allmsgs
sendemailconfirm=confirm("Do you want to send email") //Send Email confirmation
if(sendemailconfirm){
// [START gmail_quickstart]
sendemailcontainer.classList.remove('hider')
// const message =
// `From: ${myemail}\r\n` +
// `To: ${tomail}\r\n` +
// "Subject: As basic as it gets\r\n\r\n" +
// "This is the plain text body of the message. Note the blank line between the header information and the body of the message.";
// const encodedMessage = btoa(message)
// const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
// console.log("Encoded msg : ",reallyEncodedMessage);
// // sendMessage(reallyEncodedMessage)
// anotherSendMessage(reallyEncodedMessage)
// sendEmail(excel_filename)
// [END gmail_quickstart]
}else{
endemailcontainer.classList.add('hider');
}
}
})
});
});
}
// SetTimeout: figure it out later
// setTimeout(function (){
// //console.log("All json values",exceljson)
// if (exceljson.length>0){
// downloadExcelBtn.classList.remove('hide')
// downloadExcelBtn.addEventListener('click',()=>{
// const fileName = 'output.xlsx';
// const myheader=['PID','MID','status']
// const ws = XLSX.utils.json_to_sheet(exceljson,{header:myheader});
// const wb = XLSX.utils.book_new();
// XLSX.utils.book_append_sheet(wb, ws, 'output');
// XLSX.writeFile(wb, fileName);
// msg.style.color='green'
// msg.innerHTML="Excel File downloaded Successfully"
// })
// }
// }, 5000)
// Email
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()"></script>
<!-- <script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()"> -->
</script>
<script>
</script>
</body>
</html>