diff --git a/printserver/OrderSprinterPrintserver.exe b/printserver/OrderSprinterPrintserver.exe index 5c1a6e1..c9285f0 100644 Binary files a/printserver/OrderSprinterPrintserver.exe and b/printserver/OrderSprinterPrintserver.exe differ diff --git a/webapp/OrderSprinterPrintserver.exe b/webapp/OrderSprinterPrintserver.exe index 5c1a6e1..c9285f0 100644 Binary files a/webapp/OrderSprinterPrintserver.exe and b/webapp/OrderSprinterPrintserver.exe differ diff --git a/webapp/bar.html b/webapp/bar.html index 7afb156..3233eb9 100644 --- a/webapp/bar.html +++ b/webapp/bar.html @@ -5,7 +5,7 @@ - + diff --git a/webapp/bill.html b/webapp/bill.html index 9b2abba..12a721d 100644 --- a/webapp/bill.html +++ b/webapp/bill.html @@ -5,7 +5,7 @@ - + @@ -82,6 +82,10 @@ var BILL_STORNO_REASON = ["Stornogrund","Reason","Razón"]; var BILL_TOGGLE_HOST = ["Der ursprüngliche Bon wurde storniert und mit geänderter Bewirtungseigenschaft neu angelegt. Er befindet sich an erster Stelle in der Bonliste.", "Der original receipt was discarded and recreated with the changed guest receipt property. The new receipt is on top of the list", "El tique original esta descartado y iniciado de nuevo en la forma modificada"];; +var BILL_WRONG_FORMAT = ["Falsches Zahlenformat","Wrong number format","Formato de precio incorecto"]; +var BILL_FIRST_JOB = ["Erste Bon-ID","First job id","Id primero"]; +var BILL_LAST_JOB = ["Letzte Bon-ID","Last job id","Id último"]; +var BILL_BATCH = ["Stapelverarbeitung","Batch processing","Accion con muchos elementos"]; var lang = 0; @@ -101,6 +105,11 @@ function setLanguage(language) { $("#billnocancelposs").html(BILL_NO_CANCEL_POSS[lang]); $("#datetxt").html(BILL_DATE[lang]); $("#stornoreasontxt").html(BILL_STORNO_REASON[lang]); + + $("#printjobstxt").html(BILL_PRINT[lang]); + $("#fromjobidtxt").html(BILL_FIRST_JOB[lang]); + $("#tojobidtxt").html(BILL_LAST_JOB[lang]); + $("#batchheadertxt").html(BILL_BATCH[lang]); var langtxt = "de"; if (lang == 1) { @@ -129,6 +138,29 @@ function updatelistener() { }); } +function batchjoblistener() { + $("#printjobsbtn").off("click").on("click", function (e) { + e.stopImmediatePropagation(); + e.preventDefault(); + var start = $("#fromjobidfield").val(); + var end = $("#tojobidfield").val(); + + if (!isInt(start) || !isInt(end)) { + alert(BILL_WRONG_FORMAT[lang]); + return; + } + doAjax("POST","php/contenthandler.php?module=printqueue&command=batchReceiptPrintJob",{start : start, end:end }, handleBatchResult, null); + }); +} + +function handleBatchResult(answer) { + if (answer.status != "OK") { + alert("Fehler " + answer.code + ": " + answer.msg); + } else { + $("#fromjobidfield").val(""); + $("#tojobidfield").val(""); + } +} function getLastBills() { var date = $("#datepicker").datepicker("getDate"); @@ -360,7 +392,13 @@ function insertGenConfigStartRest(configResult) { setLanguage(values.userlanguage); getLastBills(); updatelistener(); + batchjoblistener(); bindWhenSelection(); + + if (values.payprinttype == "s") { + // REM* only then allow batch processing + $("#batchpanel").show(); + } } else { setTimeout(function(){document.location.href = "index.html"},250); // not logged in } @@ -383,6 +421,8 @@ $(document).on("pageinit", "#bill-page", function () { hideMenu(); $.ajaxSetup({ cache: false }); getGeneralConfigItems(); + $("#fromjobidfield").val(""); + $("#tojobidfield").val(""); }); @@ -390,7 +430,7 @@ $(document).on("pageinit", "#bill-page", function () {
@@ -409,6 +449,17 @@ $(document).on("pageinit", "#bill-page", function () { Aktualisieren

+ + +
@@ -418,7 +469,7 @@ $(document).on("pageinit", "#bill-page", function () {
-
+

Storno fehlgeschlagen

diff --git a/webapp/css/bestformat.css b/webapp/css/bestformat.css index a4e54d9..7c9fd98 100644 --- a/webapp/css/bestformat.css +++ b/webapp/css/bestformat.css @@ -1 +1 @@ -@charset "UTF-8";table.viewtable{width:100%;display:block;table-layout:fixed}table.viewtable th{background:#7abe5f;font-size:10pt;border-bottom:1px solid rgba(255,255,255,.7);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);-o-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);box-shadow:inset 0 1px 0 rgba(255,255,255,.2);padding:6px 10px}table.viewtable td{background:#eed33f;font-size:8pt;border-bottom:1px solid #fafafa;border-bottom:1px solid rgba(255,255,255,.5);padding:6px 10px;color:rgba(0,0,0,255)}table.viewtable th.complete{background:#17370b;color:rgba(255,255,255,0)}table.viewtable th.incomplete{background:#9c9224;color:rgba(0,0,0,255)}table.viewtable td.complete{background:#78bb5e;color:rgba(0,0,0,255)}table.viewtable td.incomplete{background:#eed33f;color:rgba(0,0,0,255)}table.viewtable tr:last-child td{border-bottom:0}table.viewtable tr:hover td{background-color:#faf}table.receipttable td{border:solid black 0;padding:3px;text-align:left;vertical-align:bottom}table.receipttable td.price{border:solid black 0;padding:3px;text-align:right;vertical-align:bottom}table.receipttable td.restinfo{text-align:center;vertical-align:bottom}table.receipttable td.declaration{font-weight:bold;text-align:right}table.gridtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:2px;border-color:#666;border-collapse:collapse;width:100%}table.gridtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.gridtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#fff}table.linetable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:2px;border-color:#666;border-collapse:collapse;width:100%}table.linetable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.linetable td{border-width:1px;padding:8px;border-style:solid;border-color:#666}table.linetable tr{background:#fff}table.linetable tr:hover{background-color:#faf}table.reporttable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border:solid black 2px;border-color:#666;border-collapse:collapse;width:100%;border-spacing:10px}table.reporttable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.reporttable td{border:solid black 0 padding:8px;text-align:left;vertical-align:top}table.reporttable tr{background:#d6f8be}table.reporttable tr:hover{background-color:#faf}table.commandtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.commandtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#e4d662;font-weight:bold}table.commandtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#fff;font-weight:bold}table.navitable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.navitable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#d09696;font-weight:bold}table.navitable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c08f8f}table.infotable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.infotable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold}table.infotable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff}table.billtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#000;border:solid black 2px;border-color:#000;border-collapse:collapse;width:100%;border-spacing:10px}table.billtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:left}table.billtable #pricecolheader{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:right}table.billtable td{border:solid black 0 padding:8px;background-color:#fff;text-align:left}table.billtable #pricecol{border:solid black 0 padding:8px;background-color:#fff;text-align:right}table.billtable #totalprice{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:center}.grid_right{text-align:right;font-style:italic}.userinfo{font-style:italic}.counting{position:absolute;top:0;bottom:0;right:90px;width:80px;border:0;background-color:rgb(246,246,246,0.0) !important}.counting:hover{background-color:#0f0}.goup{position:absolute;top:5px;bottom:0;right:90px;border:0;background-color:#f6f6f6 !important}.osroom-1{height:40px !important}.osroom-2{height:70px !important}.ostable-1{height:40px !important}.ostable-2{height:70px !important}.osprod-1{height:40px !important}.osprod-2{height:70px !important}.osbigbtn.ui-btn{height:40px !important;text-align:center;line-height:30px}table.prodtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:70%}table.prodtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:OrangeRed;font-weight:bold}table.prodtable .prodtype td{background-color:DarkGreen}table.prodtable tr>td:first-child{text-align:left}table.prodtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:LimeGreen;text-align:right;font-weight:bold;white-space:nowrap;max-width:50%;word-break:break-all}table.prodtable input{line-height:30px;background-color:PaleGreen;font-weight:bold}table.prodtable select{background-color:PaleGreen;font-weight:bold;width:100%}table.prodtable option.yes{background-color:green}table.prodtable option.no{background-color:red}table.prodtable .prodpriceA{width:50px;text-align:right}table.prodtable .prodpriceB{width:50px;text-align:right}table.prodtable .prodpriceC{width:50px;text-align:right}.prodinfo,.srinfo{position:absolute;top:0;bottom:0;right:20px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.waitinfo{position:absolute;top:0;bottom:0;right:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.waitinfo img{position:absolute;top:0;bottom:0;right:20px;height:35px;border:0;background-color:rgb(246,246,246,0.0) !important}.typehigher{text-align:right;background-color:rgb(246,246,246,0.0) !important}.typetop{text-align:left;background-color:rgb(246,246,246,0.0) !important}@media all and (min-width:0){.typetop img{width:100px}.typehigher img{width:100px}}@media all and (min-width:20em){.typetop img{width:120px}.typehigher img{width:120px}}@media all and (min-width:40em){.typetop img{width:160px}.typehigher img{width:160px}}.prodminus,.srminus{position:absolute;top:0;bottom:0;right:130px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodcount,.srprodcount{position:absolute;top:10px;bottom:0;right:95px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodplus,.srplus{position:absolute;top:0;bottom:0;right:60px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodplus img{width:30px}.prodminus img{width:30px}.srplus img{width:30px}.srminus img{width:30px}.srminus:hover,.prodminus:hover{height:40px;width:30px;background-color:#0f0}.srplus:hover,.prodplus:hover{height:40px;width:30px;background-color:#0f0}.prodinfo img:hover,.srinfo img:hover{background-color:#0f0}.tbusy{color:black !important;font-weight:bold;font-style:italic}.tempty{color:gray !important;color:gray !important;font-weight:normal}.overlaytxt{background:linear-gradient(red,yellow);color:black;font-weight:bold;border-radius:25px;border:3px solid #000;padding:8px}.overlayfull{background:linear-gradient(red,yellow)}.overlayempty{background:linear-gradient(green,yellow)}.overlaysize-0{font-size:7px}.overlaysize-1{font-size:12px}.overlaysize-2{font-size:15px}.prodreadyicon{position:absolute;top:0;bottom:0;right:70px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodreadyicon:hover{height:40px;background-color:#0f0}.prodreadycount{position:absolute;top:10px;bottom:0;right:40px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.changetableprodlist{width:100%;background-color:LightCyan;resize:none}.usersums{border:solid black 3px;background-color:#ffe8bc}.usersums td{border:solid black 1px;padding:3px;text-align:right;vertical-align:bottom}.taxessums{border:solid black 3px;background-color:#f0e8bc}.taxessums td{border:solid black 1px;padding:3px;text-align:right;vertical-align:bottom} \ No newline at end of file +@charset "UTF-8";table.viewtable{width:100%;display:block;table-layout:fixed}table.viewtable th{background:#7abe5f;font-size:10pt;border-bottom:1px solid rgba(255,255,255,.7);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);-o-box-shadow:inset 0 1px 0 rgba(255,255,255,.2);box-shadow:inset 0 1px 0 rgba(255,255,255,.2);padding:6px 10px}table.viewtable td{background:#eed33f;font-size:8pt;border-bottom:1px solid #fafafa;border-bottom:1px solid rgba(255,255,255,.5);padding:6px 10px;color:rgba(0,0,0,255)}table.viewtable th.complete{background:#17370b;color:rgba(255,255,255,0)}table.viewtable th.incomplete{background:#9c9224;color:rgba(0,0,0,255)}table.viewtable td.complete{background:#78bb5e;color:rgba(0,0,0,255)}table.viewtable td.incomplete{background:#eed33f;color:rgba(0,0,0,255)}table.viewtable tr:last-child td{border-bottom:0}table.viewtable tr:hover td{background-color:#faf}table.receipttable td{border:solid black 0;padding:3px;text-align:left;vertical-align:bottom}table.receipttable td.price{border:solid black 0;padding:3px;text-align:right;vertical-align:bottom}table.receipttable td.restinfo{text-align:center;vertical-align:bottom}table.receipttable td.declaration{font-weight:bold;text-align:right}table.gridtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:2px;border-color:#666;border-collapse:collapse;width:100%}table.gridtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.gridtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#fff}table.linetable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:2px;border-color:#666;border-collapse:collapse;width:100%}table.linetable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.linetable td{border-width:1px;padding:8px;border-style:solid;border-color:#666}table.linetable tr{background:#fff}table.linetable tr:hover{background-color:#faf}table.reporttable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border:solid black 2px;border-color:#666;border-collapse:collapse;width:100%;border-spacing:10px}table.reporttable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#dedede;font-weight:bold}table.reporttable td{border:solid black 0;padding:8px;text-align:left;vertical-align:top}table.reporttable tr{background:#d6f8be}table.reporttable tr:hover{background-color:#faf}table.commandtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.commandtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#e4d662;font-weight:bold}table.commandtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#fff;font-weight:bold}table.navitable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.navitable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#d09696;font-weight:bold}table.navitable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c08f8f}table.infotable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:100%}table.infotable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold}table.infotable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff}table.billtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#000;border:solid black 2px;border-color:#000;border-collapse:collapse;width:100%;border-spacing:10px}table.billtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:left}table.billtable #pricecolheader{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:right}table.billtable td{border:solid black 0;padding:8px;background-color:#fff;text-align:left}table.billtable #pricecol{border:solid black 0;padding:8px;background-color:#fff;text-align:right}table.billtable #totalprice{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:#c3c3ff;font-weight:bold;text-align:center}.grid_right{text-align:right;font-style:italic}.userinfo{font-style:italic}.counting{position:absolute;top:0;bottom:0;right:90px;width:80px;border:0;background-color:rgb(246,246,246,0.0) !important}.counting:hover{background-color:#0f0}.goup{position:absolute;top:5px;bottom:0;right:90px;border:0;background-color:#f6f6f6 !important}.osroom-1{height:40px !important}.osroom-2{height:70px !important}.ostable-1{height:40px !important}.ostable-2{height:70px !important}.osprod-1{height:40px !important}.osprod-2{height:70px !important}.osbigbtn.ui-btn{height:40px !important;text-align:center;line-height:30px}table.prodtable{font-family:verdana,arial,sans-serif;font-size:20px;color:#333;border-width:1px;border-color:#666;border-collapse:collapse;width:70%}table.prodtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:OrangeRed;font-weight:bold}table.prodtable .prodtype td{background-color:DarkGreen}table.prodtable tr>td:first-child{text-align:left}table.prodtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666;background-color:LimeGreen;text-align:right;font-weight:bold;white-space:nowrap;max-width:50%;word-break:break-all}table.prodtable input{line-height:30px;background-color:PaleGreen;font-weight:bold}table.prodtable select{background-color:PaleGreen;font-weight:bold;width:100%}table.prodtable option.yes{background-color:green}table.prodtable option.no{background-color:red}table.prodtable .prodpriceA{width:50px;text-align:right}table.prodtable .prodpriceB{width:50px;text-align:right}table.prodtable .prodpriceC{width:50px;text-align:right}.prodinfo,.srinfo{position:absolute;top:0;bottom:0;right:20px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.waitinfo{position:absolute;top:0;bottom:0;right:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.waitinfo img{position:absolute;top:0;bottom:0;right:20px;height:35px;border:0;background-color:rgb(246,246,246,0.0) !important}.typehigher{text-align:right;background-color:rgb(246,246,246,0.0) !important}.typetop{text-align:left;background-color:rgb(246,246,246,0.0) !important}@media all and (min-width:0){.typetop img{width:100px}.typehigher img{width:100px}}@media all and (min-width:20em){.typetop img{width:120px}.typehigher img{width:120px}}@media all and (min-width:40em){.typetop img{width:160px}.typehigher img{width:160px}}.prodminus,.srminus{position:absolute;top:0;bottom:0;right:130px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodcount,.srprodcount{position:absolute;top:10px;bottom:0;right:95px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodplus,.srplus{position:absolute;top:0;bottom:0;right:60px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodplus img{width:30px}.prodminus img{width:30px}.srplus img{width:30px}.srminus img{width:30px}.srminus:hover,.prodminus:hover{height:40px;width:30px;background-color:#0f0}.srplus:hover,.prodplus:hover{height:40px;width:30px;background-color:#0f0}.prodinfo img:hover,.srinfo img:hover{background-color:#0f0}.tbusy{color:black !important;font-weight:bold;font-style:italic}.tempty{color:gray !important;color:gray !important;font-weight:normal}.overlaytxt{background:linear-gradient(red,yellow);color:black;font-weight:bold;border-radius:25px;border:3px solid #000;padding:8px}.overlayfull{background:linear-gradient(red,yellow)}.overlayempty{background:linear-gradient(green,yellow)}.overlaysize-0{font-size:7px}.overlaysize-1{font-size:12px}.overlaysize-2{font-size:15px}.prodreadyicon{position:absolute;top:0;bottom:0;right:70px;height:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.prodreadyicon:hover{height:40px;background-color:#0f0}.prodreadycount{position:absolute;top:10px;bottom:0;right:40px;width:20px;border:0;background-color:rgb(246,246,246,0.0) !important}.changetableprodlist{width:100%;background-color:LightCyan;resize:none}.usersums{border:solid black 3px;background-color:#ffe8bc}.usersums td{border:solid black 1px;padding:3px;text-align:right;vertical-align:bottom}.taxessums{border:solid black 3px;background-color:#f0e8bc}.taxessums td{border:solid black 1px;padding:3px;text-align:right;vertical-align:bottom}.scrolllistview{height:150px;top:10px;overflow:auto;background-color:blanchedalmond;-webkit-overflow-scrolling:touch}.scrolllistview li{height:15px;vertical-align:middle}.selecteditem{color:black;font-weight:bold}.unselecteditem{color:gray} \ No newline at end of file diff --git a/webapp/customer/menulegend.txt b/webapp/customer/menulegend.txt index 0dafdff..b496e93 100755 --- a/webapp/customer/menulegend.txt +++ b/webapp/customer/menulegend.txt @@ -1,61 +1,5 @@ -# ***** Diese Speisekarte hat ein bestimmtes Format. **** -# ***** Das Format, insbesondere die Einrückungen, müssen **** -# ***** genau eingehalten werden, damit der Inhalt korrekt **** -# ***** übernommen werden kann. **** # -# Einrückungen bauen die Produktpalette hierarchisch auf -# Die tiefsten Einrückungen stellen die Produkte dar, alle -# Ebenen darüber die Kategorien -# -# Die einfachste Struktur sieht wie folgt aus (Beispiel): +# ***** Diese Speisekarte ist vom System bereits eingespeichert worden (erkennbar an den zugewiesenen IDs). **** # -# Speisen -# Gericht 1 ; 2,90 -# Gericht 2 ; 3,90 -# Untergruppe xy -# Gericht 3 ; 2,90 -# Getränke -# ... -# -# Kategorien und Produkte können zusätzlich noch weiter spezifiziert -# werden: -# -# Ein Produkteintrag hat folgendes Format: -# Kurzname (ID:123); NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C); Steuersatz -# dabei ist der Kurzname nur in der Kellneransicht bei der Produktauswahl zu sehen, -# anschließend wird stets der Langname angezeigt. -# Nur Kurzname und Preis (A) sind erforderlich, die anderen Teile werden bei -# Auslassung automatisch gefüllt (Preis B=C=A und Langname = Kurzname). -# -# Wurde dem Produkt bereits eine ID von OrderSprinter zugewiesen, wird diese angezeigt. -# So können spätere Produktänderungen vom OrderSprinter erkannt werden. -# Es ist wichtig, keine eigenen IDs zu vergeben, denn neue IDs werden stets vom -# OrderSprinter erzeugt! -# -# Wird ein Steuersatz angegeben, der für das Produkt vorgegeben sein soll, so -# müssen auch die Preise A und B angegeben werden. -# -# Bei Kategorien: -# Das Gleichheitszeichen dient als Trenner zwischen Namen und weiteren Eigenschaften. -# Wird ein K und B mitgegeben, so werden diese Produkte über die Küchen- -# und Bereitstellungsansicht geführt. Die Einstellung wird auf die Unterkategorien -# vererbt, wenn die darunter liegenden Kategorien keine Angabe dazu machen. -# Hinter dem zweiten Gleichheitszeichen kann die Nummer eines Arbeitsbondruckers -# des jeweiligen Typs (Speise/Getränk) angegeben werden. -# -# Wenn ein D da steht, wird als Typ "Getränk" angenommen, bei einem F "Speise". -# Auch hier wird der übergeordnete Eintrag genommen, wenn Angabe fehlt. -# -# Extras werden mit einem Ausrufezeichen am Zeilenanfang deklariert. -# Das Format ist: -# !Extraname (ID:8) # 12,34 ; (45),Langname eines Produkts,(49),(50) -# - Die ID-Angabe ist optional (kann weggelassen werden) -# - Der Wert 12,34 ist der Aufpreis -# - Hinter dem Semikolon können Komma-getrennt Produkte angegebenen werden, die -# dieses Extra haben dürfen. Angabe entweder ID des Produkts in Klammern oder -# der Langname eines Produkts. (Gibt es den Langnamen mehrfach, wird das Extra -# auch mehrfach zugewiesen.) -# -# Reservierte Buchstaben: = ; # ! -# (Diese werden als Trenner verwendet!) +# ***** Eine Erklärung der Syntax ist im Aufklappfeld "Legende" zu lesen. # diff --git a/webapp/customer/speisekarte.txt b/webapp/customer/speisekarte.txt index 4b16936..5c13186 100755 --- a/webapp/customer/speisekarte.txt +++ b/webapp/customer/speisekarte.txt @@ -1,100 +1,62 @@ +# # ***** Diese Speisekarte kann als Vorlage dienen. **** # -# Einrückungen bauen die Produktpalette hierarchisch auf -# Die tiefsten Einrückungen stellen die Produkte dar, alle -# Ebenen darüber die Kategorien +# ***** Eine Erklärung der Syntax ist im Aufklappfeld "Legende" zu lesen. # -# Ein Produkteintrag hat folgendes Format: -# Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C) -# dabei ist der Kurzname nur in der Kellneransicht bei der Produktauswahl zu sehen, -# anschließend wird stets der Langname angezeigt. -# Nur Kurzname und Preis (A) sind erforderlich, die anderen Teile werden bei -# Auslassung automatisch gefüllt (Preis B=C=A und Langname = Kurzname) -# Wird ein Steuersatz angegeben, der für das Produkt vorgegeben sein soll, so -# müssen auch die Preise A und B angegeben werden. -# Wurde dem Produkt bereits eine ID von OrderSprinter zugewiesen, wird diese angezeigt. -# So können spätere Produktänderungen vom OrderSprinter erkannt werden. -# Es ist wichtig, keine eigenen IDs zu vergeben, denn neue IDs werden stets vom -# OrderSprinter erzeugt! -# -# Bei Kategorien: -# Das Gleichheitszeichen dient als Trenner zwischen Namen und weiteren Eigenschaften. -# Wird ein K und B mitgegeben, so werden diese Produkte über die Küchen- -# und Bereitstellungsansicht geführt. Die Einstellung wird auf die Unterkategorien -# vererbt, wenn die darunter liegenden Kategorien keine Angabe dazu machen. -# Hinter dem zweiten Gleichheitszeichen kann die Nummer eines Arbeitsbondruckers -# des jeweiligen Typs (Speise/Getränk) angegeben werden. -# -# Wenn ein D da steht, wird als Typ "Getränk" angenommen, bei einem F "Speise". -# Auch hier wird der übergeordnete Eintrag genommen, wenn Angabe fehlt. -# -# Extras werden mit einem Ausrufezeichen am Zeilenanfang deklariert. -# Das Format ist: -# !Extraname (ID:8) # 12,34 ; (45),Langname eines Produkts,(49),(50) -# - Die ID-Angabe ist optional (kann weggelassen werden) -# - Der Wert 12,34 ist der Aufpreis -# - Hinter dem Semikolon können Komma-getrennt Produkte angegebenen werden, die -# dieses Extra haben dürfen. Angabe entweder ID des Produkts in Klammern oder -# der Langname eines Produkts. (Gibt es den Langnamen mehrfach, wird das Extra -# auch mehrfach zugewiesen.) -# -# Reservierte Buchstaben: = ; # ! -# (Diese werden als Trenner verwendet!) -# -Speisen = KBF - Fastfood - Pommes ; 3,00 - Schnitzel ; 4,00 - Vom Grill - El Greco 2P; 26{.}90; EL Greco 2 Personen # 20{.}90; 13{.}80 - El Greco 1P; 14{.}80; EL Greco 1 Person - Fleisch-Gerichte - Lammkotelett; 13{.}50; Lammkotelett # 11{.}30; 6{.}00 - Zigeuner/Jägerschnitzel; 10{.}50 # 9{.}80; 3{.}50 - Suzukakia 4H; 10{.}50; Suzukakia 4 Hacksteaks - Suzukakia 2H; 10{.}50; Suzukakia 2 Hacksteaks - Souvlaki; 10{.}50 - Italienische Küche - Pizza - Siciliana - klein; 7{.}50; Pizza Siciliana klein - groß; 7{.}50; Pizza Siciliana groß - Salami - klein; 6{.}20; Pizza Salami klein - groß; 7{.}80; Pizza Salami groß - Special; 6{.}90; Ital. Tagesspecial - Kategorie Selbstbedienung = - Frühstücksbuffet; 8{.}90 - Frühstücksbuffet + Kaffe; 12{.}20 - Kategorie vorbereitet = B - Deserts; 2{.}20 - Fertigprodukte; 1{.}20 - Kategorie Nur Küche = K - Tischzubereitung Fisch; 2{.}20 - Tischzubereitung Fleischmenü; 1{.}20 -Getränke = KBD - Kaffee - Cappuchino ; 2,50 - Tasse Kaffee ; 3,00 - Becher Kaffee ; 3,50 - Latte Macchiato ; 3,00 - Biere - Holsten; 1{.}60 # 1{.}00; 0{.}80 - Warsteiner; 1{.}80 # 1{.}20 - Becks Gold; 1{.}80 - Alsterwasser; 1{.}50 - Softdrinks - Coca-Cola; 2{.}50 - Fanta; 2{.}50 - Ohne Zucker = B - Cola Zero; 2{.}21 - Sprite; 2{.}50 - Eistee; 1{.}60 - Wasser - Apollinaris; 2{.}20 - still; 1{.}20; Stilles Wasser - Weine - Lambrusco; 7{.}00; Wein Lambrusco +Speisen = KBF = 1 + Fastfood = KBF = 1 + Pommes; 3,00 + Schnitzel; 4,00 + Vom Grill = KBF = 1 + EL Greco 2 Personen; 26,00 # Kurzname:El Greco 2P; PreisB:20,00; PreisC:13,00 + EL Greco 1 Person; 14,00 # Kurzname:El Greco 1P + Fleisch-Gerichte = KBF = 1 + Lammkotelett; 13,00 # PreisB:11,00; PreisC:6,00 + Zigeuner/Jägerschnitzel; 10,00 # PreisB:9,00; PreisC:3,00 + Suzukakia 4 Hacksteaks; 10,00 # Kurzname:Suzukakia 4H + Suzukakia 2 Hacksteaks; 10,00 # Kurzname:Suzukakia 2H + Souvlaki; 10,00 # ID:9 + Italienische Küche = KBF = 1 + Ital. Tagesspecial; 6,00 # Kurzname:Special + Pizza = KBF = 1 + Siciliana = KBF = 1 + Pizza Siciliana klein; 7,00 # Kurzname:klein + Pizza Siciliana groß; 7,00 # Kurzname:groß + Salami = KBF = 1 + Pizza Salami klein; 6,00 # Kurzname:klein + Pizza Salami groß; 7,00 # Kurzname:groß + Kategorie Selbstbedienung = F = 1 + Frühstücksbuffet; 8,00 + Frühstücksbuffet + Kaffe; 12,00 + Kategorie vorbereitet = BF = 1 + Deserts; 2,00 + Fertigprodukte; 1,00 + Kategorie Nur Küche = KF = 1 + Tischzubereitung Fisch; 2,00 + Tischzubereitung Fleischmenü; 1,00 +Getränke = KBD = 1 + Kaffee = KBD = 1 + Cappuchino; 2,50 + Tasse Kaffee; 3,00 + Becher Kaffee; 3,50 + Latte Macchiato; 3,00 + Biere = KBD = 1 + Holsten; 1,00 # PreisB:1,00; PreisC:0,00 + Warsteiner; 1,00 + Becks Gold; 1,00 + Alsterwasser; 1,00 + Softdrinks = KBD = 1 + Coca-Cola; 2,00 + Fanta; 2,00 + Sprite; 2,00 + Eistee; 1,00 + Ohne Zucker = BD = 1 + Cola Zero; 2,00 + Wasser = KBD = 1 + Apollinaris; 2,00 + Stilles Wasser; 1,00 # Kurzname:still + Weine = KBD = 1 + Wein Lambrusco; 7,00 # Kurzname:Lambrusco # # Es folgen die Extras !Sahne # 0,50 ; Tasse Kaffee , Becher Kaffee diff --git a/webapp/feedback.html b/webapp/feedback.html index d043a7d..5426a1b 100644 --- a/webapp/feedback.html +++ b/webapp/feedback.html @@ -4,7 +4,7 @@ - + diff --git a/webapp/index.html b/webapp/index.html index 3b29e71..7532fe3 100644 --- a/webapp/index.html +++ b/webapp/index.html @@ -7,8 +7,8 @@ - - + + diff --git a/webapp/install.html b/webapp/install.html index 3e3887d..432b0bb 100644 --- a/webapp/install.html +++ b/webapp/install.html @@ -679,7 +679,7 @@ $(document).ready(function() {   - +   diff --git a/webapp/install/installer.php b/webapp/install/installer.php index 295c4d3..2335d6e 100644 --- a/webapp/install/installer.php +++ b/webapp/install/installer.php @@ -46,9 +46,9 @@ function setTimeZone($zone) { $this->timezone = $zone; } -function openDbAndReturnPdo ($host,$db,$user,$password) { -$dsn = 'mysql:host=' . $host . ';dbname=' . $db; -$pdo = null; +function openDbAndReturnPdo ($host,$db,$user,$password) { +$dsn = 'mysql:host=' . $host . ';dbname=' . $db; +$pdo = null; try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); @@ -56,8 +56,8 @@ $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); catch (PDOException $e) { echo 'Verbindungsproblem: ' . $e->getMessage(); $pdo = null; -} -return $pdo; +} +return $pdo; } function checkPhpStatus() { @@ -95,6 +95,39 @@ $ret = array("extensions_status" => $extensions_status, "missing_extensions" => echo json_encode($ret); } +private function getForeignKeyName($pdo,$fromtable,$totable,$dbname) { +$foreignKey = null; +try { +$sql = "SELECT constraint_name as foreignkey FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE constraint_schema = '$dbname' AND table_name = '%$fromtable%' AND REFERENCED_TABLE_NAME='%$totable%'"; +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(); +$result = $stmt->fetchAll(); +if (count($result) != 1) { +return null; +} +$foreignKey = $result[0]["foreignkey"]; +} catch (Exception $e) { +return null; +} + +return $foreignKey; +} + +private function replaceForeignIdKey($pdo,$fromtable,$totable,$dbname,$foreignkeyname,$colname) { +$foreignkeyorig = $this->getForeignKeyName($pdo, $fromtable, $totable, $dbname); +if (!is_null($foreignkeyorig)) { +$this->execSql($pdo, "alter table %$fromtable% drop foreign key $foreignkeyorig"); +$this->execSql($pdo, "ALTER TABLE %$fromtable% ADD CONSTRAINT $foreignkeyname FOREIGN KEY ($colname) REFERENCES %$totable%(id)"); +} +} + +private function replaceForeignKeysToBillAndClosing($pdo,$dbname) { +$this->replaceForeignIdKey($pdo, 'billproducts', 'bill', $dbname, 'billprodref', 'billid'); +$this->replaceForeignIdKey($pdo, 'queue', 'bill', $dbname, 'queuebillref', 'billid'); +$this->replaceForeignIdKey($pdo, 'bill', 'closing', $dbname, 'billclosingref', 'closingid'); +$this->replaceForeignIdKey($pdo, 'bill', 'bill', $dbname, 'billbillref', 'ref'); +} + function updateVersion($pdo,$version) { $setVersion = "update %config% set setting=? where name='version'"; $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($setVersion)); @@ -1168,6 +1201,39 @@ return false; } } +private function execSql($pdo,$sql) { +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(); +} + +function updateUserTable1130_1200($prefix, $version, $dbname) { +$pdo = $this->pdo; +try { +if ($version != "1.1.30") { +$ret = $this->updateUserTable1129_1130($prefix, $version); +if (!$ret) { +return false; +} +} + +DbUtils::overrulePrefix($prefix); + +$this->replaceForeignKeysToBillAndClosing($pdo,$dbname); + +$this->execSql($pdo, "ALTER TABLE %user% ADD right_closing INT (1) NULL AFTER right_products"); +$this->execSql($pdo, "ALTER TABLE %histuser% ADD right_closing INT (1) NULL AFTER right_products"); +$this->execSql($pdo, "UPDATE %user% SET right_closing=right_manager"); +$this->execSql($pdo, "UPDATE %histuser% SET right_closing=right_manager"); +$this->execSql($pdo, "ALTER TABLE %user% MODIFY right_closing INT(1) NOT NULL"); +$this->execSql($pdo, "ALTER TABLE %histuser% MODIFY right_closing INT(1) NOT NULL"); + +$this->updateVersion($pdo, '1.2.0'); +return true; +} catch (PDOException $e) { +return false; +} +} + function setVersion($prefix,$theVersion) { $pdo = $this->pdo; try { @@ -1194,31 +1260,31 @@ $rect .= "f: ; E_Summe:llllllllllllllllllll;\n\nj:l;"; return $rect; } -function createTables($decpoint,$billlanguage,$currency,$timezone) -{ -$pdo = $this->pdo; +function createTables($decpoint,$billlanguage,$currency,$timezone) +{ +$pdo = $this->pdo; $this->basedb->setTimeZone($timezone); $this->basedb->dropTables($pdo); $this->basedb->createRatingsTable($pdo); -$this->createPaymentTable($pdo); -$this->basedb->createUserTable($pdo); +$this->createPaymentTable($pdo); +$this->basedb->createUserTable($pdo); $this->basedb->createRoomTable($pdo); $this->basedb->createRestTables($pdo); $this->basedb->createTableMapsTable($pdo); -$this->basedb->createTablePosTable($pdo); -$this->basedb->createConfigTable($pdo); -$this->basedb->createProdTypeTable($pdo); -$this->basedb->createProductTable($pdo); -$this->basedb->createPriceLevelTable($pdo); -$this->basedb->createClosingTable($pdo); -$this->basedb->createBillTable($pdo); -$this->basedb->createQueueTable($pdo); -$this->basedb->createBillProductsTable($pdo); +$this->basedb->createTablePosTable($pdo); +$this->basedb->createConfigTable($pdo); +$this->basedb->createProdTypeTable($pdo); +$this->basedb->createProductTable($pdo); +$this->basedb->createPriceLevelTable($pdo); +$this->basedb->createClosingTable($pdo); +$this->basedb->createBillTable($pdo); +$this->basedb->createQueueTable($pdo); +$this->basedb->createBillProductsTable($pdo); $this->basedb->createHistTables($pdo); -$this->defineHistActions($pdo); +$this->defineHistActions($pdo); $this->basedb->createPrintJobsTable($pdo); $this->basedb->createWorkTable($pdo); $this->basedb->createCommentsTable($pdo); @@ -1236,23 +1302,23 @@ $this->basedb->doSQL($pdo,"INSERT INTO `%pricelevel%` (`id` , `name`,`info`,`inf $this->basedb->doSQL($pdo,"INSERT INTO `%pricelevel%` (`id` , `name`,`info`,`info_en`,`info_esp`) VALUES ('2', 'B', 'Wochenendtarif', 'Weekend prices','Tarifa del fin de semana')"); $this->basedb->doSQL($pdo,"INSERT INTO `%pricelevel%` (`id` , `name`,`info`,`info_en`,`info_esp`) VALUES ('3', 'C', 'Happy Hour', 'Happy Hour','Happy Hour')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'pricelevel', '1')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'pricelevel', '1')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'tax', '19.0')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'togotax', '7.0')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'stornocode', '123')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'printpass', '$printpass')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'togotax', '7.0')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'stornocode', '123')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'printpass', '$printpass')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'companyinfo', 'Musterrestaurant\nBeispielstrasse 123\n12345 Musterort')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'rectemplate', '$rect')"); $resTxt = 'Vielen Dank für Ihre Reservierung am DATUM um ZEIT Uhr für ANZAHL Personen.\n\nWir freuen uns auf Ihren Besuch!\n\nBETRIEBSINFO'; $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'reservationnote', '$resTxt')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'serverurl', '')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'email', '')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'receiveremail', '')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'receiveremail', '')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'payprinttype', 's')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'billlanguage', $billlanguage)"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'currency', '$currency')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'receiptfontsize', '12')"); -$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'version', '1.1.30')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'receiptfontsize', '12')"); +$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'version', '1.2.0')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'paymentconfig', '0')"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'remoteaccesscode', null)"); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'decpoint', '$decpoint')"); @@ -1288,7 +1354,7 @@ $installDate = date('Y-m-d H:i:s'); $this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'installdate', '$installDate')"); $this->readConfigTableAndSendToHist($pdo); -return; +return; } public function getCurrentVersion() { @@ -1321,108 +1387,108 @@ return false; } } -function readConfigTableAndSendToHist($pdo) { -$sql_query = "SELECT * FROM %config%"; - -$sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)"; - -$stmt_query = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_query)); -$stmt_insert_histconfig = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histconfig)); - -$stmt_query->execute(); -$result = $stmt_query->fetchAll(); -foreach($result as $row){ -$stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); -$newRefIdForHist = $pdo->lastInsertId(); -$this->insertIntoHist($pdo, '2', $newRefIdForHist); -} +function readConfigTableAndSendToHist($pdo) { +$sql_query = "SELECT * FROM %config%"; + +$sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)"; + +$stmt_query = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_query)); +$stmt_insert_histconfig = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histconfig)); + +$stmt_query->execute(); +$result = $stmt_query->fetchAll(); +foreach($result as $row){ +$stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); +$newRefIdForHist = $pdo->lastInsertId(); +$this->insertIntoHist($pdo, '2', $newRefIdForHist); +} } -private function insertIntoHist($pdo,$action,$refIdForHist) { -date_default_timezone_set($this->timezone); -$currentTime = date('Y-m-d H:i:s'); - -$sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; -$stmt_insert_hist = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_hist)); -$stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); +private function insertIntoHist($pdo,$action,$refIdForHist) { +date_default_timezone_set($this->timezone); +$currentTime = date('Y-m-d H:i:s'); + +$sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; +$stmt_insert_hist = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_hist)); +$stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); } function insertUser($username,$adminpass,$is_admin,$right_waiter,$right_kitchen,$right_bar, $right_supply,$right_paydesk,$right_statistics,$right_bill,$right_products,$right_changeprice, -$right_manager,$right_reservation,$right_rating,$lang,$prefertablemap) { +$right_manager,$right_closing,$right_reservation,$right_rating,$lang,$prefertablemap) { $md5adminpass = md5($adminpass); $pdo = $this->pdo; -$userInsertSql = "INSERT INTO `%user%` (`id` , `username` , `userpassword`, `is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`,`right_statistics`,`right_bill`,`right_products`,`right_changeprice`,`right_manager`,`right_reservation`,`right_rating`,`language`,`prefertablemap`,`keeptypelevel`,`extrasapplybtnpos`,`active`) VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'1','1')"; +$userInsertSql = "INSERT INTO `%user%` (`id` , `username` , `userpassword`, `is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`,`right_statistics`,`right_bill`,`right_products`,`right_changeprice`,`right_manager`,`right_closing`,`right_reservation`,`right_rating`,`language`,`prefertablemap`,`keeptypelevel`,`extrasapplybtnpos`,`active`) VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'1','1')"; $stmt = $pdo->prepare(DbUtils::substTableAlias($userInsertSql)); -$stmt->execute(array($username,$md5adminpass,$is_admin,$right_waiter,$right_kitchen,$right_bar,$right_supply,$right_paydesk,$right_statistics,$right_bill,$right_products,$right_changeprice,$right_manager,$right_reservation,$right_rating,$lang,$prefertablemap,0)); +$stmt->execute(array($username,$md5adminpass,$is_admin,$right_waiter,$right_kitchen,$right_bar,$right_supply,$right_paydesk,$right_statistics,$right_bill,$right_products,$right_changeprice,$right_manager,$right_closing,$right_reservation,$right_rating,$lang,$prefertablemap,0)); $newUserIdForHist = $pdo->lastInsertId(); // now insert into hist -$sql_insert_histuser = "INSERT INTO %histuser% (`id` , `userid`, `username` , -`is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`, -`right_statistics`,`right_bill`,`right_products`,`right_changeprice`,`right_manager`,`right_reservation`,`right_rating`,`active`) VALUES ( -NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; -$stmt_insert_histuser = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histuser)); -$stmt_insert_histuser->execute(array($newUserIdForHist,$username,$is_admin,$right_waiter,$right_kitchen,$right_bar,$right_supply,$right_paydesk,$right_statistics,$right_bill,$right_products,$right_changeprice,$right_manager,$right_reservation,$right_rating,1)); -$newRefIdForHist = $pdo->lastInsertId(); +$sql_insert_histuser = "INSERT INTO %histuser% (`id` , `userid`, `username` , +`is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`, +`right_statistics`,`right_bill`,`right_products`,`right_changeprice`,`right_manager`,`right_closing`,`right_reservation`,`right_rating`,`active`) VALUES ( +NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; +$stmt_insert_histuser = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histuser)); +$stmt_insert_histuser->execute(array($newUserIdForHist,$username,$is_admin,$right_waiter,$right_kitchen,$right_bar,$right_supply,$right_paydesk,$right_statistics,$right_bill,$right_products,$right_changeprice,$right_manager,$right_closing,$right_reservation,$right_rating,1)); +$newRefIdForHist = $pdo->lastInsertId(); $this->insertIntoHist($pdo, '3', $newRefIdForHist); } - + function createPaymentTable($pdo) { -$this->basedb->createPaymentTable($pdo); - -$sql = "INSERT INTO %payment% (id,name,name_en,name_esp) VALUES (?,?,?,?)"; -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); - +$this->basedb->createPaymentTable($pdo); + +$sql = "INSERT INTO %payment% (id,name,name_en,name_esp) VALUES (?,?,?,?)"; +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); + $stmt->execute(array('1', 'Barzahlung', 'Cash', 'Contado')); $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); - -$stmt->execute(array('2', 'EC-Kartenzahlung','Electr. purse (EC)','Pago con tarjeta EC')); -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); -$stmt->execute(array('3', 'Kreditkartenzahlung','Credit card','Tarjeta de credito')); -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); -$stmt->execute(array('4', 'Rechnung','bill','Factura')); -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); -$stmt->execute(array('5', 'Ueberweisung','Bank transfer','Transferencia')); -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); -$stmt->execute(array('6', 'Lastschrift','Debit','Cargo en cuenta')); -} -public function defineHistActions ($pdo) { -$sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; -$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); - -$stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); -$stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); -$stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); -$stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten')); -$stmt->execute(array('5', 'ProdCreation', 'Neues Produkt')); -$stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration')); -$stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer')); -$stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers')); +$stmt->execute(array('2', 'EC-Kartenzahlung','Electr. purse (EC)','Pago con tarjeta EC')); +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(array('3', 'Kreditkartenzahlung','Credit card','Tarjeta de credito')); +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(array('4', 'Rechnung','bill','Factura')); +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(array('5', 'Ueberweisung','Bank transfer','Transferencia')); +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); +$stmt->execute(array('6', 'Lastschrift','Debit','Cargo en cuenta')); +} + +public function defineHistActions ($pdo) { +$sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; +$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); + +$stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); +$stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); +$stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); +$stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten')); +$stmt->execute(array('5', 'ProdCreation', 'Neues Produkt')); +$stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration')); +$stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer')); +$stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers')); } function testDbConnection($host,$dbname,$user,$pass) { -$pdo = $this->openDbAndReturnPdo($host,$dbname,$user,$pass); -if (!is_null($pdo)) { -echo json_encode("OK"); -} else { -echo json_encode("ERROR"); -} +$pdo = $this->openDbAndReturnPdo($host,$dbname,$user,$pass); +if (!is_null($pdo)) { +echo json_encode("OK"); +} else { +echo json_encode("ERROR"); +} } function writeConfigFile($host,$db,$user,$password,$prefix) { $errorlevel = " "sha512", -"private_key_bits" => 4096, -"private_key_type" => OPENSSL_KEYTYPE_RSA, +$sslconfig = array( +"digest_alg" => "sha512", +"private_key_bits" => 4096, +"private_key_type" => OPENSSL_KEYTYPE_RSA, ); -// thus the signature is exactly 512 bytes - -// Create the private and public key -$res = openssl_pkey_new($sslconfig); +// thus the signature is exactly 512 bytes + +// Create the private and public key +$res = openssl_pkey_new($sslconfig); if (is_null($res) || ($res=="")) { // openssl may be incorrectly installed return false; } - -// Extract the private key from $res to $privKey -openssl_pkey_export($res, $privKey); - -// Extract the public key from $res to $pubKey -$pubKey = openssl_pkey_get_details($res); + +// Extract the private key from $res to $privKey +openssl_pkey_export($res, $privKey); + +// Extract the public key from $res to $pubKey +$pubKey = openssl_pkey_get_details($res); $pubKey = $pubKey["key"]; $sql = "INSERT INTO `%work%` (`id` , `item`,`value`,`signature`) VALUES ( NULL,?,?,?)"; @@ -1556,7 +1622,7 @@ $checker->checkPhpStatus(); } else if ($command == 'testDbConnection') { $admin = new InstallAdmin(); try { -if (isset($_POST['host']) && isset($_POST['dbname']) && isset($_POST['user']) && isset($_POST['pass'])) { +if (isset($_POST['host']) && isset($_POST['dbname']) && isset($_POST['user']) && isset($_POST['pass'])) { $admin->testDbConnection($_POST['host'],$_POST['dbname'],$_POST['user'],$_POST['pass']); } else { echo json_encode("ERROR"); @@ -1616,7 +1682,7 @@ $zones[] = $timezone_identifiers[$i]; } echo json_encode($zones); } else if ($command == 'update') { -$installerVersion = "1.1.30"; +$installerVersion = "1.2.0"; $admin = new InstallAdmin(); $pdo = $admin->openDbAndReturnPdo($_POST['host'],$_POST['db'],$_POST['user'],$_POST['password']); @@ -1645,7 +1711,7 @@ $supportedVersions = array("1.0.22","1.0.23","1.0.24","1.0.25","1.0.26","1.0.27" "1.0.30","1.0.31","1.0.32","1.0.33","1.0.34","1.0.35","1.0.36","1.0.37","1.0.38","1.0.39", "1.0.40","1.0.41","1.0.42","1.0.43", "1.1.0","1.1.1","1.1.2","1.1.3","1.1.4","1.1.5","1.1.6","1.1.7","1.1.8", "1.1.9","1.1.10","1.1.11","1.1.12","1.1.13","1.1.14","1.1.15","1.1.16","1.1.17", -"1.1.18","1.1.19","1.1.20","1.1.21","1.1.22","1.1.23","1.1.24","1.1.25","1.1.26","1.1.27","1.1.28","1.1.29" +"1.1.18","1.1.19","1.1.20","1.1.21","1.1.22","1.1.23","1.1.24","1.1.25","1.1.26","1.1.27","1.1.28","1.1.29","1.1.30" ); if (!in_array($version, $supportedVersions)) { @@ -1653,7 +1719,7 @@ echo json_encode("Quellversion nicht unterstützt"); return; } -$ret = $admin->updateUserTable1129_1130($_POST['prefix'], $version); +$ret = $admin->updateUserTable1130_1200($_POST['prefix'], $version, $_POST['db']); if(session_id() == '') { session_start(); diff --git a/webapp/kitchen.html b/webapp/kitchen.html index 19c8818..be18a9a 100644 --- a/webapp/kitchen.html +++ b/webapp/kitchen.html @@ -5,7 +5,7 @@ - + diff --git a/webapp/manager.html b/webapp/manager.html index 34c81ea..b45da11 100644 --- a/webapp/manager.html +++ b/webapp/manager.html @@ -5,7 +5,7 @@ - + @@ -65,6 +65,7 @@ var MAN_RESERVATION = ["Reservierung","Reservation","Reserva"]; var MAN_RATING = ["Bewertung","Rating","Valoración"]; var MAN_CHANGEPRICE = ["Preisänderung während Bestellung","Change price during ordering","Modificar precio durante ordenar"]; var MAN_MANAGER = ["Verwaltung","Administration","Administración"]; +var MAN_CLOSINGRIGHT = ["Tageserfassung","Closing","Cerrar día"]; var MAN_USER_NAME = ["Benutzername","User name","Nombre de usario"]; var MAN_USER_PASS = ["Passwort","Password","Contraseña"]; var MAN_YES = ["Ja","Yes","Si"]; @@ -169,11 +170,12 @@ var MAN_BAK_REST_INFO_ALL = ['Die Datensicherung kann auch die gesamte Datenbank 'Exportar puede guarda la base de datos completamente. Con "Importar" este data se puede re-importado. ' + 'Las acciones estan escritos en un log.']; var MAN_REST_INFO = ["Der Import dauert eine Weile...","The import takes a while...","Importar necesita un rato..."]; -var MAN_UPLOAD_FILE = ["Diese Datei hochladen: ", "Upload this file: ","Importar este file: "]; +var MAN_UPLOAD_FILE = ["Diese Datei hochladen (importieren): ", "Upload this file: ","Importar este file: "]; var MAN_BAK_REST_HEAD = ["Sicherung und Import","Backup and Restore","Exportar y Importar"]; var MAN_BAK_BTN = ["Sicherung (Konfiguration)","Backup (Configuration)","Exportar (configuración)"]; var MAN_BAK_BTN_ALL = ["Sicherung (Alles)","Backup (all)","Exportar (todo)"]; var MAN_RESTORE_BTN = ["Importieren","Restore","Importar"]; +var MAN_GO_LIVE = ["Starte Produktivbetrieb","Start productive mode","Empezar trabajar realmente"]; var MAN_SHUTDOWN = ["Server herunterfahren","Shutdown server","Apagar servidor"]; var MAN_SHUTDOWN_HINT = ["(Herunterfahren nur möglich, wenn Webserver die erforderlichen Rechte besitzt).", "(Shutdown only possible if web server has the required privileges to do so.)", @@ -210,6 +212,7 @@ var MAN_PRINTER = ["Kassenbon-Drucker","Receipts Printer","Impresora de tiques"] var MAN_FOOD_PRINTER = ["Speisearbeitsbon-Drucker","Food work ticket printer","Impreso de tiques de comida"]; var MAN_DRINK_PRINTER = ["Getränkearbeitsbon-Drucker","Drinks work ticket printer","Impreso de tiques de bebidas"]; var MAN_UPDATE_PRINTJOBS = ["Aktualisieren","Update","Actualizar"]; +var MAN_CLEAR_PRINTJOBS = ["Alle Druckjobs löschen","Clear all print jobs","Remover todo"]; var MAN_PRINT_JOBS_COUNT = ["Druckaufträge","print jobs","tareas de impresión"]; var MAN_PARSE_ERROR = ["Speisekarte konnte nicht erfolgreich eingelesen werden. Stimmt die Syntax, z.B. die korrekte Einrückung?", "Menu could not be parsed - is the intendation correct?", @@ -272,6 +275,9 @@ var MAN_AESKEY_WRONG_LENGTH = ["Ein AES256-Schlüssel muss in Hex-Darstellung 64 var MAN_AESKEY_NO_HEX = ["Der AES-Schlüssel muss als Hex-Zahl angegeben werden.","The AES key must be specified as hex number","La llava AES tiene que especificado en formato hex."]; var MAN_CERTIFICATE_SN = ["Zertifikatsseriennummer", "Certificate Serial No","Certificado ID"]; var MAN_TAX = ["Steuersatz (%)","Tax (%)","Impuesto (%)"]; +var MAN_CONFIRM_GO_LIVE = ["Die Umsatz- und Logdaten wurden gelöscht und nur die Konfiguration übernommen. Deswegen ist nun ein erneutes Einloggen erforderlich.", + "The sales and log data is deleted and configuration is recreated. Therefore a log-in is required now.", + "La configuración esta re-creado. Entonces es necesario registrar de nuevo."]; var lang = 0; var generalVals = [12,2,0,3,0,1,1,0,0,1, 0,50,20,10,1,0]; @@ -391,6 +397,7 @@ function setLanguage(l) { $("#backupbtntxt").html(MAN_BAK_BTN[l]); $("#backupbtntxtall").html(MAN_BAK_BTN_ALL[l]); $("#restorebtntxt").html(MAN_RESTORE_BTN[l]); + $("#golivetxt").html(MAN_GO_LIVE[l]); $("#shutdownbtntxt").html(MAN_SHUTDOWN[l]); $("#shutdownhinttxt").html(MAN_SHUTDOWN_HINT[l]); @@ -401,6 +408,7 @@ function setLanguage(l) { $("#printjobsheader").html(MAN_PRINTJOBS[l]); $("#updateprintqueue").html(MAN_UPDATE_PRINTJOBS[l]); + $("#clearprintqueue").html(MAN_CLEAR_PRINTJOBS[l]); $("#tmimgdelbtntxt").html(MAN_TM_DEL[l]); $("#tmimgbtntxt").html(MAN_TM[l]); @@ -438,16 +446,21 @@ function createMonthSelection(label) { return monthHtml; } -function hideElementsForNonAdminUser(jsonAnswer) { - if (jsonAnswer != "Yes") { - $("#dbactionui").hide(); - } -} - -function hideElementsForNonAdminManagerUser(jsonAnswer) { - if (jsonAnswer != "Yes") { - $("#allpagecontent").hide(); - } +function showPanelsDueToUserStatus(jsonAnswer) { + if (jsonAnswer == "admin") { + $("#dbactionui").show(); + } + if (jsonAnswer == "manager" || (jsonAnswer == 'admin')) { + $("#userpart").show(); + $("#configpart").show(); + $("#printerqueue").show(); + $("#dataexport").show(); + $("#printserverdownloadpart").show(); + } + + if(jsonAnswer == "No") { + $("#allpagecontent").hide(); + } } function getSpeisekarte() { @@ -771,10 +784,10 @@ function changeConfig(changedEntries) { } function reactOnConfigChange(result) { - if (result == "OK") { + if (result.status == "OK") { alert(MAN_CONFIG_CHANGED[lang]); } else { - alert(MAN_CONFIG_CHANGE_ERROR[lang]); + alert(MAN_CONFIG_CHANGE_ERROR[lang] + ": " + result.msg); } } @@ -1006,7 +1019,6 @@ function binding() { }; if (isValid) { changeConfig(changedEntries); - setTimeout(function(){document.location.href = "manager.html"},500); } }); } @@ -1092,6 +1104,14 @@ function binding() { $("#restinfoafterclick").html(MAN_REST_INFO[lang]); }); + $("#golive").off("click").on("click", function (e) { + e.stopImmediatePropagation(); + e.preventDefault(); + areYouSure("Produktivbetrieb beginnen", "Alle Umsatz- und Logdaten löschen?", "Ja", function() { + golive(); + }); + }); + $("#shutdown_btn").off("click").on("click", function (e) { e.stopImmediatePropagation(); e.preventDefault(); @@ -1115,6 +1135,11 @@ function binding() { e.preventDefault(); doAjax("GET","php/contenthandler.php?module=printqueue&command=getPrintJobOverview",null,insertPrintQueue,null); }); + $("#clearprintqueue").off("click").on("click", function (e) { + e.stopImmediatePropagation(); + e.preventDefault(); + doAjax("GET","php/contenthandler.php?module=printqueue&command=clearprintjobs",null,insertPrintQueue,null); + }); $("#taxass_apply").off("click").on("click", function (e) { e.stopImmediatePropagation(); @@ -1486,7 +1511,7 @@ function createLabelWithOption(aLabel,displayedName,hasTheRight) { * the username and the rights that the user has to work in the * various modules. */ -function createCollapsibeOfUser(id,username,isAdmin,rWaiter,rKitchen,rBar,rSupply,rPay,rStat,rBill,rProd,rReservation,rRating,rChangeprice,rManager,forNewUser) { +function createCollapsibeOfUser(id,username,isAdmin,rWaiter,rKitchen,rBar,rSupply,rPay,rStat,rBill,rProd,rReservation,rRating,rChangeprice,rClosing, rManager,forNewUser) { var collapsiblePart = '
-
+ -
+ -
+
Wenn dieser Text dargestellt wird, liegt ein Fehler vor!
- + +
@@ -2465,7 +2617,7 @@ $(document).on("pageinit", "#admin-page", function () {
-
+

Keine Datenänderung

diff --git a/webapp/paydesk.html b/webapp/paydesk.html index 641140c..80c1ba2 100644 --- a/webapp/paydesk.html +++ b/webapp/paydesk.html @@ -5,7 +5,7 @@ - + @@ -13,7 +13,7 @@ +var P_DESCR=["Beschreibung","Description","Descripción"];var P_PRICE=["Preis","Price","Precio"];var P_TOTAL=["Total","Total","Total"];var P_ID=["Id:","Id:","Id:"];var P_ROOMSEL=["Raumauswahl","Room selection","Selección de espacio"];var P_PAYDESK_ACTIONS=["Kassenaktionen","Paydesk actions","Acciones de caja"];var P_BAR_INPUT=["Bareinlage","Input money","Insertar dinero"];var P_BAR_GET=["Barentnahme","Take money","Sacar dinero"];var P_BAR_SUM=["Einnahmen","Revenue","Cobro"];var P_TITLE=["Kasse","Paydesk","Caja"];var P_TABLE=["Tisch","Table","Mesa"];var P_TABLE_SEL=["Tischauswahl","Select table","Qué mesa?"];var P_NOT_PAID=["Ausstehend für ","Not paid for ","Impagado para "];var P_ALL=["Alles","All","Todo"];var P_CONTENT_RECEIPT=["Inhalt Kassenbon","Content of receipt","Contenido del tique"];var P_ONLY_PAY=["Nur Zahlung","Only pay","Solo pagar"];var P_PAY_PRINT=["Bondruck","Pay+Print","Pagar+Imprimir"];var P_CHANGE_CALC=["Wechselgeldrechner:","Change Calculator:","Calculadora de Cambio:"];var P_CHOOSE_PAYWAY=["Auswahl der Zahlungsart:","Selection of method of payment:","Selección del modo de pago:"];var P_CANCEL=["Abbrechen","Cancel","Cancelar"];var P_CASHTAKEOUT=["Barentnahme aus der Kasse","Cash take-out","Sacar dinero"];var P_CASHTAKIN=["Bareinlage in die Kasse","Cash insert","Insertar dinero"];var P_AMOUNT=["Betrag:","Amount:","Valor:"];var P_OVERVIEW=["Übersicht Kellnerkasse","Overview waiter purse","Resumen cartera de bolsillo"];var P_PUT_IN=["Einlegen","Insert","Insertar"];var P_TAKE_OUT=["Entnehmen","Take out","Sacar"];var P_OVERV_DETAILS=["Diese Übersicht enthält die Bar-Bewirtungseinnahme durch den Kellner seit der letzten Tageslosung sowie als weiteren Wert den Kassenstand unter Berücksichtigung der eigenen Eingaben und Entnahmen.","This overview contains the cash amount of money of this waiter since the last closing as well as the total amount of money including the own cash insert and take-out actions.","Este resumen contiene todo el dinero al contado por cobro para el camarero, y también el dinero incluido con acciones de insertar y sacar."];var P_CASH_SUM=["Bewirtungseinnahmen:","Cash by payment:","Cobro:"];var P_INCLUDE_OWN=["inkl. eigener Kassen-Eingaben/Entnahmen:","incl. own cash insert/take-outs:","incl. tomas y entradas proprias:"];var P_NO_ELEM=["Keine Rechnungselemente","No items selected","Ningún producto selecionado"];var P_NO_ELEM_DETAILS=["Es wurden keine abrechenbaren Produkte festgelegt (der Bon ist leer!).","There are no selected items. The receipt is empty!","No hay ningún elemento seleccionado para pagar."];var P_CASHACTION_OK=["Kassenaktion abgeschlossen.","Action completed.","Acción terminado."];var P_NAV=["Navigation","Navigation","Navigación"];var P_ORDER_ACTION=["-> Bestellansicht","-> Order view","-> Vista de Orden"];var P_TO_PAY=["Zu zahlen: ","To pay: ","Pagar total: "];var P_PAY_RETURN=["Zurück: ","Return: ","Torna: "];var P_CALC_PAYBACK=["Berechne","Calculate","Calcular"];var P_HAS_PAID=["Bezahlt: ","Paid: ","Pagado: "];var P_TOGO=["Außer-Haus-Verkauf","Sale with Tax No 2","Venta IVA 2"];var P_TIP=["nur Trinkg.: ","Only tip: ","Solo prop.: "];var P_TOTAL_INCL_TIP=["Zielbetrag:","Target pay:","Quiere pagar:"];var CALC_TIP_TXT=["Angabe extra Trinkg.","Do Tip separate","Propina individual"];var CALC_TOTAL_TXT=["Angabe inkl.Trinkg.","Do Tip incl.","Propina incl."];var CALC_TIP=0;var CALC_TOTAL=1;var lang=0;var receiptfontsize=12;var paymentconfig=0;var decpoint=".";var currency="";var osroombtnsize=0;var ostablebtnsize=0;var osprodbtnsize=0;var tminfo=null;var hasRooms=true;var cameFromOrdering=0;var billbrutto=0;var billnetto=0;var prodsToPayList=[];var prodsToPayListGrouping=[];var payTable="";var prodsOnReceiptList=[];var prodsOnReceiptListGrouping=[];var calcmodus=CALC_TOTAL;var workflowconfig=0;var digigopaysetready=1;function initializeMainMenu(a){$.ajax({type:"GET",dataType:"json",url:"php/contenthandler.php?module=admin&command=getJsonMenuItemsAndVersion",async:false,success:function(c){$("#versioninfo").html(c.version+" ");if(c.loggedin==1){$("#loggedinuser").html(" "+c.user);var b='
  • Module
  • ';$.each(c.menu,function(g,f){var e=f.name;var h=f.link;if((e!="Abmelden")&&(e!="Log out")&&(e!="Adios")){b+='
  • '+e+"
  • "}else{b+='
  • '+e+"
  • "}});$(a).empty().append(b).promise().done(function(){$(a).listview("refresh")});$("#menuswitch").show()}else{$("#menuswitch").hide()}},error:function(b){alert("Kommunikationsproblem zum Server bei Modulabfrage!")}});$(".modulebutton").off("click").on("click",function(c){var b=$(this).attr("href");doAjax("POST","php/contenthandler.php?module=admin&command=setLastModuleOfUser",{view:b},null,"Problem Benutzerdatenpflege")})}function hideMenu(){$("#modulepanel").panel("close");$("#menuswitch").off("click").on("click",function(a){$("#menuswitch").trigger("mouseout");a.stopImmediatePropagation();a.preventDefault();$("#modulepanel").panel("open")})}function refreshList(a){if($(a).hasClass("ui-listview")){$(a).listview("refresh")}else{$(a).trigger("create")}}function doAjax(a,b,f,e,c,g){if(typeof g==="undefined"){g=false}$.ajax({type:a,url:b,dataType:"json",data:f,async:g,success:function(h){if(e!=null){e(h)}},error:function(l,h,i){if(c!=null){var k=c+", Status: "+h+", Error:"+i+", Msg: "+l.responseText+" ("+b+")";alert("Kommunikationsfehler zum Server: "+k)}}})}function doAjaxAsync(a,b,e,c){$.ajax({type:a,url:b,dataType:"json",data:e,async:true,success:function(f){if(c!=null){c(f)}},error:function(h,f,g){}})}function doAjaxTransmitData(a,b,g,f,e,c){$.ajax({type:a,url:b,dataType:"json",data:g,async:false,success:function(h){if(f!=null){f(h,c)}},error:function(l,h,i){if(e!=null){var k=e+", Status: "+h+", Error:"+i+", Msg: "+l.responseText+" ("+b+")";alert("Kommunikationsfehler zum Server: "+k)}}})}function doAjaxSuppressError(a,b,f,e,c){$.ajax({type:a,url:b,dataType:"json",data:f,async:false,success:function(g){if(e!=null){e(g)}},error:function(g){e("ERROR")}})}function doAjaxNonJsonNonCall(a,b,c){$.ajax({type:a,data:c,url:b,async:false,error:function(e){alert("Kommunikationsproblem zum Server")}})}function toHtml(a){if(typeof a==="string"){return(a.replace(/"/g,""").replace(//g,">"))}else{return a}}function createExtraParagraph(b){if((b==null)||(b=="")){return""}var c="";for(var a=0;a+ "+toHtml(b[a])+"

    "}return c}function checkForLogIn(){doAjax("GET","php/contenthandler.php?module=admin&command=isUserAlreadyLoggedIn",null,handleTestForLoggedIn,null)}function handleTestForLoggedIn(a){if(a!="YES"){setTimeout(function(){document.location.href="index.html"},250)}}function isInt(a){if(Math.floor(a)==a&&$.isNumeric(a)){return true}else{return false}}var P_SUM=["Summe:","Sum:","Todo:"];var P_TOTAL=["Total","Total","Total"];var P_MWST=["MwSt","Tax","IVA"];var P_NETTO=["Netto","Net","Neto"];var P_BRUTTO=["Brutto","Gross","Bruto"];var P_ID=["Id:","Id:","Id:"];var P_TABLE=["Tisch:","Table:","Mesa:"];var P_WAITER=["Es bediente Sie:","Waiter:","Camarero:"];var P_NO=["Anz.","No.","Nú."];var P_DESCR=["Beschreibung","Description","Descripción"];var P_PRICE=["Preis","Price","Precio"];function genCreateReceiptHeader(b,e,h,f,k){var a='style="border: solid black 0px;padding: 3px;text-align:right;vertical-align:bottom;"';var i=P_TABLE[b]+" "+h;var c=P_WAITER[b]+" "+f;var g="";g+=" ";g+=""+i+' ID:"+e+"";g+=' ";g+=""+c+"";g+=" ";g+=""+P_NO[b]+""+P_DESCR[b]+""+P_PRICE[b]+""+P_TOTAL[b]+"";return g}function genCreateReceiptFooterNoSum(c,e,b,a){return genCreateReceiptFooter(c,e,b,"","","",a)}function genCreateReceiptFooter(a,f,b,k,e,m,n){var c='style="border: solid black 0px;padding: 3px;text-align:right;vertical-align:bottom;"';var p='style="text-align:center;vertical-align:bottom;"';var h=" ";var o=h;o+=""+P_MWST[f]+"% "+P_MWST[f]+""+P_NETTO[f]+""+P_BRUTTO[f]+"";for(var l=0;l"+k+'"+e+'"+m+""}o+=h;o+="   "+P_SUM[f]+'"+m+"";o+=h;o+="
     
    ";o+=toHtml(b).replace(/(?:\r\n|\r|\n)/g,"
    ");o+="
    ";return o}function createReceiptFooterFromDbTaxes(c,a,h,k,m){var b='style="border: solid black 0px;padding: 3px;text-align:right;vertical-align:bottom;"';var n='style="text-align:center;vertical-align:bottom;"';var f=" ";var l=f;l+=""+P_MWST[c]+"% "+P_MWST[c]+""+P_NETTO[c]+""+P_BRUTTO[c]+"";for(var g=0;g"+e.tax;l+=""+e.mwst.replace(".",m);l+=""+e.netto.replace(".",m);l+=""+e.brutto.replace(".",m);l+=""}l+=f;l+="   "+P_SUM[c]+'"+h.toFixed(2).replace(".",m)+"";l+=f;l+="
     
    ";l+=toHtml(a).replace(/(?:\r\n|\r|\n)/g,"
    ");l+="
    ";return l}function generateOneProdLine(l,h,k,a,o,f){var b='style="border: solid black 0px;padding: 3px;text-align:right;vertical-align:bottom;"';var i='style="border: solid black 0px;padding: 3px;text-align:center;vertical-align:bottom;"';var c=(parseFloat(k)).toFixed(2).replace(".",o);if(a!="A"){h+=" ("+a+")"}if(f==1){h="To-Go: "+h}var n=l*k;var g=n.toFixed(2).replace(".",o);var m="";var e='style="white-space: nowrap;overflow: hidden;text-overflow:ellipsis;width: 60%;"';m+="'+l+""+h;m=m+""+c;m+=""+n.toFixed(2).replace(".",o)+"";return m}function generateProdPart(k,b){var i=0;tablecontent="";for(i=0;i";return m}function Tablemap(b,a,c){this.tables=a;this.roomid=b;this.elem=c;this.selectedTableId=-1;if((a!=null)&&(a.length>0)){this.selectedTableId=a[0].id}}Tablemap.prototype.renderContent=function(){doAjaxTransmitData("GET","php/tablemap.php?command=getTableMap&roomid="+this.roomid,null,this.renderTableList,null,this);d=new Date();$("#mapimgpart").attr("src","php/tablemap.php?command=getTableMapImgAsPng&roomid="+this.roomid+"&tableid="+this.selectedTableId+"&"+d.getTime())};Tablemap.prototype.renderTableList=function(b,a){a.tables=b;var c=a.createList(b,"table_","tablebtn","c",a);$(a.elem).html(c);tmRefreshList(a.elem);a.binding(a)};Tablemap.prototype.createList=function(n,a,g,h,p){var m='
    ';for(var l=0;l'}m+="
    ";return m};Tablemap.prototype.binding=function(a){$(".tablebtn").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();a.selectedTableId=this.id.split("_")[1];a.renderContent(a.elem)});$("#tmimgbtn").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();a.uploadImg(a)});$("#mapimgpart").off("click").on("click",function(k){k.stopImmediatePropagation();k.preventDefault();var c=$("#mapimgpart").width();var b=$("#mapimgpart").height();var l=$(this).offset().top-$(window).scrollTop();var g=$(this).offset().left-$(window).scrollLeft();var i=Math.round((k.clientX-g));var h=Math.round((k.clientY-l));var f={tableid:a.selectedTableId,x:(100*i)/c,y:(100*h)/b};doAjaxTransmitData("POST","php/tablemap.php?command=setPosition",f,a.renderIfOk,null,a)})};Tablemap.prototype.createOverlay=function(w,g,m,s,e,h,r){var o=[];var f="";if(r==0){f="overlaysize-0"}else{if(r==1){f="overlaysize-1"}else{if(r==2){f="overlaysize-2"}}}for(var v=0;v'+x;if(u!=0){p=''+x;if(m!=""){p+="
    ("+m+": "+k+")"}else{p+="
    ("+k+")"}}p+="
    ";o[o.length]=p}}return o};Tablemap.prototype.bindingForOverlaySelection=function(a,c,b){$(".overlaytxt").off("click").on("click",function(m){m.stopImmediatePropagation();m.preventDefault();var g=this.id.split("_")[1];var h="?";for(var f=0;f0)){var u=a[0].id;var n=a[0].name;var t=(100*100)+(100*100);for(var k=0;k'}k+="";return k};Tablemap.prototype.uploadImg=function(a){var b=new FormData($("#tablemapimgform")[0]);b.append("roomid",a.roomid);$.ajax({url:"php/tablemap.php?command=uploadimg",type:"POST",dataType:"json",xhr:function(){var c=$.ajaxSettings.xhr();if(c.upload){}return c},success:function(c){if(c.status!="OK"){a.imgNotUploaded(c)}else{a.imgUploaded(c,a)}},error:function(c){a.imgNotUploaded(c)},data:b,cache:false,contentType:false,processData:false})};Tablemap.prototype.imgUploaded=function(b,a){a.renderContent()};Tablemap.prototype.imgNotUploaded=function(a){alert("Bild konnte nicht hochgeladen werden. Ist es zu groß (> 1 MB)? Oder wurde der Dateiname nicht angegeben?")};function closePrint(){document.body.removeChild(this.__container__)}function setAndStartPrint(){this.contentWindow.__container__=this;this.contentWindow.onbeforeunload=closePrint;this.contentWindow.onafterprint=closePrint;this.contentWindow.focus();this.contentWindow.print()}function printContent(c){var b=document.createElement("iframe");b.setAttribute("id","printiframe");b.onload=setAndStartPrint;b.style.visibility="hidden";b.style.position="fixed";b.style.right="0";b.style.bottom="0";var a=""+c+"";b.src="data:text/html;charset=utf-8,"+encodeURI(a);document.body.appendChild(b)}function Grouping(b,a){this.set=b;this.sortedset=[];this.group=function(){this.sortedset=[];for(var g=0;g
  • '+P_BAR_INPUT[lang]+'
  • '+P_BAR_GET[lang]+'
  • '+P_BAR_SUM[lang]+"
  • ";$("#cashactions").html(a);$("#cashactions").listview("refresh");$("#navtitle").html(P_NAV[lang]);$("#nav2order").html(P_ORDER_ACTION[lang]);$("#navactions").listview("refresh");$("#paydesktitle").html(P_TITLE[lang]);$("#OnlyPayTxt").html(P_ONLY_PAY[lang]);$("#payprinttxt").html(P_PAY_PRINT[lang]);$("#payway").html(P_CHANGE_CALC[lang]);$("#choosepayway").html(P_CHOOSE_PAYWAY[lang]);$("#canceltxt").html(P_CANCEL[lang]);$("#cashtakeouttxt").html(P_CASHTAKEOUT[lang]);$("#amounttxt").html(P_AMOUNT[lang]);$("#amounttxt2").html(P_AMOUNT[lang]);$("#cashtakeintxt").html(P_CASHTAKIN[lang]);$("#cashoverviewtxt").html(P_OVERVIEW[lang]);$("#putinact").html(P_PUT_IN[lang]);$("#takeoutact").html(P_TAKE_OUT[lang]);$("#overviewdetails").html(P_OVERV_DETAILS[lang]);$("#cashsum").html(P_CASH_SUM[lang]);$("#includeowncash").html(P_INCLUDE_OWN[lang]);$("#noelementstxt").html(P_NO_ELEM[lang]);$("#noelementsdetailstxt").html(P_NO_ELEM_DETAILS[lang]);$("#topaytxt").html(P_TO_PAY[lang]);$("#rettxt").html(P_PAY_RETURN[lang]);$("#calcreturn").html(P_CALC_PAYBACK[lang]);$("#haspaidtxt").html(P_HAS_PAID[lang]);$("#tableselimmaptxt").html(P_TABLE_SEL[lang]);setCalcModusBtn()}function getButtonSizes(){doAjax("GET","php/contenthandler.php?module=admin&command=getButtonSizes",null,fillButtonSizes,"Keine Buttongroesseninformation")}function fillButtonSizes(a){osroombtnsize=a.roombtnsize;ostablebtnsize=a.tablebtnsize;osprodbtnsize=a.prodbtnsize}function getProdSizeClass(){if(osprodbtnsize==1){return("osprod-1")}else{if(osprodbtnsize==2){return("osprod-2")}else{return""}}}function getTableSizeClass(){if(ostablebtnsize==1){return("ostable-1")}else{if(ostablebtnsize==2){return("ostable-2")}else{return""}}}function getRoomSizeClass(){if(osroombtnsize==1){return("osroom-1")}else{if(osroombtnsize==2){return("osroom-2")}else{return""}}}function insertPayments(e){var c="";var a=20;if(paymentconfig==1){a=2}var b=false;$.each(e,function(g,f){if(g'+f.name+"";if(!b){c+="


    ";b=true}}});c+=''+P_CANCEL[lang]+"";$("#paymentlist").html(c)}function hideReceiptPart(){$("#payWithoutPrint").hide();$("#payWithPrint").hide();$("#hostbutton").hide();$("#unten").hide()}function showReceiptPart(){$("#payWithoutPrint").show();$("#payWithPrint").show();$("#hostbutton").show();$("#unten").show();$("#tablemapcontent").hide();$("#togoarea").hide()}function getTableMapPreferences(){doAjax("GET","php/tablemap.php?command=getTableMapPreferences",null,insertTMInfo,"Keine TM-Information")}function insertTMInfo(a){tminfo=a;startDisplayProcess()}function shallDisplayRoom(b){for(var a=0;a'+P_NO[a]+""+P_DESCR[a]+''+P_PRICE[a]+''+P_TOTAL[a]);$.getJSON("php/contenthandler.php?module=roomtables&command=getRooms",function(f){var g=f.roomstables;var c=f.takeawayprice;var h=g.length;if(h==1){$("#info-page").data("roomid",g[0]["id"]);displayTablesOfRoom(g[0],false);if(cameFromOrdering==1){$("#startpaypage").show()}else{$("#startpaypage").hide()}}else{var b="";var e=getRoomSizeClass();$.each(g,function(l,k){b+='
  • '+k.name+"
  • "});if(c!="0.00"){b+='
  • '+P_TOGO[a]+" ("+c+" "+currency+")
  • "}$("#startpaypage").hide();$("#oben").append(b).promise().done(function(){bindTogoOrdering();$(this).off("click").on("click","a",function(k){k.stopImmediatePropagation();k.preventDefault();var i=g[this.id];$("#info-page").data("roomid",i.id);$("#startpaypage").show();displayTablesOfRoom(i,true)});refreshList(this)})}})}function bindTogoOrdering(){$(".togoorder").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();$("#info-page").data("roomid",null);$("#info-page").data("tableviewactive",0);$("#info-page").data("tid",0);$("#info-page").data("tablename",P_TOGO[lang]);$("#oben").show();getProdsToPayForTable(0,"")})}function displayTablesOfRoom(a,b){checkForLogIn();hasRooms=b;var c=$("#info-page").data("roomid");hideReceiptPart();displayUnpaidTables("Tischinfo nicht erhalten!")}$(document).ready(function(){checkForLogIn();var a=setInterval(function(){var b=$("#info-page").data("roomid");if(b!=null){displayUnpaidTables(null)}},10000);$.ajaxSetup({cache:false})});function displayUnpaidTables(a){doAjax("GET","php/contenthandler.php?module=roomtables&command=getUnpaidTables",{roomid:$("#info-page").data("roomid")},displayTables,a)}function displayTables(f){var i=f.tables;var e=f.takeawayprice;$("#info-page").data("tableviewactive",1);var a=$("#info-page").data("roomid");var g=shallDisplayRoom(a);if(g.show){$("#oben").hide();$("#tablemapcontent").show();$("#togoarea").show();d=new Date();$("#mapimgpart").attr("src","php/tablemap.php?command=getUnpaidTablesMapImgAsPng&showBubbles=0&roomid="+a+"&"+d.getTime());var b=new Tablemap(a,null,"");var c=b.createOverlay("#mapimgpart",g.pos,"",decpoint,currency,i,ostablebtnsize);$("#tableoverlay").html(c);b.bindingForOverlaySelection(handleClickInTablemap.bind(this),a,i);if(!hasRooms){if(e!="0.00"){var h='
  • '+P_TOGO[lang]+"
  • ";$("#tables-list-togo").html(h);$("#togoarea").show()}refreshList("#tables-list-togo");bindTogoOrdering()}}else{$("#oben").show();$("#tablemapcontent").hide();$("#togoarea").hide();var h='
  • '+P_TABLE_SEL[lang]+"
  • ";var k=getTableSizeClass();$.each(i,function(m,o){var n=o.pricesum.replace(".",decpoint);var l=o.name+"    ("+n+" "+currency+")";h+='
  • '+l+"
  • "});if(!hasRooms){if(e!="0.00"){h+='
  • '+P_TOGO[lang]+"
  • "}}$("#oben").empty().append(h).promise().done(function(){bindTogoOrdering();$(this).off("click").on("click",".info-go",function(n){n.stopImmediatePropagation();n.preventDefault();$("#info-page").data("roomid",null);$("#info-page").data("tableviewactive",0);var l=i[this.id]["id"];var m=i[this.id]["name"];$("#info-page").data("tid",l);$("#info-page").data("tablename",m);getProdsToPayForTable(l,m)});refreshList(this)})}}function getProdsToPayForTable(a,b){$("#startpaypage").show();if(a==0){b=P_TOGO[lang];$("#info-page").data("taxtype","togo")}else{$("#info-page").data("taxtype","normal")}$("#cashactions").hide();$("#navactions").hide();$.ajax({type:"GET",dataType:"json",data:{tableid:a},url:"php/contenthandler.php?module=queue&command=getJsonProductsOfTableToPay",async:false,success:function(e){var c=e.status;var f=e.msg;if(c!="ERROR"){showReceiptPart();$("#info-page").data("tableprods",f);bindPayButton(f,a,b);initiatePayableView(f,b)}else{alert("Fehler: "+f)}},error:function(c){alert("Sorry, there was a problem getting the products to pay for table!")}})}function initiatePayableView(a,b){$("#tableinreceipt").html(b+"
     ");clearUntenAndReceipt();createAllEntriesInReceipt();calcSum();prodsToPayList=a;payTable=b;displayProdsToPayForTable()}function displayProdsToPayForTable(){prodsToPayListGrouping=new Grouping(prodsToPayList,createHashOfPayableItem);prodsToPayListGrouping.group();var b=getProdSizeClass();var a='
  • '+P_NOT_PAID[lang]+payTable+"
  • ";a+='
  • '+P_ALL[lang]+"
  • ";var c=a+prodsToPayListGrouping.outputList(createPayableItemListElement);$("#oben").html(c);refreshList("#oben");$(".payable").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=$(this).closest("li");var i=$("#oben li").index(g)-2;var f=prodsToPayListGrouping.popSortedEntry(i);prodsOnReceiptList[prodsOnReceiptList.length]=f;displayProdsToPayForTable();displayProdsOnReceipt()});$("#payall").off("click").on("click",function(g){g.stopImmediatePropagation();g.preventDefault();for(var f=0;f0,00 '+currency+"

    ";var c=a+prodsOnReceiptListGrouping.outputList(createOnReceiptItemListElement);$("#unten").html(c);refreshList("#unten");createAllEntriesInReceipt();$(".onreceipt").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=$(this).closest("li");var i=$("#unten li").index(g)-1;var f=prodsOnReceiptListGrouping.popSortedEntry(i);prodsToPayList[prodsToPayList.length]=f;displayProdsToPayForTable();displayProdsOnReceipt()})}function generateListItem(g,c,h,e,f){var b=getProdSizeClass();var a='
  • ';a+=''+e+"
  • ";return a}function createHashOfPayableItem(b){var a=b.longname;if(b.pricelevelname!="A"){a+=" ("+b.pricelevelname+")"}a+=" - "+(parseFloat(b.price).toFixed(2).replace(".",decpoint));if(b.togo==1){a="To-Go: "+a}var c=createExtraParagraph(b.extras);return toHtml(a)+c}function createPayableItemListElement(b){var a="";if("count" in b){if(b.count>1){a=b.count+"x "}}var c=generateListItem("c","plus","payable_"+b.id,a+createHashOfPayableItem(b),"payable");return c}function createOnReceiptItemListElement(b){var a="";if("count" in b){if(b.count>1){a=b.count+"x "}}var c=generateListItem("c","plus","payable_"+b.id,a+createHashOfPayableItem(b),"onreceipt");return c}function clearUntenAndReceipt(){var a='
  • ';a+=P_CONTENT_RECEIPT[lang]+':

    0,00 '+currency+"

  • ";$("#unten").empty().append(a).promise().done(function(){refreshList("#unten")});$("#prodlistinreceipt tr").each(function(){$(this).remove()});$("#thedate").html("

     
    ")}function addEntryOrIncreaseCount(a,f){var c=0;var g=false;var e=f.prodid+"-"+f.extras.join("_")+f.price+"-"+f.pricelevelname+"#"+f.tax+"_"+f.togo;for(c=0;c"+$("#info-page").data("receipthtml")+"";var e=$("#info-page").data("escposheader");var p=$("#info-page").data("escposprods");var n=$("#info-page").data("escposfooter");var r=new Array(e,p,n,$("#info-page").data("hosting"));var g=cameFromOrdering;if(cameFromOrdering==1){if(workflowconfig==1){g=digigopaysetready}}$.ajax({type:"POST",dataType:"json",data:{ids:a,brutto:billbrutto,netto:billnetto,tableid:c,paymentid:q,tax:h,decpoint:decpoint,declareready:g,host:$("#info-page").data("hosting")},url:"php/contenthandler.php?module=queue&command=declarePaidCreateBillReturnBillId",async:false,success:function(w){var u=w.status;var v=w.msg;if(u!="ERROR"){billid=v.billid;billdate=v.date;if(billid<0){alert("Error! Bitte erneut versuchen. Error code: "+billid);window.location.reload(false)}else{var y=$("#info-page").data("billlanguage");$("#billid").html(P_ID[y]+billid);$("#billdate").html(billdate);if(o){var z=''+$("#receiptpart").html()+"
    ";var t=$("#info-page").data("payPrintType");if(t=="s"){printBill(billid)}else{$("#oben").hide();var x=""+$(".receipttable").html()+"
    ";printContent(x)}}prodsOnReceiptList=[];getProdsToPayForTable(c,m);var i=$("#oben li").size()-2;if(i>0){}else{if(cameFromOrdering==1){goToUrl("waiter.html")}else{goToUrl("paydesk.html")}}}}else{alert("Fehler: "+v)}},error:function(i){alert("Sorry, there was a problem! "+i)}})}function goToUrl(a){setTimeout(function(){document.location.href=a},500)}function printBill(a){doAjax("POST","php/contenthandler.php?module=printqueue&command=queueReceiptPrintJob",{billid:a},null,"Druckfehler")}function bindHostButton(){$("#hostbutton").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();var a=$("#info-page").data("billlanguage");if(a==0){var c=$("#info-page").data("hosting");if(c=="0"){$("#info-page").data("hosting","1")}else{$("#info-page").data("hosting","0")}createAllEntriesInReceipt()}else{if(lang==0){alert("Bewirtungsbeleg steht nur für deutsche Kassenbons zur Verfügung.")}else{if(lang==1){alert("Bewirtungsbeleg is only possible for German receipts.")}else{if(lang==2){alert("Bewirtungsbeleg se puedo usar solo para tiques alemanes.")}}}}})}function cashactions(){$(".cashaction").off("click").on("click",function(a){var b=$(this).attr("id");if(b=="cashtakeout"){startCashTakeOutProcess()}else{if(b=="cashinsert"){startCashInsertProcess()}else{if(b=="cashoverview"){startCashOverviewProcess()}}}})}function startCashInsertProcess(){$("#cashinsertdialog .sure-do").off("click").on("click",function(){$.mobile.changePage("#info-page");var a=$("#moneyToInsert").val().replace($("#info-page").data("decpoint"),".");if(isNaN(a)){alert("Keine Zahl!")}else{if((parseFloat(a)>=0)&&(parseFloat(a)<=10000)){doCashInsert(a)}else{alert("Betrag muss positiv und kleiner als 10000 sein!")}}});$.mobile.changePage("#cashinsertdialog")}function startCashTakeOutProcess(){$("#cashtakeoutdialog .sure-do").off("click").on("click",function(){$.mobile.changePage("#info-page");var a=$("#moneyToTakeOut").val().replace(decpoint,".");if(isNaN(a)){alert("Keine Zahl!")}else{if((parseFloat(a)>=0)&&(parseFloat(a)<=10000)){doCashTakeOut(a)}else{alert("Betrag muss positiv und kleiner als 10000 sein!")}}});$.mobile.changePage("#cashtakeoutdialog")}function doCashInsert(a){doAjax("POST","php/contenthandler.php?module=bill&command=doCashAction",{money:a},handleCashActionResult,"Fehler Kassenaktion")}function doCashTakeOut(a){a=0-parseFloat(a);doAjax("POST","php/contenthandler.php?module=bill&command=doCashAction",{money:a},handleCashActionResult,"Fehler Kassenaktion")}function startCashOverviewProcess(){doAjax("POST","php/contenthandler.php?module=bill&command=getCashOverviewOfUser",null,showCashOverview,"Fehler Kassenaktion")}function handleCashActionResult(a){if(a.status=="ERROR"){alert("Fehler "+a.code+": "+a.msg)}else{if(a.status=="OK"){alert(P_CASHACTION_OK[lang])}}}function showCashOverview(a){$("#cashbyguests").html((parseFloat(a.guestmoney).toFixed(2)).replace(".",decpoint));$("#cashtotal").html((parseFloat(a.total).toFixed(2)).replace(".",decpoint));$.mobile.changePage("#cashoverviewinfo")}function startDisplayProcess(){var b=location.search;if(b.indexOf("t=")<0){displayAllRooms()}else{var e="";var g=b.split(/&|\?/);for(var a=0;a diff --git a/webapp/php/admin.php b/webapp/php/admin.php index be6b63f..f2da86d 100644 --- a/webapp/php/admin.php +++ b/webapp/php/admin.php @@ -17,203 +17,257 @@ class Admin { private static $timezone = null; + private static $rights = array( + "createNewUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "updateUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "deleteUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "changepassword" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "changeConfig" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "readlogo" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "deletelogo" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + + "getCurrentUser" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "tryAuthenticate" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "setLastModuleOfUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getViewAfterLogin" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "isUserAlreadyLoggedIn" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "isLoggedinUserAdmin" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "isLoggedinUserKitchen" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "isLoggedinUserBar" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "isLoggedinUserAdminOrManagerOrTE" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "hasUserPaydeskRight" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getJsonMenuItemsAndVersion" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "getUserList" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "setTime" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "changeOwnPassword" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + + "setUserLanguage" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "setUserReceiptPrinter" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "setBtnSize" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getGeneralConfigItems" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getWaiterSettings" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getPayPrintType" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getPayments" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "autobackup" => array("loggedin" => 0, "isadmin" => 0, "rights" => null), + "shutdown" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "backup" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "restore" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "golive" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "drop" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "fill" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "fillSpeisekarte" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + "assignTaxes" => array("loggedin" => 1, "isadmin" => 1, "rights" => null), + + "exportConfigCsv" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "exportUserCsv" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")), + "setOrderVolume" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "setPreferTableMap" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "setKeepTypeLevel" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "setApplyExtrasBtnPos" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getOrderVolume" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getButtonSizes" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getPreferTableMap" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getKeepTypeLevel" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "getApplyExtrasBtnPos" => array("loggedin" => 1, "isadmin" => 0, "rights" => null), + "isInstalled" => array("loggedin" => 0, "isadmin" => 0, "rights" => null) + ); + + function __construct() { $this->dbutils = new DbUtils(); $this->userrights = new Userrights(); $this->histfiller = new HistFiller(); } + + private static function checkRights($command) { + if(session_id() == '') { + session_start(); + } + if (!array_key_exists($command, self::$rights)) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_FOUND, "msg" => ERROR_COMMAND_NOT_FOUND_MSG)); + return false; + } + $cmdRights = self::$rights[$command]; + if ($cmdRights["loggedin"] == 1) { + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); + return false; + } + } + if ($cmdRights["isadmin"] == 1) { + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); + return false; + } else { + if ($_SESSION['is_admin'] == 0) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_ADMIN, "msg" => ERROR_COMMAND_NOT_ADMIN_MSG)); + return false; + } + } + } + if (!is_null($cmdRights["rights"])) { + foreach($cmdRights["rights"] as $aRight) { + if ($aRight == 'manager_or_admin') { + if (($_SESSION['is_admin'] == 1) || ($_SESSION['right_manager'] == 1)) { + return true; + } + } + } + echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); + return false; + } + return true; + } + function handleCommand($command) { - // these command are only allowed for user with manager or admin rights - $cmdArray = array('createNewUser', 'updateUser', 'deleteUser','changepassword' , 'changeConfig', 'readlogo','deletelogo'); - if (in_array($command, $cmdArray)) { - if (!($this->userrights->hasCurrentUserRight('right_manager')) && !($this->userrights->hasCurrentUserRight('is_admin'))) { - echo "Benutzerrechte nicht ausreichend!"; - return false; - } - } + if (!self::checkRights($command)) { + return false; + } - if ($command == 'tryAuthenticate') { - $this->tryAuthenticate($_POST['userid'],$_POST['password'],$_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute'],$_POST["time"]); - } else if ($command == 'setLastModuleOfUser') { - $this->setLastModuleOfUser($_POST['view']); - } else if ($command == 'getViewAfterLogin') { - $this->getViewAfterLogin(); - } else if ($command == 'isUserAlreadyLoggedIn') { - $this->isUserAlreadyLoggedIn(); - } else if ($command == 'logout') { - $this->logout(); - } else if ($command == 'getCurrentUser') { - $this->getCurrentUser(); - } else if ($command == 'isLoggedinUserAdmin') { - $this->isLoggedinUserAdmin(); - } else if ($command == 'isLoggedinUserKitchen') { - $this->isLoggedinUserKitchen(); - } else if ($command == 'isLoggedinUserBar') { - $this->isLoggedinUserBar(); - } else if ($command == 'isLoggedinUserAdminOrManager') { - $this->isLoggedinUserAdminOrManager(); - } else if ($command == 'hasUserPaydeskRight') { - $this->hasUserPaydeskRight(); - } else if ($command == 'getJsonMenuItemsAndVersion') { - $this->getJsonMenuItemsAndVersion(); - } else if ($command == 'getUserList') { - $this->getUserList(); - } else if ($command == 'setTime') { - $this->setTime($_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute']); - } else if ($command == 'createNewUser') { - $this->createNewUser( - $_POST['username'], - $_POST['password'], - $_POST['isAdmin'], - $_POST['rWaiter'], - $_POST['rKitchen'], - $_POST['rBar'], - $_POST['rSupply'], - $_POST['rPayDesk'], - $_POST['rStat'], - $_POST['rBill'], - $_POST['rProducts'], - $_POST['rReservation'], - $_POST['rRating'], - $_POST['rChangeprice'], - $_POST['rManager'] - ); - } else if ($command == 'updateUser') { - $this->updateUser( - $_POST['userid'], - $_POST['isAdmin'], - $_POST['rWaiter'], - $_POST['rKitchen'], - $_POST['rBar'], - $_POST['rSupply'], - $_POST['rPayDesk'], - $_POST['rStat'], - $_POST['rBill'], - $_POST['rProducts'], - $_POST['rReservation'], - $_POST['rRating'], - $_POST['rChangeprice'], - $_POST['rManager'] - ); - } else if ($command == 'deleteUser') { - $this->deleteUser($_POST['userid']); - } else if ($command == 'changepassword') { - $this->changepassword($_POST['userid'],$_POST['password']); - } else if ($command == 'changeOwnPassword') { - $this->changeOwnPassword($_POST['oldPass'],$_POST['newPass']); - } else if ($command == 'setUserLanguage') { - $this->setUserLanguage($_POST['language']); - } else if ($command == 'setUserReceiptPrinter') { - $this->setUserReceiptPrinter($_POST['printer']); - } else if ($command == 'setBtnSize') { - $this->setBtnSize($_POST['btn'],$_POST['size']); - } else if ($command == 'changeConfig') { - $this->changeConfig($_POST['changed']); - } else if ($command == 'readlogo') { - $this->readlogo(); - } else if ($command == 'deletelogo') { - $this->deletelogo(); - } else if ($command == 'getGeneralConfigItems') { - $this->getGeneralConfigItems(true,null); - } else if ($command == 'getWaiterSettings') { - $this->getWaiterSettings(); - // from here on admin rights are needed - } else if ($command == 'getPayPrintType') { - $this->getPayPrintType(); - } else if ($command == 'getPayments') { - $this->getPayments(); - } else if ($command == 'autobackup') { - $this->backup('auto',$_POST['remoteaccesscode']); - } else if (($command == 'new') || ($command == 'shutdown') || ($command == 'backup') || ($command == 'restore') || ($command == 'drop') || ($command == 'fill') || ($command == 'fillSampleProdType') || ($command == 'fillSpeisekarte') || ($command == 'assignTaxes')) { - if ($this->isCurrentUserAdmin()) { - if ($command == 'fill') { - $this->fillSampleContent(); - echo json_encode(array("status" => "OK")); - } else if ($command == 'fillSampleProdType') { - $this->fillSampleProdType("samples/speisekarte.txt"); - echo json_encode(array("status" => "OK")); - } else if ($command == 'fillSpeisekarte') { - $this->fillSpeisekarte($_POST['speisekarte']); - } else if ($command == 'backup') { - $this->backup($_GET['type'],null); - return; - } else if ($command == 'restore') { - $this->restore(); - return; - } else if ($command == 'shutdown') { - $this->shutdown(); - return; - } else if ($command == 'assignTaxes') { - $this->assignTaxes($_POST['food'],$_POST['drinks']); - return; - } - } else { - echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); - } - // end area for admins - } else if ($command == 'exportConfigCsv') { - if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) { - $this->exportConfigCsv(); - } - } else if ($command == 'exportUserCsv') { - if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) { - $this->exportUserCsv(); - } - } else if ($command == 'setOrderVolume') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->setOrderVolume($_POST['volume']); - } - } else if ($command == 'setPreferTableMap') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->setPreferTableMap($_POST['prefertablemap']); - } - } else if ($command == 'setKeepTypeLevel') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->setKeepTypeLevel($_POST['keeptypelevel']); - } - } else if ($command == 'setApplyExtrasBtnPos') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->setExtrasApplyBtnPos($_POST['applyextrasbtnpos']); - } - } else if ($command == 'getOrderVolume') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->getOrderVolume(); - } - } else if ($command == 'getButtonSizes') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->getButtonSizes(); - } - } else if ($command == 'getPreferTableMap') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->getPreferTableMap(); - } - } else if ($command == 'getKeepTypeLevel') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->getKeepTypeLevel(); - } - } else if ($command == 'getApplyExtrasBtnPos') { - if ($this->isUserAlreadyLoggedInForPhp()) { - $this->getApplyExtrasBtnPos(); - } - } else if ($command == 'isInstalled') { - $this->isInstalled(); - } - else { - echo "Command not supported."; - } + if ($command == 'tryAuthenticate') { + $this->tryAuthenticate($_POST['userid'],$_POST['password'],$_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute'],$_POST["time"]); + } else if ($command == 'setLastModuleOfUser') { + $this->setLastModuleOfUser($_POST['view']); + } else if ($command == 'getViewAfterLogin') { + $this->getViewAfterLogin(); + } else if ($command == 'isUserAlreadyLoggedIn') { + $this->isUserAlreadyLoggedIn(); + } else if ($command == 'logout') { + $this->logout(); + } else if ($command == 'getCurrentUser') { + $this->getCurrentUser(); + } else if ($command == 'isLoggedinUserAdmin') { + $this->isLoggedinUserAdmin(); + } else if ($command == 'isLoggedinUserKitchen') { + $this->isLoggedinUserKitchen(); + } else if ($command == 'isLoggedinUserBar') { + $this->isLoggedinUserBar(); + } else if ($command == 'isLoggedinUserAdminOrManagerOrTE') { + $this->isLoggedinUserAdminOrManagerOrTE(); + } else if ($command == 'hasUserPaydeskRight') { + $this->hasUserPaydeskRight(); + } else if ($command == 'getJsonMenuItemsAndVersion') { + $this->getJsonMenuItemsAndVersion(); + } else if ($command == 'getUserList') { + $this->getUserList(); + } else if ($command == 'setTime') { + $this->setTime($_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute']); + } else if ($command == 'createNewUser') { + $this->createNewUser(); + } else if ($command == 'updateUser') { + $this->updateUser(); + } else if ($command == 'deleteUser') { + $this->deleteUser($_POST['userid']); + } else if ($command == 'changepassword') { + $this->changepassword($_POST['userid'],$_POST['password']); + } else if ($command == 'changeOwnPassword') { + $this->changeOwnPassword($_POST['oldPass'],$_POST['newPass']); + } else if ($command == 'setUserLanguage') { + $this->setUserLanguage($_POST['language']); + } else if ($command == 'setUserReceiptPrinter') { + $this->setUserReceiptPrinter($_POST['printer']); + } else if ($command == 'setBtnSize') { + $this->setBtnSize($_POST['btn'],$_POST['size']); + } else if ($command == 'changeConfig') { + $this->changeConfig($_POST['changed']); + } else if ($command == 'readlogo') { + $this->readlogo(); + } else if ($command == 'deletelogo') { + $this->deletelogo(); + } else if ($command == 'getGeneralConfigItems') { + $this->getGeneralConfigItems(true,null); + } else if ($command == 'getWaiterSettings') { + $this->getWaiterSettings(); + // from here on admin rights are needed + } else if ($command == 'getPayPrintType') { + $this->getPayPrintType(); + } else if ($command == 'getPayments') { + $this->getPayments(); + } else if ($command == 'autobackup') { + $this->backup('auto',$_POST['remoteaccesscode']); + } else if ($command == 'fill') { + $this->fillSampleContent(); + echo json_encode(array("status" => "OK")); + } else if ($command == 'fillSpeisekarte') { + $this->fillSpeisekarte($_POST['speisekarte']); + } else if ($command == 'backup') { + $this->backup($_GET['type'],null); + return; + } else if ($command == 'restore') { + $this->restore(); + return; + } else if ($command == 'golive') { + $this->golive(); + return; + } else if ($command == 'shutdown') { + $this->shutdown(); + return; + } else if ($command == 'assignTaxes') { + $this->assignTaxes($_POST['food'],$_POST['drinks']); + return; + } else if ($command == 'exportConfigCsv') { + if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) { + $this->exportConfigCsv(); + } + } else if ($command == 'exportUserCsv') { + if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) { + $this->exportUserCsv(); + } + } else if ($command == 'setOrderVolume') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->setOrderVolume($_POST['volume']); + } + } else if ($command == 'setPreferTableMap') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->setPreferTableMap($_POST['prefertablemap']); + } + } else if ($command == 'setKeepTypeLevel') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->setKeepTypeLevel($_POST['keeptypelevel']); + } + } else if ($command == 'setApplyExtrasBtnPos') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->setExtrasApplyBtnPos($_POST['applyextrasbtnpos']); + } + } else if ($command == 'getOrderVolume') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->getOrderVolume(); + } + } else if ($command == 'getButtonSizes') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->getButtonSizes(); + } + } else if ($command == 'getPreferTableMap') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->getPreferTableMap(); + } + } else if ($command == 'getKeepTypeLevel') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->getKeepTypeLevel(); + } + } else if ($command == 'getApplyExtrasBtnPos') { + if ($this->isUserAlreadyLoggedInForPhp()) { + $this->getApplyExtrasBtnPos(); + } + } else if ($command == 'isInstalled') { + $this->isInstalled(); + } + else { + echo "Command not supported."; + } } /*** * Is the installation already done? Or was the html/php code overwritten, i.e. a new or updated version to install? */ private function isInstalled() { - if(defined('INSTALLSTATUS')){ + if(defined('INSTALLSTATUS')){ if (INSTALLSTATUS == 'new') { echo json_encode("No"); } else { echo json_encode("Yes"); - } + } } else { // not defined -> it must be version 1.0.3 or lower --> since this is file of 1.0.4: not installed... echo json_encode("No"); @@ -221,9 +275,9 @@ class Admin { } function isUserAlreadyLoggedInForPhp() { - if(session_id() == '') { - session_start(); - } + if(session_id() == '') { + session_start(); + } if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { return false; } else { @@ -235,8 +289,8 @@ class Admin { if(session_id() == '') { session_start(); } - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { - // no user logged in + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + // no user logged in echo json_encode("NO"); } else { echo json_encode("YES"); @@ -244,9 +298,9 @@ class Admin { } function logout() { - if(session_id() == '') { + if(session_id() == '') { session_start(); - session_destroy(); + session_destroy(); } echo json_encode("OK"); } @@ -269,27 +323,27 @@ class Admin { function tryAuthenticate($userid,$password,$day,$month,$year,$hour,$minute,$unixtime) { $pdo = DbUtils::openDbAndReturnPdoStatic(); - $authenticated = false; + $authenticated = false; $sql = "SELECT * FROM %user% WHERE id=? AND active='1'"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($userid)); - $result = $stmt->fetchAll(); - - $numberOfEntries = count($result); + $result = $stmt->fetchAll(); + + $numberOfEntries = count($result); if ($numberOfEntries == 1) { - $zeile = $result[0]; - $pass_hash = $zeile['userpassword']; + $zeile = $result[0]; + $pass_hash = $zeile['userpassword']; if ($zeile['is_admin'] == 0) { // authentication-check } - - // password_verify requires PHP > 5.5, so let's use MD5 instead - // (it is no banking software...) - if (md5($password) == $pass_hash) { - $authenticated = true; - } - } + + // password_verify requires PHP > 5.5, so let's use MD5 instead + // (it is no banking software...) + if (md5($password) == $pass_hash) { + $authenticated = true; + } + } if ($authenticated) { @@ -310,16 +364,16 @@ class Admin { ini_set('session.gc_maxlifetime',65535); session_set_cookie_params(65535); - if(session_id() == '') { - session_start(); + if(session_id() == '') { + session_start(); } $username = $zeile["username"]; - - $_SESSION['angemeldet'] = true; - - // now read the rights of the user + + $_SESSION['angemeldet'] = true; + + // now read the rights of the user - $_SESSION['userid'] = $zeile['id']; + $_SESSION['userid'] = $zeile['id']; $_SESSION['currentuser'] = $username; @@ -328,7 +382,8 @@ class Admin { $rights = array($zeile['is_admin'],$zeile['right_waiter'],$zeile['right_kitchen'], $zeile['right_bar'],$zeile['right_supply'],$zeile['right_paydesk'], $zeile['right_statistics'],$zeile['right_bill'],$zeile['right_products'], - $zeile['right_reservation'],$zeile['right_changeprice'],$zeile['right_manager']); + $zeile['right_reservation'],$zeile['right_changeprice'],$zeile['right_manager'], + $zeile['right_closing']); $right_rating = $zeile['right_rating']; if (self::isOnlyRatingUser($rights,$right_rating, 1)) { @@ -346,33 +401,36 @@ class Admin { $_SESSION['right_reservation'] = false; $_SESSION['right_changeprice'] = false; $_SESSION['right_manager'] = false; + $_SESSION['right_closing'] = false; $_SESSION['keeptypelevel'] = false; - } else { - $_SESSION['is_admin'] = ($zeile['is_admin'] == 1 ? true : false); + } else { + $_SESSION['is_admin'] = ($zeile['is_admin'] == 1 ? true : false); $_SESSION['right_waiter'] = ($zeile['right_waiter'] == 1 ? true : false); if (($workflow == 2) || ($workflow == 3)) { - $_SESSION['right_kitchen'] = false; - $_SESSION['right_bar'] = false; + $_SESSION['right_kitchen'] = false; + $_SESSION['right_bar'] = false; $_SESSION['right_supply'] = false; } else { $_SESSION['right_kitchen'] = ($zeile['right_kitchen'] == 1 ? true : false); $_SESSION['right_bar'] = ($zeile['right_bar'] == 1 ? true : false); $_SESSION['right_supply'] = ($zeile['right_supply'] == 1 ? true : false); - } - $_SESSION['right_paydesk'] = ($zeile['right_paydesk'] == 1 ? true : false); - $_SESSION['right_statistics'] = ($zeile['right_statistics'] == 1 ? true : false); - $_SESSION['right_bill'] = ($zeile['right_bill'] == 1 ? true : false); + } + $_SESSION['right_paydesk'] = ($zeile['right_paydesk'] == 1 ? true : false); + $_SESSION['right_statistics'] = ($zeile['right_statistics'] == 1 ? true : false); + $_SESSION['right_bill'] = ($zeile['right_bill'] == 1 ? true : false); $_SESSION['right_products'] = ($zeile['right_products'] == 1 ? true : false); $_SESSION['right_reservation'] = ($zeile['right_reservation'] == 1 ? true : false); $_SESSION['right_rating'] = ($zeile['right_rating'] == 1 ? true : false); - $_SESSION['right_changeprice'] = ($zeile['right_changeprice'] == 1 ? true : false); + $_SESSION['right_changeprice'] = ($zeile['right_changeprice'] == 1 ? true : false); $_SESSION['right_manager'] = ($zeile['right_manager'] == 1 ? true : false); + $_SESSION['right_closing'] = ($zeile['right_closing'] == 1 ? true : false); $_SESSION['keeptypelevel'] = ($zeile['keeptypelevel'] == 1 ? true : false); } $this->userrights->setSession($_SESSION['is_admin'], $_SESSION['right_waiter'], $_SESSION['right_kitchen'], $_SESSION['right_bar'], $_SESSION['right_supply'], $_SESSION['right_paydesk'], $_SESSION['right_statistics'], - $_SESSION['right_bill'], $_SESSION['right_products'], $_SESSION['right_reservation'], $_SESSION['right_rating'], $_SESSION['right_changeprice'], $_SESSION['right_manager']); + $_SESSION['right_bill'], $_SESSION['right_products'], $_SESSION['right_reservation'], $_SESSION['right_rating'], + $_SESSION['right_changeprice'], $_SESSION['right_manager'], $_SESSION['right_closing']); $assoc = array ("0" => "roombtnsize","1" => "tablebtnsize","2" => "prodbtnsize"); @@ -409,7 +467,7 @@ class Admin { } else { Logger::logcmd("admin","authentication","Login with id $userid failed"); echo json_encode(array("status" => "NO")); - } + } } private function getMessage($pdo,$messageType) { @@ -535,8 +593,8 @@ class Admin { $sql = "UPDATE %user% SET lastmodule=? WHERE id=? AND active='1'"; $pdo = $this->dbutils->openDbAndReturnPdo(); - - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($view,$userid)); } echo json_encode(array("status" => "OK")); @@ -645,49 +703,49 @@ class Admin { if ($userLoggedIn || (!$forHtml)) { $sql = "SELECT count(id) as number,setting FROM %config% WHERE name=?"; - if (is_null($pdo)) { + if (is_null($pdo)) { $pdo = $this->dbutils->openDbAndReturnPdo(); - } - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - - $stmt->execute(array("companyinfo")); - $row = $stmt->fetchObject(); + } + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + + $stmt->execute(array("companyinfo")); + $row = $stmt->fetchObject(); $companyInfo = $row->setting; $stmt->execute(array("rectemplate")); $row = $stmt->fetchObject(); - $rectemplate = $row->setting; - - $stmt->execute(array("decpoint")); - $row = $stmt->fetchObject(); - $decpoint = $row->setting; - - $stmt->execute(array("version")); - $row = $stmt->fetchObject(); - $version = $row->setting; - - $stmt->execute(array("payprinttype")); - $row = $stmt->fetchObject(); - $payprinttype = $row->setting; + $rectemplate = $row->setting; + + $stmt->execute(array("decpoint")); + $row = $stmt->fetchObject(); + $decpoint = $row->setting; + + $stmt->execute(array("version")); + $row = $stmt->fetchObject(); + $version = $row->setting; + + $stmt->execute(array("payprinttype")); + $row = $stmt->fetchObject(); + $payprinttype = $row->setting; $stmt->execute(array("cancelunpaidcode")); $row = $stmt->fetchObject(); $cancelunpaidcode = $row->setting; - - $stmt->execute(array("tax")); - $row = $stmt->fetchObject(); - $tax = $row->setting; - - $stmt->execute(array("togotax")); - $row = $stmt->fetchObject(); + + $stmt->execute(array("tax")); + $row = $stmt->fetchObject(); + $tax = $row->setting; + + $stmt->execute(array("togotax")); + $row = $stmt->fetchObject(); $togotax = $row->setting; - $stmt->execute(array("serverurl")); - $row = $stmt->fetchObject(); + $stmt->execute(array("serverurl")); + $row = $stmt->fetchObject(); $serverurl = $row->setting; - $stmt->execute(array("email")); - $row = $stmt->fetchObject(); + $stmt->execute(array("email")); + $row = $stmt->fetchObject(); $email = $row->setting; $stmt->execute(array("bigfontworkreceipt")); @@ -731,7 +789,7 @@ class Admin { } // for update reasons check for null - $stmt->execute(array("receiveremail")); + $stmt->execute(array("receiveremail")); $row = $stmt->fetchObject(); $receiveremail = ""; if (!is_null($row)) { @@ -762,16 +820,16 @@ class Admin { } restore_error_handler(); - $stmt->execute(array("billlanguage")); - $row = $stmt->fetchObject(); + $stmt->execute(array("billlanguage")); + $row = $stmt->fetchObject(); $billlanguage = $row->setting; - $stmt->execute(array("currency")); - $row = $stmt->fetchObject(); + $stmt->execute(array("currency")); + $row = $stmt->fetchObject(); $currency = $row->setting; - $stmt->execute(array("receiptfontsize")); - $row = $stmt->fetchObject(); + $stmt->execute(array("receiptfontsize")); + $row = $stmt->fetchObject(); $receiptfontsize = $row->setting; $stmt->execute(array("reservationnote")); @@ -819,9 +877,9 @@ class Admin { date_default_timezone_set(DbUtils::getTimeZone()); $now = getdate(); - + $retVal = array("companyinfo" => $companyInfo, "rectemplate" => $rectemplate, "version" => $version, "decpoint" => $decpoint, - "serverurl" => $serverurl, "email" => $email, "receiveremail" => $receiveremail, "billlanguage" => $billlanguage, + "serverurl" => $serverurl, "email" => $email, "receiveremail" => $receiveremail, "billlanguage" => $billlanguage, "payprinttype" => $payprinttype, "tax" => $tax, "togotax" => $togotax, "currency" => $currency, "userlanguage" => $userlang, "receiptprinter" => $receiptprinter, "receiptfontsize" => $receiptfontsize, "reservationnote" => $reservationnote, "paymentconfig" => $paymentconfig, @@ -868,13 +926,13 @@ class Admin { } function getViewAfterLogin() { - if ($this->isUserAlreadyLoggedInForPhp()) { + if ($this->isUserAlreadyLoggedInForPhp()) { $userid = $_SESSION['userid']; $rights = array($_SESSION['is_admin'],$_SESSION['right_waiter'],$_SESSION['right_kitchen'], $_SESSION['right_bar'],$_SESSION['right_supply'],$_SESSION['right_paydesk'], $_SESSION['right_statistics'],$_SESSION['right_bill'],$_SESSION['right_products'], - $_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager']); + $_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager'],$_SESSION['right_closing']); $right_rating = $_SESSION['right_rating']; if (self::isOnlyRatingUser($rights, $right_rating, true)) { @@ -886,10 +944,10 @@ class Admin { $sql = "SELECT lastmodule FROM %user% WHERE id=? AND active='1'"; $pdo = $this->dbutils->openDbAndReturnPdo(); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array($userid)); - $row =$stmt->fetchObject(); + $stmt->execute(array($userid)); + $row =$stmt->fetchObject(); - $view = "preferences.html"; + $view = "preferences.html"; if ($row != null) { $newView = $row->lastmodule; if ($newView != null) { @@ -916,7 +974,7 @@ class Admin { // always ok $valid = true; } else if ($view == 'manager.html') { - if (($_SESSION['is_admin'] == 1) || ($_SESSION['right_manager'] == 1)) { + if (($_SESSION['is_admin'] == 1) || ($_SESSION['right_manager'] == 1) || ($_SESSION['right_closing'] == 1)) { $valid = true; } } else { @@ -927,8 +985,8 @@ class Admin { if ($valid == false) { $view = "preferences.html"; } - - echo json_encode($view); + + echo json_encode($view . "?v=1.2.0"); } } @@ -941,81 +999,78 @@ class Admin { } } - function isLoggedinUserAdminOrManager() { - if ($this->hasCurrentUserRight('is_admin') || $this->hasCurrentUserRight('right_manager')) { + function isLoggedinUserAdminOrManagerOrTE() { + if ($this->hasCurrentUserRight('is_admin')) { + echo json_encode("admin"); + } else if ($this->hasCurrentUserRight('right_manager')) { + echo json_encode("manager"); + } else if ($this->hasCurrentUserRight('right_closing')) { + echo json_encode("closing"); + } else { + echo json_encode(NO); + } + } + + function isLoggedinUserKitchen() { + if ($this->hasCurrentUserRight('right_kitchen')) { echo json_encode(YES); } else { echo json_encode(NO); - } - } - - function isLoggedinUserKitchen() { - if ($this->hasCurrentUserRight('right_kitchen')) { - echo json_encode(YES); - } else { - echo json_encode(NO); - } - } - - function isLoggedinUserBar() { - if ($this->hasCurrentUserRight('right_bar')) { - echo json_encode(YES); - } else { - echo json_encode(NO); - } - } - - function hasUserPaydeskRight() { - if ($this->hasCurrentUserRight('right_paydesk')) { - echo json_encode(YES); - } else { - echo json_encode(NO); } } - function hasUserReservationRight() { - if ($this->hasCurrentUserRight('right_reservation')) { - echo json_encode(YES); - } else { - echo json_encode(NO); - } + function isLoggedinUserBar() { + if ($this->hasCurrentUserRight('right_bar')) { + echo json_encode(YES); + } else { + echo json_encode(NO); + } + } + + function hasUserPaydeskRight() { + if ($this->hasCurrentUserRight('right_paydesk')) { + echo json_encode(YES); + } else { + echo json_encode(NO); + } + } + + function hasUserReservationRight() { + if ($this->hasCurrentUserRight('right_reservation')) { + echo json_encode(YES); + } else { + echo json_encode(NO); + } } function hasCurrentUserRight($whichRight) { if(session_id() == '') { session_start(); - } - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { - // no user logged in - return false; - } else { - return ($_SESSION[$whichRight]); + } + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + // no user logged in + return false; + } else { + return ($_SESSION[$whichRight]); } } // for internal request function isCurrentUserAdmin() { - return $this->hasCurrentUserRight('is_admin'); + return $this->hasCurrentUserRight('is_admin'); } function fillSampleContentBySqlFile($pdo,$sqlFile) { - $handle = fopen ($sqlFile, "r"); - while (!feof($handle)) { + $handle = fopen ($sqlFile, "r"); + while (!feof($handle)) { $sql = fgets($handle); - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(); - } + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(); + } fclose ($handle); } - private function fillSampleProdType($fileName) { - $speisekartenHandler = new TypeAndProductFileManager(); - $speisekartenHandler->manageSpeisekarteFile($fileName); - - $this->histfiller->readProdTableAndSendToHist(); - } - private function assignTaxes($foodTax,$drinksTax) { $pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo->beginTransaction(); @@ -1038,7 +1093,7 @@ class Admin { $stmt->execute(array($foodTax,0)); $stmt->execute(array($drinksTax,1)); - $this->histfiller->readAllProdsAndFillHistByDb($pdo); + HistFiller::readAllProdsAndFillHistByDb($pdo); $pdo->commit(); echo json_encode (array("status" => "OK")); @@ -1050,7 +1105,7 @@ class Admin { } private function fillSpeisekarte($speisekarte) { - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); $pdo->beginTransaction(); $ret = $this->fillSpeisekarteCore($pdo,$speisekarte); @@ -1081,8 +1136,8 @@ class Admin { private function fillSampleContent() { $pdo = DbUtils::openDbAndReturnPdoStatic(); - // first remove previous content, then fill the SQL file - $sql = "DELETE FROM `%queue%`"; + // first remove previous content, then fill the SQL file + $sql = "DELETE FROM `%queue%`"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); $this->fillSampleContentBySqlFile($pdo,"samples/queuecontent.txt"); @@ -1091,11 +1146,11 @@ class Admin { $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); - $sql = "DELETE FROM `%histuser%`"; + $sql = "DELETE FROM `%histuser%`"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); - $sql = "DELETE FROM `%user%`"; + $sql = "DELETE FROM `%user%`"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); $this->fillSampleContentBySqlFile($pdo,"samples/usercontent.txt"); @@ -1111,17 +1166,17 @@ class Admin { * Return all the entries for the main menu (the modules) */ private function getJsonMenuItemsAndVersionCore() { - if(session_id() == '') { - session_start(); + if(session_id() == '') { + session_start(); } $mainMenu = array(); $currentUser = ""; $waiterMessage = ""; $loggedIn = true; - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { // no user logged in $mainMenu[] = array("name" => "Startseite", "link" => "index.html"); - $loggedIn = false; + $loggedIn = false; } else { $lang = $_SESSION['language']; $kitchentxt = array("Küche","Kitchen","Cocina"); @@ -1140,32 +1195,33 @@ class Admin { $rights = array($_SESSION['is_admin'],$_SESSION['right_waiter'],$_SESSION['right_kitchen'], $_SESSION['right_bar'],$_SESSION['right_supply'],$_SESSION['right_paydesk'], $_SESSION['right_statistics'],$_SESSION['right_bill'],$_SESSION['right_products'], - $_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager']); + $_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager'], + $_SESSION['right_closing']); $right_rating = $_SESSION['right_rating']; if (!self::isOnlyRatingUser($rights, $right_rating, true)) { - if ($_SESSION['right_waiter']) { $mainMenu[] = array("name" => $waitertxt[$lang], "link" => "waiter.html?v=1.1.30"); }; - if ($_SESSION['right_kitchen']) { $mainMenu[] = array("name" => $kitchentxt[$lang], "link" => "kitchen.html?v=1.1.30"); }; - if ($_SESSION['right_bar']) { $mainMenu[] = array("name" => "Bar", "link" => "bar.html?v=1.1.30"); }; - if ($_SESSION['right_supply']) { $mainMenu[] = array("name" => $supplytxt[$lang], "link" => "supplydesk.html?v=1.1.30"); }; - if ($_SESSION['right_paydesk']) { $mainMenu[] = array("name" => $paydesktxt[$lang], "link" => "paydesk.html?v=1.1.30"); }; - if ($_SESSION['right_statistics']) { $mainMenu[] = array("name" => $stattxt[$lang], "link" => "reports.html?v=1.1.30"); }; - if ($_SESSION['right_bill']) { $mainMenu[] = array("name" => $bontxt[$lang], "link" => "bill.html?v=1.1.30"); }; - if ($_SESSION['right_products']) { $mainMenu[] = array("name" => $prodtxt[$lang], "link" => "products.html?v=1.1.30"); }; - if ($_SESSION['right_reservation']) { $mainMenu[] = array("name" => $restxt[$lang], "link" => "reservation.html?v=1.1.30"); }; - if ($_SESSION['right_rating']) { $mainMenu[] = array("name" => $ratingtxt[$lang], "link" => "rating.html?v=1.1.30"); }; - if ($_SESSION['right_manager'] || $_SESSION['is_admin']) { $mainMenu[] = array("name" => $admintxt[$lang], "link" => "manager.html?v=1.1.30"); }; - $mainMenu[] = array("name" => $settingtxt[$lang], "link" => "preferences.html?v=1.1.30"); - $mainMenu[] = array("name" => "Feedback", "link" => "feedback.html?v=1.1.30"); + if ($_SESSION['right_waiter']) { $mainMenu[] = array("name" => $waitertxt[$lang], "link" => "waiter.html?v=1.2.0"); }; + if ($_SESSION['right_kitchen']) { $mainMenu[] = array("name" => $kitchentxt[$lang], "link" => "kitchen.html?v=1.2.0"); }; + if ($_SESSION['right_bar']) { $mainMenu[] = array("name" => "Bar", "link" => "bar.html?v=1.2.0"); }; + if ($_SESSION['right_supply']) { $mainMenu[] = array("name" => $supplytxt[$lang], "link" => "supplydesk.html?v=1.2.0"); }; + if ($_SESSION['right_paydesk']) { $mainMenu[] = array("name" => $paydesktxt[$lang], "link" => "paydesk.html?v=1.2.0"); }; + if ($_SESSION['right_statistics']) { $mainMenu[] = array("name" => $stattxt[$lang], "link" => "reports.html?v=1.2.0"); }; + if ($_SESSION['right_bill']) { $mainMenu[] = array("name" => $bontxt[$lang], "link" => "bill.html?v=1.2.0"); }; + if ($_SESSION['right_products']) { $mainMenu[] = array("name" => $prodtxt[$lang], "link" => "products.html?v=1.2.0"); }; + if ($_SESSION['right_reservation']) { $mainMenu[] = array("name" => $restxt[$lang], "link" => "reservation.html?v=1.2.0"); }; + if ($_SESSION['right_rating']) { $mainMenu[] = array("name" => $ratingtxt[$lang], "link" => "rating.html?v=1.2.0"); }; + if ($_SESSION['right_manager'] || $_SESSION['is_admin'] || $_SESSION['right_closing']) { $mainMenu[] = array("name" => $admintxt[$lang], "link" => "manager.html?v=1.2.0"); }; + $mainMenu[] = array("name" => $settingtxt[$lang], "link" => "preferences.html?v=1.2.0"); + $mainMenu[] = array("name" => "Feedback", "link" => "feedback.html?v=1.2.0"); } $mainMenu[] = array("name" => $logout[$lang], "link" => "logout.php"); $currentUser = $_SESSION['currentuser']; - $waiterMessage = $this->getMessage(null, "waitermessage"); + $waiterMessage = $this->getMessage(null, "waitermessage"); } // CAUTION: change version also in config.txt!!! - $mainMenuAndVersion = array ("version" => "OrderSprinter 1.1.30", + $mainMenuAndVersion = array ("version" => "OrderSprinter 1.2.0", "user" => $currentUser, "menu" => $mainMenu, "waitermessage" => $waiterMessage, @@ -1209,45 +1265,65 @@ class Admin { } - function createNewUser($username, $password, $isAdmin, $rWaiter, $rKitchen, $rBar, $rSupply, $rPayDesk, $rStat, $rBill, $rProducts, $rReservation, $rRating, $rChangeprice, $rManager) { + function createNewUser() { $pdo = DbUtils::openDbAndReturnPdoStatic(); + $username = $_POST['username']; + $isAdmin = $_POST['isAdmin']; + $password = $_POST['password']; $sql = "SELECT count(id) as countid FROM %user% WHERE active='1' AND username=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($username)); $row = $stmt->fetchObject(); if ($row->countid > 0) { - echo json_encode("exists"); + echo json_encode(array("status" => "ERROR", "code" => ERROR_NAME_EXISTS_ALREADY, "msg" => ERROR_NAME_EXISTS_ALREADY_MSG)); return; } else { // create the new user - if(session_id() == '') { - session_start(); - } + if(session_id() == '') { + session_start(); + } $lang = $_SESSION['language']; if ($isAdmin && !($this->isCurrentUserAdmin())) { - echo json_encode("noadmin"); + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_ADMIN, "msg" => ERROR_COMMAND_NOT_ADMIN_MSG)); return; } else { // instead if password_hash (PHP > 5.5) use MD5... $password_hash = md5($password); - $userInsertSql = "INSERT INTO `%user%` (`id` , `username` , `userpassword`, `is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`,`right_statistics`,`right_bill`,`right_products`,`right_reservation`,`right_rating`,`right_changeprice`,`right_manager`,`language`,`receiptprinter`,`prefertablemap`,`keeptypelevel`,`extrasapplybtnpos`,`active`) VALUES ("; - $userInsertSql .= " NULL, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($userInsertSql)); - $stmt->execute(array($username,$password_hash,$isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRating,$rChangeprice,$rManager,$lang,1,1,0,1,1)); + $keys = array('id','userpassword','language'); + $vals = array(null,$password_hash,$lang); + $quests = array('?','?','?'); + + foreach(DbUtils::$userCols as $userCol) { + if (!is_null($userCol["new"])) { + $quests[] = '?'; + $keys[] = $userCol["col"]; + $vals[] = $_POST[$userCol['new']]; + } else if (isset($userCol["default"])) { + $quests[] = '?'; + $keys[] = $userCol["col"]; + $vals[] = $userCol["default"]; + } + } + + $keysStr = join(",",$keys); + $questsStr = join(",",$quests); + $userInsertSql = "INSERT INTO %user% (" . $keysStr . ") VALUES(" . $questsStr . ")"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($userInsertSql)); + $stmt->execute($vals); + $lastId = $pdo->lastInsertId(); - echo json_encode("OK"); + echo json_encode(array("status" => "OK")); } } - // now this has to be logged in the history tables... - $this->histfiller->createUserInHist($pdo,$lastId,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRating,$rChangeprice,$rManager); + // now this has to be logged in the history tables... + HistFiller::createUserInHist($pdo,$lastId); } function getPayPrintType() { @@ -1256,25 +1332,25 @@ class Admin { } function getPayments() { - if(session_id() == '') { - session_start(); + if(session_id() == '') { + session_start(); } - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); - $lang = $_SESSION['language']; + $lang = $_SESSION['language']; $sql = "SELECT id,name FROM %payment%"; if ($lang == 1) { $sql = "SELECT id,name_en as name FROM %payment%"; } else if ($lang == 2) { $sql = "SELECT id,name_esp as name FROM %payment%"; } - + $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt_query->execute(); + $stmt_query->execute(); $result = $stmt_query->fetchAll(); $retArray = array(); - + foreach($result as $row) { $entry = array("id"=> $row['id'], "name" => $row['name']); $retArray[] = $entry; @@ -1283,11 +1359,11 @@ class Admin { } function sendJsonValueFromConfigTable($pdo,$whichValue) { - $theVal = $this->getValueFromConfigTable($pdo,$whichValue); - if ($theVal == null) { - echo json_encode(""); - } else { - echo json_encode($theVal); + $theVal = $this->getValueFromConfigTable($pdo,$whichValue); + if ($theVal == null) { + echo json_encode(""); + } else { + echo json_encode($theVal); } } @@ -1296,12 +1372,12 @@ class Admin { $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($whichValue)); $row = $stmt->fetchObject(); - - $numberOfEntries = $row->countid; - $theValue = null; - if ($numberOfEntries == 1) { - $theValue = $row->setting; - } + + $numberOfEntries = $row->countid; + $theValue = null; + if ($numberOfEntries == 1) { + $theValue = $row->setting; + } return $theValue; } @@ -1428,10 +1504,10 @@ class Admin { $this->changeOneConfigDbItem($pdo,$dbcol,$aVal,"%config%",true); } } - if ($problem) { - echo json_encode("FAILED"); + if (!$problem) { + echo json_encode(array("status" => "OK")); } else { - echo json_encode("OK"); + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG)); } } @@ -1454,28 +1530,30 @@ class Admin { } if ($doHist) { - // now this has to be logged in the history tables... + // now this has to be logged in the history tables... $this->histfiller->updateConfigInHist($pdo,$theItem, $theValue); } } private function findActiveUserWithName($username) { - $sql_find_id = "SELECT id FROM %user% WHERE active='1' AND username='$username'"; - $pdo = $this->dbutils->openDbAndReturnPdo(); - $stmt_query = $pdo->query($this->dbutils->resolveTablenamesInSqlString($sql_find_id)); - $row =$stmt_query->fetchObject(); + $sql_find_id = "SELECT id FROM %user% WHERE active='1' AND username='$username'"; + $pdo = $this->dbutils->openDbAndReturnPdo(); + $stmt_query = $pdo->query($this->dbutils->resolveTablenamesInSqlString($sql_find_id)); + $row =$stmt_query->fetchObject(); $theUserId = $row->id; return $theUserId; } - function updateUser($theUserId, $isAdmin, $rWaiter, $rKitchen, $rBar, $rSupply, $rPayDesk, $rStat, $rBill, $rProducts, $rReservation, $rRat, $rChangeprice, $rManager) { + function updateUser() { // get the name of the user - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = DbUtils::openDbAndReturnPdoStatic(); + + $theUserId = $_POST['userid']; + $isAdmin = $_POST['isAdmin']; $sql = "SELECT username,is_admin FROM %user% WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($theUserId)); $row = $stmt->fetchObject(); - $username = $row->username; $userToModIsAdmin = $row->is_admin; $doChangeAdminRights = false; @@ -1486,17 +1564,26 @@ class Admin { if ($doChangeAdminRights && !($this->isCurrentUserAdmin())) { echo json_encode("noadmin"); } else { - $sql = "UPDATE %user% SET is_admin=?, right_waiter=?,right_kitchen=?,right_bar=?,right_supply=?,right_paydesk=?,right_statistics=?,right_bill=?,right_products=?,right_reservation=?,right_rating=?,right_changeprice=?,right_manager=? WHERE active='1' AND id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array($isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,$theUserId)); - - // now this has to be logged in the history tables... - - $this->histfiller->updateUserInHist($pdo,$theUserId,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,'1'); + $keys = array(); + $vals = array(); + + foreach(DbUtils::$userCols as $userCol) { + if (!is_null($userCol["update"])) { + $keys[] = $userCol["col"] . "=?"; + $vals[] = $_POST[$userCol["update"]]; + } + } + $vals[] = $theUserId; + + $keysStr = join(",",$keys); + $sql = "UPDATE %user% SET " . $keysStr . " WHERE active='1' AND id=?"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute($vals); - echo json_encode("OK"); - } + HistFiller::updateUserInHist($pdo,$theUserId); + + echo json_encode("OK"); + } } function deleteUser($theUserId) { @@ -1524,20 +1611,17 @@ class Admin { $stmt = $pdo->prepare(DbUtils::substTableAlias($userSql)); $stmt->execute(array($theUserId)); - $this->histfiller->updateOneUser($pdo,$theUserId); - + HistFiller::updateUserInHist($pdo,$theUserId); + echo json_encode("OK"); } } } function getCurrentUser() { - if(session_id() == '') { - session_start(); - } - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { - // no user logged in - echo json_encode("Nobody"); + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + // no user logged in + echo json_encode("Nobody"); } else { echo json_encode($_SESSION['currentuser']); } @@ -1569,17 +1653,17 @@ class Admin { echo json_encode("noadmin"); } else { $password_hash = md5($password); - $userSql = "UPDATE %user% set userpassword=? WHERE active='1' AND id=?"; + $userSql = "UPDATE %user% set userpassword=? WHERE active='1' AND id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($userSql)); - $stmt->execute(array($password_hash,$userid)); + $stmt->execute(array($password_hash,$userid)); echo json_encode("OK"); } } function setUserLanguage($language) { - if(session_id() == '') { - session_start(); - } + if(session_id() == '') { + session_start(); + } $currentuserid = $_SESSION['userid']; $_SESSION['language'] = intval($language); @@ -1591,16 +1675,16 @@ class Admin { } function setUserReceiptPrinter($printer) { - if(session_id() == '') { - session_start(); - } - $currentuserid = $_SESSION['userid']; - $_SESSION['receiptprinter'] = intval($printer); + if(session_id() == '') { + session_start(); + } + $currentuserid = $_SESSION['userid']; + $_SESSION['receiptprinter'] = intval($printer); - $pdo = DbUtils::openDbAndReturnPdoStatic(); - $sql = "UPDATE %user% set receiptprinter=? WHERE active='1' AND id=?"; + $pdo = DbUtils::openDbAndReturnPdoStatic(); + $sql = "UPDATE %user% set receiptprinter=? WHERE active='1' AND id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($printer,$currentuserid)); + $stmt->execute(array($printer,$currentuserid)); echo json_encode("OK"); } @@ -1620,8 +1704,8 @@ class Admin { } function changeOwnPassword($oldpassword,$newpassword) { - if(session_id() == '') { - session_start(); + if(session_id() == '') { + session_start(); } $currentuser = $_SESSION['currentuser']; $oldp_hash = md5($oldpassword); @@ -1650,49 +1734,49 @@ class Admin { $newp_hash = md5($newpassword); $sql = "UPDATE %user% set userpassword=? WHERE active='1' AND username=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($newp_hash,$currentuser)); + $stmt->execute(array($newp_hash,$currentuser)); echo json_encode("OK"); } else { echo json_encode("FAILED"); } } - private function writeCsvHeader($defaultFilename) { - header("Content-type: text/x-csv"); - header("Content-Disposition: attachment; filename=$defaultFilename"); - header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - header("Pragma: no-cache"); + private function writeCsvHeader($defaultFilename) { + header("Content-type: text/x-csv"); + header("Content-Disposition: attachment; filename=$defaultFilename"); + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header("Pragma: no-cache"); header("Expires: 0"); } private function exportConfigCsv() { $pdo = DbUtils::openDbAndReturnPdoStatic(); $this->writeCsvHeader("datenexport-config.csv"); - - echo("Eintragsid; Datum ; Konfiguration; Wert;Beschreibung\n"); - - $sql = "SELECT DISTINCT %hist%.id as id,date,"; - $sql .= "%config%.name as configitem,%histconfig%.setting as setting,description "; - $sql .= " FROM %hist%, %histconfig%, %histactions%, %config% "; + + echo("Eintragsid; Datum ; Konfiguration; Wert;Beschreibung\n"); + + $sql = "SELECT DISTINCT %hist%.id as id,date,"; + $sql .= "%config%.name as configitem,%histconfig%.setting as setting,description "; + $sql .= " FROM %hist%, %histconfig%, %histactions%, %config% "; $sql .= " WHERE (refid=%histconfig%.id) "; - $sql .= " AND %histconfig%.configid = %config%.id "; - $sql .= " AND (action='2' OR action='6') "; - $sql .= " AND (action=%histactions%.id) "; - $sql .= " ORDER BY date,id"; + $sql .= " AND %histconfig%.configid = %config%.id "; + $sql .= " AND (action='2' OR action='6') "; + $sql .= " AND (action=%histactions%.id) "; + $sql .= " ORDER BY date,id"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); $result = $stmt->fetchAll(); - foreach($result as $zeile) { - $val1 = $zeile['id']; - $val2 = $zeile['date']; - $val3 = $zeile['configitem']; + foreach($result as $zeile) { + $val1 = $zeile['id']; + $val2 = $zeile['date']; + $val3 = $zeile['configitem']; $val4 = str_replace("\r\n","",$zeile['setting']); - $val4 = str_replace("\n","",$val4); - $val5 = $zeile['description']; - - echo "$val1; $val2; \"$val3\"; \"$val4\"; \"$val5\"\n"; + $val4 = str_replace("\n","",$val4); + $val5 = $zeile['description']; + + echo "$val1; $val2; \"$val3\"; \"$val4\"; \"$val5\"\n"; } } @@ -1700,11 +1784,11 @@ class Admin { $pdo = DbUtils::openDbAndReturnPdoStatic(); $this->writeCsvHeader("datenexport-benutzer.csv"); - echo("Eintragsid; Datum ; Benutzerid; Benutzername; Adminrechte; Kellnerrechte;Kuechenrechte; Barrechte; Bereitstellungsrechte; Kassenrechte; Reportrechte; Kassenbonrechte; Angebotsrechte; Beurteilungsrechte; Preisänderungsrechte; Managerrechte; Aktiviert\n"); + echo("Eintragsid; Datum ; Benutzerid; Benutzername; Adminrechte; Kellnerrechte;Kuechenrechte; Barrechte; Bereitstellungsrechte; Kassenrechte; Reportrechte; Kassenbonrechte; Angebotsrechte; Beurteilungsrechte; Preisänderungsrechte; Tageserfassungsrecht; Managerrechte; Aktiviert\n"); $sql = "SELECT DISTINCT %hist%.id as id,date,"; $sql .= "userid,username,is_admin,right_waiter,right_kitchen,right_bar,right_supply,"; - $sql .= "right_paydesk,right_statistics,right_bill,right_products,right_rating,right_changeprice,right_manager,active,"; + $sql .= "right_paydesk,right_statistics,right_bill,right_products,right_rating,right_changeprice,right_closing,right_manager,active,"; $sql .= "description "; $sql .= " FROM %hist%, %histuser%, %histactions% "; $sql .= " WHERE (refid=%histuser%.id) "; @@ -1732,12 +1816,13 @@ class Admin { $val13 = ($zeile['right_products'] == '1' ? "Ja" : "Nein"); $val14 = ($zeile['right_rating'] == '1' ? "Ja" : "Nein"); $val15 = ($zeile['right_changeprice'] == '1' ? "Ja" : "Nein"); - $val16 = ($zeile['right_manager'] == '1' ? "Ja" : "Nein"); - $val17 = ($zeile['active'] == '1' ? "Ja" : "Nein"); - $val18 = $zeile['description']; + $val16 = ($zeile['right_closing'] == '1' ? "Ja" : "Nein"); + $val17 = ($zeile['right_manager'] == '1' ? "Ja" : "Nein"); + $val18 = ($zeile['active'] == '1' ? "Ja" : "Nein"); + $val19 = $zeile['description']; echo "$val1; $val2; $val3; $val4; $val5; $val6; $val7; $val8; $val9; $val10;"; - echo "$val11;$val12;$val13;$val14;$val15;$val16;$val17;$val18\n"; + echo "$val11;$val12;$val13;$val14;$val15;$val16;$val17;$val18;$val19\n"; } } @@ -1814,8 +1899,7 @@ class Admin { if ($theType == "configuration") { $tables = $this->getConfigTablesToBackupRestore(); } else { - $histFiller = new HistFiller(); - $histFiller->insertSaveHistEntry($pdo); + HistFiller::insertSaveHistEntry($pdo); $tables = $this->getAllTablesToBackupRestore(); } @@ -1961,8 +2045,7 @@ class Admin { } if (!$typeIsOnlyConfig) { - $histFiller = new HistFiller(); - $histFiller->insertRestoreHistEntry($pdo); + HistFiller::insertRestoreHistEntry($pdo); } $basedb->signLastBillid($pdo); @@ -2023,6 +2106,91 @@ class Admin { } } + + private function golive() { + try { + $pdo = DButils::openDbAndReturnPdoStatic(); + self::doSql($pdo, "DELETE FROM %hist%", null); + self::doSql($pdo, "DELETE FROM %histprod%", null); + self::doSql($pdo, "DELETE FROM %histconfig%", null); + self::doSql($pdo, "DELETE FROM %histuser%", null); + + HistFiller::readUserTableAndSendToHist($pdo); + + $products = new Products(); + $menu = $products->getSpeisekarte($pdo); + if ($menu['status'] != "OK") { + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG)); + return; + } else { + self::doSql($pdo, "SET foreign_key_checks = 0;", null); + self::doSql($pdo, "DELETE FROM %queueextras%", null); + self::doSql($pdo, "DELETE FROM %extrasprods%", null); + self::doSql($pdo, "DELETE FROM %extras%", null); + self::doSql($pdo, "DELETE FROM %billproducts%", null); + self::doSql($pdo, "DELETE FROM %queue%", null); + self::doSql($pdo, "DELETE FROM %printjobs%", null); + self::doSql($pdo, "DELETE FROM %bill%", null); + self::doSql($pdo, "DELETE FROM %ratings%", null); + self::doSql($pdo, "DELETE FROM %closing%", null); + + self::doSql($pdo, "SET foreign_key_checks = 1;", null); + + $ret = $this->fillSpeisekarteCore($pdo, $menu['msg']); + + self::doSql($pdo, "DELETE FROM %products% WHERE removed is not null", null); + self::doSql($pdo, "SET foreign_key_checks = 0;", null); + self::doSql($pdo, "DELETE FROM %prodtype% WHERE removed is not null", null); + self::doSql($pdo, "SET foreign_key_checks = 1;", null); + + if ($ret["status"] != "OK") { + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG)); + return; + } + HistFiller::readAllProdsAndFillHistByDb($pdo); + + self::doSql($pdo, "DELETE w FROM %histprod% w INNER JOIN %hist% e ON refid=w.id WHERE action='4'", null); + self::doSql($pdo, "DELETE FROM %hist% where action='4'", null); + } + + self::doSql($pdo, "alter table %bill% drop foreign key billbillref", null); + self::doSql($pdo, "alter table %billproducts% drop foreign key billprodref", null); + self::doSql($pdo, "alter table %queue% drop foreign key queuebillref", null); + self::doSql($pdo, "ALTER TABLE %bill% DROP id", null); + self::doSql($pdo, "ALTER TABLE %bill% ADD id INT (10) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", null); + self::doSql($pdo, "ALTER TABLE %bill% ADD CONSTRAINT billbillref FOREIGN KEY (ref) REFERENCES %bill%(id)", null); + self::doSql($pdo, "ALTER TABLE %billproducts% ADD CONSTRAINT billprodref FOREIGN KEY (billid) REFERENCES %bill%(id)", null); + self::doSql($pdo, "ALTER TABLE %queue% ADD CONSTRAINT queuebillref FOREIGN KEY (billid) REFERENCES %bill%(id)", null); + self::doSql($pdo, "alter table %bill% drop foreign key billclosingref", null); + self::doSql($pdo, "ALTER TABLE %closing% DROP id", null); + self::doSql($pdo, "ALTER TABLE %closing% ADD id INT (10) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", null); + self::doSql($pdo, "ALTER TABLE %bill% ADD CONSTRAINT billclosingref FOREIGN KEY (closingid) REFERENCES %closing%(id)", null); + + $basedb = new Basedb(); + $basedb->setPrefix(TAB_PREFIX); + $basedb->setTimeZone(DbUtils::getTimeZone()); + $basedb->signLastBillid($pdo); + + $histFiller = new HistFiller(); + $histFiller->readConfigTableAndSendToHist(); + + self::doSql($pdo, "DELETE FROM %resttables% WHERE removed is not null", null); + self::doSql($pdo, "DELETE FROM %room% WHERE removed is not null", null); + + echo json_encode(array("status" => "OK")); + } catch(Exception $e) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG)); + } + } + + private static function doSql($pdo,$sql,$params) { + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + if (is_null($params)) { + $stmt->execute(); + } else { + $stmt->execute($params); + } + } } ?> \ No newline at end of file diff --git a/webapp/php/closing.php b/webapp/php/closing.php index 01933ec..3eefe8e 100644 --- a/webapp/php/closing.php +++ b/webapp/php/closing.php @@ -1,6 +1,6 @@ hasCurrentUserManagerOrAdminRights())) { +// all commands require closing,manager or admin rights +if (!($this->hasCurrentUserManagerOrAdminOrClosingRights())) { if ($command != 'exportCsv') { echo json_encode(array("status" => "ERROR", "code" => ERROR_MANAGER_NOT_AUTHOTRIZED, "msg" => ERROR_MANAGER_NOT_AUTHOTRIZED_MSG)); } else { @@ -32,7 +32,7 @@ if($command == 'createClosing') { $this->createClosing($_POST['remark']); } else if ($command == 'getClosings') { $this->getClosings($_GET['month'], $_GET['year']); -} else if ($command == 'exportCsv') { +} else if ($command == 'exportCsv') { $this->exportCsv($_GET['closingid']); } else if ($command == 'emailCsv') { $this->emailCsv($_GET['closingid'],$_GET['emailaddress'],$_GET['topic']); @@ -45,23 +45,23 @@ echo "Command not supported."; } } -private function hasCurrentUserManagerOrAdminRights() { -session_start(); -if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { -// no user logged in -return false; -} else { -return ($_SESSION['right_manager'] || $_SESSION['is_admin']); -} +private function hasCurrentUserManagerOrAdminOrClosingRights() { +session_start(); +if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { +// no user logged in +return false; +} else { +return ($_SESSION['right_manager'] || $_SESSION['right_closing'] || $_SESSION['is_admin']); +} } -private function getDecPoint() { -$sql = "SELECT name,setting FROM %config% WHERE name=?"; -$pdo = $this->dbutils->openDbAndReturnPdo(); -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); -$stmt->execute(array("decpoint")); -$row = $stmt->fetchObject(); -return($row->setting); +private function getDecPoint() { +$sql = "SELECT name,setting FROM %config% WHERE name=?"; +$pdo = $this->dbutils->openDbAndReturnPdo(); +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt->execute(array("decpoint")); +$row = $stmt->fetchObject(); +return($row->setting); } private function createClosing ($remark) { @@ -73,14 +73,14 @@ $decpoint = $this->getDecPoint(); // first create a closing entry -date_default_timezone_set(DbUtils::getTimeZone()); +date_default_timezone_set(DbUtils::getTimeZone()); $closingTime = date('Y-m-d H:i:s'); $pdo = $this->dbutils->openDbAndReturnPdo(); $pdo->beginTransaction(); - + $closingEntrySql = "INSERT INTO `%closing%` (`id` , `closingdate`,`remark`,`billcount`,`billsum`,`signature`) VALUES (NULL ,?,?,?,?,?)"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($closingEntrySql)); +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($closingEntrySql)); $stmt->execute(array($closingTime,$remark,0,0.0,null)); $newClosingId = $pdo->lastInsertId(); @@ -88,17 +88,17 @@ $newClosingId = $pdo->lastInsertId(); $sql = "SELECT id FROM %bill% WHERE closingid is null AND (tableid >= '0' OR status='c') "; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(); -$result = $stmt->fetchAll(); -$utils = new CommonUtils(); +$result = $stmt->fetchAll(); +$utils = new CommonUtils(); -$ok = true; -foreach($result as $row) { +$ok = true; +foreach($result as $row) { $aBillId = $row['id']; if (!$utils->verifyBill($pdo, $aBillId)) { $ok=false; break; -} -} +} +} if (!$ok) { echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG)); return; @@ -110,17 +110,17 @@ $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($declareClose $stmt->execute(); $sql ="SELECT count(id) as billstotake FROM %bill% WHERE closingid=? AND (tableid >= '0' OR status='c')"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($newClosingId)); -$row = $stmt->fetchObject(); +$row = $stmt->fetchObject(); $billsToTake = $row->billstotake; $pricesum = null; // now calculate the sum of the prices of this closing if ($billsToTake > 0) { -$sql = "SELECT sum(brutto) as pricesum FROM %bill% WHERE closingid=? AND (tableid >= '0' OR status='c')"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); -$stmt->execute(array($newClosingId)); +$sql = "SELECT sum(brutto) as pricesum FROM %bill% WHERE closingid=? AND (tableid >= '0' OR status='c')"; +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt->execute(array($newClosingId)); $row = $stmt->fetchObject(); $pricesum = $row->pricesum; } @@ -142,7 +142,7 @@ openssl_free_key($pkeyid); // now add values to closing table to prepare for electronic signature $sql = "UPDATE %closing% SET billcount=?, billsum=?,signature=? WHERE id=?"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($billsToTake,$pricesum,$signature,$newClosingId)); // now clean the extras that are assigned to queue - we do not need them anymore @@ -150,7 +150,7 @@ $sql = "DELETE FROM %queueextras%"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(); -$sql = "DELETE FROM %queue% WHERE id not in (select distinct queueid FROM %billproducts%) AND billid is null"; +$sql = "DELETE FROM %queue% WHERE id not in (select distinct queueid FROM %billproducts%) AND billid is null"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(); @@ -212,8 +212,8 @@ $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($closingid)); $row = $stmt->fetchObject(); -$numberOfReturns = $row->countid; -$sum = 0.0; +$numberOfReturns = $row->countid; +$sum = 0.0; if ($numberOfReturns > 0) { $sum = floatval($row->billsum); } @@ -269,7 +269,7 @@ $monthText = "0" . $month; $lastDayInMonth = date("t", mktime(0, 0, 0, $month, 1, $year)); $dateStart = $year . $monthText . "01"; -$dateEnd = $year . $monthText . $lastDayInMonth; +$dateEnd = $year . $monthText . $lastDayInMonth; $sql = "SELECT id,closingdate,remark FROM %closing% WHERE DATE(closingdate) BETWEEN ? AND ? ORDER BY closingdate DESC;"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($dateStart,$dateEnd)); @@ -286,7 +286,7 @@ $taxessums = $this->getTaxesGroupedOfClosing($pdo,$theId); $cashops = $this->getCashOpsOfClosing($pdo,$theId); $closingEntry = array("id" => $theId, "closingDate" => $closingDate, "remark" => $remark, "totalsum" => $totalSum, "cashsum" => $cashSum, "usersums" => $userSums, "taxessums" => $taxessums,"cashops" => $cashops); $resultarray[] = $closingEntry; -} +} echo json_encode(array("status" => "OK", "msg" => $resultarray)); } @@ -314,61 +314,61 @@ $this->retrieveClosingFromDb($pdo,$closingid, true, false); } private function emailCsvCore($pdo,$closingid,$toEmail,$topic,$startdate,$enddate,$billsum,$billcount) { -$msg = $this->retrieveClosingFromDb($pdo,$closingid, false, true); +$msg = $this->retrieveClosingFromDb($pdo,$closingid, false, true); + +$msg = "Zeitraum: $startdate - $enddate\nBrutto-Summe: $billsum\nEnthaltene Bons: $billcount\n\n" . $msg; +$msg = str_replace("\n", "\r\n", $msg); -$msg = "Zeitraum: $startdate - $enddate\nBrutto-Summe: $billsum\nEnthaltene Bons: $billcount\n\n" . $msg; -$msg = str_replace("\n", "\r\n", $msg); - $topictxt = $topic . " " . $closingid . "\r\n"; - -if (Emailer::sendEmail($pdo, $msg, $toEmail, $topictxt)) { -return true; -} else { -return false; + +if (Emailer::sendEmail($pdo, $msg, $toEmail, $topictxt)) { +return true; +} else { +return false; } } private function emailCsv($closingid,$toEmail,$topic) { // additional info to insert into email $decpoint = $this->getDecPoint(); $pdo = $this->dbutils->openDbAndReturnPdo(); -$prevClosingDate = self::getDateOfPreviousClosing($pdo,$closingid); -if (is_null($prevClosingDate)) { -$prevClosingDate = ""; +$prevClosingDate = self::getDateOfPreviousClosing($pdo,$closingid); +if (is_null($prevClosingDate)) { +$prevClosingDate = ""; } $sql = "SELECT closingdate, billcount, billsum FROM %closing% WHERE id=?"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); -$stmt->execute(array($closingid)); +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt->execute(array($closingid)); $row = $stmt->fetchObject(); $billsum = number_format($row->billsum, 2, $decpoint, ''); $billcount = $row->billcount; $closdate = $row->closingdate; if ($this->emailCsvCore($pdo,$closingid, $toEmail, $topic, $prevClosingDate,$closdate,$billsum,$billcount)) { -echo json_encode(array("status" => "OK")); -} else { -echo json_encode(array("status" => "ERROR", "code" => ERROR_EMAIL_FAILURE, "msg" => ERROR_EMAIL_FAILURE_MSG)); -} +echo json_encode(array("status" => "OK")); +} else { +echo json_encode(array("status" => "ERROR", "code" => ERROR_EMAIL_FAILURE, "msg" => ERROR_EMAIL_FAILURE_MSG)); +} } -private function getGeneralItemFromDb($field) { -$pdo = $this->dbutils->openDbAndReturnPdo(); -$this->getGeneralItemFromDbWithPdo($pdo, $field); +private function getGeneralItemFromDb($field) { +$pdo = $this->dbutils->openDbAndReturnPdo(); +$this->getGeneralItemFromDbWithPdo($pdo, $field); } private function getGeneralItemFromDbWithPdo($pdo,$field) { -if (is_null($pdo)) { +if (is_null($pdo)) { $pdo = $this->dbutils->openDbAndReturnPdo(); -} - -$aValue=""; -$sql = "SELECT setting FROM %config% where name='$field'"; -$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); -$stmt->execute(); -$row =$stmt->fetchObject(); -if ($row != null) { -$aValue = $row->setting; -} -return $aValue; +} + +$aValue=""; +$sql = "SELECT setting FROM %config% where name='$field'"; +$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); +$stmt->execute(); +$row =$stmt->fetchObject(); +if ($row != null) { +$aValue = $row->setting; +} +return $aValue; } public static function getDateOfPreviousClosing($pdoval,$closingid) { @@ -380,43 +380,43 @@ $pdo = $pdoval; // ids can be generated but not used in case of rollback $sql = "SELECT MAX(id) as previousid FROM %closing% WHERE idprepare(DbUtils::substTableAlias($sql)); -$stmt->execute(array($closingid)); -$row =$stmt->fetchObject(); -if ($row != null) { +$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); +$stmt->execute(array($closingid)); +$row =$stmt->fetchObject(); +if ($row != null) { $previousId = intval($row->previousid); $sql = "SELECT closingdate FROM %closing% WHERE id=?"; -$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); +$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($previousId)); $row =$stmt->fetchObject(); if ($row != null) { return $row->closingdate; } else { return null; -} +} } else { return null; -} +} } private function returnErrorInconsDB($doCsvExport,$onlyresultreturn) { -if ($doCsvExport) { -echo "ERROR - signatures do not fit"; -} else if ($onlyresultreturn) { -return "Tagesabschluss-Datum: $closingdate\nBemerkung: $remark\nStatus: Inkonsistente Datenbank\n\ncsv-Daten:\n" . $csv; -} else { -echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG)); +if ($doCsvExport) { +echo "ERROR - signatures do not fit"; +} else if ($onlyresultreturn) { +return "Tagesabschluss-Datum: $closingdate\nBemerkung: $remark\nStatus: Inkonsistente Datenbank\n\ncsv-Daten:\n" . $csv; +} else { +echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG)); } } private function retrieveClosingFromDb($pdo,$closingid,$doCsvExport,$onlyresultreturn) { -if(session_id() == '') { -session_start(); +if(session_id() == '') { +session_start(); } - + $l = $_SESSION['language']; -$commonUtils = new CommonUtils(); +$commonUtils = new CommonUtils(); $currency = $commonUtils->getCurrency(); $decpoint = $this->getDecPoint(); @@ -425,22 +425,22 @@ $previousClosingDate = self::getDateOfPreviousClosing(null,$closingid); $csv = ""; if ($doCsvExport || $onlyresultreturn) { -$file_name = "tagesabschluss.csv"; -header("Content-type: text/x-csv"); -header("Content-Disposition: attachment; filename=$file_name"); -header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); -header("Pragma: no-cache"); +$file_name = "tagesabschluss.csv"; +header("Content-type: text/x-csv"); +header("Content-Disposition: attachment; filename=$file_name"); +header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); +header("Pragma: no-cache"); header("Expires: 0"); -$csv .= $this->t['ID'][$l] . ";" . $this->t['Date'][$l] . ";" . $this->t['Prod'][$l] . ";" . $this->t['Brutto'][$l] . "($currency);"; -$csv .= $this->t['Netto'][$l] . "($currency);"; +$csv .= $this->t['ID'][$l] . ";" . $this->t['Date'][$l] . ";" . $this->t['Prod'][$l] . ";" . $this->t['Brutto'][$l] . "($currency);"; +$csv .= $this->t['Netto'][$l] . "($currency);"; $csv .= $this->t['Tax'][$l] . ";"; $csv .= $this->t['PayWay'][$l] . ";"; $csv .= $this->t['Userid'][$l] . ";"; $csv .= $this->t['User'][$l] . ";"; $csv .= $this->t['State'][$l] . ";"; $csv .= $this->t['Ref'][$l] . "\n"; - + } $sql = "SELECT closingdate,remark,signature,billsum,billcount FROM %closing% WHERE id=?"; @@ -460,29 +460,29 @@ $billIdsAndPaymentsForThatClosing = $stmt->fetchAll(); $foundBillCount = count($billIdsAndPaymentsForThatClosing); -if (is_null($previousClosingDate)) { -$startDate = ""; +if (is_null($previousClosingDate)) { +$startDate = ""; } else { $startDate = $previousClosingDate; } -$billsumstr = number_format($billsum, 2, ".", ''); +$billsumstr = number_format($billsum, 2, ".", ''); $data = "I($closingid)-S($startDate)-E($closingdate)-D($billcount)-S($billsumstr)"; -$pubkeyid = $commonUtils->getCert($pdo); +$pubkeyid = $commonUtils->getCert($pdo); $ok = openssl_verify($data, $signature, $pubkeyid); -openssl_free_key($pubkeyid); +openssl_free_key($pubkeyid); if (($ok == 0) || ($billcount <> $foundBillCount)) { // something went wrong! $this->returnErrorInconsDB($doCsvExport, $onlyresultreturn); -return; -} +return; +} $retValues = array(); - -for ($index=0;$index < count($billIdsAndPaymentsForThatClosing);$index++) { + +for ($index=0;$index < count($billIdsAndPaymentsForThatClosing);$index++) { $aBillId = $billIdsAndPaymentsForThatClosing[$index]['id']; if (!$commonUtils->verifyBill($pdo, $aBillId)) { -$this->returnErrorInconsDB($doCsvExport, $onlyresultreturn); +$this->returnErrorInconsDB($doCsvExport, $onlyresultreturn); return; } @@ -497,46 +497,46 @@ $tax = $billIdsAndPaymentsForThatClosing[$index]['tax']; $ref = $billIdsAndPaymentsForThatClosing[$index]['ref']; $ref = ($ref == null ? "" : $ref); -if ($status == 'c') { +if ($status == 'c') { $statusTxt = $this->t['cashact'][$l]; // "Bareinlage/-entnahme"; $brutto = number_format($brutto, 2, $decpoint, ''); $netto = number_format($netto, 2, $decpoint, ''); -$tax = number_format($tax, 2, $decpoint, ''); -$retValues[] = array ( -"billid" => $aBillId, -"paidtime" => $billdate, -"productname" => $this->t['cashaction'][$l], // Kassenaktion +$tax = number_format($tax, 2, $decpoint, ''); +$retValues[] = array ( +"billid" => $aBillId, +"paidtime" => $billdate, +"productname" => $this->t['cashaction'][$l], // Kassenaktion "price" => $brutto, "netto" => $netto, -"tax" => number_format(0.00, 2, $decpoint, ''), -"payment" => $paymentArray[$paymentid], -"userid" => $userid, -"username" => $username, -"status" => $statusTxt, -"ref" => $ref); +"tax" => number_format(0.00, 2, $decpoint, ''), +"payment" => $paymentArray[$paymentid], +"userid" => $userid, +"username" => $username, +"status" => $statusTxt, +"ref" => $ref); if ($doCsvExport || $onlyresultreturn) { -$csv .= "$aBillId; \"$billdate\" ; \"" . $this->t['cashaction'][$l] . "\" ; \"$brutto\" ; \"$netto\" ; \"$tax\" ; \"$paymentArray[$paymentid]\";$userid; \"$username\"; \"$statusTxt\"; $ref\n"; -} +$csv .= "$aBillId; \"$billdate\" ; \"" . $this->t['cashaction'][$l] . "\" ; \"$brutto\" ; \"$netto\" ; \"$tax\" ; \"$paymentArray[$paymentid]\";$userid; \"$username\"; \"$statusTxt\"; $ref\n"; +} } else { $sql = "SELECT DISTINCT productname,price,%queue%.tax as tax FROM %queue%,%billproducts% WHERE %billproducts%.billid=? AND %billproducts%.queueid=%queue%.id"; -if ($status == 'x') { -$statusTxt = $this->t["laterCancelled"][$l]; -} else if ($status == 's') { -$statusTxt = $this->t["storno"][$l]; -} else { +if ($status == 'x') { +$statusTxt = $this->t["laterCancelled"][$l]; +} else if ($status == 's') { +$statusTxt = $this->t["storno"][$l]; +} else { $statusTxt = ""; -$sql = "SELECT productname,paidtime,price,tax FROM %queue% WHERE billid=?"; -} +$sql = "SELECT productname,paidtime,price,tax FROM %queue% WHERE billid=?"; +} $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($aBillId)); $result = $stmt->fetchAll(); -foreach ($result as $zeile) { +foreach ($result as $zeile) { $productname = $zeile['productname']; $tax = $zeile['tax']; - -$paidtime = ($billdate == null ? "" : $billdate) ; + +$paidtime = ($billdate == null ? "" : $billdate) ; $price = ($status == 's' ? 0.0-floatval($zeile['price']) : $zeile['price']); $netto = $price/(1 + $tax/100.0); @@ -559,9 +559,9 @@ $retValues[] = array ( $productname = str_replace('"','""',$productname); if ($doCsvExport || $onlyresultreturn) { $csv .= "$aBillId; \"$paidtime\" ; \"$productname\" ; \"$price\" ; \"$netto\" ; \"$formattedtax\" ; \"$paymentArray[$paymentid]\"; $userid; \"$username\"; \"$statusTxt\"; $ref\n"; -} } -} +} +} } if ($doCsvExport) { echo $csv; @@ -655,6 +655,6 @@ echo json_encode(array("status" => "OK", "msg" => $retVal)); return $retVal; } } -} - +} + ?> \ No newline at end of file diff --git a/webapp/php/dbutils.php b/webapp/php/dbutils.php index 40d699d..11f60e5 100644 --- a/webapp/php/dbutils.php +++ b/webapp/php/dbutils.php @@ -59,31 +59,31 @@ class DbUtils { return $pdo; } function openDbAndReturnPdo () { - $dsn = 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB; - $user = MYSQL_USER; + $dsn = 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB; + $user = MYSQL_USER; $password = MYSQL_PASSWORD; - $pdo = null; - try { - $pdo = new PDO($dsn, $user, $password); - $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - catch (PDOException $e) { - echo 'Connection failed: ' . $e->getMessage(); + $pdo = null; + try { + $pdo = new PDO($dsn, $user, $password); + $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } + catch (PDOException $e) { + echo 'Connection failed: ' . $e->getMessage(); } return $pdo; } function testDbAccess($host,$dbname,$user,$pass) { - $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname; - $user = $user; - $password = $pass; - $pdo = null; - try { - $pdo = new PDO($dsn, $user, $password); - $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - catch (PDOException $e) { - // + $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname; + $user = $user; + $password = $pass; + $pdo = null; + try { + $pdo = new PDO($dsn, $user, $password); + $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } + catch (PDOException $e) { + // } if ($pdo != null) { return true; @@ -155,5 +155,54 @@ class DbUtils { return self::$timezone; } } + + public static $userCols = array( + array("col" => 'id', "hist" => 1, "new" => null, "update" => null), + array("col" => 'username', "hist" => 1, "new" => 'username', "update" => null), + array("col" => 'userpassword', "hist" => 0, "new" => null, "update" => null), + array("col" => 'is_admin', "hist" => 1, "new" => 'isAdmin', "update" => 'isAdmin'), + array("col" => 'right_waiter', "hist" => 1, "new" => 'rWaiter', "update" => 'rWaiter'), + array("col" => 'right_kitchen', "hist" => 1, "new" => 'rKitchen', "update" => 'rKitchen'), + array("col" => 'right_bar', "hist" => 1, "new" => 'rBar', "update" => 'rBar'), + array("col" => 'right_supply', "hist" => 1, "new" => 'rSupply', "update" => 'rSupply'), + array("col" => 'right_paydesk', "hist" => 1, "new" => 'rPayDesk', "update" => 'rPayDesk'), + array("col" => 'right_statistics', "hist" => 1, "new" => 'rStat', "update" => 'rStat'), + array("col" => 'right_bill', "hist" => 1, "new" => 'rBill', "update" => 'rBill'), + array("col" => 'right_products', "hist" => 1, "new" => 'rProducts', "update" => 'rProducts'), + array("col" => 'right_reservation', "hist" => 1, "new" => 'rReservation', "update" => 'rReservation'), + array("col" => 'right_rating', "hist" => 1, "new" => 'rRating', "update" => 'rRating'), + array("col" => 'right_changeprice', "hist" => 1, "new" => 'rChangeprice', "update" => 'rChangeprice'), + array("col" => 'right_manager', "hist" => 1, "new" => 'rManager', "update" => 'rManager'), + array("col" => 'right_closing', "hist" => 1, "new" => 'rClosing', "update" => 'rClosing'), + array("col" => 'active', "hist" => 1, "new" => null ,"default" => 1, "update" => null), + array("col" => 'lastmodule', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'ordervolume', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'language', "hist" => 0, "new" => null, "update" => null), + array("col" => 'receiptprinter', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'roombtnsize', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'tablebtnsize', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'prodbtnsize', "hist" => 0, "new" => null ,"default" => null, "update" => null), + array("col" => 'prefertablemap', "hist" => 0, "new" => null ,"default" => 1, "update" => null), + array("col" => 'keeptypelevel', "hist" => 0, "new" => null ,"default" => 0, "update" => null), + array("col" => 'extrasapplybtnpos', "hist" => 0, "new" => null ,"default" => 1, "update" => null) + ); + + + public static $prodCols = array( + array("col" => 'id', "hist" => 1), + array("col" => 'shortname', "hist" => 1), + array("col" => 'longname', "hist" => 1), + array("col" => 'priceA', "hist" => 1), + array("col" => 'priceB', "hist" => 1), + array("col" => 'priceC', "hist" => 1), + array("col" => 'tax', "hist" => 1), + array("col" => 'category', "hist" => 0), + array("col" => 'favorite', "hist" => 1), + array("col" => 'sorting', "hist" => 1), + array("col" => 'available', "hist" => 1), + array("col" => 'audio', "hist" => 1), + array("col" => 'removed', "hist" => 0) + ); + } ?> \ No newline at end of file diff --git a/webapp/php/globals.php b/webapp/php/globals.php index 0205c5b..4f40e83 100644 --- a/webapp/php/globals.php +++ b/webapp/php/globals.php @@ -8,13 +8,13 @@ define ( 'ERROR_NOT_AUTHOTRIZED', '2' ); define ( 'ERROR_BILL_NOT_AUTHOTRIZED', '3'); define ( 'ERROR_BILL_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Bons)'); -define ( 'ERROR_PAYDESK_NOT_AUTHOTRIZED', '4'); +define ( 'ERROR_PAYDESK_NOT_AUTHOTRIZED', '4'); define ( 'ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Kasse)'); -define ( 'ERROR_MANAGER_NOT_AUTHOTRIZED', '5'); +define ( 'ERROR_MANAGER_NOT_AUTHOTRIZED', '5'); define ( 'ERROR_MANAGER_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Verwaltung)'); -define ( 'ERROR_PRODUCTS_NOT_AUTHOTRIZED', '6'); +define ( 'ERROR_PRODUCTS_NOT_AUTHOTRIZED', '6'); define ( 'ERROR_PRODUCTS_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Produktangebot)'); define ( 'ERROR_BILL_NOT_STORNO_CODE', '7'); @@ -26,31 +26,31 @@ define ( 'ERROR_BILL_WRONG_NUMERIC_VALUE_MSG', 'Rechnungsnummer falsch'); define ( 'ERROR_BILL_ALREADY_CLOSED', '10'); define ( 'ERROR_BILL_ALREADY_CLOSED_MSG', 'Bon schon in Tagesabschluss'); -define ( 'ERROR_BILL_ALREADY_CANCELLED', '11'); +define ( 'ERROR_BILL_ALREADY_CANCELLED', '11'); define ( 'ERROR_BILL_ALREADY_CANCELLED_MSG', 'Bon schon storniert'); -define ( 'ERROR_BILL_LESS_MONEY_TO_TAKE_OUT', '12'); +define ( 'ERROR_BILL_LESS_MONEY_TO_TAKE_OUT', '12'); define ( 'ERROR_BILL_LESS_MONEY_TO_TAKE_OUT_MSG', 'Weniger Geld in Kasse als entnommen werden soll'); -define ( 'ERROR_GENERAL_PAYDESK_SUM', '13'); +define ( 'ERROR_GENERAL_PAYDESK_SUM', '13'); define ( 'ERROR_GENERAL_PAYDESK_SUM_MSG', 'Aktueller Kassenbestand nicht ermittelbar'); define ( 'ERROR_GENERAL_ID_TYPE', '14'); define ( 'ERROR_GENERAL_ID_TYPE_MSG', 'Falscher Typ des Referenzschluessels'); -define ( 'ERROR_GENERAL_DB_NOT_READABLE', '15'); +define ( 'ERROR_GENERAL_DB_NOT_READABLE', '15'); define ( 'ERROR_GENERAL_DB_NOT_READABLE_MSG', 'Datenbankleseprozess abgebrochen'); -define ( 'ERROR_DB_PAR_ACCESS', '16'); +define ( 'ERROR_DB_PAR_ACCESS', '16'); define ( 'ERROR_DB_PAR_ACCESS_MSG', 'Gleichzeitiger DB-Zugriff'); -define ( 'ERROR_EMAIL_FAILURE', '17'); +define ( 'ERROR_EMAIL_FAILURE', '17'); define ( 'ERROR_EMAIL_FAILURE_MSG', 'Emailversand fehlgeschlagen'); -define ( 'ERROR_INCONSISTENT_DB', '17'); +define ( 'ERROR_INCONSISTENT_DB', '17'); define ( 'ERROR_INCONSISTENT_DB_MSG', 'Inkonsistente Datenbank'); -define ( 'ERROR_RES_NOT_AUTHOTRIZED', '18'); +define ( 'ERROR_RES_NOT_AUTHOTRIZED', '18'); define ( 'ERROR_RES_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Reservierung)'); define ( 'ERROR_DB_PRIVS_MISSING', '19'); @@ -88,4 +88,13 @@ define ( 'ERROR_BILL_CANCEL_IMOSSIBLE_MSG', 'Stornierung unmöglich'); define ( 'FOOD_PRINT_TYPE', 1); define ( 'DRINK_PRINT_TYPE', 2); define ( 'PAY_PRINT_TYPE', 3); + +define ( 'ERROR_COMMAND_NOT_FOUND', 29); +define ( 'ERROR_COMMAND_NOT_FOUND_MSG', 'Rechte für Kommando konnten nicht verifiziert werden'); + +define ( 'ERROR_COMMAND_NOT_ADMIN', 30); +define ( 'ERROR_COMMAND_NOT_ADMIN_MSG', 'Benutzer besitzt keine Admin-Rechte'); + +define ( 'ERROR_COMMAND_ERROR', 31); +define ( 'ERROR_COMMAND_ERROR_MSG', 'Kommando konnte nicht korrekt ausgeführt werden'); ?> \ No newline at end of file diff --git a/webapp/php/printqueue.php b/webapp/php/printqueue.php index 4b53a8c..6439009 100644 --- a/webapp/php/printqueue.php +++ b/webapp/php/printqueue.php @@ -7,18 +7,18 @@ require_once ('bill.php'); require_once ('closing.php'); class PrintQueue { - var $dbutils; + var $dbutils; var $userrights; var $admin; - function __construct() { - $this->dbutils = new DbUtils(); + function __construct() { + $this->dbutils = new DbUtils(); $this->userrights = new Userrights(); - $this->admin = new Admin(); + $this->admin = new Admin(); } - function handleCommand($command) { - // these command are only allowed for user with waiter rights + function handleCommand($command) { + // these command are only allowed for user with waiter rights if ($command == 'getNextReceiptPrintJobs') { // REM* feature level $fl = null; @@ -59,10 +59,16 @@ class PrintQueue { } else if ($command == 'getLogoAsWbmp') { $this->getLogoAsWbmp(); } else if ($command == 'getPrintJobOverview') { - $this->getPrintJobOverview(); + $pdo = DbUtils::openDbAndReturnPdoStatic(); + $this->getPrintJobOverview($pdo); + } else if ($command == 'clearprintjobs') { + $pdo = DbUtils::openDbAndReturnPdoStatic(); + $this->clearprintjobs($pdo); + } else if ($command == 'batchReceiptPrintJob') { + $this->batchReceiptPrintJob($_POST['start'],$_POST['end']); } else { echo "Kommando nicht erkannt!"; - } + } } function testConnection($md5pass) { @@ -96,7 +102,7 @@ class PrintQueue { $stmt->execute(array($content,intval($kind) + 1,$printer)); } - function getPrintJobOverview() { + function getPrintJobOverview($pdo) { if (!($this->userrights->hasCurrentUserRight('right_manager')) && !($this->userrights->hasCurrentUserRight('is_admin')) ) { @@ -104,8 +110,6 @@ class PrintQueue { return; } - $pdo = DbUtils::openDbAndReturnPdoStatic(); - $jobs = array(); for ($printer=1;$printer<7;$printer++) { // bills: @@ -128,6 +132,60 @@ class PrintQueue { echo json_encode(array("status" => "OK", "msg" => $jobs)); } + // REM* delete all printjobs + function clearprintjobs($pdo) { + if (!($this->userrights->hasCurrentUserRight('right_manager')) && + !($this->userrights->hasCurrentUserRight('is_admin')) + ) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PRIVS_MISSING, "msg" => ERROR_DB_PRIVS_MISSING_MSG)); + return; + } + $sql = "DELETE FROM %printjobs%"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(); + $this->getPrintJobOverview($pdo); + } + + function batchReceiptPrintJob($start,$end) { + try { + $start = intval($start); + $end = intval($end); + } catch (Exception $ex) { + echo json_encode(array("status" => "ERROR", "code" => NUMBERFORMAT_ERROR, "msg" => NUMBERFORMAT_ERROR_MSG)); + return; + } + if(!($this->userrights->hasCurrentUserRight('right_bill'))) { + echo json_encode(array("status" => "ERROR", "code" => ERROR_BILL_NOT_AUTHOTRIZED, "msg" => ERROR_BILL_NOT_AUTHOTRIZED_MSG)); + } else { + // REM* sort it that start is <= end job id + if ($start > $end) { + $tmp = $end; + $end = $start; + $start = $tmp; + } + if(session_id() == '') { + session_start(); + } + $printer = $_SESSION['receiptprinter']; + $pdo = DbUtils::openDbAndReturnPdoStatic(); + + for($jobId=$start;$jobId <= $end;$jobId++) { + // REM* check if bill id exists + $sql = "SELECT count(id) as countid FROM %bill% WHERE id=?"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array($jobId)); + $row =$stmt->fetchObject(); + if ($row->countid == 1) { + // REM* yes, print + $printInsertSql = "INSERT INTO `%printjobs%` (`id` , `content`,`type`,`printer`) VALUES ( NULL,?,?,?)"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($printInsertSql)); + $stmt->execute(array($jobId,'3',$printer)); + } + } + echo json_encode(array("status" => "OK")); + } + } + function queueReceiptPrintJob($billid) { // waiter, or manager, bill, admin rights required if (!($this->userrights->hasCurrentUserRight('right_paydesk')) && @@ -162,6 +220,7 @@ class PrintQueue { if (!($this->userrights->hasCurrentUserRight('right_paydesk')) && !($this->userrights->hasCurrentUserRight('right_manager')) && !($this->userrights->hasCurrentUserRight('right_bill')) && + !($this->userrights->hasCurrentUserRight('right_closing')) && !($this->userrights->hasCurrentUserRight('right_waiter')) && !($this->userrights->hasCurrentUserRight('is_admin')) ) { @@ -191,14 +250,14 @@ class PrintQueue { } function isPasswordCorrect($pass,$verbose) { - $sql = "SELECT setting FROM %config% WHERE name=?"; - $pdo = $this->dbutils->openDbAndReturnPdo(); - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array("printpass")); - $row =$stmt->fetchObject(); - - if ($row != null) { - $passInDb = $row->setting; + $sql = "SELECT setting FROM %config% WHERE name=?"; + $pdo = $this->dbutils->openDbAndReturnPdo(); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt->execute(array("printpass")); + $row =$stmt->fetchObject(); + + if ($row != null) { + $passInDb = $row->setting; if ($passInDb != null) { // plain comparison if ($pass == $passInDb) { @@ -207,12 +266,12 @@ class PrintQueue { if ($verbose) { echo "Error: Falscher Printpass!"; } - } + } } else { if ($verbose) { echo "Error: kein Printpass in DB gesetzt!"; } - } + } } if ($verbose) { echo "Error: DB konnte nicht abgefragt werden!"; @@ -400,11 +459,11 @@ class PrintQueue { function deletePrintJob($pass,$id) { - $isCorrect = $this->isPasswordCorrect($pass,false); + $isCorrect = $this->isPasswordCorrect($pass,false); if ($isCorrect) { $sql = "DELETE FROM %printjobs% WHERE id=?"; - $pdo = $this->dbutils->openDbAndReturnPdo(); - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $pdo = $this->dbutils->openDbAndReturnPdo(); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($id)); echo json_encode(array("status" => "OK", "code" => OK, "msg" => "Druckauftrag erfolgreich gelöscht.")); } else { diff --git a/webapp/php/products.php b/webapp/php/products.php index 3f750f9..4ceaa5d 100644 --- a/webapp/php/products.php +++ b/webapp/php/products.php @@ -6,6 +6,7 @@ require_once ('commonutils.php'); require_once ('utilities/userrights.php'); require_once ('utilities/HistFiller.php'); require_once ('utilities/sorter.php'); +require_once ('utilities/TypeAndProducts/ProductEntry.php'); class Products { var $dbutils; @@ -57,9 +58,10 @@ class Products { $this->getMenuLevelUp($_GET['ref']); } else if ($command == 'getSpeisekarte') { if ($this->userrights->hasCurrentUserRight('is_admin') || ($this->userrights->hasCurrentUserRight('right_manager'))) { - $this->getSpeisekarte(); + $pdo = DbUtils::openDbAndReturnPdoStatic(); + echo json_encode($this->getSpeisekarte($pdo)); } else { - echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); + echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG)); } } else if ($command == 'exportCsv') { if (($this->userrights->hasCurrentUserRight('is_admin')) @@ -109,8 +111,6 @@ class Products { $this->getPriceLevelInfo(); } else if ($command == 'setPriceLevelInfo') { $this->setPriceLevelInfo($_POST['priceLevelId']); - } else if ($command == 'getSpeisekarte') { - $this->getSpeisekarte(); } else if ($command == 'getAudioFiles') { $this->getAudioFiles(); } else if ($command == 'addGeneralComment') { @@ -389,7 +389,7 @@ class Products { function readDbProducts($pdo) { $speisekarte = $this->readDbProductsWithRef_json_version($pdo,0,0); - $speisekarte .= $this->readExtrasFromDb(null); + $speisekarte .= $this->readExtrasFromDb($pdo); return $speisekarte; } @@ -402,7 +402,7 @@ class Products { $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_OBJ); $extrasTxt = ""; - $decpoint = $this->getDecPoint(); + $decpoint = $this->getDecPoint($pdo); foreach ($result as $aRes) { $extrasTxt .= "!" . $aRes->name . " (ID:" . $aRes->id . ") #" ; $priceTxt = number_format($aRes->price, 2, $decpoint, ''); @@ -423,9 +423,8 @@ class Products { return $extrasTxt; } - private function getDecPoint() { + private function getDecPoint($pdo) { $sql = "SELECT name,setting FROM %config% WHERE name=?"; - $pdo = $this->dbutils->openDbAndReturnPdo(); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array("decpoint")); $row = $stmt->fetchObject(); @@ -435,7 +434,7 @@ class Products { private function exportCsv() { $pdo = DbUtils::openDbAndReturnPdoStatic(); - $decpoint = $this->getDecPoint(); + $decpoint = $this->getDecPoint($pdo); $file_name = "datenexport-produkte.csv"; header("Content-type: text/x-csv"); header("Content-Disposition: attachment; filename=$file_name"); @@ -913,11 +912,8 @@ class Products { if ($changeExtras == 1) { $this->changeExtraAssignment($pdo, $id, $extras); } - $histextra = self::getExtrasForProd($pdo,$id); - // now this has to be logged in the history tables... - $this->histfiller->updateProdInHist($pdo,$id, $shortname, $longname, $priceA, $priceB, $priceC, $tax, - NULL, $available,$audioFile,$favorite,$histextra); + HistFiller::updateProdInHist($pdo,$id); } else { $prodids = self::getAllProdIdOfSameTypeAndBelow($pdo,$id); @@ -934,14 +930,7 @@ class Products { } private static function updateHistOnlyForExtrasOfProd($pdo,$aProdId,$histextra) { - $sql = "SELECT shortname,longname,priceA,priceB,priceC,tax,available,audio,favorite FROM %products% WHERE id=?"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($aProdId)); - $row = $stmt->fetchObject(); - - $histfiller = new HistFiller(); - $histfiller->updateProdInHist($pdo,$aProdId, $row->shortname, $row->longname, $row->priceA, $row->priceB, $row->priceC, - $row->tax, NULL, $row->available,$row->audio,$row->favorite,$histextra); + HistFiller::updateProdInHist($pdo, $aProdId); } function changeExtraAssignment($pdo,$prodid,$extras) { @@ -1037,9 +1026,7 @@ class Products { $pdo->commit(); // now this has to be logged in the history tables... - - $this->histfiller->createProdInHist ($pdo,$newProdId, $shortname, $longname, $priceA, $priceB, $priceC,$tax, - NULL, $available,$audioFile,$favorite); + HistFiller::createProdInHist($pdo, $newProdId); echo json_encode("OK: sql"); } @@ -1119,9 +1106,8 @@ class Products { // return in text format private function readDbProductsWithRef_json_version($pdo,$ref,$depth) { - $decpoint = $this->getDecPoint(); + $decpoint = $this->getDecPoint($pdo); $text = ""; - $allProdsAndTypesInThisLevel = array(); $allProdsInThisLevel = $this->getProductsWithReferenz($pdo,$ref); $allTypesInThisLevel = $this->getProdTypesWithReferenz($pdo,$ref); @@ -1130,33 +1116,8 @@ class Products { $aProd = $allProdsInThisLevel[$index_prod]; // Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C) - $shortname = $aProd['shortname'] . " (ID:" . $aProd['id'] . ")"; - $longname = $aProd['longname']; - - $available = $aProd['available']; - $prodid = $aProd['id']; - - // prices (back from db-point to wished decimal point) - $priceA = str_replace('.',$decpoint,$aProd['priceA']); - $priceB = str_replace('.',$decpoint,$aProd['priceB']); - $priceC = str_replace('.',$decpoint,$aProd['priceC']); - $tax = str_replace('.',$decpoint,$aProd['tax']); - - $prodstart = "$shortname ; $priceA"; - if ($aProd['shortname'] != $longname) { - $prodstart .= " ; " . $longname; - } - - if ($tax == "null") { - $tax = null; - } - - if (($priceB != $priceA) || ($priceC != $priceA) || (!is_null($tax))) { - $prodText = "$prodstart # $priceB ; $priceC; $tax"; - } else { - $prodText = "$prodstart"; - } - $text .= substr ( " " , 0 ,$depth) . $prodText . "\n"; + $prodText = ProductEntry::createProductStr($aProd,$decpoint); + $text .= substr(" ", 0, $depth) . $prodText . "\n"; } for ($index_type=0;$index_type < count($allTypesInThisLevel);$index_type++) { @@ -1230,20 +1191,18 @@ class Products { } } - private function getSpeisekarte() { - $pdo = DbUtils::openDbAndReturnPdoStatic(); + public function getSpeisekarte($pdo) { $legend = file_get_contents("../customer/menulegend.txt"); - $decpoint = $this->getDecPoint(); - $pdo = $this->dbutils->openDbAndReturnPdo(); + $decpoint = $this->getDecPoint($pdo); $sql = "SELECT * FROM %products% WHERE removed is null"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); $numberOfProds = $stmt->rowCount(); $sql = "SELECT * FROM %prodtype% WHERE removed is null"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(); $numberOfProdTypes = $stmt->rowCount(); @@ -1256,7 +1215,7 @@ class Products { $text = $legend . $this->readDbProducts($pdo); } - echo json_encode(array("status" => "OK","msg" => $text, "predef" => $predef)); + return array("status" => "OK","msg" => $text, "predef" => $predef); } private function endsWith($haystack, $needle) diff --git a/webapp/php/queuecontent.php b/webapp/php/queuecontent.php index 5fc900a..79c63a7 100644 --- a/webapp/php/queuecontent.php +++ b/webapp/php/queuecontent.php @@ -19,9 +19,9 @@ class QueueContent { } function handleCommand($command) { - header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); + header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); if ($command == "getJsonTableNameFromId") { $this->getJsonTableNameFromId($_GET['tableid']); @@ -29,7 +29,7 @@ class QueueContent { } // these command are only allowed for user with supply rights - $cmdArray = array('getJsonAllPreparedProducts', 'getJsonLastDeliveredProducts', 'declareProductBeDelivered', 'declareMultipleProductsDelivered','declareProductNotBeDelivered'); + $cmdArray = array('getJsonAllPreparedProducts', 'getJsonLastDeliveredProducts', 'declareProductBeDelivered', 'declareMultipleProductsDelivered','declareProductNotBeDelivered'); if (in_array($command, $cmdArray)) { if (!($this->userrights->hasCurrentUserRight('right_supply'))) { echo "Benutzerrechte nicht ausreichend!"; @@ -39,29 +39,29 @@ class QueueContent { // these command are only allowed for user with kitchen or bar rights $cmdArray = array('declareProductBeCookingOrCooked', 'declareProductNOTBeCooked'); - if (in_array($command, $cmdArray)) { - if (!($this->userrights->hasCurrentUserRight('right_kitchen')) && !($this->userrights->hasCurrentUserRight('right_bar'))) { - echo "Benutzerrechte nicht ausreichend!"; - return false; - } + if (in_array($command, $cmdArray)) { + if (!($this->userrights->hasCurrentUserRight('right_kitchen')) && !($this->userrights->hasCurrentUserRight('right_bar'))) { + echo "Benutzerrechte nicht ausreichend!"; + return false; + } } // these command are only allowed for user with waiter rights - $cmdArray = array('addProductListToQueue', 'removeProductFromQueue', 'changeTable','getProdsForTableChange'); - if (in_array($command, $cmdArray)) { - if (!($this->userrights->hasCurrentUserRight('right_waiter'))) { - echo "Benutzerrechte nicht ausreichend!"; - return false; - } + $cmdArray = array('addProductListToQueue', 'removeProductFromQueue', 'changeTable','getProdsForTableChange'); + if (in_array($command, $cmdArray)) { + if (!($this->userrights->hasCurrentUserRight('right_waiter'))) { + echo "Benutzerrechte nicht ausreichend!"; + return false; + } } - // these command are only allowed for user with paydesk rights - $cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId'); - if (in_array($command, $cmdArray)) { + // these command are only allowed for user with paydesk rights + $cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId'); + if (in_array($command, $cmdArray)) { if (!($this->userrights->hasCurrentUserRight('right_paydesk'))) { - echo json_encode(array("status" => "ERROR", "code" => ERROR_PAYDESK_NOT_AUTHOTRIZED, "msg" => ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG)); - return false; - } + echo json_encode(array("status" => "ERROR", "code" => ERROR_PAYDESK_NOT_AUTHOTRIZED, "msg" => ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG)); + return false; + } } if ($command == 'addProductListToQueue') { @@ -104,7 +104,7 @@ class QueueContent { $this->declarePaidCreateBillReturnBillId($_POST['ids'],$_POST['brutto'],$_POST['netto'],$_POST['tableid'],$_POST['paymentid'],$_POST['tax'],$_POST['decpoint'],$_POST['declareready'],$_POST['host']); } else { echo "Command not supported."; - } + } } // needed if paydesk gets the tableid by direct call @@ -124,13 +124,13 @@ class QueueContent { } function getUserName($userid) { - $pdo = $this->dbutils->openDbAndReturnPdo(); - - $sql = "SELECT username FROM %user% WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array($userid)); - $row =$stmt->fetchObject(); - if ($row != null) { + $pdo = $this->dbutils->openDbAndReturnPdo(); + + $sql = "SELECT username FROM %user% WHERE id=?"; + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt->execute(array($userid)); + $row =$stmt->fetchObject(); + if ($row != null) { return($row->username); } else { return ""; @@ -161,8 +161,8 @@ class QueueContent { * $kind=0 -> return only food elements, =1 -> return drinks */ private function getJsonAllQueueItemsToMake($kind) { - // current time - date_default_timezone_set(DbUtils::getTimeZone()); + // current time + date_default_timezone_set(DbUtils::getTimeZone()); $currentTime = date('Y-m-d H:i:s'); $pdo = $this->dbutils->openDbAndReturnPdo(); @@ -514,17 +514,17 @@ class QueueContent { } private function getJsonLastMadeItems($kind) { - $pdo = DbUtils::openDbAndReturnPdoStatic(); + $pdo = DbUtils::openDbAndReturnPdoStatic(); // first sort all non-ready products ordered by ordertime - if ($this->areBillExisting($pdo)) { - $sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables%,%bill% "; + if ($this->areBillExisting($pdo)) { + $sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables%,%bill% "; } else { $sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables% "; } $sql .= "WHERE (readytime <> '0000-00-00 00:00:00' AND "; $sql .= "delivertime = '0000-00-00 00:00:00' AND "; - $sql .= "ordertime is not null AND "; - $sql .= "%queue%.productid=%products%.id AND "; + $sql .= "ordertime is not null AND "; + $sql .= "%queue%.productid=%products%.id AND "; $sql .= "%queue%.tablenr = %resttables%.id AND "; $sql .= "%products%.category=%prodtype%.id AND "; $sql .= "%prodtype%.kind=? AND "; @@ -532,14 +532,14 @@ class QueueContent { $sql .= "%queue%.workprinted='0') "; if ($this->areBillExisting($pdo)) { - // now remove closed items - $sql .= "AND (%queue%.billid is null OR ("; + // now remove closed items + $sql .= "AND (%queue%.billid is null OR ("; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; - } + } $sql .= "ORDER BY readytime DESC LIMIT 10;"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($kind)); + $stmt->execute(array($kind)); $result1 = $stmt->fetchAll(); if ($this->areBillExisting($pdo)) { @@ -570,7 +570,7 @@ class QueueContent { $result2 = $stmt->fetchAll(); $result = array_merge($result1,$result2); - + $resultarray = array(); foreach($result as $zeile) { $extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']); @@ -578,16 +578,16 @@ class QueueContent { $productid = $zeile['prodid']; $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); if ($useConditions["usekitchen"] == 1) { - // yes, display it in kitchen view as cooked - $arr = array("id" => $zeile['id'], - "tablename" => $zeile['tableno'], - "longname" => $zeile['longname'], + // yes, display it in kitchen view as cooked + $arr = array("id" => $zeile['id'], + "tablename" => $zeile['tableno'], + "longname" => $zeile['longname'], "option" => $zeile['anoption'], - "extras" => $extras, - "readytime" => $zeile['readytime'] - ); + "extras" => $extras, + "readytime" => $zeile['readytime'] + ); $resultarray[] = $arr; - } + } } // now look for items that are made and auto-delivered @@ -600,40 +600,40 @@ class QueueContent { echo json_encode($resultarray); } - private function appendProdsForBarKitchenAndAutoDelivery($pdo,$kind,$resultarray) { - $sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid "; - $sql .= "FROM %queue%,%resttables%,%products%,%bill%,%prodtype% "; - $sql .= "WHERE (%queue%.productid=%products%.id "; + private function appendProdsForBarKitchenAndAutoDelivery($pdo,$kind,$resultarray) { + $sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid "; + $sql .= "FROM %queue%,%resttables%,%products%,%bill%,%prodtype% "; + $sql .= "WHERE (%queue%.productid=%products%.id "; $sql .= "AND %queue%.tablenr=%resttables%.id "; - $sql .= "AND %queue%.readytime <> '0000-00-00 00:00:00' "; - $sql .= "AND toremove <> '1' AND "; + $sql .= "AND %queue%.readytime <> '0000-00-00 00:00:00' "; + $sql .= "AND toremove <> '1' AND "; $sql .= "ordertime is not null AND "; - $sql .= "(%queue%.productid = %products%.id AND %products%.category = %prodtype%.id AND %prodtype%.kind=? AND %prodtype%.usesupplydesk='0' AND %prodtype%.usekitchen='1') AND "; - $sql .= "%queue%.workprinted='0') "; - - // now remove closed items - $sql .= "AND (%queue%.billid is null OR ("; - $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; - + $sql .= "(%queue%.productid = %products%.id AND %products%.category = %prodtype%.id AND %prodtype%.kind=? AND %prodtype%.usesupplydesk='0' AND %prodtype%.usekitchen='1') AND "; + $sql .= "%queue%.workprinted='0') "; + + // now remove closed items + $sql .= "AND (%queue%.billid is null OR ("; + $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; + $sql = $sql . "ORDER BY delivertime DESC LIMIT 10"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($kind)); $result = $stmt->fetchAll(); - foreach ($result as $zeile) { + foreach ($result as $zeile) { $productid = $zeile['prodid']; - $extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']); - $deliveredProd = array( + $extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']); + $deliveredProd = array( "id" => $zeile['id'], - "tablename" => $zeile['tableno'], - "longname" => $zeile['longname'], + "tablename" => $zeile['tableno'], + "longname" => $zeile['longname'], "option" => $zeile['anoption'], - "extras" => $extras, - "readytime" => $zeile['delivertime'] - ); - $resultarray[] = $deliveredProd; - } - return($resultarray); + "extras" => $extras, + "readytime" => $zeile['delivertime'] + ); + $resultarray[] = $deliveredProd; + } + return($resultarray); } /* @@ -641,17 +641,17 @@ class QueueContent { */ function declareProductBeCookingOrCooked($queueid,$action) { if (is_numeric($queueid)) { - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); $pdo->beginTransaction(); // is product already cooking or will it be set to cooking? $sql = "SELECT cooking,productid FROM %queue% WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array($queueid)); - $row =$stmt->fetchObject(); - if ($row != null) { + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt->execute(array($queueid)); + $row =$stmt->fetchObject(); + if ($row != null) { $cooking = $row->cooking; - $productid = $row->productid; + $productid = $row->productid; if ($action == 'r') { // product shall be declared ready @@ -660,11 +660,11 @@ class QueueContent { $pdo->rollBack(); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG)); } else { - $this->reallyDeclareAsCooked($pdo,$queueid); - $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); - if ($useConditions["usesupply"] == 0) { - // can bypass the supplydesk - $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); + $this->reallyDeclareAsCooked($pdo,$queueid); + $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); + if ($useConditions["usesupply"] == 0) { + // can bypass the supplydesk + $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); } $pdo->commit(); echo json_encode(array("status" => "OK")); @@ -673,30 +673,30 @@ class QueueContent { // product shall be declared as cooking (in progress) if (!is_null($cooking)) { // a product must not be cooking before it can becomes cooking - $pdo->rollBack(); + $pdo->rollBack(); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG)); } else { $userid = $this->getUserId(); $updSql = "UPDATE %queue% SET cooking=? WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updSql)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updSql)); $stmt->execute(array($userid,$queueid)); $pdo->commit(); echo json_encode(array("status" => "OK")); } - } + } } else { $pdo->rollBack(); } } else { echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG)); - } + } } private function reallyDeclareAsCooked($pdo,$queueid) { - date_default_timezone_set(DbUtils::getTimeZone()); - $readytime = date('Y-m-d H:i:s'); + date_default_timezone_set(DbUtils::getTimeZone()); + $readytime = date('Y-m-d H:i:s'); $insertSql = "UPDATE %queue% SET readytime=? WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql)); $stmt->execute(array($readytime,$queueid)); } @@ -705,15 +705,15 @@ class QueueContent { */ function declareProductNotBeCooked($queueid) { if (is_numeric($queueid)) { - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); $pdo->beginTransaction(); // first: is the product still declared as delivered? $sql = "SELECT id FROM %queue% WHERE id=? AND readytime <> '0000-00-00 00:00:00'"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(array($queueid)); - $row =$stmt->fetchObject(); - if ($row != null) { + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt->execute(array($queueid)); + $row =$stmt->fetchObject(); + if ($row != null) { $foundid = $row->id; if ($foundid == $queueid) { $sql = "UPDATE %queue% SET readytime='0000-00-00 00:00:00', delivertime='0000-00-00 00:00:00', cooking=NULL WHERE id=?"; @@ -728,7 +728,7 @@ class QueueContent { } else { $pdo->rollBack(); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG)); - } + } } else { echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG)); } @@ -756,7 +756,7 @@ class QueueContent { } private function getUseKitchenAndSupplyForProdWithPdo($pdo,$prodid) { - $sql = "SELECT usekitchen, usesupplydesk FROM %prodtype%,%products% WHERE %products%.category=%prodtype%.id AND %products%.id=?"; + $sql = "SELECT usekitchen, usesupplydesk FROM %prodtype%,%products% WHERE %products%.category=%prodtype%.id AND %products%.id=?"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($prodid)); $row = $stmt->fetchObject(); @@ -767,12 +767,12 @@ class QueueContent { } } - /* - * Add a product list to the queue as if it was ordered by the waiter. - * The ordertime is set by the time that this method is invoked. - * - * If product shall not be run over kitchen or supplydesk this is - * managed here as well + /* + * Add a product list to the queue as if it was ordered by the waiter. + * The ordertime is set by the time that this method is invoked. + * + * If product shall not be run over kitchen or supplydesk this is + * managed here as well */ function addProductListToQueue($theTableid,$prods,$doPrint,$payprinttype) { if (intval($theTableid) == 0) { @@ -798,10 +798,10 @@ class QueueContent { $stmt->execute(array('workflowconfig')); $row = $stmt->fetchObject(); $workflowconfig = $row->setting; - - // get current pricelevel - $currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo); - $currentPriceLevelId = $currentPriceLevel["id"]; + + // get current pricelevel + $currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo); + $currentPriceLevelId = $currentPriceLevel["id"]; $insertedQueueIds = array(); @@ -812,29 +812,29 @@ class QueueContent { $theOption = $aProd["option"]; $theChangedPrice = $aProd["changedPrice"]; $theChangedPrice = str_replace(',','.',$theChangedPrice); - - // now get the price for this pricelevel - $getPriceSql = "SELECT priceA,priceB,priceC,longname,tax FROM %products% where id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($getPriceSql)); - $stmt->execute(array($productid)); - $row = $stmt->fetchObject(); - if ($row == null) { - echo "Fehler: Preise nicht vorhanden"; // error - return; + + // now get the price for this pricelevel + $getPriceSql = "SELECT priceA,priceB,priceC,longname,tax FROM %products% where id=?"; + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($getPriceSql)); + $stmt->execute(array($productid)); + $row = $stmt->fetchObject(); + if ($row == null) { + echo "Fehler: Preise nicht vorhanden"; // error + return; } - + $productname = $row->longname; - if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) { - $price_for_level_A = $row->priceA; - $price_for_level_B = $row->priceB; - $price_for_level_C = $row->priceC; - - $price = $price_for_level_A; // default - levl 1 - if ($currentPriceLevelId == 2) { - $price = $price_for_level_B; - } else if ($currentPriceLevelId == 3) { - $price = $price_for_level_C; - } // else: use default price A + if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) { + $price_for_level_A = $row->priceA; + $price_for_level_B = $row->priceB; + $price_for_level_C = $row->priceC; + + $price = $price_for_level_A; // default - levl 1 + if ($currentPriceLevelId == 2) { + $price = $price_for_level_B; + } else if ($currentPriceLevelId == 3) { + $price = $price_for_level_C; + } // else: use default price A } else { $price = $theChangedPrice; } @@ -870,19 +870,19 @@ class QueueContent { $price += floatval($row->price); } } - - if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) { - // first get category of product - $useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid); - - date_default_timezone_set(DbUtils::getTimeZone()); - $ordertime = date('Y-m-d H:i:s'); - - $insertSql = "INSERT INTO `%queue%` ( - `id` , `tablenr`,`productid`,`pricelevel`,`price`,`tax`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`) - VALUES ( - NULL , ?,?,?,?,?,?,?,?,?,?,?, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL,NULL,'0',NULL,'0');"; - + + if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) { + // first get category of product + $useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid); + + date_default_timezone_set(DbUtils::getTimeZone()); + $ordertime = date('Y-m-d H:i:s'); + + $insertSql = "INSERT INTO `%queue%` ( + `id` , `tablenr`,`productid`,`pricelevel`,`price`,`tax`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`) + VALUES ( + NULL , ?,?,?,?,?,?,?,?,?,?,?, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL,NULL,'0',NULL,'0');"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($insertSql)); $stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$tax,$productname,$ordertime,$_SESSION['userid'],$theOption,($theChangedPrice == "NO" ? 0 : 1),$togo)); $queueid = $pdo->lastInsertId(); @@ -895,26 +895,26 @@ class QueueContent { $sql = "INSERT INTO %queueextras% (`id`,`queueid`,`extraid`,`name`) VALUES(NULL,?,?,?)"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($queueid,$extraid,$extraname)); - } + } } if (($workflowconfig == 3) && ($doPrint == 0)) { $this->reallyDeclareAsCooked($pdo,$queueid); $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); } else { - if ($useConditions["usekitchen"] == 0) { - // no - can bypass the kitchen - $this->reallyDeclareAsCooked($pdo,$queueid); - // then also look for supplydesk, since kitchen action won't do this! - if ($useConditions["usesupply"] == 0) { - // can bypass the supplydesk - $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); - // THIS autop declares as "prepared" (cooked)!!! - } + if ($useConditions["usekitchen"] == 0) { + // no - can bypass the kitchen + $this->reallyDeclareAsCooked($pdo,$queueid); + // then also look for supplydesk, since kitchen action won't do this! + if ($useConditions["usesupply"] == 0) { + // can bypass the supplydesk + $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); + // THIS autop declares as "prepared" (cooked)!!! + } } else { $insertedQueueIds[] = $queueid; } - } + } } } @@ -941,7 +941,7 @@ class QueueContent { */ function removeProductFromQueue($queueid,$isPaid,$isCooking,$isReady) { if (is_numeric($queueid)) { - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); $sql = "SELECT count(id) as countid FROM %bill%"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); @@ -949,7 +949,7 @@ class QueueContent { $row = $stmt->fetchObject(); $hasBills = ($row->countid > 0 ? true : false); - if ($hasBills) { + if ($hasBills) { $sql = "UPDATE %queue%,%bill% "; } else { $sql = "UPDATE %queue% "; @@ -976,9 +976,9 @@ class QueueContent { $sql .= " billid = %bill%.id AND %bill%.closingid is null)) "; } $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - + $stmt->execute(array($queueid)); - $rowsAffected = $stmt->rowCount(); + $rowsAffected = $stmt->rowCount(); if ($rowsAffected == 1) { echo json_encode(array("status" => "OK")); } else { @@ -1016,7 +1016,7 @@ class QueueContent { */ function getJsonLongNamesOfProdsForTableNotDelivered($tableid) { if (is_numeric($tableid)) { - $prods = array(); + $prods = array(); $pdo = DbUtils::openDbAndReturnPdoStatic(); @@ -1096,7 +1096,7 @@ class QueueContent { $prods[] = $prodEntry; } echo json_encode($prods); - } + } } @@ -1107,27 +1107,43 @@ class QueueContent { $tableid = null; } - $sql = "SELECT count(%queue%.id) as mycount,productname, GROUP_CONCAT(%queue%.id) AS queueids FROM "; + + $sql = "SELECT %queue%.id as queueid,productname FROM "; $sql .= "%queue% WHERE "; $sql .= "(tablenr=? OR (tablenr IS NULL AND ? IS NULL)) AND ordertime is not null AND isclosed is null AND billid is null "; - $sql .= "GROUP BY productid"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($tableid,$tableid)); - $unpaidresult = $stmt->fetchAll(); - - $sql = "SELECT count(%queue%.id) as mycount,productname, GROUP_CONCAT(%queue%.id) AS queueids FROM "; + $unpaidresultungrouped = $stmt->fetchAll(); + + $sql = "SELECT %queue%.id as queueid,productname FROM "; $sql .= "%queue% LEFT OUTER JOIN %bill% ON %queue%.billid=%bill%.id WHERE "; $sql .= "(tablenr=? OR (tablenr IS NULL AND ? IS NULL)) AND ordertime is not null AND isclosed is null AND billid is null AND ("; $sql .= "%queue%.delivertime = '0000-00-00 00:00:00' OR "; $sql .= "(%queue%.delivertime <> '0000-00-00 00:00:00' AND workprinted='1')) "; - $sql .= "GROUP BY productid"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($tableid,$tableid)); - $undeliveredresult = $stmt->fetchAll(); + $undeliveredresultungrouped = $stmt->fetchAll(); + $merged = array(); + foreach($unpaidresultungrouped as $entry) { + $qid = $entry["queueid"]; + $prodname = $entry["productname"]; + $status = "unpaid"; + if ($this->isQueueIdInList($qid, $undeliveredresultungrouped)) { + $status = "unpaid_undelivered"; + } + $merged[] = array("queueid" => $qid,"productname" => $prodname,"status" => $status); + } - echo json_encode(array("status" => "OK","unpaid" => $unpaidresult,"undeliveredunpaid" => $undeliveredresult)); + echo json_encode(array("status" => "OK","msg" => $merged)); + } + + function isQueueIdInList($queueid,$list) { + foreach($list as $entry) { + if ($entry['queueid'] == $queueid) { + return true; + } + } + return false; } @@ -1155,13 +1171,13 @@ class QueueContent { function getJsonProductsOfTableToPay($tableid) { $pdo = DbUtils::openDbAndReturnPdoStatic(); - $sql = "SELECT %queue%.id as id,longname,%queue%.price as price,%queue%.tax,%pricelevel%.name as pricelevelname,%products%.id as prodid,%queue%.togo as togo - FROM %queue% + $sql = "SELECT %queue%.id as id,longname,%queue%.price as price,%queue%.tax,%pricelevel%.name as pricelevelname,%products%.id as prodid,%queue%.togo as togo + FROM %queue% INNER JOIN %products% ON %queue%.productid = %products%.id INNER JOIN %pricelevel% ON %queue%.pricelevel = %pricelevel%.id "; if ($tableid == 0) { $sql .= "WHERE tablenr is null "; - } else { + } else { $sql .= "WHERE tablenr = $tableid "; } $sql .= "AND paidtime is null AND toremove <> '1' AND ordertime is not null AND isclosed is null ORDER BY ordertime;"; @@ -1170,10 +1186,10 @@ class QueueContent { $stmt->execute(); $result = $stmt->fetchAll(); $prodsToPay = array(); - foreach ($result as $zeile) { + foreach ($result as $zeile) { $thePrice = $zeile['price']; $theTax = $zeile['tax']; - $thePriceLevelName = $zeile['pricelevelname']; + $thePriceLevelName = $zeile['pricelevelname']; $longName = $zeile['longname']; $togo = $zeile["togo"]; $queueid = $zeile['id']; @@ -1190,23 +1206,23 @@ class QueueContent { // are listed up. It can be used as a receipt to print later function displayBill($billtableitems,$totalPrice) { $currency = $this->commonUtils->getCurrency(); - $numberOfItemsToPay = count($billtableitems); - if ($numberOfItemsToPay > 0) { - echo "

    "; - echo ""; - for ($i=0;$i < $numberOfItemsToPay; $i++) { - $aProductToPay = $billtableitems[$i]; - echo ""; - echo ""; - } - echo ""; - } - + $numberOfItemsToPay = count($billtableitems); + if ($numberOfItemsToPay > 0) { + echo "

    Speise/GetränkPreis ($currency)
    " . $aProductToPay['textOfButton'] . "" . $aProductToPay['price'] . "
    Gesamtpreis: " . $totalPrice . " $currency
    "; + echo ""; + for ($i=0;$i < $numberOfItemsToPay; $i++) { + $aProductToPay = $billtableitems[$i]; + echo ""; + echo ""; + } + echo ""; + } + echo "
    Speise/GetränkPreis ($currency)
    " . $aProductToPay['textOfButton'] . "" . $aProductToPay['price'] . "
    Gesamtpreis: " . $totalPrice . " $currency
    "; } - // ********************************** - // * Bereitstellung * + // ********************************** + // * Bereitstellung * // ********************************** @@ -1216,8 +1232,8 @@ class QueueContent { $delivertime = date('Y-m-d H:i:s'); $updateSql = "UPDATE %queue% SET delivertime=? WHERE id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql)); - $stmt->execute(array($delivertime,$queueid)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql)); + $stmt->execute(array($delivertime,$queueid)); // then it was probably already prepared $updateSql = "UPDATE %queue% SET readytime=? WHERE id=?"; @@ -1230,12 +1246,12 @@ class QueueContent { if (is_numeric($queueid)) { $pdo = $this->dbutils->openDbAndReturnPdo(); $this->declareProductBeDeliveredWithGivenPdo($pdo, $queueid); - } + } } function declareMultipleProductsDelivered($queueids) { $ids = explode(",",$queueids); - $pdo = DbUtils::openDbAndReturnPdoStatic(); + $pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo->beginTransaction(); for ($i=0;$i < count($ids); $i++) { @@ -1250,12 +1266,12 @@ class QueueContent { function declareProductNotBeDelivered($queueid) { $pdo = DbUtils::openDbAndReturnPdoStatic(); - if (is_numeric($queueid)) { - date_default_timezone_set(DbUtils::getTimeZone()); - $delivertime = date('Y-m-d H:i:s'); + if (is_numeric($queueid)) { + date_default_timezone_set(DbUtils::getTimeZone()); + $delivertime = date('Y-m-d H:i:s'); $updateSql = "UPDATE %queue% SET delivertime='0000-00-00 00:00:00' WHERE id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql)); - $stmt->execute(array($queueid)); + $stmt->execute(array($queueid)); } } @@ -1307,12 +1323,12 @@ class QueueContent { $stmt->execute(); $dbresult = $stmt->fetchAll(); - - // create a table that is optimal (sqrt-like size) - $numberOfIcons = count($dbresult); + + // create a table that is optimal (sqrt-like size) + $numberOfIcons = count($dbresult); $arrayOfProdsForTable = array(); $idsProdsOfTable = ''; // this is a hack! All queueids of a table redundant for "Deliver all" - foreach($dbresult as $zeile) { + foreach($dbresult as $zeile) { $theAction= "deliver"; $longname = $zeile['longname']; @@ -1323,14 +1339,14 @@ class QueueContent { "longname" => $zeile['longname'], "option" => $zeile['anoption'], "extras" => $extras, - "status" => "ready_to_deliver"); + "status" => "ready_to_deliver"); $arrayOfProdsForTable[] = $anProdElem; if ($idsProdsOfTable == '') { $idsProdsOfTable = $idsProdsOfTable . $zeile['id']; } else { $idsProdsOfTable = $idsProdsOfTable . ',' . $zeile['id']; - } - } + } + } return array("prods" => $arrayOfProdsForTable, "ids" => $idsProdsOfTable); } @@ -1384,8 +1400,8 @@ class QueueContent { $sql .= "%queue%.workprinted='0') "; if ($this->areBillExisting($pdo)) { - // now remove closed items - $sql .= "AND (%queue%.billid is null OR ("; + // now remove closed items + $sql .= "AND (%queue%.billid is null OR ("; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; } $sql .= " ORDER BY tablenr"; @@ -1440,18 +1456,18 @@ class QueueContent { $tableheadeline = $commonUtils->getTableNameFromId($pdo,$tableid); $preparedProds[] = array( "tableheadline" => $tableheadeline, - "tableid" => $tableid, + "tableid" => $tableid, "tablestatus" => $tablestatus, - "ids" => $arrayOfProdsAndIdsOfATable['ids'], + "ids" => $arrayOfProdsAndIdsOfATable['ids'], "prodsOfTable" => $arrayOfProdsOfATable); } else { $tablestatus = "incomplete"; $tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($pdo,$tableid); $preparedProds_incomplete_tables[] = array( "tableheadline" => $tableheadeline, - "tableid" => $tableid, + "tableid" => $tableid, "tablestatus" => $tablestatus, - "ids" => $arrayOfProdsAndIdsOfATable['ids'], + "ids" => $arrayOfProdsAndIdsOfATable['ids'], "prodsOfTable" => $arrayOfProdsOfATable); } } @@ -1473,7 +1489,7 @@ class QueueContent { $sql .= "FROM %queue%,%resttables%,%products% "; } $sql .= "WHERE (delivertime <> '0000-00-00 00:00:00' "; - $sql .= "AND %queue%.productid=%products%.id "; + $sql .= "AND %queue%.productid=%products%.id "; $sql .= "AND %queue%.tablenr=%resttables%.id "; $sql .= "AND toremove <> '1' AND "; $sql .= "ordertime is not null AND "; @@ -1481,8 +1497,8 @@ class QueueContent { $sql .= "%queue%.workprinted='0') "; if ($this->areBillExisting($pdo)) { - // now remove closed items - $sql .= "AND (%queue%.billid is null OR ("; + // now remove closed items + $sql .= "AND (%queue%.billid is null OR ("; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; } @@ -1520,9 +1536,9 @@ class QueueContent { $lastDeliveredProds = array(); foreach($result as $zeile) { - $productid = $zeile['prodid']; - $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); - if ($useConditions["usesupply"] == 1) { + $productid = $zeile['prodid']; + $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); + if ($useConditions["usesupply"] == 1) { // yes, display it in supplydesk view as cooked $extras = $this->getExtrasOfQueueItem(null,$zeile['id']); @@ -1533,17 +1549,17 @@ class QueueContent { "option" => $zeile['anoption'], "extras" => $extras, "delivertime" => $zeile['delivertime'], - "tablename" => $zeile['tableno']); + "tablename" => $zeile['tableno']); $lastDeliveredProds[] = $deliveredProd; - } + } } echo json_encode($lastDeliveredProds); } - // ********************************** - // * Kasse * - // ********************************** + // ********************************** + // * Kasse * + // ********************************** /* * Test if all queue items with the given ids are not paid @@ -1559,7 +1575,7 @@ class QueueContent { $ids_array = explode ( ',', $ids ); - $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo = $this->dbutils->openDbAndReturnPdo(); $pdo->beginTransaction(); // check if all items are not paid yet! @@ -1568,10 +1584,10 @@ class QueueContent { $anId = $ids_array[$i]; if (is_numeric($anId)) { $sql = "SELECT count(id) as countid FROM %queue% WHERE paidtime is not null AND id=?"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(array($anId)); - $row =$stmt->fetchObject(); - if ($row != null) { + $row =$stmt->fetchObject(); + if ($row != null) { $aCount = $row->countid; if (($aCount != null) && ($aCount == 1)) { $allNotPaid = false; @@ -1580,8 +1596,8 @@ class QueueContent { } } - // current time - date_default_timezone_set(DbUtils::getTimeZone()); + // current time + date_default_timezone_set(DbUtils::getTimeZone()); $currentTime = date('Y-m-d H:i:s'); $billid = (-1); @@ -1590,14 +1606,14 @@ class QueueContent { // find highest bill id $sql = "SELECT id from %bill% ORDER BY id DESC"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(); $numberOfIds = $stmt->rowCount(); $newprevbrutto = 0; $newprevnetto = 0; if ($numberOfIds > 0) { - $row =$stmt->fetchObject(); + $row =$stmt->fetchObject(); if ($row != null) { $billid = intval($row->id)+1; $sql = "SELECT brutto,netto,prevbrutto,prevnetto FROM %bill% WHERE id=?"; @@ -1637,11 +1653,11 @@ class QueueContent { $stmt->execute(array($billid,$currentTime,$brutto,$netto,$newprevbrutto,$newprevnetto,$tableid,$paymentId,$userid,$host,$signature)); // now declare them all to be paid: - for ($i=0;$iprepare(DbUtils::substTableAlias($updateSql)); $stmt->execute(array($currentTime,$billid,$queueid)); } else { @@ -1651,7 +1667,7 @@ class QueueContent { } $billProdsSql = "INSERT INTO `%billproducts%` (`queueid`,`billid`) VALUES ( ?,?)"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billProdsSql)); + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billProdsSql)); $stmt->execute(array($queueid,$billid)); } } @@ -1664,11 +1680,11 @@ class QueueContent { } - private function getUserId() { - if(session_id() == '') { - session_start(); - } - return $_SESSION['userid']; + private function getUserId() { + if(session_id() == '') { + session_start(); + } + return $_SESSION['userid']; } } diff --git a/webapp/php/utilities/HistFiller.php b/webapp/php/utilities/HistFiller.php index afcfefa..0f14b7c 100644 --- a/webapp/php/utilities/HistFiller.php +++ b/webapp/php/utilities/HistFiller.php @@ -1,197 +1,145 @@ dbutils = new DbUtils(); +class HistFiller { + var $dbutils; + + function __construct() { + $this->dbutils = new DbUtils(); } - - + public function defineHistActions () { $pdo = $this->dbutils->openDbAndReturnPdo(); - $sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - - $stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); - $stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); - $stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); + $sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + + $stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); + $stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); + $stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); $stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten')); $stmt->execute(array('5', 'ProdCreation', 'Neues Produkt')); $stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration')); $stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer')); $stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers')); $stmt->execute(array('9', 'DbSave', 'Komplettsicherung der Datenbank')); - $stmt->execute(array('10', 'DbRestore', 'Wiederherstellung der Datenbank aus einer Sicherungskopie')); + $stmt->execute(array('10','DbRestore', 'Wiederherstellung der Datenbank aus einer Sicherungskopie')); } - public function readUserTableAndSendToHist($pdo) { - $sql = "SELECT * FROM %user%"; - $this->readSqlUserTableAndSendToHist($pdo,$sql,'3'); + private static function getColNamesForHistTable($tableDescr) { + $cols = array(); + foreach($tableDescr as $aCol) { + if ($aCol["hist"] == 1) { + $cols[] = $aCol["col"]; + } + } + return $cols; + } + + private static function getColNamesForUserHistTable() { + return self::getColNamesForHistTable(DbUtils::$userCols); + } + + public static function readUserTableAndSendToHist($pdo) { + $sql = "SELECT * FROM %user%"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array()); + $result = $stmt->fetchAll(); + foreach($result as $aUser) { + self::createUserInHist($pdo, $aUser["id"]); + } + } + public static function createUserInHist($pdo,$userid) { + $pdo->beginTransaction(); + self::updateOrCreateUserInHist($pdo,$userid,'7'); + $pdo->commit(); + } + public static function updateUserInHist($pdo,$userid) { + $pdo->beginTransaction(); + self::updateOrCreateUserInHist($pdo,$userid,'8'); + $pdo->commit(); + } + private static function updateOrCreateUserInHist($pdo,$userid,$histaction) { + self::updateOrCreateEntryInHist($pdo, $userid, $histaction, self::getColNamesForUserHistTable(), 'userid', 'user','histuser',null,null); + } + + public static function readAllProdsAndFillHistByDb($pdo) { + $sql = "SELECT id FROM %products% WHERE removed is null"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array()); + $result = $stmt->fetchAll(); + foreach($result as $anElement) { + self::createProdInHist($pdo, $anElement["id"]); + } + } + private static function getColNamesForProdHistTable() { + return self::getColNamesForHistTable(DbUtils::$prodCols); + } + public static function createProdInHist($pdo,$prodid) { + self::updateOrCreateProdInHist($pdo,$prodid,'5'); + } + public static function updateProdInHist($pdo,$prodid) { + self::updateOrCreateProdInHist($pdo,$prodid,'4'); + } + private static function getExtrasList($pdo,$prodid) { + $sql = "SELECT GROUP_CONCAT(%extras%.name) as extraslist FROM %extras%,%extrasprods% WHERE %extrasprods%.prodid=? AND %extrasprods%.extraid=%extras%.id"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array($prodid)); + $row =$stmt->fetchObject(); + return $row->extraslist; + } + private static function updateOrCreateProdInHist($pdo,$prodid,$histaction) { + $extras = self::getExtrasList($pdo, $prodid); + $extraCol = (is_null($extras) ? null : 'extras'); + self::updateOrCreateEntryInHist($pdo, $prodid, $histaction, self::getColNamesForProdHistTable(), 'prodid', 'products', 'histprod',$extraCol,$extras); + } + + + private static function updateOrCreateEntryInHist($pdo,$id,$histaction,$colsInSourceTable,$idInHist,$sourcetable, $histtable,$extraCol,$extraVal) { + + $sql = "SELECT * from %". $sourcetable . "% WHERE id=?"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array($id)); + $row = $stmt->fetchObject(); + + $cols = $colsInSourceTable; + array_splice($cols, 0, 1, $idInHist); + $valuesStr = implode(",", $cols); + $quests = array(); + $vals = array(); + + foreach($colsInSourceTable as $aHistCol) { + $vals[] = $row->$aHistCol; + $quests[] = "?"; + } + + $sql_insert_hist = "INSERT INTO %". $histtable . "% (id," . $valuesStr . ") VALUES(NULL," . implode(",",$quests) . ")"; + $stmt_insert_hist = $pdo->prepare(DbUtils::substTableAlias($sql_insert_hist)); + $stmt_insert_hist->execute($vals); + $newRefIdForHist = $pdo->lastInsertId(); + + if (!is_null($extraCol)) { + $sql = "UPDATE %". $histtable . "% SET " . $extraCol . "=? WHERE id=?"; + $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); + $stmt->execute(array($extraVal,$newRefIdForHist)); + } + + self::insertIntoHist($pdo, $histaction, $newRefIdForHist); + } + + public static function insertSaveHistEntry($pdo) { + self::insertIntoHist($pdo, 9, null); } - public function updateOneUser($pdo,$userid) { - $sql = "SELECT * FROM %user% WHERE id='$userid'"; - $this->readSqlUserTableAndSendToHist($pdo,$sql,'8'); - } - - /* - * Read the complete user table and fill in these values to the histtable - */ - private function readSqlUserTableAndSendToHist($pdo,$sql_query, $histaction) { - $sql_insert_histuser = "INSERT INTO %histuser% (id,userid,username, - is_admin,right_waiter,right_kitchen,right_bar,right_supply,right_paydesk,right_statistics, - right_bill,right_products,right_reservation,right_rating,right_changeprice,right_manager,active) VALUES ( - NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - $pdo->beginTransaction(); - - $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query)); - $stmt_insert_histuser = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histuser)); - - $stmt_query->execute(); - $result = $stmt_query->fetchAll(); - foreach($result as $row){ - $stmt_insert_histuser->execute(array($row['id'], $row['username'], - $row['is_admin'],$row['right_waiter'],$row['right_kitchen'],$row['right_bar'], - $row['right_supply'],$row['right_paydesk'],$row['right_statistics'],$row['right_bill'], - $row['right_products'],$row['right_reservation'],$row['right_rating'],$row['right_changeprice'],$row['right_manager'],$row['active'])); - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, $histaction, $newRefIdForHist); - } - $pdo->commit(); - } - - public function updateUserInHist($pdo,$userid,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,$active) - { - $this->updateOrCreateUserInHist($pdo,$userid,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat, - $rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,$active,'8'); - } - - public function createUserInHist($pdo,$lastId,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rRes,$rRat,$rChangeprice,$rManager) - { - $this->updateOrCreateUserInHist($pdo,$lastId,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat, - $rBill,$rProducts,$rRes,$rRat,$rChangeprice,$rManager,'1','7'); - } - - public function updateOrCreateUserInHist($pdo,$id,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rRes,$rRat,$rChangeprice,$rManager, - $active,$histaction) { - - $sql_insert_histuser = "INSERT INTO %histuser% (`id` , `userid`, `username` , - `is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`, - `right_statistics`,`right_bill`,`right_products`,`right_reservation`,`right_rating`,`right_changeprice`,`right_manager`,`active`) VALUES ( - NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - $pdo->beginTransaction(); - $stmt_insert_histuser = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histuser)); - $stmt_insert_histuser->execute(array($id,$username, - $isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rRes,$rRat,$rChangeprice,$rManager, - $active)); - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, $histaction, $newRefIdForHist); - $pdo->commit(); - } - - public function insertSaveHistEntry($pdo) { - $this->insertIntoHist($pdo, 9, null); - } - - public function insertRestoreHistEntry($pdo) { - $this->insertIntoHist($pdo, 10, null); - } - - public function readAllProdsAndFillHistByDb($pdo) { - - $sql = "SELECT id FROM %products% WHERE removed is null"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array()); - $result = $stmt->fetchAll(); - - foreach ($result as $aProd) { - $prodid = $aProd["id"]; - - $sql = "SELECT GROUP_CONCAT(%extras%.name) as extraslist FROM %extras%,%extrasprods% WHERE %extrasprods%.prodid=? AND %extrasprods%.extraid=%extras%.id"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($prodid)); - $row =$stmt->fetchObject(); - $extrasList = $row->extraslist; - - $sql = "INSERT INTO %histprod% (id,prodid,shortname,longname,priceA,priceB,priceC,tax,sorting,available,extras) "; - $sql .= "SELECT null,id as prodid,shortname,longname,priceA,priceB,priceC,tax,sorting,available,'$extrasList' as extras FROM %products% "; - $sql .= "WHERE %products%.id=?"; - $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($prodid)); - - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, '1', $newRefIdForHist); - } - } - - /* - * Read the complete products table and fill in these values to the histtable - */ - public function readProdTableAndSendToHist($pdo) { - $sql_query = "SELECT * FROM %products% WHERE removed is null"; - - $sql_insert_histprod = "INSERT INTO %histprod% (id,prodid,shortname,longname, - priceA,priceB,priceC,tax,sorting,available,favorite) VALUES ( - NULL,?,?,?,?,?,?,?,?,?,?)"; - - $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query)); - $stmt_insert_histprod = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histprod)); - - $stmt_query->execute(); - $result = $stmt_query->fetchAll(); - foreach($result as $row){ - $stmt_insert_histprod->execute(array($row['id'], $row['shortname'], - $row['longname'],$row['priceA'],$row['priceB'],$row['priceC'], - $row['tax'],$row['sorting'],$row['available'],'0')); - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, '1', $newRefIdForHist); - } - } - - public function updateProdInHist($pdo,$prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available,$audioFile,$favorite,$histextra) { - $this->updateOrCreateProdInHist($pdo,$prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available, '4',$audioFile,$favorite,$histextra); - } - - public function createProdInHist($pdo,$prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available,$audioFile,$favorite) { - $this->updateOrCreateProdInHist($pdo,$prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available, '5',$audioFile,$favorite,null); - } - - public function updateOrCreateProdInHist($pdo,$prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available, $histaction,$audioFile,$favorite,$histextra) { - - $sql_insert_histprod = "INSERT INTO %histprod% (id,prodid,shortname,longname, - priceA,priceB,priceC,tax,sorting,available,audio,favorite,extras) VALUES ( - NULL,?,?,?,?,?,?,?,?,?,?,?,?)"; - - if (is_null($pdo)) { - $pdo = $this->dbutils->openDbAndReturnPdo(); - } - $stmt_insert_histprod = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histprod)); - $stmt_insert_histprod->execute(array($prodid,$shortname,$longname, - $priceA,$priceB,$priceC,$tax,$sorting,$available,$audioFile,$favorite,$histextra)); - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, $histaction, $newRefIdForHist); + public static function insertRestoreHistEntry($pdo) { + self::insertIntoHist($pdo, 10, null); } public function updateConfigInHist($pdo,$theItem, $theValue) { $sql_find_id = "SELECT id FROM %config% WHERE name='$theItem'"; $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)"; - + $pdo->beginTransaction(); $stmt_query = $pdo->query(DbUtils::substTableAlias($sql_find_id)); @@ -201,40 +149,40 @@ class HistFiller { $stmt_insert_histconfig = $pdo->prepare(DbUtils::substTableAlias($sql_insert_histconfig)); $stmt_insert_histconfig->execute(array($theConfigId,"$theValue")); $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, '6', $newRefIdForHist); + self::insertIntoHist($pdo, '6', $newRefIdForHist); $pdo->commit(); } - /* - * Read the complete config table and fill in these values to the histtable - */ - public function readConfigTableAndSendToHist() { - $sql_query = "SELECT * FROM %config%"; - - $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES ( - NULL,?,?)"; - - $pdo = $this->dbutils->openDbAndReturnPdo(); - $pdo->beginTransaction(); - - $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query)); - $stmt_insert_histconfig = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histconfig)); - - $stmt_query->execute(); - $result = $stmt_query->fetchAll(); - foreach($result as $row){ - $stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); - $newRefIdForHist = $pdo->lastInsertId(); - $this->insertIntoHist($pdo, '2', $newRefIdForHist); - } - $pdo->commit(); + /* + * Read the complete config table and fill in these values to the histtable + */ + public function readConfigTableAndSendToHist() { + $sql_query = "SELECT * FROM %config%"; + + $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES ( + NULL,?,?)"; + + $pdo = $this->dbutils->openDbAndReturnPdo(); + $pdo->beginTransaction(); + + $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query)); + $stmt_insert_histconfig = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histconfig)); + + $stmt_query->execute(); + $result = $stmt_query->fetchAll(); + foreach($result as $row){ + $stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); + $newRefIdForHist = $pdo->lastInsertId(); + $this->insertIntoHist($pdo, '2', $newRefIdForHist); + } + $pdo->commit(); } - private function insertIntoHist($pdo,$action,$refIdForHist) { - date_default_timezone_set(DbUtils::getTimeZone()); - $currentTime = date('Y-m-d H:i:s'); - $sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; - $stmt_insert_hist = $pdo->prepare(DbUtils::substTableAlias($sql_insert_hist)); - $stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); + private static function insertIntoHist($pdo,$action,$refIdForHist) { + date_default_timezone_set(DbUtils::getTimeZone()); + $currentTime = date('Y-m-d H:i:s'); + $sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; + $stmt_insert_hist = $pdo->prepare(DbUtils::substTableAlias($sql_insert_hist)); + $stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); } } diff --git a/webapp/php/utilities/TypeAndProducts/ProductEntry.php b/webapp/php/utilities/TypeAndProducts/ProductEntry.php index 5585ba3..549dec4 100644 --- a/webapp/php/utilities/TypeAndProducts/ProductEntry.php +++ b/webapp/php/utilities/TypeAndProducts/ProductEntry.php @@ -1,110 +1,158 @@ probably two prices - $otherPrices = $priceparts[1]; - // are there level 2&3 or only 2? - $otherPriceParts = explode(';', $otherPrices, 3); - $price_level_B = floatval(str_replace(",",".",(string) $otherPriceParts[0])); - if (count($otherPriceParts) == 1) { - $numberOfPrices = 2; - } else if (count($otherPriceParts) == 2) { - $price_level_C = floatval(str_replace(",",".",(string) $otherPriceParts[1])); - $numberOfPrices = 3; - } else if (count($otherPriceParts) == 3) { - $price_level_C = floatval(str_replace(",",".",(string) $otherPriceParts[1])); - $price_tax = floatval(str_replace(",",".",(string) $otherPriceParts[2])); - $numberOfPrices = 4; - } else { - // undefined - $numberOfPrices = 1; // fall back to default - } - } - $parts = explode(';', $priceparts[0], 4); - $this->shortName = trim($parts[0]); - - $matches = array(); - preg_match('/\(ID:([0-9]+)\)$/', $this->shortName,$matches,PREG_OFFSET_CAPTURE); - if (count($matches) > 0) { - $theMatch = $matches[0]; - $this->prodid = intval(substr($theMatch[0],4,strlen($theMatch[0])-5)); - $theMatchPos = $theMatch[1]; - $this->shortName = trim(substr($this->shortName,0,$theMatchPos-1)); - } - - $this->longName = $this->shortName; - $this->priceA = floatval(str_replace(",",".",(string) $parts[1])); - // default: all the same price - $this->priceB = $this->priceA; - $this->priceC = $this->priceA; - $this->tax = null; - if ($numberOfPrices == 2) { - $this->priceB = $price_level_B; // A = C, only B is different - } else if ($numberOfPrices == 3) { - $this->priceB = $price_level_B; - $this->priceC = $price_level_C; - } else if ($numberOfPrices == 4) { - $this->priceB = $price_level_B; - $this->priceC = $price_level_C; - $this->tax = $price_tax; - } - - if (count($parts) > 2) { - $thirdpart = trim($parts[2]); - if ($thirdpart != "") { - // in this case the button name is the not same as the name on the bill - $this->longName = trim($parts[2]); - } - } - return array("status" => "OK"); - } catch (Exception $e) { - return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $aTextLine); +class ProductEntry { + + private $shortName; // the name that shall appear on the button of the waiter + private $priceA; // the price of the product (default) + private $priceB; // price level B + private $priceC; // price level C + private $tax; + private $longName; // the name that shall appear on the receipt + private $prodid = null; + private $available = 1; + + private static $PRICE_B = "PreisB"; + private static $PRICE_C = "PreisC"; + private static $TAX = "Fixsteuersatz"; + private static $SHORTNAME = "Kurzname"; + private static $AVAILABLE = "vorhanden"; + private static $ID = "ID"; + + // + public static function createProductStr($aProd, $decpoint) { + + $shortname = $aProd['shortname']; + $longname = $aProd['longname']; + $prodId = $aProd['id']; + + $available = $aProd['available']; + $priceA = str_replace('.', $decpoint, $aProd['priceA']); + $priceB = str_replace('.', $decpoint, $aProd['priceB']); + $priceC = str_replace('.', $decpoint, $aProd['priceC']); + $tax = str_replace('.', $decpoint, $aProd['tax']); + + $prodText = "$longname; $priceA"; + $extArr = array(); + + if ($shortname != $longname) { + $extArr[] = self::$SHORTNAME . ":" . $shortname; + } + + if (!is_null($tax) && ($tax != "null")) { + $extArr[] = self::$TAX . ":" . $tax; + } + + if (($priceB != $priceA) || ($priceC != $priceA)) { + $extArr[] = self::$PRICE_B . ":$priceB"; + $extArr[] = self::$PRICE_C . ":$priceC"; + } + + if ($available == 0) { + $extArr[] = self::$AVAILABLE . ":nein"; + } + if (!is_null($prodId)) { + $extArr[] = self::$ID . ":" . $prodId; + } + + if (count($extArr) > 0) { + $prodText .= " # " . join("; ", $extArr); + } + + return $prodText; + } + + function parse($aTextLine) { + try { + $aTextLine = trim($aTextLine); + $propertyparts = explode('#', $aTextLine, 2); + + $shortAndPriceA = $propertyparts[0]; + $basic = explode(';',$shortAndPriceA); + $this->longName = $basic[0]; + $this->priceA = floatval(str_replace(",",".",(string) $basic[1])); + + $this->priceB = null; + $this->priceC = null; + $this->shortName = null; + + if (count($propertyparts) > 1) { + if (trim($propertyparts[1]) == "") { + return; } + $exts = explode(";",$propertyparts[1]); + foreach($exts as $anExtProp) { + $parts = explode(":",$anExtProp); + $identifier = trim($parts[0]); + $value = trim($parts[1]); + if ($identifier == self::$PRICE_B) { + $this->priceB = floatval(str_replace(",",".",(string) $value)); + } else if ($identifier == self::$PRICE_C) { + $this->priceC = floatval(str_replace(",",".",(string) $value)); + } else if ($identifier == self::$AVAILABLE) { + if (($value == "ja") || ($value == "yes") || ($value == "si") || ($value == "1")) { + $this->available = 1; + } else { + $this->available = 0; + } + } else if ($identifier == self::$TAX) { + $this->tax = floatval(str_replace(",",".",(string) $value)); + } else if ($identifier == self::$SHORTNAME) { + $this->shortName = $value; + } else if ($identifier == self::$ID) { + $this->prodid = $value; + } + } + } + + if (is_null($this->priceB)) { + $this->priceB = $this->priceA; + } + if (is_null($this->priceC)) { + $this->priceC = $this->priceA; + } + if (is_null($this->shortName)) { + $this->shortName = $this->longName; + } + return array("status" => "OK"); + } catch (Exception $e) { + return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $aTextLine); } + } - function getShortName() { - return $this->shortName; - } - function getPriceA() { - return $this->priceA; - } - function getPriceB() { - return $this->priceB; - } - function getPriceC() { - return $this->priceC; - } - function getTax() { - return $this->tax; - } - function getLongName() { - return $this->longName; - } - function getProdId() { - return $this->prodid; - } - function toString() { - return "S:" . $this->shortName . " PA:" . $this->priceA . " PB:" . $this->priceB . " PC:" . $this->priceC . " Tax:" . $this->tax . " R:" . $this->longName; - } + function getShortName() { + return $this->shortName; + } + + function getPriceA() { + return $this->priceA; + } + + function getPriceB() { + return $this->priceB; + } + + function getPriceC() { + return $this->priceC; + } + + function getTax() { + return $this->tax; + } + + function getLongName() { + return $this->longName; + } + + function getProdId() { + return $this->prodid; + } + + function getAvailable() { + return $this->available; + } + + function toString() { + return "S:" . $this->shortName . " PA:" . $this->priceA . " PB:" . $this->priceB . " PC:" . $this->priceC . " Tax:" . $this->tax . " R:" . $this->longName; + } } ?> \ No newline at end of file diff --git a/webapp/php/utilities/TypeAndProducts/TypeAndProductFileManager.php b/webapp/php/utilities/TypeAndProducts/TypeAndProductFileManager.php index f14dc37..f6e7deb 100644 --- a/webapp/php/utilities/TypeAndProducts/TypeAndProductFileManager.php +++ b/webapp/php/utilities/TypeAndProducts/TypeAndProductFileManager.php @@ -47,26 +47,26 @@ class TypeAndProductFileManager { private $nextIdOfProdType = 1; - var $dbutils; - - function __construct() { - $this->dbutils = new DbUtils(); + var $dbutils; + + function __construct() { + $this->dbutils = new DbUtils(); } /* * Look at the beginning of a line and count the number of spaces or tabs */ - private function intendingOfText($text) { - $charCounter = 0; - while (($text[$charCounter] == ' ') || ($text[$charCounter] == "\t")) { - $charCounter++; - } - return $charCounter; + private function intendingOfText($text) { + $charCounter = 0; + while (($text[$charCounter] == ' ') || ($text[$charCounter] == "\t")) { + $charCounter++; + } + return $charCounter; } - private function startsWith($aText, $needle) - { - return $needle === "" || strpos($aText, $needle) === 0; + private function startsWith($aText, $needle) + { + return $needle === "" || strpos($aText, $needle) === 0; } /* @@ -84,27 +84,27 @@ class TypeAndProductFileManager { // now really read the file so that content starts at index 1 $index = 1; - $handle = fopen ($fileName, "r"); - while (!feof($handle)) { + $handle = fopen ($fileName, "r"); + while (!feof($handle)) { $textline = fgets($handle); if(!($this->startsWith($textline,'#'))) { $depth = $this->intendingOfText($textline); - $this->entries->add(new LineItem($depth,$index,$textline)); + $this->entries->add(new LineItem($depth,$index,$textline)); $index++; - } - } + } + } fclose ($handle); } private function findNextIdOfProdType($pdo) { - $index = 1; - - $sql = "SELECT id FROM %prodtype% ORDER BY id DESC LIMIT 1"; - $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(); - $row =$stmt->fetchObject(); - if ($row != null) { - $index = intval($row->id) +1; + $index = 1; + + $sql = "SELECT id FROM %prodtype% ORDER BY id DESC LIMIT 1"; + $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); + $stmt->execute(); + $row =$stmt->fetchObject(); + if ($row != null) { + $index = intval($row->id) +1; } $this->nextIdOfProdType = $index; } @@ -119,30 +119,30 @@ class TypeAndProductFileManager { $stmt->execute(array('1')); } - /* - * read in the "Speisekarte.txt" - * put the content in the array list "EntryList" as it is - * without any modifications - */ - private function parseContent($pdo,$speisekarte) { - // remove old content if any + /* + * read in the "Speisekarte.txt" + * put the content in the array list "EntryList" as it is + * without any modifications + */ + private function parseContent($pdo,$speisekarte) { + // remove old content if any $this->entries = new EntryList(); - $this->extras = array(); + $this->extras = array(); self::removeExtras($pdo); - // get max number of prodtype id -> the old ones will be kept! - $index = $this->nextIdOfProdType; + // get max number of prodtype id -> the old ones will be kept! + $index = $this->nextIdOfProdType; $lines = explode("\n", $speisekarte); - $previousDepth = 0; + $previousDepth = 0; for ($i=0;$istartsWith($textline,'!')) && (strlen($cleanLine) > 0)) { $this->extras[] = $textline; - } else if(!($this->startsWith($textline,'#')) && (strlen($cleanLine) > 0)) { + } else if(!($this->startsWith($textline,'#')) && (strlen($cleanLine) > 0)) { $depth = $this->intendingOfText($textline); if ($depth > ($previousDepth+1)) { return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline); @@ -153,12 +153,12 @@ class TypeAndProductFileManager { if (is_null($newLineItem)) { return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline); } else { - $this->entries->add($newLineItem); + $this->entries->add($newLineItem); $index++; - } - } + } + } } - return array("status" => "OK"); + return array("status" => "OK"); } /* @@ -207,8 +207,8 @@ class TypeAndProductFileManager { $ref = intval($entry->getReference()); $entry->setId($theId-1); $theName = $entry->getName(); - if ($ref >= $idOfEntryToRemove) { - $entry->setReference($ref-1); + if ($ref >= $idOfEntryToRemove) { + $entry->setReference($ref-1); } } } @@ -308,7 +308,7 @@ class TypeAndProductFileManager { for ($i = 0;$i < $this->entries->size(); $i++) { $usekitchen = 1; // default $usesupplydesk = 1; // default - $printer = 1; // default + $printer = 1; // default $theEntry = $this->entries->get($i); $parts = explode(';', $theEntry->getName(), 2); @@ -323,23 +323,22 @@ class TypeAndProductFileManager { $theRefId = $theEntry->getReference(); $id = $theEntry->getId(); - $insertSql = "INSERT INTO `%prodtype%` (`id`, `name`, `reference`, `usekitchen`, `usesupplydesk`, `kind`,`printer`) VALUES (?,?,?,?,?,?,?)"; + $insertSql = "INSERT INTO `%prodtype%` (`id`, `name`, `reference`, `usekitchen`, `usesupplydesk`, `kind`,`printer`) VALUES (?,?,?,?,?,?,?)"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql)); try { if ($theEntry->getDepth() > 0) { $stmt->execute(array($id,$theProdTypeName,$theRefId,$usekitchen,$usesupplydesk,$kind,$printer)); } else { - $stmt->execute(array($id,$theProdTypeName,null,$usekitchen,$usesupplydesk,$kind,$printer)); + $stmt->execute(array($id,$theProdTypeName,null,$usekitchen,$usesupplydesk,$kind,$printer)); } } catch (Exception $e) { return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $theProdTypeName); - } + } } return array("status" => "OK"); } private function fillProductDbTable($pdo,$leafArray) { - $histFiller = new HistFiller(); for ($i=0;$i < $leafArray->size(); $i++) { $theLeafEntry = $leafArray->get($i); $product = new ProductEntry(); @@ -354,7 +353,7 @@ class TypeAndProductFileManager { $shortName = $product->getShortName(); $longName = $product->getLongName(); $prodid = $product->getProdId(); - $available = 1; // default: product is available + $available = $product->getAvailable(); $favorite = 0; $category = $theLeafEntry->getReference(); @@ -375,10 +374,10 @@ class TypeAndProductFileManager { $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($shortName,$longName,$priceA,$priceB,$priceC,$tax, $category,$available,$favorite)); $prodid = $pdo->lastInsertId(); - $histFiller->createProdInHist($pdo, $prodid, $shortName, $longName, $priceA, $priceB, $priceC, $tax, 0, $available, null, $favorite); + HistFiller::createProdInHist($pdo, $prodid); } else { - $sql = "SELECT shortname,longname,priceA,priceB,priceC,tax,category FROM %products% WHERE id=?"; + $sql = "SELECT shortname,longname,priceA,priceB,priceC,tax,available,category FROM %products% WHERE id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($prodid)); $row = $stmt->fetchObject(); @@ -388,19 +387,20 @@ class TypeAndProductFileManager { || ($row->priceA != $priceA) || ($row->priceB != $priceB) || ($row->priceC != $priceC) + || ($row->available != $available) || ($row->tax != $tax)); if ($changed) { - $sql = "UPDATE %products% SET shortname=?,longname=?,priceA=?,priceB=?,priceC=?,tax=? WHERE id=?"; + $sql = "UPDATE %products% SET shortname=?,longname=?,priceA=?,priceB=?,priceC=?,tax=?,available=? WHERE id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); - $stmt->execute(array($shortName,$longName,$priceA,$priceB,$priceC,$tax,$prodid)); + $stmt->execute(array($shortName,$longName,$priceA,$priceB,$priceC,$tax,$available,$prodid)); $sql = "SELECT sorting,available,favorite,audio FROM %products% WHERE id=?"; $stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt->execute(array($prodid)); $row = $stmt->fetchObject(); - $histFiller->updateOrCreateProdInHist($pdo, $prodid, $shortName, $longName, $priceA, $priceB, $priceC, $tax, $row->sorting, $row->available, '4', $row->audio, $row->favorite, null); + HistFiller::updateProdInHist($pdo, $prodid); } $sql = "UPDATE %products% SET category=?,removed=? WHERE id=?"; @@ -437,7 +437,7 @@ class TypeAndProductFileManager { if ($theEntry->getReference() > 0) { $theRefEntry = $this->entries->get($theEntry->getReference()); $product = new ProductEntry($theEntry->getName()); - // echo $theEntry->getName() . " -> " . $theRefEntry->getName() . " ---- "; + // echo $theEntry->getName() . " -> " . $theRefEntry->getName() . " ---- "; echo $product->toString() . " -> " . $theRefEntry->getName() . "
    "; } else { echo $theEntry->getName() . " -> null
    "; @@ -447,51 +447,51 @@ class TypeAndProductFileManager { function manageSpeisekarte($pdo,$content) { - $this->findNextIdOfProdType($pdo); - // first remove previous content + $this->findNextIdOfProdType($pdo); + // first remove previous content $sql = "UPDATE %products% SET removed='1'"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt->execute(); - - $sql = "UPDATE `%prodtype%` SET removed='1'"; + + $sql = "UPDATE `%prodtype%` SET removed='1'"; $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); - $stmt->execute(); + $stmt->execute(); // now fill in the new content - + $ret = $this->parseContent($pdo,$content); if ($ret["status"] != "OK") { return $ret; } - - // now look on the first depth level (0). This level has - // to be treated individually as staring point because later - // on it will be iterated recursively - + + // now look on the first depth level (0). This level has + // to be treated individually as staring point because later + // on it will be iterated recursively + // look at all elements at depth level 0 - - for ($i=0;$i<$this->entries->size();$i++) { + + for ($i=0;$i<$this->entries->size();$i++) { $anEntry = $this->entries->get($i); - if ($anEntry->getDepth() == 0) { - // highest level - $this->findAllSubItemsOfIndex($i,1,1,FOOD,null); - } + if ($anEntry->getDepth() == 0) { + // highest level + $this->findAllSubItemsOfIndex($i,1,1,FOOD,null); + } } - //Debug ausgabe - for ($i=0;$i<$this->entries->size();$i++) { - $anEntry = $this->entries->get($i); - $theId = $anEntry->getId(); - $theName = $anEntry->getName(); - $theRef = $anEntry->getReference(); + //Debug ausgabe + for ($i=0;$i<$this->entries->size();$i++) { + $anEntry = $this->entries->get($i); + $theId = $anEntry->getId(); + $theName = $anEntry->getName(); + $theRef = $anEntry->getReference(); } - + $this->sortOutLeafs(); - + $ret = $this->fillProdTypeDbTable($pdo); if ($ret["status"] != "OK") { return $ret; - } + } $ret = $this->fillProductDbTable($pdo,$this->leafArray); // now add the extras @@ -501,7 +501,7 @@ class TypeAndProductFileManager { $anExtra = new ExtraItem($pdo,$anExtraLine); $prodInstance->createExtraCore($pdo, $anExtra->getName(), $anExtra->getPrice(), $anExtra->getAssignedProdIds()); } - return $ret; + return $ret; } } ?> \ No newline at end of file diff --git a/webapp/php/utilities/basedb.php b/webapp/php/utilities/basedb.php index 9b0c3f3..1731f62 100644 --- a/webapp/php/utilities/basedb.php +++ b/webapp/php/utilities/basedb.php @@ -218,6 +218,7 @@ class Basedb { `right_bill` INT (1) NOT NULL, `right_products` INT (1) NOT NULL, `right_manager` INT (1) NOT NULL, + `right_closing` INT (1) NOT NULL, `right_reservation` INT (1) NOT NULL, `right_rating` INT (1) NOT NULL, `right_changeprice` INT (1) NOT NULL, @@ -469,10 +470,10 @@ class Basedb { `host` INT(2) NULL, `reason` VARCHAR ( 150 ) NULL, `signature`blob NULL, - FOREIGN KEY (closingid) REFERENCES %closing%(id), + FOREIGN KEY billclosingref (closingid) REFERENCES %closing%(id), FOREIGN KEY (paymentid) REFERENCES %payment%(id), FOREIGN KEY (userid) REFERENCES %user%(id), - FOREIGN KEY (ref) REFERENCES %bill%(id) + FOREIGN KEY billbillref (ref) REFERENCES %bill%(id) ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ; "; $stmt = $pdo->prepare($this->resolveTablenamesInSqlString($sql)); @@ -510,7 +511,7 @@ class Basedb { FOREIGN KEY (tablenr) REFERENCES %resttables%(id), FOREIGN KEY (pricelevel) REFERENCES %pricelevel%(id), FOREIGN KEY (productid) REFERENCES %products%(id), - FOREIGN KEY (billid) REFERENCES %bill%(id), + FOREIGN KEY queuebillref (billid) REFERENCES %bill%(id), FOREIGN KEY (cooking) REFERENCES %user%(id), FOREIGN KEY (orderuser) REFERENCES %user%(id) ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ; @@ -524,7 +525,7 @@ class Basedb { `queueid` INT( 10 ) NOT NULL, `billid` INT(10) NOT NULL, FOREIGN KEY (queueid) REFERENCES %queue%(id), - FOREIGN KEY (billid) REFERENCES %bill%(id) + FOREIGN KEY billprodref (billid) REFERENCES %bill%(id) ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ; "; $this->doSQL($pdo,$sql); @@ -586,6 +587,7 @@ class Basedb { `right_bill` INT (1) NOT NULL, `right_products` INT (1) NOT NULL, `right_manager` INT (1) NOT NULL, + `right_closing` INT (1) NOT NULL, `right_reservation` INT (1) NOT NULL, `right_rating` INT (1) NOT NULL, `right_changeprice` INT (1) NOT NULL, diff --git a/webapp/php/utilities/userrights.php b/webapp/php/utilities/userrights.php index f369277..7bfe217 100644 --- a/webapp/php/utilities/userrights.php +++ b/webapp/php/utilities/userrights.php @@ -16,13 +16,15 @@ define ( 'R_RES', 512); define ( 'R_RAT', 1024); define ( 'R_MAN', 2048); define ( 'R_CP', 4096); +define ( 'R_CL', 8192); class Userrights { - function setSession($isAdm,$rWait,$rKit,$rBar,$rSupply,$rPay,$rStat,$rBill,$rProd,$rRes,$rRat,$rChangePrice,$rMan) { + function setSession($isAdm,$rWait,$rKit,$rBar,$rSupply,$rPay,$rStat,$rBill,$rProd,$rRes,$rRat,$rChangePrice,$rMan,$rClos) { $ret = R_ADM * ($isAdm ? 1:0) | R_WAI * ($rWait ? 1:0) | R_KIT * ($rKit ? 1:0) | R_BAR * ($rBar ? 1:0) | R_SUP * ($rSupply ? 1:0) | R_PAY * ($rPay ? 1:0); - $ret |= R_STA * ($rStat ? 1:0) | R_BIL * ($rBill ? 1:0) | R_PRO * ($rProd ? 1:0) | R_RES * ($rRes ? 1:0) | R_RAT * ($rRat ? 1:0) | R_CP * ($rChangePrice ? 1:0) | R_MAN * (($rMan ? 1:0) ? 1:0); + $ret |= R_STA * ($rStat ? 1:0) | R_BIL * ($rBill ? 1:0) | R_PRO * ($rProd ? 1:0) | R_RES * ($rRes ? 1:0) | R_RAT * ($rRat ? 1:0) | + R_CP * ($rChangePrice ? 1:0) | R_MAN * (($rMan ? 1:0) | R_CL * (($rClos ? 1:0))); $_SESSION['allrights'] = $ret; } @@ -49,33 +51,33 @@ class Userrights { * can the current call the currentCmd */ function canUserCallCommands($currentCmd, $cmdArray,$right) { - session_start(); - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { - // no user logged in - return false; + session_start(); + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + // no user logged in + return false; } else { // user is logged in if (in_array($currentCmd, $cmdArray)) { - // yes, the current command is in the set of commands to test! + // yes, the current command is in the set of commands to test! if ($_SESSION[$right]) { return true; - } + } } return false; } } - function isCurrentUserAdmin() { + function isCurrentUserAdmin() { if(session_id() == '') { session_start(); - } - if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { - // no user logged in - return false; - } else { - return ($_SESSION['is_admin']); - } + } + if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { + // no user logged in + return false; + } else { + return ($_SESSION['is_admin']); + } } diff --git a/webapp/preferences.html b/webapp/preferences.html index 7b97b35..e982f59 100644 --- a/webapp/preferences.html +++ b/webapp/preferences.html @@ -5,7 +5,7 @@ - + diff --git a/webapp/products.html b/webapp/products.html index fb5cec7..1bb6691 100644 --- a/webapp/products.html +++ b/webapp/products.html @@ -7,7 +7,7 @@ - + diff --git a/webapp/rating.html b/webapp/rating.html index 40c2556..37c02e4 100644 --- a/webapp/rating.html +++ b/webapp/rating.html @@ -7,7 +7,7 @@ - + diff --git a/webapp/reports.html b/webapp/reports.html index 5380278..673198c 100644 --- a/webapp/reports.html +++ b/webapp/reports.html @@ -7,7 +7,7 @@ - + diff --git a/webapp/reservation.html b/webapp/reservation.html index 3fd3eaf..ff6ddae 100644 --- a/webapp/reservation.html +++ b/webapp/reservation.html @@ -5,7 +5,7 @@ - + diff --git a/webapp/supplydesk.html b/webapp/supplydesk.html index 11875ac..c60d199 100644 --- a/webapp/supplydesk.html +++ b/webapp/supplydesk.html @@ -5,7 +5,7 @@ - + diff --git a/webapp/utilities.js b/webapp/utilities.js index 0d8d1eb..0ac6ca8 100644 --- a/webapp/utilities.js +++ b/webapp/utilities.js @@ -173,4 +173,11 @@ function handleTestForLoggedIn(answer) { if (answer != "YES") { setTimeout(function(){document.location.href = "index.html"},250); } +} +function isInt(value) { + if(Math.floor(value) == value && $.isNumeric(value)) { + return true; + } else { + return false; + } } \ No newline at end of file diff --git a/webapp/waiter.html b/webapp/waiter.html index e6f06e9..b331b45 100644 --- a/webapp/waiter.html +++ b/webapp/waiter.html @@ -4,7 +4,7 @@ - + @@ -30,7 +30,7 @@ +var W_TABLES=["Tische","Tables","Mesas"];var W_ROOMS=["Räume","Rooms","Espacios"];var W_SELECTION=["Auswahl","Selection","Selección"];var W_LAST_SELECTED=["zuletzt","last","seleccionado"];var W_FAVS=["Favoriten","Favorites","Favoritos"];var W_NEW_ORDER=["Neue Order","New Orders","Ordenes nuevas"];var W_KIT_BAR=["nicht serviert/unbezahlt","unserved/unpaid","no servido/impagado"];var W_OTHER_PROD=["Auswahl Produktkategorie","Select product categroy","Categoría diferente"];var W_WORK_TICKET=["Arbeitsbon","Work ticket","Tique de trabajar"];var W_NOTE=["Bemerkung","Comment","Comentario"];var W_SEND_ORDERS=["Bestellung senden","Send orders","Enviar Ordenes"];var W_TO_PAYDESK=["-> Kasse","-> Paydesk","-> Caja"];var W_TABLECHANGE=["Tischwechsel","Change table","Cambiar mesa"];var W_ROOMTABLE=["Raum-Tisch","Room-Table","Espacio-Mesa"];var W_TABLE_SEL=["Tischauswahl","Select table","Qué mesa?"];var W_UNDELIV_INFO=["Liste enthält die Produkte die noch in der Küchen-/Baransicht sind, sowie unbezahlte Produkte, die die Bereitstellungsansicht nicht durchlaufen.","List contains the products which are still in kitchen or bar view, as well as unpaid products that do not pass the supplydesk view.","La lista contiene los productos que estan todavía en modulo de cocina/bar, también productos impagados que no pasan vista de productos preparados."];var W_REMOVE_ERROR=["Ansicht nicht mehr aktuell - Liste wird neu geladen.","View is obsolete - List will be reloaded.","Vista no esta actual - vamos a actualisar la lista."];var W_FOOD_FOR=["Speisen für","Food for","Comidas para"];var W_DRINKS_FOR=["Getränke für","Beverage for","Bebidas para"];var W_ACT_NEW_ORD_EL=["Aktion auswählen","Select action","Que acción?"];var W_ACT_CHANGE=["Ändern","Modify","Modificar"];var W_ACT_CHANGE_ALL=["Alle Ändern","Modify all","Modificar todo"];var W_ACT_CHANGE_ONE=["Einen Artikel ändern","Modify one item","Modificar un artículo"];var W_APPLY=["Anwenden","Apply","Aplicar"];var W_CANCEL=["Abbrechen","Cancel","Cancelar"];var W_STILL_UNSENT_ORDERS=["Es sind noch ungesendete Orders vorhanden!","There are unsent orders in the list","Hay elementos in la liste que no han enviados"];var W_EXTRAS=["Extras/Optionen","Add-ons/Options","Opciones"];var W_OPEN_PANEL=["Extras-Auswahl noch offen","Add-ons selection still open","Selección de opciones todavía abierta"];var W_DEL=["Löschen","Delete","Removar"];var W_MSG=["Nachricht","Message","Mensaje"];var W_CHANGE_PRICE=["Neuer Preis: ","New price: ","Cambiar precio: "];var W_PRICE=["Preis","Price","Precio"];var W_WRONG_FORMAT=["Falsches Zahlenformat","Wrong number format","Formato de precio incorecto"];var W_TOGO=["Außer-Haus-Verkauf","Sale with Tax No 2","Venta IVA 2"];var W_YES=["Ja","Yes","Si"];var W_NO=["Nein","No","No"];var W_DISCARD_NO_ASK=["Es sind noch ungesendete Orders vorhanden! Sollen diese verworfen werden?","There are still unsent orders. Do you want to discard them?","Hay todavía ordenes non-enviados. Removarlos?"];var W_DISCARD_HEADER=["Neue Orders verwerfen?","Discard new orders?","Removar ordenes nuevos?"];var W_SEARCH=["Produktsuche","Product search","Buscar producto"];var W_SEARCHRESULTS=["Suchergebnis","Search Result","Encontrado"];var W_WRONG_PIN=["Falscher Stornocode","Wrong cancel code","Codigo falso"];var W_NO_ORDERS=["Keine gebuchten Orders vorhanden!","No orders available!","No hay ningún orden!"];var W_TO_PAY=["offen","to pay","a pagar"];var W_MOVE_PRODS=["Produkte verschieben","Move products","Productos a otra mesa"];var W_NO_PRODS_SELECTED=["Es wurden keine Produkte ausgewählt!","You have not chosen any products!","No ha seleccionado ningún producto!"];var W_MAX_PRICE_EXCEEDED=["Der Maximalwert für den Preis wurde überschritten!","The max. value for the price is exceeded!","El valor del precio es más que el maximum!"];var W_REORDER=["Nachbestellen","Reorder","Order una vez mas"];var W_REMOVE=["Entfernen","Remove","Removar"];var W_SELALL=["Alles auswählen","Select all","Elegir todo"];var W_UNSELALL=["Alles abwählen","Unselect all","No elegir nada"];var CHANGE_ALL=0;var CHANGE_ONE=1;var WORKFLOW_DIGI_WORK=0;var WORKFLOW_DIGI=1;var WORKFLOW_WORK=2;var WORKFLOW_WORK_SEND=3;function Grouping(b,a){this.set=b;this.sortedset=[];this.group=function(){this.sortedset=[];for(var g=0;g/g,">"))}function setLanguage(h){lang=h;$("#roomtableheader2").html(W_ROOMTABLE[lang]);$("#tableselection").html(W_TABLE_SEL[lang]);$("#actiontxt").html(W_ACT_NEW_ORD_EL[lang]);$("#actdeltxt").html(W_DEL[lang]);$("#discard_new_orders_yes").html(W_YES[lang]);$("#discard_new_orders_no").html(W_NO[lang]);$("#discardnewordersask").html(W_DISCARD_NO_ASK[lang]);$("#discardnoheader").html(W_DISCARD_HEADER[lang]);$("#moveprods").html(W_MOVE_PRODS[lang]);var f="";if(prominentsearch==0){f+='
    '}else{f+='
    '}f+="
    ";var e='
    ';if(prominentsearch==0){$("#searchposition-normal").html(f)}else{$("#searchposition-prominent").html(f)}var b=e;if((workflowconfig==WORKFLOW_DIGI_WORK)||(workflowconfig==WORKFLOW_DIGI)||(workflowconfig==WORKFLOW_WORK_SEND)){b+=''+W_SEND_ORDERS[lang]+""}if((workflowconfig==WORKFLOW_DIGI_WORK)||(workflowconfig==WORKFLOW_WORK)||(workflowconfig==WORKFLOW_WORK_SEND)){b+=''+W_WORK_TICKET[lang]+""}b+=''+W_TO_PAYDESK[lang]+'';$("#commandbuttons").html(b);$("#waiterui").trigger("create");var c='
    ';$("#actremark").html(c);if(rightchangeprice==1){var a='';$("#actchangepricesection").html(a);var g='";$("#actdiscount").html(g)}$("#actionneworderconfirm_all").html(W_ACT_CHANGE_ALL[lang]);$("#actionneworderconfirm_one").html(W_ACT_CHANGE_ONE[lang]);$("#actionnewordercancel").html(W_CANCEL[lang]);$("#select-comment").off("click").on("click",function(k){k.stopImmediatePropagation();k.preventDefault();var i=$("#select-comment").find(":selected").val();$("#optionfield").val(i)});$("#act-select-comment").off("click").on("click",function(k){k.stopImmediatePropagation();k.preventDefault();var i=$("#act-select-comment").find(":selected").val();$("#act-optionfield").val(i)});$("#discard_new_orders_no").off("click").on("click",function(i){i.stopImmediatePropagation();i.preventDefault();parent.history.back()});$("#discard_new_orders_no").off("click").on("click",function(i){i.stopImmediatePropagation();i.preventDefault();parent.history.back()});$("#discard_new_orders_yes").off("click").on("click",function(i){i.stopImmediatePropagation();i.preventDefault();neworders=[];gotoOtherPage($("#discardnewordersdlg").data("link"))});$("#prodbackbtn").off("click").on("click",function(i){if(neworders.length!=0){i.stopImmediatePropagation();i.preventDefault();hideMenuProd();$("#discardnewordersdlg").data("link","back_table");$.mobile.changePage("#discardnewordersdlg")}else{parent.history.back()}});$("#searchField").off("keyup").on("keyup",function(i){generateSearchResults()})}function generateSearchResults(){var e=$("#searchField").val().trim().toLowerCase();if(e.length<3){$("#searchResult").html("")}else{var c=getProdSizeClass();var b='";$("#searchResult").html(b);$("#searchResult").trigger("create");$(".srinfo").off("click").on("click",function(i){i.stopImmediatePropagation();i.preventDefault();var f=this.id.split("_")[1];var h=getProdEntry(f);var g=h.price;alert(W_PRICE[lang]+": "+g+" "+currency)});$(".srplus").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=this.id.split("_")[1];var f=getSearchProdCount(g);$("#srprodcount_"+g).html(f+1)});$(".srminus").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=this.id.split("_")[1];var f=getSearchProdCount(g);if(f==2){$("#srprodcount_"+g).html("");selectedProdCount=1}else{if(f>2){$("#srprodcount_"+g).html(f-1)}}});$(".searchresult").off("click").on("click",function(g){g.stopImmediatePropagation();g.preventDefault();var f=this.id.split("_")[1];selectedProdCount=getSearchProdCount(f);clearSearchAndGoToHigherTypeIfExtrasOpen();levelOneType=0;handleClickOnProd(f)})}}function fillGenCommentsList(f){if(f.status!="OK"){alert("Fehler "+f.code+": "+f.msg);return}var b='';var e=f.msg;var c=0;for(c=0;c'+a+""}htmlComments=b;predefinedComments=b;$("#select-comment").html(b);$("#select-comment").selectmenu("refresh")}function initializeMainMenu(a,h,e,i,g){$("#"+e).html(" "+a.user);$("#"+i).html(a.version+" ");var k='
  • Module
  • ';$.each(a.menu,function(n,m){var l=m.name;var o=m.link;if(g){k+='
  • '+l+"
  • "}else{k+='
  • '+l+"
  • "}});$(h).empty().append(k).promise().done(function(){refreshList(h)});if(h=="#modulemenu-room"){var c=a.waitermessage;if(c!=""){$("#waitermessage").show();var b='
  • '+W_MSG[lang]+"
  • ";var f='
  • '+c+"
  • ";$("#waitermessage").html(b+f);refreshList("#waitermessage")}else{$("#waitermessage").hide()}}$(".modulebutton").off("click").on("click",function(m){var l=$(this).attr("href");doJsonAjaxAsync("POST","php/contenthandler.php?module=admin&command=setLastModuleOfUser",{view:l},null,"Problem Benutzerdatenpflege",false)})}function refreshList(a){if($(a).hasClass("ui-listview")){$(a).listview("refresh")}else{$(a).trigger("create")}}function gotoOtherPage(a){var b=a.split("_");if(b[0]=="menu"){doJsonAjax("POST","php/contenthandler.php?module=admin&command=setLastModuleOfUser",{view:b[1]},null,null);setTimeout(function(){document.location.href=b[1]},250)}else{if(b[0]=="back"){$("#discardnewordersdlg").dialog("close");parent.history.back()}}}function moduleForward(a){if(neworders.length==0){gotoOtherPage(a)}else{hideMenuProd();$("#discardnewordersdlg").data("link",a);$.mobile.changePage("#discardnewordersdlg")}}function getPayPrintType(){doJsonAjax("GET","php/contenthandler.php?module=admin&command=getPayPrintType",null,insertPayPrintType,"Fehler Druckkonfiguration")}function insertPayPrintType(a){$("#workprintarea").data("payPrintType",a)}function getUserHasRightForPaydesk(){doJsonAjax("GET","php/contenthandler.php?module=admin&command=hasUserPaydeskRight",null,hasUserPaydeskRight,"Fehler Kassenberechtigung")}function hasUserPaydeskRight(a){$("#gopaydesk_btn").data("allowed",a)}function hideMenuRoom(){$("#modulepanel-room").panel("close");$("#menuswitch").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();$("#modulepanel-room").panel("open")})}function hideMenuTable(){$("#modulepanel-table").panel("close");$("#menuswitchtable").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();$("#modulepanel-table").panel("open")})}function hideMenuProd(){$("#modulepanel-prod").panel("close");$("#menuswitchprod").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();$("#modulepanel-prod").panel("open")})}function addProductToQueueNoGuiUpdate(f,l,g,c,e){var b=getProdProperties(f);var a=b.name;var h=b.price;var m={name:a,option:l,extras:g,prodid:f,price:h,changedPrice:c,togo:e};for(var k=0;k";var l=groupedNewOrders.count.length;for(f=0;f1){k=""+g.toString()+"x "+k}var e=groupedNewOrders.prodids[f];if(h!=""){h="

    "+toHtml(h)+"

    "}var b=groupedNewOrders.changedPrices[f];var a=groupedNewOrders.togos[f];var n="";var c=groupedNewOrders.extras[f];if((c!=null)&&(c!="")){n=""+c+""}if(b!="NO"){b=b.replace(".",decpoint);if(a!=0){m+='
  • '+k+h+n+" ("+b+" - To-Go)
  • "}else{m+='
  • '+k+h+n+" ("+b+")
  • "}}else{if(a!=0){m+='
  • '+k+h+n+" - To-Go
  • "}else{m+='
  • '+k+h+n+"
  • "}}}$("#neworders").html(m);refreshList("#neworders");binding_neworderelem()}function getProdSizeClass(){if(osprodbtnsize==1){return("osprod-1")}else{if(osprodbtnsize==2){return("osprod-2")}}return""}function binding_neworderelem(){$(".neworder_el").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();var b=$("#neworders li").index($(this).closest("li"))-1;var a={count:groupedNewOrders.count[b],name:groupedNewOrders.name[b],price:groupedNewOrders.price[b],option:groupedNewOrders.option[b],extras:groupedNewOrders.extras[b],prodid:groupedNewOrders.prodids[b],origidxs:groupedNewOrders.origidxs[b],changedPrices:groupedNewOrders.changedPrices[b],togos:groupedNewOrders.togos[b]};$("#actiononneworderel").data("entry",a);$("#actiononneworderel").data("newcount",a.count);$("#actiononneworderel").data("groupedListIndex",b);$("#act-optionfield").val(a.option);$("#togocheckbox").prop("checked",a.togos==1?true:false);actionSelOnNewOrderElem()})}function sendNewOrders(c,f,a){var g=$("#typprodpage").data("table-info");var b=g[1];if(neworders.length!=0){var e={tableid:b,prods:neworders,print:(c?1:0),payprinttype:f};$("#typprodpage").data("neworders",[]);if(f=="s"){doJsonAjax("POST","php/contenthandler.php?module=queue&command=addProductListToQueue",e,a,"Fehler bei Produktversand")}else{doJsonAjax("POST","php/contenthandler.php?module=queue&command=addProductListToQueue",e,fillPrintAreaAndPrint,"Fehler bei Produktversand")}}else{if(c&¬DeliveredProdsAvailable){}}}function reloadPage(){tableListActive=false;setTimeout(function(){document.location.href="waiter.html"},250)}function gotoTablePage(){var a=$("#tables-page").data("allroomtables");var b=a.length;if(!isTogoOrderSelected||(b==1)){$.mobile.changePage("#tables-page")}else{reloadPage()}}function removeProductFromQueue(a,c,f,e,b){if(!b){alert(W_WRONG_PIN[lang]);return}$.ajax({type:"POST",dataType:"json",url:"php/contenthandler.php?module=queue&command=removeProductFromQueue",data:{queueid:a,isPaid:c,isCooking:f,isReady:e},async:false,success:function(k){if(k.status!="OK"){alert(W_REMOVE_ERROR[lang])}var i=$("#typprodpage").data("table-info");var g=i[1];var h="php/contenthandler.php?module=queue&command=getJsonLongNamesOfProdsForTableNotDelivered&tableid="+g;fillNotDeliveredProductsOfATable(h)},error:function(g){alert("Sorry, Fehler bei Produktentfernung!")}})}function reorderProduct(e,a,f){var c=[];for(var b=0;b'+k.name+""});a+='
  • '+W_TOGO[lang];var f=h.takeawayprice;var c=f.replace(".",decpoint)+" "+currency;if(f!=0){a+=" ("+W_TO_PAY[lang]+": "+c+")"}a+=createServeInfo(null,h.takeawayprodcount,h.takeawayprodready);a+="
  • ";$("#room-list").append(a).promise().done(function(){bindTogoOrdering();bindServeClick();$(this).off("click").on("click","a",function(l){l.stopImmediatePropagation();l.preventDefault();var k=b[this.id];currentRoomIndex=this.id;isTogoOrderSelected=false;$("#tables-page").data("roomdetail",k);nextPage="tables-page";$.mobile.changePage("#tables-page")});refreshList(this)})}})}function shallDisplayRoom(b){for(var a=0;a"+c.productname+b+"";a+="
  • "+g+"
  • "}$("#productsToMoveList").html(a);refreshList("#productsToMoveList");handleClickOnMoveableProd()}function handleClickOnMoveableProd(){$(".prodToMoveEl").off("click").on("click",function(f){f.stopImmediatePropagation();f.preventDefault();var b=this.id.split("_")[1];var a=prodsToMove[b];var c=a["class"];if(c=="unselecteditem"){a["class"]="selecteditem"}else{a["class"]="unselecteditem"}updateProdToMoveList()});$("#moveprods").off("click").on("click",function(k){k.stopImmediatePropagation();k.preventDefault();var g=[];for(var f=0;f'+W_TOGO[lang]+"";$("#tables-list-togo").html(k);$("#togoarea").show();refreshList("#tables-list-togo");bindTogoOrdering();bindServeClick()}}else{$(h).show();$("#togoarea").hide();$("#tablemapcontent").hide();var k='
  • '+W_TABLES[lang]+"
  • ";var f="";if(ostablebtnsize==1){f="ostable-1"}else{if(ostablebtnsize==2){f="ostable-2"}}$.each(l,function(p,s){var r=s.pricesum;var n=r.replace(".",decpoint)+" "+currency;var o=s.prodcount;var m=s.prodready;var q=s.readyQueueIds;if(r!=0){k+='
  • '+s.name+" ("+W_TO_PAY[lang]+": "+n+")"+createServeInfo(s.id,o,m)+"
  • "}else{k+='
  • '+s.name+createServeInfo(s.id,o,m)+"
  • "}});if(c=="t"){k+='
  • '+W_TOGO[lang]+"
  • "}$(h).empty().append(k).promise().done(function(){bindTogoOrdering();bindServeClick();$(this).off("click").on("click",".info-go",function(p){p.stopImmediatePropagation();p.preventDefault();var o=g;var m=l[this.id]["id"];var n=l[this.id]["name"];forwardDisplayToProductView.call(this,a,m,n)});refreshList(this)})}}function bindServeClick(){$(".prodreadyicon").off("click").on("click",function(l){l.stopImmediatePropagation();l.preventDefault();var f=this.id.split("_")[1];var h=queueIdsOfTakeAway;if((f!=null)&&(f!="n")){var a=$("#tables-page").data("roomdetail");var c=a.tables;for(var b=0;b0){var k=h.join();doJsonAjax("POST","php/contenthandler.php?module=queue&command=declareMultipleProductsDelivered",{queueids:k},updateAfterDelivery,"Bereitstellung")}})}function updateAfterDelivery(a){if(tableListActive){updateTableList()}else{reloadPage()}}function bindTogoOrdering(){$(".togoorder").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();isTogoOrderSelected=true;forwardDisplayToProductView.call(this,0,0,W_TOGO[lang])})}function forwardDisplayToProductView(b,a,c){neworders=[];updateNewOrdersGui();var e=new Array(b,a,c);$("#typprodpage").data("table-info",e);nextPage="typprodpage";$.mobile.changePage("#typprodpage");neworders=[];updateNewOrdersGui()}function attachAndDisplayFirstRefTypes(e){$("#typprodpage").data("types_prods",e);var a=e.prods;var c=[];for(var b=0;b";if(applyExtraBtnPos!=1){k+='
  • '+W_APPLY[lang]+"
  • "}for(var f=0;f=0){b="f";h="check"}k+='
  • '+toHtml(g)+"
  • "}if(applyExtraBtnPos!=2){k+='
  • '+W_APPLY[lang]+"
  • "}k+=createHigherLine(l);return k}function bindExtrasSel(){$(".extrasel").off("click").on("click",function(m){m.stopImmediatePropagation();m.preventDefault();var a=this.id.split("_");var b=a[1];var f=a[2];if((b=="abottom")||(b=="atop")){var k=getProdEntry(f);var c=k.extras;var n=[];for(var h=0;h=0){n[n.length]={id:b,name:l}}}addProductToNewOrdersList(f,n)}else{if(w_extras.indexOf(b)>=0){w_extras.splice(w_extras.indexOf(b),1)}else{w_extras[w_extras.length]=b}var o=listOfExtras(f);$("#typeproducts-list").html(o);refreshList("#typeproducts-list");bindExtrasSel();bindHigherButtons()}})}function lastSelectedProdToStr(){return" ("+W_LAST_SELECTED[lang]+": "+lastSelectedProduct+")"}function listOfTypesProds(e){var a='
  • '+W_SELECTION[lang]+"";if(lastSelectedProduct!=""){a+=lastSelectedProdToStr()}a+="
  • ";var b=$("#typprodpage").data("types_prods");var c=getProdSizeClass();$.each(b.types,function(g,f){if(parseInt(f.ref)==e){a+='
  • '+toHtml(f.name)+"
  • "}});$.each(b.prods,function(f,g){if(parseInt(g.ref)==e){a+='
  • '+toHtml(g.name);a+=createProdInfoTxt(g.id);a+="
  • "}});if(e!=0){a+=createHigherLine(c)}return a}function createHigherLine(b){var a='
  • ';a+='
    ';a+='
    ';a+='
    ';a+="
    ";a+="
  • ";return a}function createProdInfoTxt(b){var a="";a+="
    ";a+="
    ";a+="
    ";return a}function createSearchProdInfoTxt(b){var a="";a+="
    ";a+="
    ";a+="
    ";return a}function createServeInfo(e,c,b){if(supplyright==0){return""}if(e==null){e="n"}if(b>0){var a=""+b+"("+c+")";if(b>=c){a+="
    "}else{a+="
    "}return a}else{return""}}function getProdEntry(e){var b=$("#typprodpage").data("types_prods");var c=0;var a=b.prods;for(c=0;c";var b=$("#typprodpage").data("types_prods");var c=getProdSizeClass();var a=false;$.each(b.prods,function(f,g){if(parseInt(g.favorite)==1){a=true;e+='
  • '+toHtml(g.longname);e+=createProdInfoTxt(g.id);e+="
  • "}});e+="";if(a){$("#favarea").html(e);$("#favarea").trigger("create")}else{$("#favarea").html("");$("#favarea").trigger("create")}}function bindFavEvent(){$(".fav").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();levelOneType=0;var a=this.id.split("_")[1];selectedProdCount=getProdCount(a);handleClickOnProd(a)})}function displayTypesProds(c,b){window.scrollTo(0,0);if(c==0){fillFavArea();bindFavEvent()}else{$("#favarea").html("")}if(b==null){idOfHigherType=c;var a=listOfTypesProds(parseInt(c));extrasMenuOpen=false}else{var a=listOfExtras(parseInt(c));extrasMenuOpen=true}$("#typeproducts-list").empty().append(a).promise().done(function(){refreshList("#typeproducts-list");$(this).off("click").on("click","a",function(i){i.stopImmediatePropagation();i.preventDefault();$("#searchField").val("");generateSearchResults();var g=this.id;var f=g.split("_");if(f[0]=="t"){if(c==0){levelOneType=f[1];c=f[1]}displayTypesProds(f[1],null)}else{var h=f[1];selectedProdCount=getProdCount(h);handleClickOnProd(h)}});bindHigherButtons()});$(".prodinfo").off("click").on("click",function(i){i.stopImmediatePropagation();i.preventDefault();var f=this.id.split("_")[1];var h=getProdEntry(f);var g=h.price;alert(W_PRICE[lang]+": "+g+" "+currency)});$(".prodplus").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=this.id.split("_")[1];var f=getProdCount(g);$("#prodcount_"+g).html(f+1)});$(".prodminus").off("click").on("click",function(h){h.stopImmediatePropagation();h.preventDefault();var g=this.id.split("_")[1];var f=getProdCount(g);if(f==2){$("#prodcount_"+g).html("");selectedProdCount=1}else{if(f>2){$("#prodcount_"+g).html(f-1)}}})}function getHigherType(){var c=$("#typprodpage").data("types_prods");var b=c.types;var f=0;if(!extrasMenuOpen){for(var e=0;e0)){w_extras=[];w_allextras=a;idOfHigherType=c.ref;displayTypesProds(b,a);bindExtrasSel()}else{addProductToNewOrdersList(b,null)}}function addProductToNewOrdersList(f,e){var i=$("#typprodpage").data("table-info");var c=i[1];addProductToQueue(f,e,"NO",0);var a=getProdAudio(parseInt(f));var b=parseInt($("#typprodpage").data("ordervolume"))/10;if(a!=""){var h="customer/"+a;if(a.match(/mp3$/)){$("#audiofile").html('')}else{if(a.match(/ogg$/)){$("#audiofile").html('')}else{if(a.match(/wav$/)){$("#audiofile").html('')}}}document.getElementById("audiofile").load();document.getElementById("audiofile").volume=b;document.getElementById("audiofile").play()}else{if(b>0.5){beep()}}var g="php/contenthandler.php?module=queue&command=getJsonLongNamesOfProdsForTableNotDelivered&tableid="+c;fillNotDeliveredProductsOfATable(g);if(keeptypelevel==0){displayTypesProds(levelOneType,null)}else{if(extrasMenuOpen){displayTypesProds(idOfHigherType,null)}}refreshList("#typeproducts-list")}function beep(){var a=new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");a.play()}function fetchTypeProdsFromServer(){doJsonAjaxAsync("GET","php/contenthandler.php?module=products&command=getAllTypesAndAvailProds",null,attachAndDisplayFirstRefTypes,true)}var waitProdTimer=null;function fillTypeProdList(b){var a=$("#typprodpage").data("types_prods");if(a!=undefined){displayTypesProds(b,null)}else{waitProdTimer=setInterval(function(){var c=$("#typprodpage").data("types_prods");if(c!=undefined){clearInterval(waitProdTimer);displayTypesProds(b,null)}},200)}}function fillTypeProdList_(a){displayTypesProds(a,null)}function createTxtAssignedProd(e){var b="";if(e.option!=""){b=" ("+toHtml(e.option)+")"}var c=e.longname;if(e.togo==1){c="To-Go: "+c}if(e.pricechanged==1){c+=" - "+e.price.replace(".",decpoint)}var a="";if(e.isready=="1"){a+=" ☞"}if(e.isCooking=="1"){a+=" ♨"}if(e.isPaid=="1"){a+=" ☑"}return toHtml(c)+b+a+"
    "+createExtraParagraph(e.extras)}function createListElOfAssignedProd(b){var a="";if("count" in b){if(b.count>1){a=b.count+"x "}}if(b.isready=="0"){return'
  • '+a+createTxtAssignedProd(b)+"
  • "}else{return'
  • '+a+createTxtAssignedProd(b)+"
  • "}}function fillAssignedProdList(b){if(b.length>0){notDeliveredProdsAvailable=true}else{notDeliveredProdsAvailable=false}$("#cancelcodefield").val("");if(cancelunpaidcode!=""){if(b.length>0){$("#cancelcodearea").show()}else{$("#cancelcodearea").hide()}}else{$("#cancelcodearea").hide()}var c=new Grouping(b,createTxtAssignedProd);c.group();var a='
  • '+W_KIT_BAR[lang]+"
  • ";a+=c.outputList(createListElOfAssignedProd);$("#orderedprod-list-0").html(a);refreshList("#orderedprod-list-0");$("#undeliveredheader").off("click").on("click",function(f){f.stopImmediatePropagation();f.preventDefault();alert(W_UNDELIV_INFO[lang])});bindingOfAssignedProds(c)}function bindingOfAssignedProds(a){$(".notdelprod").off("click").on("click","a",function(k){k.stopImmediatePropagation();k.preventDefault();var g=true;if(cancelunpaidcode!=""){if($("#cancelcodefield").val()!=cancelunpaidcode){g=false}}var b=$(this).closest("li");var n=$("#orderedprod-list-0 li").index(b)-1;var h=a.getItemsOfRow(n);var p=h[0];var c=p.id;var m=p.isready;var i=p.isPaid;var o=p.isCooking;if((i=="1")&&(m=="1")){var f="Entfernen oder nachbestellen?";var l=this;doYouWantDelOrReorder("Produkt wurde schon zubereitet und bezahlt",f,W_REMOVE[lang],function(){removeProductFromQueue(c,i,o,m,g)},function(){reorderProduct(p.prodid,p.extrasids,p.extras)})}else{if(m=="1"){var f="Entfernen oder nachbestellen?";var l=this;doYouWantDelOrReorder("Produkt wurde schon zubereitet.",f,W_REMOVE[lang],function(){removeProductFromQueue(c,i,o,m,g)},function(){reorderProduct(p.prodid,p.extrasids,p.extras)})}else{if(i=="1"){var f="Entfernen oder nachbestellen?";var l=this;doYouWantDelOrReorder("Produkt wurde schon bezahlt.",f,W_REMOVE[lang],function(){removeProductFromQueue(c,i,o,m,g)},function(){reorderProduct(p.prodid,p.extrasids,p.extras)})}else{if(o=="1"){var f="Entfernen oder nachbestellen?";var l=this;doYouWantDelOrReorder("Produkt wird soeben zubereitet.",f,W_REMOVE[lang],function(){removeProductFromQueue(c,i,o,m,g)},function(){reorderProduct(p.prodid,p.extrasids,p.extras)})}else{var f="Entfernen oder nachbestellen?";var l=this;doYouWantDelOrReorder("",f,W_REMOVE[lang],function(){removeProductFromQueue(c,i,o,m,g)},function(){reorderProduct(p.prodid,p.extrasids,p.extras)})}}}}})}function fillNotDeliveredProductsOfATable(a){doJsonAjaxAsync("GET",a,null,fillAssignedProdList,true)}function fillOrderVolume(a){$("#typprodpage").data("ordervolume",a)}function checkForLogIn(){doJsonAjax("GET","php/contenthandler.php?module=admin&command=isUserAlreadyLoggedIn",null,handleTestForLoggedIn,null)}function handleTestForLoggedIn(a){if(a!="YES"){setTimeout(function(){document.location.href="index.html"},250)}}$(document).on("pagebeforeshow","#typprodpage",function(){lastSelectedProduct="";tableListActive=false;if(nextPage==""){reloadPage()}$("#tablemapcontent").hide();$.ajaxSetup({cache:false});hideMenuProd();getPayPrintType();checkForLogIn();doJsonAjax("GET","php/contenthandler.php?module=admin&command=getOrderVolume",null,fillOrderVolume,"Keine Ordertoninformation");$("#workprintarea").html("");var a=$(this).data("table-info");var c=a[0];var b=a[1];$("#changetablewhatdialog").data("fromtableid",b);var e=a[2];$("#typprodpage h1").html("Tisch: "+e);$("#optionfield").val("");fillTypeProdList(0);var f="php/contenthandler.php?module=queue&command=getJsonLongNamesOfProdsForTableNotDelivered&tableid="+b;fillNotDeliveredProductsOfATable(f);$("#workprint_btn").data("tableid",b);$("#gopaydesk_btn").data("tableid",b);$("#workprint_btn").data("tablename",e);bindPrintButton();bindGoPayDeskButton();bindChangetableButton();bindSendNewOrdersButton();getUserHasRightForPaydesk()});function bindSendNewOrdersButton(){$("#sendorder_btn").off("click").on("click",function(a){a.stopImmediatePropagation();a.preventDefault();lastSelectedProduct="";if(extrasMenuOpen){alert(W_OPEN_PANEL[lang])}else{sendNewOrders(false,"s",gotoTablePage)}})}function bindPrintButton(){$("#workprint_btn").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();lastSelectedProduct="";if(extrasMenuOpen){alert(W_OPEN_PANEL[lang])}else{if(neworders.length>0){var a=$("#workprintarea").data("payPrintType");sendNewOrders(true,a,gotoTablePage)}else{alert(W_NO_ORDERS[lang])}}})}function bindGoPayDeskButton(){$("#gopaydesk_btn").off("click").on("click",function(b){b.stopImmediatePropagation();b.preventDefault();lastSelectedProduct="";if(neworders.length>0){var a=$("#workprintarea").data("payPrintType");if(waitergopayprint==1){sendNewOrders(true,a,goToPayDesk)}else{sendNewOrders(false,a,goToPayDesk)}}else{if(notDeliveredProdsAvailable){goToPayDesk()}else{alert(W_NO_ORDERS[lang])}}})}function goToPayDesk(){var a=$("#gopaydesk_btn").data("allowed");if(a.toLowerCase()=="yes"){window.location.href="paydesk.html?t="+$("#gopaydesk_btn").data("tableid")}else{alert("Fehlendes Benutzerrecht für Kasse")}}function createRoomOrTableList(b,c){var a='
  • '+c+"
  • ";$.each(b,function(f,e){a+='
  • '+e.name+"
  • "});return a}function handleClickInChangeTablemap(a){$("#changetablewhatdialog").data("totableid",a.tableid);$.mobile.changePage("#changetablewhatdialog")}function displayTableDialog(e,g,c){$("#header_tchange").html("Tischauswahl");var f=shallDisplayRoom(e);if(f.show){$("#roomOrTableList").hide();$("#tablemapcontentchangetable").show();d=new Date();$("#mapimgpartchangetable").attr("src","php/tablemap.php?command=getTableMapImgAsPng&roomid="+e+"&"+d.getTime());var b=new Tablemap(e,null,"");b.bindingForSelection("#mapimgpartchangetable",handleClickInChangeTablemap.bind(this),f.pos,e);if(c){$.mobile.changePage("#tablechangedialog")}$("#changetablebackbtn").off("click").on("click",function(h){$("#tablemapcontentchangetable").hide();$("#roomOrTableList").show()})}else{$("#roomOrTableList").show();var a=createRoomOrTableList(g,"Tische");$("#roomOrTableList").empty().append(a).promise().done(function(){if(c){$.mobile.changePage("#tablechangedialog")}refreshList("#roomOrTableList");$(this).off("click").on("click",".info-go",function(i){i.stopImmediatePropagation();i.preventDefault();var h=($(this).attr("id")).split("_")[1];$("#changetablewhatdialog").data("totableid",g[h].id);$.mobile.changePage("#changetablewhatdialog")})})}}function resultOfChangeTable(a){if(a.status!="OK"){alert("Fehler "+a.code+": "+a.msg+"\n\nMöglicherweise hat ein Kollege\nin der Zwischenzeit Produkte zugestellt.")}else{alert("Tischwechsel durchgeführt!")}window.location.href="waiter.html"}function bindChangetableButton(){$("#changetable_btn").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();var b=$("#tables-page").data("allroomtables");var f=b.length;if(f==1){displayTableDialog(b[0].id,b[0].tables,true)}else{$("#header_tchange").html("Raumauswahl");var a=createRoomOrTableList(b,W_ROOMS[lang]);$("#roomOrTableList").empty().append(a).promise().done(function(){$.mobile.changePage("#tablechangedialog");refreshList("#roomOrTableList");$(this).off("click").on("click",".info-go",function(h){h.stopImmediatePropagation();h.preventDefault();var g=($(this).attr("id")).split("_")[1];displayTableDialog(b[g].id,b[g].tables,false)})})}})}function createHtmlOfKind(e,a,k){var g="";for(var b=0;b"+c+"
    "+h+"

    "}}return g}function createExtraParagraph(b){if((b==null)||(b=="")){return""}var c="";for(var a=0;a"}return c}function arrayContainsKind(b,e,g){var a=false;for(var c=0;c";if(o.status=="OK"){var b=o.msg;var f=$("#workprintarea").data("payPrintType");var g="";var m=$("#workprint_btn").data("tablename");if(arrayContainsKind(b,0,1)){var e="

    Speisen für "+m+" (Printer 1)


    ";var l=e+"
    "+i+"

    "+createHtmlOfKind(b,0,1)+"

    ";g+=l+"
    "}if(arrayContainsKind(b,0,2)){var e="

    Speisen für "+m+" (Printer 2)


    ";var l=e+"
    "+i+"

    "+createHtmlOfKind(b,0,2)+"

    ";g+=l+"
    "}if(arrayContainsKind(b,1,1)){var c="

    Getränke für "+m+" (Printer 1)


    ";var k=c+"
    "+i+"

    "+createHtmlOfKind(b,1,1)+"

    ";g+=k+"
    "}if(arrayContainsKind(b,1,2)){var c="

    Getränke für "+m+" (Printer 2)


    ";var k=c+"
    "+i+"

    "+createHtmlOfKind(b,1,2)+"

    ";g+=k+"
    "}$("#workprintarea").html(g);window.print();setTimeout(function(){document.location.href="waiter.html"},250)}else{alert("Druckdaten konnten nicht angefordert werden")}}function printJob(h,c,f,b,g,a){var e={header:h,table:c,timestamp:f,prods:b,type:g,printer:a};doJsonAjax("POST","php/contenthandler.php?module=printqueue&command=queueWorkPrintJob",e,null,"Druckfehler")}function updateNotDeliveredList(){var a=$("#typprodpage").data("table-info");var c=a[1];var e="php/contenthandler.php?module=queue&command=getJsonLongNamesOfProdsForTableNotDelivered&tableid="+c;var b="#orderedprod-list-0";fillNotDeliveredProductsOfATable(e)}function doJsonAjax(a,b,f,e,c){$.ajax({type:a,url:b,dataType:"json",data:f,async:true,success:function(g){if(e!=null){e(g)}},error:function(k,g,h){if(c!=null){var i=c+", Status: "+g+", Error:"+h+", Msg: "+k.responseText+" ("+b+")";alert("Kommunikationsfehler zum Server: "+i)}}})}function doJsonAjaxAsync(a,b,e,c,f){$.ajax({type:a,url:b,dataType:"json",data:e,async:f,success:function(g){if(c!=null){c(g)}},error:function(i,g,h){}})}function doYouWantDelOrReorder(e,f,c,b,a){$("#delOrReorderDlg .sure-1").text(f);$("#delOrReorderDlg .sure-2").text(e);$("#delOrReorderDlg .sure-cancel").text(W_CANCEL[lang]);$("#delOrReorderDlg .sure-do").text(c).off("click.delOrReorderDlg").on("click.delOrReorderDlg",function(){b()});$("#delOrReorderDlg .reorder").text(W_REORDER[lang]).off("click.delOrReorderDlg").on("click.delOrReorderDlg",function(){a()});$(this).off("click.delOrReorderDlg");$.mobile.changePage("#delOrReorderDlg")}function areYouSure(c,b,a,e){$("#sure .sure-1").text(c);$("#sure .sure-2").text(b);$("#sure .sure-do").text(a).off("click.sure").on("click.sure",function(){e()});$(this).off("click.sure");$.mobile.changePage("#sure")}function changePriceInActPanel(a){if(rightchangeprice){$("#act-changepricefield").val(a.toFixed(2).replace(".",decpoint))}}function actionSelOnNewOrderElem(){var b=$("#actiononneworderel").data("entry");var a=$("#actiononneworderel").data("newcount");$("#act_count").html(a);$("#act_name").html(b.name+" ("+b.price+" "+currency+")");if(b.option!=""){$("#act_option").html(" ("+b.option+")")}if(rightchangeprice){if(b.changedPrices!="NO"){$("#act-changepricefield").val(b.changedPrices)}}$("#act-select-comment").html(predefinedComments);$.mobile.changePage("#actiononneworderel");if(a==1){$("#actionneworderconfirm_all").html(W_ACT_CHANGE[lang]);$("#actionneworderconfirm_one").hide()}else{$("#actionneworderconfirm_all").html(W_ACT_CHANGE_ALL[lang]);$("#actionneworderconfirm_one").html(W_ACT_CHANGE_ONE[lang]);$("#actionneworderconfirm_one").show()}$("#act-select-comment").selectmenu("refresh");$("#togocheckbox").checkboxradio("refresh");$("#actminusone").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();reduceOneNewOrderItem();actionSelOnNewOrderElem($("#actiononneworderel").data("entry"),$("#actiononneworderel").data("groupedListIndex"))});$("#actplusone").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();increaseOneNewOrderItem();actionSelOnNewOrderElem($("#actiononneworderel").data("entry"),$("#actiononneworderel").data("groupedListIndex"))});$("#actdel").off("click").on("click",function(c){delOneNewOrderItem();actionSelOnNewOrderElem($("#actiononneworderel").data("entry"),$("#actiononneworderel").data("groupedListIndex"));actionNewOrderConfirm(CHANGE_ONE)});$("#actionneworderconfirm_all").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();$("#actiononneworderel").dialog("close");actionNewOrderConfirm(CHANGE_ALL)});$("#actionneworderconfirm_one").off("click").on("click",function(c){c.stopImmediatePropagation();c.preventDefault();$("#actiononneworderel").dialog("close");actionNewOrderConfirm(CHANGE_ONE)});$("#actionnewordercancel").off("click").on("click",function(c){binding_neworderelem()});$("#discount1").off("click").on("click",function(f){f.stopImmediatePropagation();f.preventDefault();var c=b.price;changePriceInActPanel(c-c*discount1/100)});$("#discount2").off("click").on("click",function(f){f.stopImmediatePropagation();f.preventDefault();var c=b.price;changePriceInActPanel(c-c*discount2/100)});$("#discount3").off("click").on("click",function(f){f.stopImmediatePropagation();f.preventDefault();var c=b.price;changePriceInActPanel(c-c*discount3/100)})}function actionNewOrderConfirm(h){var c=$("#actiononneworderel").data("entry");var n=$("#act-optionfield").val();if(rightchangeprice==1){var f=$("#act-changepricefield").val().trim();f=f.replace(",",".");if(f>999.99){alert(W_MAX_PRICE_EXCEEDED[lang]);return}if(f==""){f="NO"}else{if(!$.isNumeric(f)){alert(W_WRONG_FORMAT[lang]);return}else{$("#act-changepricefield").val("")}}}else{f="NO"}var g=$("#togocheckbox").prop("checked");if(g){g=1}else{g=0}if(h==CHANGE_ONE){var b=c.origidxs;neworders[b[0]].option=n;neworders[b[0]].changedPrice=f;neworders[b[0]].togo=g}else{var b=c.origidxs;for(m=0;m0){var b=c.origidxs;var q=b[0];var l=neworders[q].prodid;var f=neworders[q].changedPrice;var g=neworders[q].togo;var n=neworders[q].option;var k=neworders[q].extras;for(m=0;m0){$("#actiononneworderel").data("newcount",a-1)}}function delOneNewOrderItem(){$("#actiononneworderel").data("newcount",0)}function increaseOneNewOrderItem(){var b=$("#actiononneworderel").data("entry");var a=$("#actiononneworderel").data("newcount");$("#actiononneworderel").data("newcount",a+1)}function group(h){var x=[];var e=[];var z=[];var s=[];var o=[];var g=[];var v=[];var w=[];var a=[];var m=[];var y={count:x,joinedvals:e,name:z,price:s,option:o,extras:g,prodids:v,origidxs:w,changedPrices:a,togos:m};var u=0;for(u=0;u+ "+toHtml(c[t].name)+"

    "}}var q=z+"-"+o+"-"+b;if(f!="NO"){q=z+"-"+o+"-"+b+f}if(l==1){q+=" - To-Go"}var k=y.joinedvals.indexOf(q);if(k>=0){y.count[k]=y.count[k]+1;idxarr=y.origidxs[k];idxarr[idxarr.length]=u;y.origidxs[k]=idxarr}else{var n=y.count.length;y.count[n]=1;y.joinedvals[n]=q;y.name[n]=z;y.price[n]=s;y.option[n]=o;y.extras[n]=b;y.prodids[n]=p;y.changedPrices[n]=f;y.togos[n]=l;y.origidxs[n]=[u]}}return y};
    @@ -218,9 +218,13 @@ var W_TABLES=["Tische","Tables","Mesas"];var W_ROOMS=["Räume","Rooms","Espacios

    Auswahl der Orderelemente

    Welche Orderelemente sollen dem neuen Tisch zugewiesen werden?

    + Alles/nichts auswählen +
    + +
      + +
    +