-
Notifications
You must be signed in to change notification settings - Fork 0
/
amisMenuJs.html
800 lines (685 loc) · 30.2 KB
/
amisMenuJs.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
<script>
//http://mikecostello.github.io/jquery-slide-text-left/
!function(e){function t(t,n,d,a){n.delay(d).animate({width:"toggle"},e.proxy(n.text,n,t)).animate({width:"toggle"},a)}e.fn.slideTextLeft=function(n,d){var a=!1,o=e.fn.slideTextLeft.defaults;return"number"==typeof d&&(o.delay=d),e.isArray(n)?o.words=n:"string"==typeof n?(o.words=n,a=!0):e.isPlainObject(n)&&(o=e.extend({},e.fn.slideTextLeft.defaults,n)),this.each(function(){var n=e(this),d=n.text(),s=e.meta?e.extend({},o,n.data()):o,i=0;s.words.length&&(n.css({"white-space":"nowrap",overflow:"hidden","vertical-align":"bottom"}),d.length&&d!==s.words[0]||(n.text(s.words[0]),i=1),function e(){var d=a?s.words:s.words[i],o=a?null:e;t(d,n,s.delay,o),i=(i+1)%s.words.length}())})},e.fn.slideTextLeft.defaults={words:[],delay:2e3}}(jQuery);
</script>
<script>
var hideLoading, showLoading, userToken;
/**
* firebase user data
* @type {Object}
*/
var user_data = {};
//-----------------------------------------------------------------
// Initialize Firebase
//-----------------------------------------------------------------
var config = {
apiKey: "<?= apiKey ?>",
authDomain: "<?= dbName ?>.firebaseapp.com",
databaseURL: "https://<?= dbName ?>.firebaseio.com",
projectId: "<?= dbName ?>",
storageBucket: "<?= dbName ?>.appspot.com",
messagingSenderId: "924659512730",
sidebarNetworkErrorMsg:"There is a problem with the network, please try again later.",
devMode:<?= (devMode)?>,
isMaster:(<?=isMaster?>==='true'),
spreadSheetId: "<?= spreadSheetId ?>"
};
firebase.initializeApp( config );
//-----------------------------------------------------------------
// END Initialize Firebase
//-----------------------------------------------------------------
/**
* list of countries
* @type {[string]}
*/
var countries=[
];
/**
* countryAccount firebase object
* @type {Object}
*/
var countryAccount={};
/**
* show the loading spinner
* @param {array(string)} loadingTextStrings array with the loading texts to show during the loading
*/
showLoading = function(loadingTextStrings) {
loadingTextStrings=(loadingTextStrings || ["Loading"]);
$('#loadingText').empty().append("<h4></h4>");
$('#loadingText h4').slideTextLeft(loadingTextStrings);
$('#loading').show();
};
/**
* callBack For All google script calls
*/
hideLoading = function() {
$('#loading').hide();
};
/**
* callback WITH PROTECTION SHEET
* @deprecated not used
*/
hideLoadingWithProtection = function() {
//this protect the sheet and avoid script error
google.script.run.withSuccessHandler(hideLoadingDiv).LIB_FUNC( "AmisMarketApp.protectSheet");
};
hideLoadingWithLoadData = function() {
//this protect the sheet and avoid script error
google.script.run.withSuccessHandler(hideLoading).LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startFetchMaster",'',true, $( "#countryName" ).val(),false);
};
hideLoadingWithDeleteData = function() {
//this protect the sheet and avoid script error
google.script.run.withSuccessHandler(hideLoading).LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startFetchMaster",'',true, $( "#countryName" ).val(),true);
};
/**
* hide the loading spinner
*/
hideLoadingDiv = function() {
$('#loading').hide();
};
/**
* get the sheet config from firebase
* @param {string} sheetId the sheetId, current spreadsheet will be used if undefined
* @param {function} onSuccess callback called with the countryRegister object
* @return {Promise}
* @throws {InvalidArgument}
*/
function getSheetConfig(sheetId, onSuccess) {
if (!sheetId) {
throw "InvalidArgument";
}
return firebase.database().ref('config/countries/'+sheetId).once('value');
}
/**
* reads all the countries in firebase
* @param {function} onSuccess callback called with the countryRegister object
* @return {void}
*/
function getAllCountries(onSuccess) {
firebase.database().ref('/config/countryRegister').once('value').then(function(value) {
onSuccess(value);
});
}
/**
* get the countryLabel node from firebase
* @param {function} onSuccess callback called with the countryRegister object
* @return {void}
*/
function getCountryLabels(onSuccess) {
firebase.database().ref('/config/countryLabels').once('value').then(function(value) {
onSuccess(value);
});
}
/**
* populate the countryName select and the countries global array from firebase
* @param {Function} callback callback called on finish, no params
* @return {void}
*/
function populateCountries(callback) {
getCountryLabels(function(data){
var countryLabels=data.val();
for (var country in countryLabels) {
if (countryLabels.hasOwnProperty(country)) {
$('#countryName').append('<option value="'+ country +'">'+ countryLabels[country] +'</option>');
countries.push(country);
}
}
callback();
});
}
/**
* gets the countryAccount in firebase
* @param {Function} callback callback called on finish, taking countryAccount as param
* @return {void}
*/
function getCountryAccount(callback) {
firebase.database().ref('/config/countryAccount').once('value').then(function(data) {
countryAccount=data.val();
callback(data.val());
});
}
/**
* populate the account select
* @param {Function} callback callback called on finish, no params
* @return {void}
*/
function populateAccount(callback) {
getCountryAccount(function(data){
var _email;
countryAccount=data;
for (var country in data) {
if (data.hasOwnProperty(country) && data[country].toString()!=="false") {
_email=data[country];
$("#account").append('<option value="'+ _email +'">'+ _email +'</option>');
}
}
callback();
})
}
/**
* onLogged events
* @param {object} user The signed-in user info
* @param {function} onSuccess callback called if successfully logged in
*/
function onLoggedState(user, onSuccess){
onSuccess=(onSuccess || function(){});
console.log( 'user logged', user );
//change the sidebarmenu
//google.script.run.changeSidebar();
//----------------------------------
//hide form show menu logged in
//----------------------------------
//google.script.run.hideShow();
firebase.database().ref('/users_data/' + user.email.replace(/\./g, "%")).once('value').then(function(snapshot) {
user_data = snapshot.val();
if(!user_data){
//alert("User "+user.email+" is not authorized!");
google.script.run.LIB_FUNC( "AmisMarketApp.Utility.popUpAlert", "User "+user.email+" is not authorized!");
google.script.host.close();
return;
}
console.log('USER_DATA', user_data);
$(".isSecretariat").toggle(user_data.type==="secretariat");
$(".isAdmin").toggle(user_data.type==="admin");
$(".isAdmin.isSecretariat").toggle(user_data.type==="secretariat" || user_data.type==="admin");
$(".isMaster").toggle(config.isMaster);
$(".isNotMaster").toggle(!config.isMaster);
//set user name into label
$( "#userLabel" ).text( user.email );
if ( user_data.type==="admin" ) {
//show create country sheet
$( "#create-sheet-form" ).show();
populateCountries(function(){
populateAccount(function() {
});
});
} else {
//show normal menu
$( "#userActionsDiv" ).show();
}
//----------------------------------
//END --hide form show menu logged in
//----------------------------------
console.info( 'user', user.uid );
//.then is used to get the token value
$.when(user.getToken(), getSheetConfig(config.spreadSheetId))
.then( function( data, sheetConfig ) {
userToken=data;
sheetConfig=sheetConfig.val();
sYear=sheetConfig.year;
console.log( 'gettoken', data );
google.script.run.LIB_FUNC( "AmisMarketApp.FirebaseConnector.setToken", data );
// Store in session the token
google.script.run.LIB_FUNC( "AmisMarketApp.onLogin" );
//sets fc button labels
$("#addFrcA .season-label").text(sYear-1+"/"+(sYear-2000));
$("#addFrcB .season-label").text(sYear+"/"+(sYear+1-2000));
checkIfValidSpreadSheetYear(function(){
$( "#loading" ).hide();
});
onSuccess();
} );
}, function(error){
google.script.run.LIB_FUNC( "AmisMarketApp.Utility.popUpAlert", "User "+user.email+" is not authorized!");
google.script.host.close();
});
}
/**
* verify the token, refresh it if expired then call the callback
* @param {Function} callback
*/
function verifyToken(callback) {
firebase.auth().currentUser.getToken( /* forceRefresh */).then( function( idToken ) {
callback();
} ).catch( function( error ) {
//refresh the token
firebase.auth().currentUser.getToken(true).then(function(idToken) {
console.log('refresh token ok', idToken);
google.script.run.LIB_FUNC( "AmisMarketApp.FirebaseConnector.setToken", idToken );
callback();
}).catch(function(error) {
console.log('refresh token ko', error);
});
} );
}
/**
* show a popup with the google login
* @param {function} onSuccess callback called if successfully logged in
*/
function loginWithGoogle(onSuccess) {
onSuccess=(onSuccess || function(){});
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup( provider ).then( function( result ) {
onLoggedState(result.user, onSuccess);
} ).catch( function( error ) {
console.log('ERROR', error);
if (error.code && error.code==="auth/operation-not-supported-in-this-environment") {
google.script.run.LIB_FUNC("AmisMarketApp.Utility.popUpAlert", "Your browser is not supported. Please use Chrome or Firefox.");
google.script.host.close();
return;
} else if(error.code && /^auth\/.*/.test(error.code) && error.code!=="auth/popup-blocked"){
google.script.run.LIB_FUNC("AmisMarketApp.Utility.popUpAlert",error.message+"\\nPlease try to reopen the sidebar.");
google.script.host.close();
return;
}
//alert("User "+error.email+" is not authorized!");
google.script.run.LIB_FUNC( "AmisMarketApp.Utility.popUpAlert",'Something went wrong with the login or the network doesn\'t work.\\nPlease ensure that popup lock is DISABLED. Then try again.');
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
var debugMailMsg=
"Google Login failed <br>"+
"<b>errorCode</b>: " + error.code+"<br>"+
"<b>errorMessage</b>: " + error.message+"<br>"+
"<b>email</b>: " + error.email+"<br>"+
"<b>credential</b>: " + error.credential;
debugEmail(debugMailMsg);
} );
}
/**
* send a debug email with as much as info as possible
* @param {string} msg detail to add to the email
* @return {void}
*/
function debugEmail(msg) {
var emailMsg="";
emailMsg=msg+"<br>"+
"<b>User agent</b>: "+navigator.userAgent+"<br>"+
"<b>Sidebar Stacktrace</b>: "+(new Error()).stack;
google.script.run.LIB_FUNC( "AmisMarketApp.Utility.sendErrorEmails", emailMsg);
}
/**
* not used in the code, just for use in the browser console
*/
function logout(){
firebase.auth().signOut()
}
/**
* sets a wrong token (development use)
*/
function wrongToken(){
google.script.run.LIB_FUNC( "AmisMarketApp.FirebaseConnector.setToken", 123 );
userToken=123;
console.log("Set a wrong token");
}
/**
* save all the data in all sheets to firebase
* @return {void}
*/
function saveAllSheet() {
showLoading(["Saving data", "Sending data to the database", "Synchronizing the sheet"]);
google.script.run
.withSuccessHandler(hideLoading)
.withFailureHandler( function(error){
if (error.message==="InvalidSheetData") {
hideLoading();
} else {
googleScriptRunFailureHandler(saveAllSheet)(error);
}
} )
.LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startSync", userToken );
//disable the button himself
$( "#addFrcA" ).prop( "disabled", false );
$( "#addFrcB" ).prop( "disabled", false );
}
/**
* verify the data on the sheet
*/
function verifySheet() {
showLoading(["Verifying the sheet", "Doing a style check", "Restoring the formulas", "Checking the values"]);
google.script.run
.withSuccessHandler(hideLoading)
.withFailureHandler(hideLoading)
.LIB_FUNC( "AmisMarketApp.ProtectionMaker.validateSheet" );
}
/**
* overwrite sheet's data with firebase data
* @param {object} event jQuery event
* @param {bool} forceload (default false) if true doesn't ask the user for loading data
* @return {void}
*/
function fetchData(event,forceload) {
forceload=(forceload || false);
showLoading(["Loading data from the database", "Synchronizing the sheet"]);
google.script.run
.withSuccessHandler( hideLoading )
.withFailureHandler( googleScriptRunFailureHandler(function(){
fetchData(null, true);
}))
.LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startFetch", userToken, forceload );
}
/**
* show old forecast
* @return {void}
*/
function showHistoricalSeries() {
showLoading(["Showing historical series"]);
google.script.run.withSuccessHandler( hideLoading ).LIB_FUNC( "AmisMarketApp.ForecastUtility.showOldForecasts" );
}
/**
* hoide old forecast
* @return {void}
*/
function hideHistoricalSeries() {
showLoading(["Hiding historical series","Hiding forecasts"]);
google.script.run.withSuccessHandler( hideLoading ).LIB_FUNC( "AmisMarketApp.ForecastUtility.hideOldAndUnactiveForecast", userToken );
}
/**
* closure failure handler to manage network Errors
* @param {function} retryCalback callback to execute after successfully refreshed the token
* @return {function} the failure callback
*/
function googleScriptRunFailureHandler( retryCalback ) {
return function(error){
error=(error || "");
console.log('ERROR', error);
//token expired
if ( error.hasOwnProperty( "message" ) && ( error.message === "Network401Error" ) ) {
loginWithGoogle(retryCalback);
} else if(error === "NetworkError: Connection failure due to HTTP 0") {
alert( config.sidebarNetworkErrorMsg );
hideLoading();
} else {
//error managed by the Library
hideLoading();
debugEmail(error);
}
};
}
/**
* create google sheet function
* @return {void}
*/
function createSheet() {
var countryName = $( "#countryName" ).val();
var account = $( "#account" ).val();
if (countryName==='all') {
createAllSpreadsheet(account);
} else {
//prevent redirect actions
showLoading(["Creating the sheet", "Sharing the sheet with the user", "Sending the email to the user"]);
google.script.run
.withSuccessHandler( hideLoadingWithDeleteData )
.withFailureHandler( googleScriptRunFailureHandler(createSheet) )
.LIB_FUNC( "AmisMarketApp.ShareSheet.createSheet", countryName, account, userToken );
}
return false;
}
/**
* change event on COUNTRY SELECTED
* @param {object} event the event
* @return {void}
*/
function countryChange(event) {
//selected value
var valueSelected = event.target.value;
if((valueSelected != '') && (valueSelected != 'all')) {
showLoading(["Updating Master","Updating Master"]);
google.script.run
.withSuccessHandler(hideLoadingWithLoadData)
.withFailureHandler( googleScriptRunFailureHandler(function(){
countryChange(event);
}))
.LIB_FUNC("AmisMarketApp.MasterUtility.writeNoteAndDataForCountriesMaster",valueSelected,false);
}
}
/**
* creates all spreadsheet for each country
* @param {string} account account email
* @param {number} countryIndex don't put it, leave undefined
* @return {void}
*/
function createAllSpreadsheet(account, countryIndex) {
countryIndex=(countryIndex || 0);
if (!countries[countryIndex] || !account) {
hideLoading();
return;
}
createNationalSpreadsheet(countries[countryIndex], account, function(){
createAllSpreadsheet(account, countryIndex+1)
});
}
/**
* crate a national spreadsheet and share it with the user
* @param {string} country the country, NO UPPERCASE
* @param {string} account account email
* @param {Function} callback callback to execute if all the processes succeded
* @return {void}
*/
function createNationalSpreadsheet(country, account, callback) {
callback=(callback || function(){});
if (!country || !account) {
return;
}
showLoading(["Updating Master","Updating Master"]);
// Preparing the spreadsheet-------------------------
console.log("Preparing the spreadsheet for "+country);
google.script.run
.withSuccessHandler(function(){
// Loading data-------------------------
console.log("Loading data for "+country);
google.script.run
.withSuccessHandler(function(){
//Creating the spreadsheet-------------------------
console.log("Creating the spreadsheet for "+country);
google.script.run
.withSuccessHandler( function(){
//Erasing spreadsheet data-------------------------
console.log("Erasing spreadsheet data of "+country);
google.script.run.
withSuccessHandler(function(){
console.log("Created the spreadsheet for "+country);
callback();
})
.withFailureHandler(function(error){
console.error("Failed Erasing spreadsheet data of "+country, error);
})
.LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startFetchMaster",'',true, country,true);
} )
.withFailureHandler( function(error){
console.error("Failed creating the spreadsheet for "+country, error);
} )
.LIB_FUNC( "AmisMarketApp.ShareSheet.createSheet", country, account, userToken );
})
.withFailureHandler(function(error){
console.error("Failed loading data for "+country, error);
})
.LIB_FUNC( "AmisMarketApp.SyncMasterSheet.startFetchMaster",'',true, country,false);
})
.withFailureHandler( googleScriptRunFailureHandler(function(error){
console.error("Failed preparing the spreadsheet for "+country, error);
}))
.LIB_FUNC("AmisMarketApp.MasterUtility.writeNoteAndDataForCountriesMaster",country,false);
}
/**
* start the excel exportation and download the generated excel file
* @return {void}
*/
function excelExport() {
//prevent redirect actions
showLoading(["Creating the excel file", "writing data to the excel file", "Prepare the file to download"]);
google.script.run
.withSuccessHandler(function(spreadSheetId){
window.location='https://docs.google.com/spreadsheets/d/'+spreadSheetId+'/export?exportFormat=xlsx';
hideLoading();
})
.withFailureHandler( googleScriptRunFailureHandler(excelExport))
.LIB_FUNC("AmisMarketApp.ExcelExport.startExport",userToken);
}
/**
* opens the excelExport spreadsheet in a new window
* @return {void}
*/
function openExcelExportSpreadsheet() {
//prevent redirect actions
showLoading(["Connecting to firebase","Reading data from firebase"]);
google.script.run
.withSuccessHandler(function(spreadSheetId){
var url='https://docs.google.com/spreadsheets/d/'+spreadSheetId;
window.open(url,'_blank');
hideLoading();
})
.withFailureHandler( googleScriptRunFailureHandler(openExcelExportSpreadsheet))
.LIB_FUNC("AmisMarketApp.ExcelExport.getExcelExportSheetId",undefined, userToken);
}
/**
* opens the firebase config node of this spreadsheet in a new window
* @return {void}
*/
function openFirebaseCountryConfigNode() {
//prevent redirect actions
showLoading(["Connecting to firebase","Reading data from firebase"]);
google.script.run
.withSuccessHandler(function(node){
var url='https://console.firebase.google.com/project/'+config.projectId+'/database/data/'+node;
window.open(url,'_blank');
hideLoading();
})
.withFailureHandler( googleScriptRunFailureHandler(openFirebaseCountryConfigNode))
.LIB_FUNC("AmisMarketApp.FirebaseConnector.getSheetConfigNode");
}
/**
* removes all spreadsheet from firebase: empty countries node and set all countryRegister property to 'false'. This function doesn't erase the data node
* @return {void}
*/
function removeAllSpreadsheetsFromFb() {
if (!confirm("Want to removes all spreadsheet from firebase?")) {
return false;
}
//prevent redirect actions
showLoading(["Connecting to firebase","Removing data from firebase"]);
google.script.run
.withSuccessHandler(function(){
hideLoading();
})
.withFailureHandler( googleScriptRunFailureHandler(removeAllSpreadsheetsFromFb))
.LIB_FUNC("AmisMarketApp.ShareSheet.removeAllSpreadsheetsFromFb", userToken);
return false;
}
/**
* update the mapping on firebase (batchRowArray & batchRowColumn)
* @return {void}
*/
function updateFbMapping() {
//prevent redirect actions
showLoading(["Connecting to firebase","Updating data to firebase"]);
google.script.run
.withSuccessHandler(function(){
hideLoading();
})
.withFailureHandler( googleScriptRunFailureHandler(updateFbMapping))
.LIB_FUNC("AmisMarketApp.AmisNamedRanges.DbMapping.updateFbMapping", userToken);
return false;
}
/**
* reads All NamedRanges and print them in console
* @return {void}
*/
function getAllNamedRanges() {
//prevent redirect actions
showLoading(["Reading"]);
google.script.run
.withSuccessHandler(function(data){
console.log('namedRanges', data);
hideLoading();
})
.LIB_FUNC("AmisMarketApp.AmisNamedRanges.getAllNamedRanges");
return false;
}
/**
* che if the year of season is correct
*
* @param {function} callback callback to run
* @returns {void}
*/
function checkIfValidSpreadSheetYear(callback){
//prevent redirect actions
google.script.run
.withSuccessHandler(function(valid){
if (!valid) {
google.script.run.LIB_FUNC("AmisMarketApp.Utility.popUpAlert","The year of seasons seems to be outdated.\\nThe AMIS administrator has been notified.");
debugEmail("Year of season invalid");
google.script.host.close();
return;
}
callback();
})
.withFailureHandler(function(error){
googleScriptRunFailureHandler(checkIfValidSpreadSheetYear)(error);
})
.LIB_FUNC("AmisMarketApp.Seasons.isValidSpreadSheetYear", userToken);
}
/**
* change the seasons of the forecasts by adding a new year
* @return {void}
*/
function addYear(){
//prevent redirect actions
showLoading(["Reading database", "Switching forecasts", "Creating new season", "Saving data"]);
google.script.run
.withSuccessHandler(function(data){
hideLoading();
})
.withFailureHandler(function(error){
if (error.message==="InvalidSpreadSheetYear") {
hideLoading();
} else {
googleScriptRunFailureHandler(addYear)(error);
}
} )
.LIB_FUNC("AmisMarketApp.Seasons.changeSeason", userToken);
return false;
}
$( document ).ready( function() {
var unsubOnAuthStateChanged=firebase.auth().onAuthStateChanged(function(user) {
console.log('UNSUBONAUTHSTATECHANGED');
window.user=user;
// unsubOnAuthStateChanged();
if (user) {
console.log('USER authenticated', user);
onLoggedState(user);
} else {
loginWithGoogle();
}
});
//binding SAVE function with AMIS MARKET API
$( "#buttonSave" ).click(saveAllSheet);
$("#buttonVerify").click(verifySheet);
$( "#addFrcA" ).bind( "click", function() {
showLoading(["Loading sheet's data","Creating the new forecast", "Saving the data", "Sending data to the database"]);
verifyToken(function(){
//google.script.run.withSuccessHandler(hideLoadingWithProtection).LIB_FUNC( "AmisMarketApp.ForecastUtility.addForecast16_17", userToken);
google.script.run.withSuccessHandler(hideLoading).LIB_FUNC( "AmisMarketApp.ForecastUtility.addNewForecast", 0);
});
//disable the button himself
$( "#addFrcA" ).prop( "disabled", true );
} );
$( "#addFrcB" ).bind( "click", function() {
showLoading(["Loading sheet's data","Creating the new forecast", "Saving the data", "Sending data to the database"]);
verifyToken(function(){
//google.script.run.withSuccessHandler(hideLoadingWithProtection).LIB_FUNC( "AmisMarketApp.ForecastUtility.addForecast17_18", userToken);
google.script.run.withSuccessHandler(hideLoading).LIB_FUNC( "AmisMarketApp.ForecastUtility.addNewForecast", 1);
});
//disable the button himself
$( "#addFrcB" ).prop( "disabled", true );
} );
//binding FETCH function with AMIS MARKET API
$("#buttonFetch").click(fetchData);
//bind create google sheet function
$( "#createSheetButton" ).click( createSheet);
//bind Show/hide historical series
$("#showHistoricalSeries").click(showHistoricalSeries);
$("#hideHistoricalSeries").click(hideHistoricalSeries);
//on change event on COUNTRY SELECTED
$("#countryName").change(countryChange);
//start the excel exportation and download the generated excel file
$("#excelExportBtn").click(excelExport);
$("#removeAllSpreadsheetsBtn").click(removeAllSpreadsheetsFromFb);
$("#updateFbMappingBtn").click(updateFbMapping);
$("#addYear").click(addYear);
} )
</script>