summaryrefslogtreecommitdiffstats
path: root/dist/js/meals.js
diff options
context:
space:
mode:
authorsijanec <sijanecantonluka@gmail.com>2020-09-23 18:37:16 +0200
committersijanec <sijanecantonluka@gmail.com>2020-09-23 18:37:16 +0200
commit616c225661687b05ab82160f5b7d6dcb4d39b8e6 (patch)
tree08cdbdf9e80784cea0c58981c656fe94ae821edc /dist/js/meals.js
parentjson bi lahko preveril (diff)
downloadbeziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar.gz
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar.bz2
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar.lz
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar.xz
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.tar.zst
beziapp-616c225661687b05ab82160f5b7d6dcb4d39b8e6.zip
Diffstat (limited to 'dist/js/meals.js')
-rwxr-xr-xdist/js/meals.js25
1 files changed, 14 insertions, 11 deletions
diff --git a/dist/js/meals.js b/dist/js/meals.js
index 6bec928..514f040 100755
--- a/dist/js/meals.js
+++ b/dist/js/meals.js
@@ -1,5 +1,7 @@
-const API_ENDPOINT="https://lopolis-api.gimb.tk/";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);});}
+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
+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);}});}
@@ -7,21 +9,22 @@ async function getMenus(dataauth,callback,callbackparams=[]){setLoading(true);le
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 loadMeals(){getToken(getMenus,[displayMeals,[]]);}
-function displayMeals(meals){let root_element=document.getElementById("meals-collapsible");for(const[date,mealzz]of Object.entries(meals.data)){let unabletochoosequestionmark="";let readonly=mealzz.readonly;var datum=new Date(date);let subject_entry=document.createElement("li");let subject_header=document.createElement("div");subject_header.classList.add("collapsible-header");subject_header.classList.add("collapsible-header-root");let subject_header_text=document.createElement("span");if(mealzz.readonly){unabletochoosequestionmark=`*${S("readOnly")}*`;}
-subject_header_text=`${dateString.day(datum.getDay())}, ${datum.getDate()}. ${dateString.month(datum.getMonth())} ${datum.getFullYear()} (${mealzz.meal} @ ${mealzz.location}) ${unabletochoosequestionmark}`;let subject_body=document.createElement("div");subject_body.className="collapsible-body";let subject_body_root=document.createElement("ul");subject_body_root.className="collection";for(const[dindex,dmil]of Object.entries(mealzz.menu_options)){let meal_node=document.createElement("li");meal_node.className="collection-item";meal_node.classList.add("collection-item")
-meal_node.classList.add("meal-node");meal_node.dataset["index"]=dindex;if(!readonly){meal_node.onclick=()=>{setMenu(date,dmil.value);}}
-let meal_node_div=document.createElement("div");let meal_lefttext=document.createElement("span");let meal_righttext=document.createElement("div");meal_righttext.className="secondary-content";if(dmil.selected){meal_lefttext.innerHTML=`<i>${dmil.text}</i>`;meal_righttext.innerText=S("selected");}else{meal_lefttext.innerText=dmil.text;meal_righttext.innerText="";}
-meal_node_div.appendChild(meal_lefttext);meal_node_div.appendChild(meal_righttext);meal_node.appendChild(meal_node_div);subject_body_root.appendChild(meal_node);}
-var subject_header_text_span=document.createElement("span");subject_header_text_span.innerText=subject_header_text;subject_header.appendChild(subject_header_text_span);subject_body.append(subject_body_root);subject_entry.append(subject_header);subject_entry.append(subject_body);root_element.append(subject_entry);}
-$("#meals-collapsible").append(root_element);}
-function clearMeals(){const table=document.getElementById("meals-collapsible");while(table.firstChild){table.removeChild(table.firstChild);}}
+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}
+transformed_meals.push(meal_object);}
+meals_calendar_obj.removeAllEvents();meals_calendar_obj.addEventSource(transformed_meals);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)){console.log(mealdata);if(mealdata.selected==true||mealzz.readonly==true){toBeSentChoices[mealzzdate]=mealdata.value;break;}}}}
+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 setupEventListeners(){$("#meals-login").click(()=>{lopolisLogin();});$("#meals-logout").click(()=>{lopolisLogout();});}
-document.addEventListener("DOMContentLoaded",async()=>{checkLogin();setupEventListeners();let coll_elem=document.querySelectorAll('.collapsible');M.Collapsible.init(coll_elem,{});$("#refresh-icon").click(function(){refreshMeals();});let elems=document.querySelectorAll('.modal');M.Modal.init(elems,{});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});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
+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";}
+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("a");menu_option_a_el.innerText=option_object.text;if(option_object.selected!=null){if(option_object.selected){menu_option_a_el.className="selected-meal";}}
+menu_option_a_el.style="waves-effect";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_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});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