diff options
author | Anton Luka Šijanec <sijanecantonluka@gmail.com> | 2020-09-27 22:11:50 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-27 22:11:50 +0200 |
commit | 80e48e2b88f85f03d88bf45a2f2b90e91e386c19 (patch) | |
tree | 944d1350550541f65ed70f906bfdb65fedef7e76 /dist/js/meals.js | |
parent | Merge pull request #27 from beziapp/dev (diff) | |
parent | changelog (diff) | |
download | beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar.gz beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar.bz2 beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar.lz beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar.xz beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.tar.zst beziapp-80e48e2b88f85f03d88bf45a2f2b90e91e386c19.zip |
Diffstat (limited to 'dist/js/meals.js')
-rwxr-xr-x | dist/js/meals.js | 35 |
1 files changed, 17 insertions, 18 deletions
diff --git a/dist/js/meals.js b/dist/js/meals.js index adaf275..fa25e40 100755 --- a/dist/js/meals.js +++ b/dist/js/meals.js @@ -1,30 +1,29 @@ -const API_ENDPOINT="https://lopolis-api.gimb.tk/";var meals_calendar_obj=null;var meals_data_global={};function getDateString(){let date=new Date();let year_str=date.getFullYear();let month_str=date.getMonth()+1 +const API_ENDPOINT="https://lopolis-api.gimb.tk/";var meals_calendar_obj=null;var meals_data_global={};var checkouts_data_global={};function getDateString(){let date=new Date();let year_str=date.getFullYear();let month_str=date.getMonth()+1 month_str=month_str.toString().padStart(2,"0");let day_str=date.getDate();day_str=day_str.toString().padStart(2,"0");let date_string=year_str+"-"+month_str+"-"+day_str;return date_string;} async function checkLogin(){localforage.getItem("logged_in_lopolis").then((value)=>{if(value!=true){$("#meals-container").hide();$("#meals-login-container").show();}else{$("#meals-container").show();$("#meals-login-container").hide();loadMeals();}}).catch((err)=>{console.log(err);});} function setLoading(state){if(state){$("#loading-bar").removeClass("hidden");}else{$("#loading-bar").addClass("hidden");}} -async function getToken(callback,callbackparams=[]){setLoading(true);let promises_to_run=[localforage.getItem("lopolis_username").then((value)=>{username=value;}),localforage.getItem("lopolis_password").then((value)=>{password=value;})];await Promise.all(promises_to_run);$.ajax({url:API_ENDPOINT+"gettoken",crossDomain:true,contentType:"application/json",data:JSON.stringify({"username":username,"password":password}),dataType:"json",cache:false,type:"POST",success:(dataauth)=>{if(dataauth==null||dataauth.error==true){UIAlert(D("authenticationError"),"getToken(): response error or null");localforage.setItem("logged_in_lopolis",false).then(function(){checkLogin();});}else if(dataauth.error==false){let empty={};empty.token=dataauth.data;let argumentsToCallback=[empty].concat(callbackparams);callback(...argumentsToCallback);}else{UIAlert(D("authenticationError"),"getToken(): invalid response, no condition met");} -setLoading(false);},error:()=>{UIAlert(D("lopolisAPIConnectionError"),"getToken(): AJAX error");setLoading(false);}});} -async function getMenus(dataauth,callback,callbackparams=[]){setLoading(true);let current_date=new Date();let mealsgathered={};let promises_to_wait_for=[];for(let iteration=1;iteration<=2;iteration++){promises_to_wait_for[iteration]=$.ajax({url:API_ENDPOINT+"getmenus",crossDomain:true,contentType:"application/json",data:JSON.stringify({"month":current_date.getMonth()+iteration,"year":current_date.getFullYear()}),headers:{"Authorization":`Bearer ${dataauth.token}`},dataType:"json",cache:false,type:"POST",success:(meals)=>{if(meals==null||meals.error==true){UIAlert(D("errorGettingMenus"),"getMenus(): response error or null");setLoading(false);localforage.setItem("logged_in_lopolis",false).then(()=>{checkLogin();});}else if(meals.error==false){setLoading(false);mealsgathered[iteration]=meals;}else{setLoading(false);UIAlert(D("errorUnexpectedResponse"),"getMenus(): invalid response, no condition met");}},error:()=>{setLoading(false);UIAlert(D("lopolisAPIConnectionError"),"getMenus(): AJAX error");}});} -await Promise.all(promises_to_wait_for);let allmeals={};let passtocallback={};for(const[index,monthmeals]of Object.entries(mealsgathered)){allmeals=mergeDeep(allmeals,monthmeals.data);} -passtocallback.data=allmeals;passtocallback.token=dataauth.token;let toBePassed=[passtocallback].concat(callbackparams);callback(...toBePassed);} +async function getToken(callback,callbackparams=[]){setLoading(true);let promises_to_run=[localforage.getItem("lopolis_username").then((value)=>{username=value;}),localforage.getItem("lopolis_password").then((value)=>{password=value;})];await Promise.all(promises_to_run);try{var lopolisClient=new lopolisc();var response=await lopolisClient.login(username,password);}catch(e){console.log(e);UIAlert(D("authenticationError"),"getToken(): invalid response, no condition met");await localforage.setItem("logged_in_lopolis",false);return false;} +await localforage.setItem("logged_in_lopolis",true);let empty={};empty.token={};let argumentsToCallback=[empty].concat(callbackparams);callback(...argumentsToCallback);} +async function getMenus(dataauth,callback,callbackparams=[]){setLoading(true);let passtocallback={};let allmeals,allcheckouts;let tries=3;while(true){try{let lopolisClient=new lopolisc();allmeals=await lopolisClient.fetchAllMeals();allcheckouts=await lopolisClient.fetchAllCheckouts();}catch(e){console.log(e);UIAlert(D("lopolisAPIConnectionError"),"getMenus(): AJAX error");if(tries--<0){return false;}else{continue;}} +break;} +passtocallback.data=allmeals;passtocallback.checkouts=allcheckouts;passtocallback.token="tokens-not-used-anymore";let toBePassed=[passtocallback].concat(callbackparams);callback(...toBePassed);} async function loadMeals(){getToken(getMenus,[displayMeals,[]]);} -function displayMeals(meals){meals_data_global=meals.data;let transformed_meals=[];for(const[date,mealzz]of Object.entries(meals.data)){let bg_color="#877F02";let fg_color="#FFFFFF";if(mealzz.readonly)bg_color="#8d9288";let meal_date=new Date(date+"+00:00");let meal_object={start:meal_date.toISOString().substring(0,10),title:S("meal"),id:date,allDay:true,backgroundColor:bg_color,textColor:fg_color} +function displayMeals(meals){meals_data_global=meals.data;checkouts_data_global=meals.checkouts;let transformed_meals=[];for(const[date,mealzz]of Object.entries(meals.data)){let bg_color="#877F02";let fg_color="#FFFFFF";if(mealzz.readonly)bg_color="#8d9288";let meal_date=new Date(date+"+00:00");let meal_object={start:meal_date.toISOString().substring(0,10),title:mealzz.meal,id:date,allDay:true,backgroundColor:bg_color,textColor:fg_color} transformed_meals.push(meal_object);} -meals_calendar_obj.removeAllEvents();meals_calendar_obj.addEventSource(transformed_meals);return;} +meals_calendar_obj.removeAllEvents();meals_calendar_obj.addEventSource(transformed_meals);setLoading(false);return;} function clearMeals(){meals_calendar_obj.removeAllEvents();} function refreshMeals(){clearMeals();loadMeals();} -function lopolisLogout(){localforage.setItem("logged_in_lopolis",false);$("#meals-collapsible").html("");checkLogin();} -async function lopolisLogin(){setLoading(true);var usernameEl=$("#meals-username");var passwordEl=$("#meals-password");$.ajax({url:API_ENDPOINT+"gettoken",crossDomain:true,contentType:"application/json",data:JSON.stringify({"username":usernameEl.val(),"password":passwordEl.val()}),dataType:"json",cache:false,type:"POST",success:async function(data){if(data==null){UIAlert(S("requestForAuthenticationFailed"),"lopolisLogin(): date is is null");setLoading(false);usernameEl.val("");passwordEl.val("");}else if(data.error==true){UIAlert(S("loginFailed"),"lopolisLogin(): login failed. data.error is true");usernameEl.val("");passwordEl.val("");setLoading(false);}else{let promises_to_run=[localforage.setItem("logged_in_lopolis",true),localforage.setItem("lopolis_username",usernameEl.val()),localforage.setItem("lopolis_password",passwordEl.val())];await Promise.all(promises_to_run);checkLogin();UIAlert("Credential match!");}},error:()=>{UIAlert(D("loginError"),"lopolisLogin(): ajax.error");setLoading(false);}});} -async function setMenus(currentmeals=69,toBeSentChoices){if(currentmeals===69){getToken(getMenus,[setMenus,toBeSentChoices]);return;} -for(const[mealzzdate,mealzz]of Object.entries(currentmeals.data)){if(mealzzdate in toBeSentChoices===false){for(const[mealid,mealdata]of Object.entries(mealzz.menu_options)){if(mealdata.selected==true||mealzz.readonly==true){toBeSentChoices[mealzzdate]=mealdata.value;break;}}}} -setLoading(true);$.ajax({url:API_ENDPOINT+"setmenus",crossDomain:true,contentType:"application/json",data:JSON.stringify({"choices":toBeSentChoices}),headers:{"Authorization":"Bearer "+currentmeals.token},dataType:"json",cache:false,type:"POST",success:(response)=>{if(response===null||response.error==true){UIAlert(D("errorSettingMeals"),"setMenus(): response error or null");}else if(response.error==false){UIAlert(D("mealSet"),"setMenus(): meni nastavljen");}else{UIAlert(D("errorUnexpectedResponse"),"setMenus(): invalid response, no condition met");} -setLoading(false);},error:()=>{setLoading(false);UIAlert(D("lopolisAPIConnectionError"),"setMenus(): AJAX error");}});} -async function setMenu(date,menu){let choice={};choice[date]=menu;getToken(getMenus,[setMenus,choice]);} +function lopolisLogout(){localforage.setItem("logged_in_lopolis",false).then(()=>{clearMeals();checkLogin();});} +async function lopolisLogin(){setLoading(true);var usernameEl=$("#meals-username");var passwordEl=$("#meals-password");try{let l=new lopolisc();await l.login(usernameEl.val(),passwordEl.val());}catch(e){UIAlert(D("loginError"),"lopolisLogin(): ajax.error");setLoading(false);return false;} +let promises_to_run=[localforage.setItem("logged_in_lopolis",true),localforage.setItem("lopolis_username",usernameEl.val()),localforage.setItem("lopolis_password",passwordEl.val())];await Promise.all(promises_to_run);checkLogin();UIAlert("Credential match!");return true;} function setupEventListeners(){$("#meals-login").click(()=>{lopolisLogin();});$("#meals-logout").click(()=>{lopolisLogout();});} -var mealClickHandler=(eventClickInfo)=>{let meal_date=eventClickInfo.event.id;let meal_object=meals_data_global[meal_date];$("#meal-type").text(meal_object.meal);let meal_date_obj=new Date(meal_date);$("#meal-date").text(dateString.longFormatted(meal_date_obj));if(!(meal_object.readonly)){document.getElementById("meal-readonly").style.display="none";}else{document.getElementById("meal-readonly").style.display="block";} +var mealClickHandler=(eventClickInfo)=>{let meal_date=eventClickInfo.event.id;let meal_object=meals_data_global[meal_date];$("#checkout_label").show();let can_do_checkout=true;let checkout_object;try{checkout_object=checkouts_data_global[meal_date];}catch(e){$("#checkout_label").hide();let can_do_checkout=false;} +if(checkout_object==undefined||checkout_object==null){can_do_checkout=false;} +console.log(checkout_object);if(can_do_checkout){let cc=$("#checkout_checkbox");cc[0].checked=!(checkout_object.checked);cc.off();cc.on("change",()=>{let l=new lopolisc();checkouts_data_global[meal_date].checked=!(cc[0].checked);setLoading(true);l.setCheckouts(checkouts_data_global).then(()=>{UIAlert(D("successfulCheckingInOut"),"successfulcheckinginout");setLoading(false);}).catch(()=>{UIAlert(D("errorCheckingInOut"),"errorcheckinginout");setLoading(false);});});cc.prop("disabled",checkout_object.readonly);} +$("#meal-type").text(meal_object.meal);let meal_date_obj=new Date(meal_date);$("#meal-date").text(dateString.longFormatted(meal_date_obj));if(!(meal_object.readonly)){document.getElementById("meal-readonly").style.display="none";}else{document.getElementById("meal-readonly").style.display="block";} document.getElementById("meal-options").innerHTML="";for(const[option_index,option_object]of Object.entries(meal_object.menu_options)){let menu_option_li_el=document.createElement("li");let menu_option_a_el=document.createElement("button");menu_option_a_el.innerText=option_object.text;let classlist="";if(option_object.selected!=null){if(option_object.selected){classlist="color: green; font-weight: bold";}} -menu_option_a_el.classList="waves-effect waves-light btn-large";menu_option_a_el.style="color: var(--color-text); background-color: rgba(0,0,0,0); line-height: 1.2; height:auto; "+classlist+" !important";menu_option_a_el.id="menu_index_"+option_index;if(!(meal_object.readonly)){menu_option_a_el.onclick=()=>{setMenu(meal_date,option_object.value);menu_option_a_el.className="to-be-selected-meal";let sidenav_element=document.getElementById("meal-info");let sidenav_instance=M.Sidenav.getInstance(sidenav_element);sidenav_instance.close();};} +menu_option_a_el.classList="waves-effect waves-light btn-large";menu_option_a_el.style="color: var(--color-text); background-color: rgba(0,0,0,0); line-height: 1.2; height:auto; "+classlist+" !important";menu_option_a_el.id="menu_index_"+option_index;if(!(meal_object.readonly)){menu_option_a_el.disabled=false;menu_option_a_el.onclick=()=>{setLoading(true);let l=new lopolisc();l.chooseMenu(meals_data_global[meal_date],option_index);l.setMeals(meals_data_global).then(()=>{UIAlert(D("mealSet"),"meal set!");setLoading(false);}).catch(()=>{UIAlert(D("errorSettingMeals"),"error setting meals");setLoading(false);});menu_option_a_el.className="to-be-selected-meal";let sidenav_element=document.getElementById("meal-info");let sidenav_instance=M.Sidenav.getInstance(sidenav_element);sidenav_instance.close();};}else{menu_option_a_el.disabled=true;} menu_option_li_el.appendChild(menu_option_a_el);document.getElementById("meal-options").appendChild(menu_option_li_el);} let sidenav_element=document.getElementById("meal-info");let sidenav_instance=M.Sidenav.getInstance(sidenav_element);sidenav_instance.open();} -document.addEventListener("DOMContentLoaded",async()=>{checkLogin();var calendarEl=document.getElementById("meals-calendar");meals_calendar_obj=new FullCalendar.Calendar(calendarEl,{firstDay:1,plugins:["dayGrid"],defaultDate:getDateString(),navLinks:false,editable:false,events:[],eventClick:mealClickHandler,height:"parent"});meals_calendar_obj.render();setupEventListeners();$("#refresh-icon").click(function(){refreshMeals();});const menus=document.querySelectorAll('.side-menu');M.Sidenav.init(menus,{edge:'right',draggable:true});const modals=document.querySelectorAll('.side-modal');M.Sidenav.init(modals,{edge:'left',draggable:false});document.getElementsByClassName("fc-today-button")[0].style="display:none !important";var elemsx=document.querySelectorAll('select');M.FormSelect.init(elemsx);var datepickerelems=document.querySelectorAll('.datepicker');var today=new Date();M.Datepicker.init(datepickerelems,{firstDay:1,minDate:today,showDaysInNextAndPreviousMonths:true,showClearBtn:true,format:"dddd, dd. mmmm yyyy"});refreshMeals();});
\ No newline at end of file +document.addEventListener("DOMContentLoaded",async()=>{await find_chosen_lang();checkLogin();var calendarEl=document.getElementById("meals-calendar");meals_calendar_obj=new FullCalendar.Calendar(calendarEl,{firstDay:1,plugins:["dayGrid"],defaultDate:getDateString(),navLinks:false,editable:false,events:[],eventClick:mealClickHandler,height:"parent"});meals_calendar_obj.render();setupEventListeners();$("#refresh-icon").click(function(){setLoading(true);refreshMeals();});const menus=document.querySelectorAll('.side-menu');M.Sidenav.init(menus,{edge:'right',draggable:true});const modals=document.querySelectorAll('.side-modal');M.Sidenav.init(modals,{edge:'left',draggable:false});document.getElementsByClassName("fc-today-button")[0].style="display:none !important";var elemsx=document.querySelectorAll('select');M.FormSelect.init(elemsx);var datepickerelems=document.querySelectorAll('.datepicker');var today=new Date();M.Datepicker.init(datepickerelems,{firstDay:1,minDate:today,showDaysInNextAndPreviousMonths:true,showClearBtn:true,format:"dddd, dd. mmmm yyyy"});});
\ No newline at end of file |