OrderSprinter 1.2.0

This commit is contained in:
Geno 2020-11-19 22:59:47 +01:00
parent 2cdb1242c5
commit 27a1ab8de0
34 changed files with 2132 additions and 1686 deletions

Binary file not shown.

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />
@ -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.", 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", "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"];; "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; var lang = 0;
@ -101,6 +105,11 @@ function setLanguage(language) {
$("#billnocancelposs").html(BILL_NO_CANCEL_POSS[lang]); $("#billnocancelposs").html(BILL_NO_CANCEL_POSS[lang]);
$("#datetxt").html(BILL_DATE[lang]); $("#datetxt").html(BILL_DATE[lang]);
$("#stornoreasontxt").html(BILL_STORNO_REASON[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"; var langtxt = "de";
if (lang == 1) { 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() { function getLastBills() {
var date = $("#datepicker").datepicker("getDate"); var date = $("#datepicker").datepicker("getDate");
@ -360,7 +392,13 @@ function insertGenConfigStartRest(configResult) {
setLanguage(values.userlanguage); setLanguage(values.userlanguage);
getLastBills(); getLastBills();
updatelistener(); updatelistener();
batchjoblistener();
bindWhenSelection(); bindWhenSelection();
if (values.payprinttype == "s") {
// REM* only then allow batch processing
$("#batchpanel").show();
}
} else { } else {
setTimeout(function(){document.location.href = "index.html"},250); // not logged in setTimeout(function(){document.location.href = "index.html"},250); // not logged in
} }
@ -383,6 +421,8 @@ $(document).on("pageinit", "#bill-page", function () {
hideMenu(); hideMenu();
$.ajaxSetup({ cache: false }); $.ajaxSetup({ cache: false });
getGeneralConfigItems(); getGeneralConfigItems();
$("#fromjobidfield").val("");
$("#tojobidfield").val("");
}); });
@ -390,7 +430,7 @@ $(document).on("pageinit", "#bill-page", function () {
<div data-role="page" id="bill-page"> <div data-role="page" id="bill-page">
<div data-role="panel" id="modulepanel" data-position="right" data-display="overlay"> <div data-role="panel" id="modulepanel" data-position="right" data-display="overlay">
<ul data-role="listview" id="modulemenu" data-divider-theme="a" data-inset="true"> <ul data-role="listview" id="modulemenu" data-divider-theme="a" data-inset="true">
<li data-role="list-divider" data-theme="b" data-role="heading">Module</li> <li data-role="list-divider" data-theme="b">Module</li>
</ul> </ul>
</div><!-- /panel --> </div><!-- /panel -->
<div data-role="header" data-theme="b" data-position="fixed" id="theheader"> <div data-role="header" data-theme="b" data-position="fixed" id="theheader">
@ -409,6 +449,17 @@ $(document).on("pageinit", "#bill-page", function () {
<a href="#" data-role="button" data-theme="f" id="updatebtn"><span id="updatebtntxt">Aktualisieren</span></a> <a href="#" data-role="button" data-theme="f" id="updatebtn"><span id="updatebtntxt">Aktualisieren</span></a>
<br><br> <br><br>
<div id=billlist></div> <div id=billlist></div>
<div id="batchpanel" data-role="collapsible" data-collapsed="false" data-theme="e" data-content-theme="c" style="display:none;">
<h3><span id="batchheadertxt">Stapelverarbeitung</span></h3>
<p>
<form>
<span id="fromjobidtxt">Erste Bon-ID:</span><input type="text" id="fromjobidfield" style="background-color:white;"/><br>
<span id="tojobidtxt">Letzte Bon-ID:</span><input type="text" id="tojobidfield" style="background-color:white;" /><br>
<a href="#" data-role="button" data-icon="check" id="printjobsbtn" data-theme="f"><span id="printjobstxt">Drucken</span></a>
</form>
</div>
<div id=receiptbill></div> <div id=receiptbill></div>
</div> </div>
<div data-role="footer" data-theme="b" id="thefooterr"> <div data-role="footer" data-theme="b" id="thefooterr">
@ -418,7 +469,7 @@ $(document).on("pageinit", "#bill-page", function () {
</div><!-- /grid-a --> </div><!-- /grid-a -->
</div> <!-- footer --> </div> <!-- footer -->
<div data-role="popup" id="cancelfailed" name="cancelfailed" data-overlay-theme="a" style="max-width:70%;" class="ui-corner-all"> <div data-role="popup" id="cancelfailed" data-overlay-theme="a" style="max-width:70%;" class="ui-corner-all">
<div data-role="header" class="ui-corner-top"> <div data-role="header" class="ui-corner-top">
<h1>Storno fehlgeschlagen</h1> <h1>Storno fehlgeschlagen</h1>
</div> </div>

File diff suppressed because one or more lines are too long

View File

@ -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 # ***** Diese Speisekarte ist vom System bereits eingespeichert worden (erkennbar an den zugewiesenen IDs). ****
# Die tiefsten Einrückungen stellen die Produkte dar, alle
# Ebenen darüber die Kategorien
#
# Die einfachste Struktur sieht wie folgt aus (Beispiel):
# #
# Speisen # ***** Eine Erklärung der Syntax ist im Aufklappfeld "Legende" zu lesen.
# 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!)
# #

View File

@ -1,100 +1,62 @@
#
# ***** Diese Speisekarte kann als Vorlage dienen. **** # ***** Diese Speisekarte kann als Vorlage dienen. ****
# #
# Einrückungen bauen die Produktpalette hierarchisch auf # ***** Eine Erklärung der Syntax ist im Aufklappfeld "Legende" zu lesen.
# Die tiefsten Einrückungen stellen die Produkte dar, alle
# Ebenen darüber die Kategorien
# #
# Ein Produkteintrag hat folgendes Format: Speisen = KBF = 1
# Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C) Fastfood = KBF = 1
# dabei ist der Kurzname nur in der Kellneransicht bei der Produktauswahl zu sehen, Pommes; 3,00
# anschließend wird stets der Langname angezeigt. Schnitzel; 4,00
# Nur Kurzname und Preis (A) sind erforderlich, die anderen Teile werden bei Vom Grill = KBF = 1
# Auslassung automatisch gefüllt (Preis B=C=A und Langname = Kurzname) EL Greco 2 Personen; 26,00 # Kurzname:El Greco 2P; PreisB:20,00; PreisC:13,00
# Wird ein Steuersatz angegeben, der für das Produkt vorgegeben sein soll, so EL Greco 1 Person; 14,00 # Kurzname:El Greco 1P
# müssen auch die Preise A und B angegeben werden. Fleisch-Gerichte = KBF = 1
# Wurde dem Produkt bereits eine ID von OrderSprinter zugewiesen, wird diese angezeigt. Lammkotelett; 13,00 # PreisB:11,00; PreisC:6,00
# So können spätere Produktänderungen vom OrderSprinter erkannt werden. Zigeuner/Jägerschnitzel; 10,00 # PreisB:9,00; PreisC:3,00
# Es ist wichtig, keine eigenen IDs zu vergeben, denn neue IDs werden stets vom Suzukakia 4 Hacksteaks; 10,00 # Kurzname:Suzukakia 4H
# OrderSprinter erzeugt! Suzukakia 2 Hacksteaks; 10,00 # Kurzname:Suzukakia 2H
# Souvlaki; 10,00 # ID:9
# Bei Kategorien: Italienische Küche = KBF = 1
# Das Gleichheitszeichen dient als Trenner zwischen Namen und weiteren Eigenschaften. Ital. Tagesspecial; 6,00 # Kurzname:Special
# Wird ein K und B mitgegeben, so werden diese Produkte über die Küchen- Pizza = KBF = 1
# und Bereitstellungsansicht geführt. Die Einstellung wird auf die Unterkategorien Siciliana = KBF = 1
# vererbt, wenn die darunter liegenden Kategorien keine Angabe dazu machen. Pizza Siciliana klein; 7,00 # Kurzname:klein
# Hinter dem zweiten Gleichheitszeichen kann die Nummer eines Arbeitsbondruckers Pizza Siciliana groß; 7,00 # Kurzname:groß
# des jeweiligen Typs (Speise/Getränk) angegeben werden. Salami = KBF = 1
# Pizza Salami klein; 6,00 # Kurzname:klein
# Wenn ein D da steht, wird als Typ "Getränk" angenommen, bei einem F "Speise". Pizza Salami groß; 7,00 # Kurzname:groß
# Auch hier wird der übergeordnete Eintrag genommen, wenn Angabe fehlt. Kategorie Selbstbedienung = F = 1
# Frühstücksbuffet; 8,00
# Extras werden mit einem Ausrufezeichen am Zeilenanfang deklariert. Frühstücksbuffet + Kaffe; 12,00
# Das Format ist: Kategorie vorbereitet = BF = 1
# !Extraname (ID:8) # 12,34 ; (45),Langname eines Produkts,(49),(50) Deserts; 2,00
# - Die ID-Angabe ist optional (kann weggelassen werden) Fertigprodukte; 1,00
# - Der Wert 12,34 ist der Aufpreis Kategorie Nur Küche = KF = 1
# - Hinter dem Semikolon können Komma-getrennt Produkte angegebenen werden, die Tischzubereitung Fisch; 2,00
# dieses Extra haben dürfen. Angabe entweder ID des Produkts in Klammern oder Tischzubereitung Fleischmenü; 1,00
# der Langname eines Produkts. (Gibt es den Langnamen mehrfach, wird das Extra Getränke = KBD = 1
# auch mehrfach zugewiesen.) Kaffee = KBD = 1
# Cappuchino; 2,50
# Reservierte Buchstaben: = ; # ! Tasse Kaffee; 3,00
# (Diese werden als Trenner verwendet!) Becher Kaffee; 3,50
# Latte Macchiato; 3,00
Speisen = KBF Biere = KBD = 1
Fastfood Holsten; 1,00 # PreisB:1,00; PreisC:0,00
Pommes ; 3,00 Warsteiner; 1,00
Schnitzel ; 4,00 Becks Gold; 1,00
Vom Grill Alsterwasser; 1,00
El Greco 2P; 26{.}90; EL Greco 2 Personen # 20{.}90; 13{.}80 Softdrinks = KBD = 1
El Greco 1P; 14{.}80; EL Greco 1 Person Coca-Cola; 2,00
Fleisch-Gerichte Fanta; 2,00
Lammkotelett; 13{.}50; Lammkotelett # 11{.}30; 6{.}00 Sprite; 2,00
Zigeuner/Jägerschnitzel; 10{.}50 # 9{.}80; 3{.}50 Eistee; 1,00
Suzukakia 4H; 10{.}50; Suzukakia 4 Hacksteaks Ohne Zucker = BD = 1
Suzukakia 2H; 10{.}50; Suzukakia 2 Hacksteaks Cola Zero; 2,00
Souvlaki; 10{.}50 Wasser = KBD = 1
Italienische Küche Apollinaris; 2,00
Pizza Stilles Wasser; 1,00 # Kurzname:still
Siciliana Weine = KBD = 1
klein; 7{.}50; Pizza Siciliana klein Wein Lambrusco; 7,00 # Kurzname:Lambrusco
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
# #
# Es folgen die Extras # Es folgen die Extras
!Sahne # 0,50 ; Tasse Kaffee , Becher Kaffee !Sahne # 0,50 ; Tasse Kaffee , Becher Kaffee

View File

@ -4,7 +4,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -7,8 +7,8 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" type="text/css" href="css/numfield.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/numfield.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -679,7 +679,7 @@ $(document).ready(function() {
<tr id=updateline> <tr id=updateline>
<td>&nbsp;</td> <td>&nbsp;</td>
<td align=center> <td align=center>
<button id="updatebtn">Update -> 1.1.30</button> <button id="updatebtn">Update -> 1.2.0</button>
</td> </td>
<td>&nbsp;</td> <td>&nbsp;</td>
</tr> </tr>

View File

@ -46,9 +46,9 @@ function setTimeZone($zone) {
$this->timezone = $zone; $this->timezone = $zone;
} }
function openDbAndReturnPdo ($host,$db,$user,$password) { function openDbAndReturnPdo ($host,$db,$user,$password) {
$dsn = 'mysql:host=' . $host . ';dbname=' . $db; $dsn = 'mysql:host=' . $host . ';dbname=' . $db;
$pdo = null; $pdo = null;
try { try {
$pdo = new PDO($dsn, $user, $password); $pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
@ -56,8 +56,8 @@ $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch (PDOException $e) { catch (PDOException $e) {
echo 'Verbindungsproblem: ' . $e->getMessage(); echo 'Verbindungsproblem: ' . $e->getMessage();
$pdo = null; $pdo = null;
} }
return $pdo; return $pdo;
} }
function checkPhpStatus() { function checkPhpStatus() {
@ -95,6 +95,39 @@ $ret = array("extensions_status" => $extensions_status, "missing_extensions" =>
echo json_encode($ret); 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) { function updateVersion($pdo,$version) {
$setVersion = "update %config% set setting=? where name='version'"; $setVersion = "update %config% set setting=? where name='version'";
$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($setVersion)); $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) { function setVersion($prefix,$theVersion) {
$pdo = $this->pdo; $pdo = $this->pdo;
try { try {
@ -1194,31 +1260,31 @@ $rect .= "f: ; E_Summe:llllllllllllllllllll;\n\nj:l;";
return $rect; return $rect;
} }
function createTables($decpoint,$billlanguage,$currency,$timezone) function createTables($decpoint,$billlanguage,$currency,$timezone)
{ {
$pdo = $this->pdo; $pdo = $this->pdo;
$this->basedb->setTimeZone($timezone); $this->basedb->setTimeZone($timezone);
$this->basedb->dropTables($pdo); $this->basedb->dropTables($pdo);
$this->basedb->createRatingsTable($pdo); $this->basedb->createRatingsTable($pdo);
$this->createPaymentTable($pdo); $this->createPaymentTable($pdo);
$this->basedb->createUserTable($pdo); $this->basedb->createUserTable($pdo);
$this->basedb->createRoomTable($pdo); $this->basedb->createRoomTable($pdo);
$this->basedb->createRestTables($pdo); $this->basedb->createRestTables($pdo);
$this->basedb->createTableMapsTable($pdo); $this->basedb->createTableMapsTable($pdo);
$this->basedb->createTablePosTable($pdo); $this->basedb->createTablePosTable($pdo);
$this->basedb->createConfigTable($pdo); $this->basedb->createConfigTable($pdo);
$this->basedb->createProdTypeTable($pdo); $this->basedb->createProdTypeTable($pdo);
$this->basedb->createProductTable($pdo); $this->basedb->createProductTable($pdo);
$this->basedb->createPriceLevelTable($pdo); $this->basedb->createPriceLevelTable($pdo);
$this->basedb->createClosingTable($pdo); $this->basedb->createClosingTable($pdo);
$this->basedb->createBillTable($pdo); $this->basedb->createBillTable($pdo);
$this->basedb->createQueueTable($pdo); $this->basedb->createQueueTable($pdo);
$this->basedb->createBillProductsTable($pdo); $this->basedb->createBillProductsTable($pdo);
$this->basedb->createHistTables($pdo); $this->basedb->createHistTables($pdo);
$this->defineHistActions($pdo); $this->defineHistActions($pdo);
$this->basedb->createPrintJobsTable($pdo); $this->basedb->createPrintJobsTable($pdo);
$this->basedb->createWorkTable($pdo); $this->basedb->createWorkTable($pdo);
$this->basedb->createCommentsTable($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 ('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 `%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 , '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 , '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 , '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 , '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 , 'companyinfo', 'Musterrestaurant\nBeispielstrasse 123\n12345 Musterort')");
$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'rectemplate', '$rect')"); $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'; $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 , '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 , '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 , '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 , '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 , '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 , '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 , '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 , '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 , '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 , 'remoteaccesscode', null)");
$this->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'decpoint', '$decpoint')"); $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->basedb->doSQL($pdo,"INSERT INTO `%config%` (`id` , `name`, `setting`) VALUES (NULL , 'installdate', '$installDate')");
$this->readConfigTableAndSendToHist($pdo); $this->readConfigTableAndSendToHist($pdo);
return; return;
} }
public function getCurrentVersion() { public function getCurrentVersion() {
@ -1321,108 +1387,108 @@ return false;
} }
} }
function readConfigTableAndSendToHist($pdo) { function readConfigTableAndSendToHist($pdo) {
$sql_query = "SELECT * FROM %config%"; $sql_query = "SELECT * FROM %config%";
$sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)"; $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)";
$stmt_query = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_query)); $stmt_query = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_query));
$stmt_insert_histconfig = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histconfig)); $stmt_insert_histconfig = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histconfig));
$stmt_query->execute(); $stmt_query->execute();
$result = $stmt_query->fetchAll(); $result = $stmt_query->fetchAll();
foreach($result as $row){ foreach($result as $row){
$stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); $stmt_insert_histconfig->execute(array($row['id'],$row['setting']));
$newRefIdForHist = $pdo->lastInsertId(); $newRefIdForHist = $pdo->lastInsertId();
$this->insertIntoHist($pdo, '2', $newRefIdForHist); $this->insertIntoHist($pdo, '2', $newRefIdForHist);
} }
} }
private function insertIntoHist($pdo,$action,$refIdForHist) { private function insertIntoHist($pdo,$action,$refIdForHist) {
date_default_timezone_set($this->timezone); date_default_timezone_set($this->timezone);
$currentTime = date('Y-m-d H:i:s'); $currentTime = date('Y-m-d H:i:s');
$sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; $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 = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_hist));
$stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); $stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist));
} }
function insertUser($username,$adminpass,$is_admin,$right_waiter,$right_kitchen,$right_bar, 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_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); $md5adminpass = md5($adminpass);
$pdo = $this->pdo; $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 = $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(); $newUserIdForHist = $pdo->lastInsertId();
// now insert into hist // now insert into hist
$sql_insert_histuser = "INSERT INTO %histuser% (`id` , `userid`, `username` , $sql_insert_histuser = "INSERT INTO %histuser% (`id` , `userid`, `username` ,
`is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`, `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 ( `right_statistics`,`right_bill`,`right_products`,`right_changeprice`,`right_manager`,`right_closing`,`right_reservation`,`right_rating`,`active`) VALUES (
NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt_insert_histuser = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql_insert_histuser)); $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)); $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(); $newRefIdForHist = $pdo->lastInsertId();
$this->insertIntoHist($pdo, '3', $newRefIdForHist); $this->insertIntoHist($pdo, '3', $newRefIdForHist);
} }
function createPaymentTable($pdo) { function createPaymentTable($pdo) {
$this->basedb->createPaymentTable($pdo); $this->basedb->createPaymentTable($pdo);
$sql = "INSERT INTO %payment% (id,name,name_en,name_esp) VALUES (?,?,?,?)"; $sql = "INSERT INTO %payment% (id,name,name_en,name_esp) VALUES (?,?,?,?)";
$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql));
$stmt->execute(array('1', 'Barzahlung', 'Cash', 'Contado')); $stmt->execute(array('1', 'Barzahlung', 'Cash', 'Contado'));
$stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql)); $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) { $stmt->execute(array('2', 'EC-Kartenzahlung','Electr. purse (EC)','Pago con tarjeta EC'));
$sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql));
$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('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); $stmt->execute(array('4', 'Rechnung','bill','Factura'));
$stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql));
$stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); $stmt->execute(array('5', 'Ueberweisung','Bank transfer','Transferencia'));
$stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten')); $stmt = $pdo->prepare($this->basedb->resolveTablenamesInSqlString($sql));
$stmt->execute(array('5', 'ProdCreation', 'Neues Produkt')); $stmt->execute(array('6', 'Lastschrift','Debit','Cargo en cuenta'));
$stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration')); }
$stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer'));
$stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers')); 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) { function testDbConnection($host,$dbname,$user,$pass) {
$pdo = $this->openDbAndReturnPdo($host,$dbname,$user,$pass); $pdo = $this->openDbAndReturnPdo($host,$dbname,$user,$pass);
if (!is_null($pdo)) { if (!is_null($pdo)) {
echo json_encode("OK"); echo json_encode("OK");
} else { } else {
echo json_encode("ERROR"); echo json_encode("ERROR");
} }
} }
function writeConfigFile($host,$db,$user,$password,$prefix) { function writeConfigFile($host,$db,$user,$password,$prefix) {
$errorlevel = "<?php\nerror_reporting(E_ERROR);\n\n"; // development: E_ALL $errorlevel = "<?php\nerror_reporting(E_ERROR);\n\n"; // development: E_ALL
$hostlines = "// Zum Aufbau der Verbindung zur Datenbank\n"; $hostlines = "// Zum Aufbau der Verbindung zur Datenbank\n";
$hostlines .= "// die Daten erhalten Sie von Ihrem Provider\n"; $hostlines .= "// die Daten erhalten Sie von Ihrem Provider\n";
$hostlines .= "defined('MYSQL_HOST') || define ( 'MYSQL_HOST','$host' );"; $hostlines .= "defined('MYSQL_HOST') || define ( 'MYSQL_HOST','$host' );";
$userlines = "defined('MYSQL_USER') || define ( 'MYSQL_USER', '$user' );"; $userlines = "defined('MYSQL_USER') || define ( 'MYSQL_USER', '$user' );";
$dbpasslines = "defined('MYSQL_PASSWORD') || define ( 'MYSQL_PASSWORD', '$password' );"; $dbpasslines = "defined('MYSQL_PASSWORD') || define ( 'MYSQL_PASSWORD', '$password' );";
$dblines = "defined('MYSQL_DB') || define ( 'MYSQL_DB', '$db' );"; $dblines = "defined('MYSQL_DB') || define ( 'MYSQL_DB', '$db' );";
$dbloglines = "defined('LOG') || define ( 'LOG', false );"; $dbloglines = "defined('LOG') || define ( 'LOG', false );";
$prefixlines = "defined('TAB_PREFIX') || define ('TAB_PREFIX', '$prefix');"; $prefixlines = "defined('TAB_PREFIX') || define ('TAB_PREFIX', '$prefix');";
$installstatusline = "defined('INSTALLSTATUS') || define ('INSTALLSTATUS', 'installed');"; $installstatusline = "defined('INSTALLSTATUS') || define ('INSTALLSTATUS', 'installed');";
@ -1436,25 +1502,25 @@ file_put_contents("../php/config1.php", $configText);
} }
function createSslKeys($pdo) { function createSslKeys($pdo) {
$sslconfig = array( $sslconfig = array(
"digest_alg" => "sha512", "digest_alg" => "sha512",
"private_key_bits" => 4096, "private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA, "private_key_type" => OPENSSL_KEYTYPE_RSA,
); );
// thus the signature is exactly 512 bytes // thus the signature is exactly 512 bytes
// Create the private and public key // Create the private and public key
$res = openssl_pkey_new($sslconfig); $res = openssl_pkey_new($sslconfig);
if (is_null($res) || ($res=="")) { if (is_null($res) || ($res=="")) {
// openssl may be incorrectly installed // openssl may be incorrectly installed
return false; return false;
} }
// Extract the private key from $res to $privKey // Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey); openssl_pkey_export($res, $privKey);
// Extract the public key from $res to $pubKey // Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res); $pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"]; $pubKey = $pubKey["key"];
$sql = "INSERT INTO `%work%` (`id` , `item`,`value`,`signature`) VALUES ( NULL,?,?,?)"; $sql = "INSERT INTO `%work%` (`id` , `item`,`value`,`signature`) VALUES ( NULL,?,?,?)";
@ -1556,7 +1622,7 @@ $checker->checkPhpStatus();
} else if ($command == 'testDbConnection') { } else if ($command == 'testDbConnection') {
$admin = new InstallAdmin(); $admin = new InstallAdmin();
try { 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']); $admin->testDbConnection($_POST['host'],$_POST['dbname'],$_POST['user'],$_POST['pass']);
} else { } else {
echo json_encode("ERROR"); echo json_encode("ERROR");
@ -1616,7 +1682,7 @@ $zones[] = $timezone_identifiers[$i];
} }
echo json_encode($zones); echo json_encode($zones);
} else if ($command == 'update') { } else if ($command == 'update') {
$installerVersion = "1.1.30"; $installerVersion = "1.2.0";
$admin = new InstallAdmin(); $admin = new InstallAdmin();
$pdo = $admin->openDbAndReturnPdo($_POST['host'],$_POST['db'],$_POST['user'],$_POST['password']); $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.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.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.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)) { if (!in_array($version, $supportedVersions)) {
@ -1653,7 +1719,7 @@ echo json_encode("Quellversion nicht unterstützt");
return; return;
} }
$ret = $admin->updateUserTable1129_1130($_POST['prefix'], $version); $ret = $admin->updateUserTable1130_1200($_POST['prefix'], $version, $_POST['db']);
if(session_id() == '') { if(session_id() == '') {
session_start(); session_start();

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />
@ -65,6 +65,7 @@ var MAN_RESERVATION = ["Reservierung","Reservation","Reserva"];
var MAN_RATING = ["Bewertung","Rating","Valoración"]; 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_CHANGEPRICE = ["Preisänderung während Bestellung","Change price during ordering","Modificar precio durante ordenar"];
var MAN_MANAGER = ["Verwaltung","Administration","Administración"]; 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_NAME = ["Benutzername","User name","Nombre de usario"];
var MAN_USER_PASS = ["Passwort","Password","Contraseña"]; var MAN_USER_PASS = ["Passwort","Password","Contraseña"];
var MAN_YES = ["Ja","Yes","Si"]; 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. ' 'Exportar puede guarda la base de datos completamente. Con "Importar" este data se puede re-importado. '
+ 'Las acciones estan escritos en un log.']; + '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_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 (<i>importieren</i>): ", "Upload this file: ","Importar este file: "];
var MAN_BAK_REST_HEAD = ["Sicherung und Import","Backup and Restore","Exportar y Importar"]; 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 = ["Sicherung (Konfiguration)","Backup (Configuration)","Exportar (configuración)"];
var MAN_BAK_BTN_ALL = ["Sicherung (Alles)","Backup (all)","Exportar (todo)"]; var MAN_BAK_BTN_ALL = ["Sicherung (Alles)","Backup (all)","Exportar (todo)"];
var MAN_RESTORE_BTN = ["Importieren","Restore","Importar"]; 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 = ["Server herunterfahren","Shutdown server","Apagar servidor"];
var MAN_SHUTDOWN_HINT = ["(Herunterfahren nur möglich, wenn Webserver die erforderlichen Rechte besitzt).", 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.)", "(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_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_DRINK_PRINTER = ["Getränkearbeitsbon-Drucker","Drinks work ticket printer","Impreso de tiques de bebidas"];
var MAN_UPDATE_PRINTJOBS = ["Aktualisieren","Update","Actualizar"]; 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_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?", 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?", "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_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_CERTIFICATE_SN = ["Zertifikatsseriennummer", "Certificate Serial No","Certificado ID"];
var MAN_TAX = ["Steuersatz (%)","Tax (%)","Impuesto (%)"]; 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 lang = 0;
var generalVals = [12,2,0,3,0,1,1,0,0,1, 0,50,20,10,1,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]); $("#backupbtntxt").html(MAN_BAK_BTN[l]);
$("#backupbtntxtall").html(MAN_BAK_BTN_ALL[l]); $("#backupbtntxtall").html(MAN_BAK_BTN_ALL[l]);
$("#restorebtntxt").html(MAN_RESTORE_BTN[l]); $("#restorebtntxt").html(MAN_RESTORE_BTN[l]);
$("#golivetxt").html(MAN_GO_LIVE[l]);
$("#shutdownbtntxt").html(MAN_SHUTDOWN[l]); $("#shutdownbtntxt").html(MAN_SHUTDOWN[l]);
$("#shutdownhinttxt").html(MAN_SHUTDOWN_HINT[l]); $("#shutdownhinttxt").html(MAN_SHUTDOWN_HINT[l]);
@ -401,6 +408,7 @@ function setLanguage(l) {
$("#printjobsheader").html(MAN_PRINTJOBS[l]); $("#printjobsheader").html(MAN_PRINTJOBS[l]);
$("#updateprintqueue").html(MAN_UPDATE_PRINTJOBS[l]); $("#updateprintqueue").html(MAN_UPDATE_PRINTJOBS[l]);
$("#clearprintqueue").html(MAN_CLEAR_PRINTJOBS[l]);
$("#tmimgdelbtntxt").html(MAN_TM_DEL[l]); $("#tmimgdelbtntxt").html(MAN_TM_DEL[l]);
$("#tmimgbtntxt").html(MAN_TM[l]); $("#tmimgbtntxt").html(MAN_TM[l]);
@ -438,16 +446,21 @@ function createMonthSelection(label) {
return monthHtml; return monthHtml;
} }
function hideElementsForNonAdminUser(jsonAnswer) { function showPanelsDueToUserStatus(jsonAnswer) {
if (jsonAnswer != "Yes") { if (jsonAnswer == "admin") {
$("#dbactionui").hide(); $("#dbactionui").show();
} }
} if (jsonAnswer == "manager" || (jsonAnswer == 'admin')) {
$("#userpart").show();
function hideElementsForNonAdminManagerUser(jsonAnswer) { $("#configpart").show();
if (jsonAnswer != "Yes") { $("#printerqueue").show();
$("#allpagecontent").hide(); $("#dataexport").show();
} $("#printserverdownloadpart").show();
}
if(jsonAnswer == "No") {
$("#allpagecontent").hide();
}
} }
function getSpeisekarte() { function getSpeisekarte() {
@ -771,10 +784,10 @@ function changeConfig(changedEntries) {
} }
function reactOnConfigChange(result) { function reactOnConfigChange(result) {
if (result == "OK") { if (result.status == "OK") {
alert(MAN_CONFIG_CHANGED[lang]); alert(MAN_CONFIG_CHANGED[lang]);
} else { } else {
alert(MAN_CONFIG_CHANGE_ERROR[lang]); alert(MAN_CONFIG_CHANGE_ERROR[lang] + ": " + result.msg);
} }
} }
@ -1006,7 +1019,6 @@ function binding() {
}; };
if (isValid) { if (isValid) {
changeConfig(changedEntries); changeConfig(changedEntries);
setTimeout(function(){document.location.href = "manager.html"},500);
} }
}); });
} }
@ -1092,6 +1104,14 @@ function binding() {
$("#restinfoafterclick").html(MAN_REST_INFO[lang]); $("#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) { $("#shutdown_btn").off("click").on("click", function (e) {
e.stopImmediatePropagation(); e.stopImmediatePropagation();
e.preventDefault(); e.preventDefault();
@ -1115,6 +1135,11 @@ function binding() {
e.preventDefault(); e.preventDefault();
doAjax("GET","php/contenthandler.php?module=printqueue&command=getPrintJobOverview",null,insertPrintQueue,null); 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) { $("#taxass_apply").off("click").on("click", function (e) {
e.stopImmediatePropagation(); e.stopImmediatePropagation();
@ -1486,7 +1511,7 @@ function createLabelWithOption(aLabel,displayedName,hasTheRight) {
* the username and the rights that the user has to work in the * the username and the rights that the user has to work in the
* various modules. * 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 = '<div data-role="collapsible" id="' + id + '"'; var collapsiblePart = '<div data-role="collapsible" id="' + id + '"';
if (forNewUser) { if (forNewUser) {
collapsiblePart += ' data-theme="d" data-content-theme="d">'; collapsiblePart += ' data-theme="d" data-content-theme="d">';
@ -1511,6 +1536,7 @@ function createCollapsibeOfUser(id,username,isAdmin,rWaiter,rKitchen,rBar,rSuppl
collapsiblePart += createLabelWithOption("reservation",MAN_RESERVATION[lang],rReservation); collapsiblePart += createLabelWithOption("reservation",MAN_RESERVATION[lang],rReservation);
collapsiblePart += createLabelWithOption("rating",MAN_RATING[lang],rRating); collapsiblePart += createLabelWithOption("rating",MAN_RATING[lang],rRating);
collapsiblePart += createLabelWithOption("changeprice",MAN_CHANGEPRICE[lang],rChangeprice); collapsiblePart += createLabelWithOption("changeprice",MAN_CHANGEPRICE[lang],rChangeprice);
collapsiblePart += createLabelWithOption("closingright",MAN_CLOSINGRIGHT[lang],rClosing);
collapsiblePart += createLabelWithOption("manager",MAN_MANAGER[lang],rManager); collapsiblePart += createLabelWithOption("manager",MAN_MANAGER[lang],rManager);
if (forNewUser) { if (forNewUser) {
@ -1531,6 +1557,7 @@ function fillUserListIntoGui(userinfo) {
$.each(userinfo, function (i, aUser) { $.each(userinfo, function (i, aUser) {
var userid = aUser.id; var userid = aUser.id;
var username = aUser.username; var username = aUser.username;
userPart += createCollapsibeOfUser( userPart += createCollapsibeOfUser(
"userid_" + userid, "userid_" + userid,
username, username,
@ -1546,6 +1573,7 @@ function fillUserListIntoGui(userinfo) {
aUser.right_reservation == 1, aUser.right_reservation == 1,
aUser.right_rating == 1, aUser.right_rating == 1,
aUser.right_changeprice == 1, aUser.right_changeprice == 1,
aUser.right_closing == 1,
aUser.right_manager == 1, aUser.right_manager == 1,
false false
); );
@ -1554,7 +1582,7 @@ function fillUserListIntoGui(userinfo) {
userPart += createCollapsibeOfUser( userPart += createCollapsibeOfUser(
"userid_newuser", "userid_newuser",
MAN_NEW_USER[lang], MAN_NEW_USER[lang],
false,false,false,false,false,false,false,false,false,false,false,false,false,true); false,false,false,false,false,false,false,false,false,false,false,false,false,false,true);
$("#userlist").html(userPart); $("#userlist").html(userPart);
$('#userpart').trigger('create'); $('#userpart').trigger('create');
@ -1597,6 +1625,7 @@ function dynamicUserBinding() {
var rRating = newUserInfoContainer.find("#userlabel_rating").val(); var rRating = newUserInfoContainer.find("#userlabel_rating").val();
var rChangeprice = newUserInfoContainer.find("#userlabel_changeprice").val(); var rChangeprice = newUserInfoContainer.find("#userlabel_changeprice").val();
var rManager = newUserInfoContainer.find("#userlabel_manager").val(); var rManager = newUserInfoContainer.find("#userlabel_manager").val();
var rClosing = newUserInfoContainer.find("#userlabel_closingright").val();
if ((username.length == 0) || (password.length == 0)) { if ((username.length == 0) || (password.length == 0)) {
alert ("Benutzername oder Passwort sind nicht gesetzt"); alert ("Benutzername oder Passwort sind nicht gesetzt");
@ -1616,7 +1645,8 @@ function dynamicUserBinding() {
rReservation: rReservation, rReservation: rReservation,
rRating: rRating, rRating: rRating,
rChangeprice : rChangeprice, rChangeprice : rChangeprice,
rManager: rManager rManager: rManager,
rClosing: rClosing
}; };
doAjax("POST","php/contenthandler.php?module=admin&command=createNewUser",data,doCreateNewUser,"Anlegen neuer Benutzer"); doAjax("POST","php/contenthandler.php?module=admin&command=createNewUser",data,doCreateNewUser,"Anlegen neuer Benutzer");
} }
@ -1641,6 +1671,7 @@ function dynamicUserBinding() {
var rRating = userInfoContainer.find("#userlabel_rating").val(); var rRating = userInfoContainer.find("#userlabel_rating").val();
var rChangeprice = userInfoContainer.find("#userlabel_changeprice").val(); var rChangeprice = userInfoContainer.find("#userlabel_changeprice").val();
var rManager = userInfoContainer.find("#userlabel_manager").val(); var rManager = userInfoContainer.find("#userlabel_manager").val();
var rClosing = userInfoContainer.find("#userlabel_closingright").val();
var data = { var data = {
userid: userid, userid: userid,
@ -1656,7 +1687,8 @@ function dynamicUserBinding() {
rReservation: rReservation, rReservation: rReservation,
rRating: rRating, rRating: rRating,
rChangeprice: rChangeprice, rChangeprice: rChangeprice,
rManager: rManager rManager: rManager,
rClosing: rClosing
}; };
doAjax("POST","php/contenthandler.php?module=admin&command=updateUser",data,askAndFillUserListNoData,"Benutzerdaten"); doAjax("POST","php/contenthandler.php?module=admin&command=updateUser",data,askAndFillUserListNoData,"Benutzerdaten");
}); });
@ -1711,14 +1743,11 @@ function reloadPage(dummyData) {
} }
function doCreateNewUser(result) { function doCreateNewUser(result) {
if (result == "exists") { if (result.status == "OK") {
alert ("Benutzer existiert bereits"); askAndFillUserList("OK");
} } else {
else if (result == "noadmin") { alert("Fehler: " + result.msg);
alert (MAN_NO_ADMIN_CREATE[lang]); }
} else {
askAndFillUserList("OK");
}
} }
function handleResultOfDbAction(jsonText) { function handleResultOfDbAction(jsonText) {
@ -1949,6 +1978,20 @@ function initroomfield(roomfield_json) {
var roomMap = new Roommap("#tablemaps"); var roomMap = new Roommap("#tablemaps");
} }
function golive() {
doAjax("POST","php/contenthandler.php?module=admin&command=golive",null,handleGoLive,"Produktivbetriebsstart");
}
function handleGoLive(answer) {
if (answer.status == "OK") {
alert(MAN_CONFIRM_GO_LIVE[lang]);
setTimeout(function(){document.location.href = "logout.php"},250);
} else {
alert("Error: " + answer.msg);
}
}
function roomfield_prefill() { function roomfield_prefill() {
var n = $("#maxrooms_val").val(); var n = $("#maxrooms_val").val();
var m = $("#maxtables_val").val(); var m = $("#maxtables_val").val();
@ -2051,12 +2094,10 @@ function insertPrintQueue(queue) {
$(document).on("pageinit", "#admin-page", function () { $(document).on("pageinit", "#admin-page", function () {
initializeMainMenu("#modulemenu"); initializeMainMenu("#modulemenu");
getGeneralConfigItems(); getGeneralConfigItems();
doAjax("GET","php/contenthandler.php?module=admin&command=isLoggedinUserAdminOrManager",null,hideElementsForNonAdminManagerUser,"Fehler"); doAjax("GET","php/contenthandler.php?module=admin&command=isLoggedinUserAdminOrManagerOrTE",null,showPanelsDueToUserStatus,"Fehler");
askAndFillUserList(); askAndFillUserList();
hideMenu(); hideMenu();
doAjax("GET","php/contenthandler.php?module=admin&command=isLoggedinUserAdmin",null,hideElementsForNonAdminUser,"Pruefe Adminberechtigung");
createYearPartFor("select-year","#yearselection",'#closinglist'); createYearPartFor("select-year","#yearselection",'#closinglist');
createYearPartFor("select-year-export-start","#yearselectionexportstart",'#dataexport'); createYearPartFor("select-year-export-start","#yearselectionexportstart",'#dataexport');
@ -2133,7 +2174,7 @@ $(document).on("pageinit", "#admin-page", function () {
</div><!-- closinglist --> </div><!-- closinglist -->
<div id="dataexport" data-role="collapsible" data-content-theme="c"> <div id="dataexport" data-role="collapsible" data-content-theme="c" style="display:none;">
<h3><span id="dataexporttxt">Datenexport</span></h3> <h3><span id="dataexporttxt">Datenexport</span></h3>
<p><span id="dataexportdettxt">Hier können Sie eine csv-Datei erzeugen lassen, die ... <p><span id="dataexportdettxt">Hier können Sie eine csv-Datei erzeugen lassen, die ...
</span> </span>
@ -2180,13 +2221,13 @@ $(document).on("pageinit", "#admin-page", function () {
</div> <!-- collapsible Abrechnung und Datenexport --> </div> <!-- collapsible Abrechnung und Datenexport -->
<div id="userpart" data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint"> <div id="userpart" data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" style="display:none;">
<h3><span id="usertxt">Benutzer</span></h3> <h3><span id="usertxt">Benutzer</span></h3>
<div id="userlist" data-role="collapsible" data-theme="c" data-content-theme="c"> <div id="userlist" data-role="collapsible" data-theme="c" data-content-theme="c">
</div> <!-- userlist --> </div> <!-- userlist -->
</div> <!-- Benutzer --> </div> <!-- Benutzer -->
<div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="configpart"> <div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="configpart" style="display:none;">
<h3><span id="configtxt">Konfiguration</span></h3> <h3><span id="configtxt">Konfiguration</span></h3>
<form action="#" method="get"> <form action="#" method="get">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
@ -2316,7 +2357,7 @@ $(document).on("pageinit", "#admin-page", function () {
<button type="submit" data-theme="f" data-icon="check" id="changeConfig">Ändern</button> <button type="submit" data-theme="f" data-icon="check" id="changeConfig">Ändern</button>
</form><!-- Konfiguration --> </form><!-- Konfiguration -->
<img id="logoimgpart" height="70px" src=php/contenthandler.php?module=printqueue&command=getLogoAsPng /> <img id="logoimgpart" height="70px" src="php/contenthandler.php?module=printqueue&command=getLogoAsPng" />
<form id="logoform" enctype="multipart/form-data" action="php/contenthandler.php?module=admin&command=readlogo" method="POST" data-ajax="false"> <form id="logoform" enctype="multipart/form-data" action="php/contenthandler.php?module=admin&command=readlogo" method="POST" data-ajax="false">
<input type="hidden" name="MAX_FILE_SIZE" value="16777210" /> <input type="hidden" name="MAX_FILE_SIZE" value="16777210" />
<span id=upllogotxt>Logo-Datei hochladen:</span> <span id=upllogotxt>Logo-Datei hochladen:</span>
@ -2329,13 +2370,18 @@ $(document).on("pageinit", "#admin-page", function () {
</form> </form>
</div> <!-- Konfiguration --> </div> <!-- Konfiguration -->
<div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="printerqueue"> <div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="printerqueue" style="display:none;">
<h3><span id="printjobsheader">Druckerwarteschlangen</span></h3> <h3><span id="printjobsheader">Druckerwarteschlangen</span></h3>
<p><div id=printjobsarea>Daten</div></p> <p><div id=printjobsarea>Daten</div>
<div><button type="submit" data-theme="f" data-icon="check" id="updateprintqueue">Refresh</button></div>
<div class="ui-grid-a" class="noprint">
<div class="ui-block-a"><button type="submit" data-theme="f" data-icon="check" id="updateprintqueue">Refresh</button></div>
<div class="ui-block-b"><button type="submit" data-theme="d" data-icon="delete" id="clearprintqueue">Clear print jobs</button></div>
</div><!-- /grid-a -->
</div> <!-- Druckerwarteschlangen --> </div> <!-- Druckerwarteschlangen -->
<div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="dbactionui"> <div data-role="collapsible" data-collapsed="true" data-theme="e" data-content-theme="c" class="noprint" id="dbactionui" style="display:none;">
<h3><span id="dbtxt">Datenbank</span></h3> <h3><span id="dbtxt">Datenbank</span></h3>
<div data-role="collapsible" data-collapsed="true" data-theme="f" data-content-theme="c" class="noprint" id="dbactionspeisenconfig"> <div data-role="collapsible" data-collapsed="true" data-theme="f" data-content-theme="c" class="noprint" id="dbactionspeisenconfig">
@ -2344,8 +2390,113 @@ $(document).on("pageinit", "#admin-page", function () {
<div class="ui-block-a"><button data-theme="e" data-icon="plus" id="readsamplemenu"><span id=samplemenutxt>Beispielkarte</span></button></div> <div class="ui-block-a"><button data-theme="e" data-icon="plus" id="readsamplemenu"><span id=samplemenutxt>Beispielkarte</span></button></div>
<div class="ui-block-b grid_right"><button type="submit" data-theme="f" class="applySpeisekarte" data-icon="check" id="readspeisekarte">Anwenden</button></div> <div class="ui-block-b grid_right"><button type="submit" data-theme="f" class="applySpeisekarte" data-icon="check" id="readspeisekarte">Anwenden</button></div>
</div><!-- /grid-a --> </div><!-- /grid-a -->
<div data-role="collapsible" data-collapsed="true" data-theme="e" data-collapsed-icon="info" data-expanded-icon="info" data-content-theme="c" class="noprint" id="menulegenddiv">
<p><h3><span id="legendheader">Legende</span></h3>
<h2>Aufbau der Speisekarte</h2>
<p>Die Syntax der Speisekarte ist sehr strikt. Das Format, insbesondere die Einrückungen, müssen genau
eingehalten werden, damit der Inhalt korrekt übernommen werden kann!
<h3>Struktur</h3>
<p>Einrückungen bilden das Produktangebot hierarchisch ab. Die tiefsten Einrückungen stellen die <i>Produkte</i> dar,
alle Eebenen darüber die <i>Kategorien</i>.
<p>Die einfachste Form einer Speisekarte (Angabe des Langnames und des Preises für alle Preisstufen) sieht folgendermaßen aus:
<pre>
Speisen
Gericht 1 ; 2,90
Gericht 2 ; 3,90
Untergruppe xy
Gericht 3 ; 2,90
Getränke
...
</pre>
<p>In diesem Beispiel wurde jedem Produkt ein Preis zugewiesen, der für alle Preisstufen verwendet wird. Kategorien und Produkte können zusätzlich noch weiter spezifiziert werden.
<h3>Produkteinträge</h3>
<p>Ein Produkteintrag hat in der einfachsten Schreibweise folgende Syntax: <i>Produktname; Preis</i>. Sollen jedoch weitere Eigenschaften
festgelegt werden, können diese hinter einem Doppelkreuz per Semikolon getrennt angegeben werden: <i>Produktname; Preis # Eigenschaft1:Wert1; Eigenschaft2: Wert2</i>.
<p>Folgende Eigenschaften können angegeben werden:
<ul>
<li><b>ID</b>: Eine ID wird vom System festgelegt, sobald ein Produkt erstmalig angelegt wurde. Wenn ein Produkt verändert wird,
so sollte man die ID-Kennzeichnung beibehalten. Nur so kann das System das Produkt eindeutig identifizieren und in der
Statistik später eindeutig zuordnen. Es ist wichtig, keine eigenen IDs zu vergeben, denn neue IDs werden stets
vom OrderSprinter erzeugt!
<li><b>Kurzname</b>: Der Kurzname ist die Produktbezeichnung, die auf dem Bestellterminal erscheint. Wenn beispielsweise die übergeordnete
Kategorie <i>Cola</i> lautet, kann man darunter Produkte mit den Kurznamen <i>0,3l</i> und <i>0,5l</i> eintragen und damit die Übersicht auf
mobilen Geräten verbessern. Der Langname sollte jedoch die komplette Bezeichnung enthalten (<i>Cola 0,2l</i> und <i>Cola 0,5l</i>). Wird
der Kurzname nicht angegeben, wird automatisch der Langname verwendet.
<li><b>vorhanden</b>: Wenn ein Produkt zwar in der Speisekarte eingetragen werden soll, jedoch temporär nicht verfügbar ist, kann man dies
kennzeichnen, indem man den Wert auf <i>0</i> oder <i>nein</i> setzt.
<li><b>PreisB</b>: Preis der Preisstufe B. Wird diese Eigenschaft nicht angegeben, wird der Preis A verwendet, d.h. der Preis vor dem Doppelkreuz.
<li><b>PreisC</b>: Preis der Preisstufe C. Wird diese Eigenschaft nicht angegeben, wird der Preis A verwendet, d.h. der Preis vor dem Doppelkreuz.
<li><b>Fixsteuersatz</b>: Es ist möglich, einem Produkt einen fixen Umsatzsteuersatz zuzuordnen, so dass das Produkt bei der Bestellung
unabhängig von der Zuordnung <i>Tischbestellung</i> oder <i>Außer-Haus-Bestellung</i> immer den hier zugeordneten Steuersatz zugeordnet
bekommt.
</ul>
<p>Ein Produkteintrag mit weiteren Eigenschaften kann beispielsweise so aussehen:
<pre>
Cola 0,2l; 2,30 # Kurzname: 0.2l; vorhanden:nein; PreisB: 1,90
</pre>
<h3>Kategorien</h3>
<p>Das Gleichheitszeichen dient als Trenner zwischen Namen und weiteren Eigenschaften.
Wird ein <i>K</i> und <i>B</i> 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 enthalten.
Hinter dem zweiten Gleichheitszeichen kann die Nummer eines Arbeitsbondruckers
des jeweiligen Typs (Speise/Getränk) angegeben werden.
<p>Wenn ein <i>D</i> angegeben ist, wird als Typ <b>Getränk</b> angenommen, bei einem <i>F</i> <b>Speise</b>.
Wenn die Angabe fehlt, wird die Eigenschaft des übergeordneten Eintrags verwendet.
<h3>Extras</h3>
<p>Extras werden mit einem Ausrufezeichen am Zeilenanfang deklariert. Nach dem Namen und der (vom OrderSprinter vergebenenen ID, die also
nicht vom Benutzer angegeben werden muss), können nach einem Semikolon die Produkte angegeben werden, die mit diesem Extra
verkauft werden dürfen. Zur Angabe eines Produktes kann man dessen Name oder in Klammern dessen ID verwenden. Ein Eintrag
hat demnach folgendes Aussehen (Beispiel):
<pre>
!Extraname (ID:8) 12,34 ; (45),Langname eines Produkts,(49),(50)
</pre>
<p>Dabei gilt:
<ul>
<li>Die ID-Angabe ist optional (kann weggelassen werden). Wenn OrderSprinter diese hinzugefügt hat, sollte man sie
beibehalten. Ein selbt erstellter neuer Extras-Eintrag sollte keine ID-Nummer enthalten.
<li>Der Wert 12,34 ist der Aufpreis.
<li>Hinter dem Semikolon wurden Komma-getrennt Produkte angegeben, die mit diesem Extra bestellt werden können, in diesem Fall
die Produkte mit der ID 45, 49 und 50 sowie ein Produkt mit dem Langnamen <i>Langname eines Produkts</i>.
</ul>
<p><i>Hinweis:</i> Gibt es den Langnamen mehrfach, wird das Extra auch mehrfach zugewiesen.
<h3>Reservierte Buchstaben</h3>
<p>Aus der beschriebenen Syntax ergibt sich, dass einige Buchstaben eine spezielle Bedeutung haben und nicht überall
verwendet werden dürfen:
<ul>
<li><b>#</b>: Ein Doppelkreuz zu Beginn einer Zeile leitet einen Kommentar ein, d.h. diese Zeile wird nicht interpretiert. Innerhalb
einer Zeile trennt das Doppelkreuz die Grundeigenschaften eines Produkts von den optionalen Eigenschaften.
<li><b>=</b>: Das Gleichheitszeichen hat bei einem Kategorieneintrag die Funktion eines Trennzeichens.
<li><b>;</b>: Das Semikolon wird bei einem Produkteintrag als Trenner der Eigenschaften verwendet.
<li><b>!</b>: Das Ausrufezeichen am Anfang einer Zeile leitet die Deklaration eines Extras ein.
</ul>
</div>
<textarea cols="40" rows="8" name="speiseninfo" id="speiseninfo" data-theme="a" style='font-family:"monospace"'></textarea> <textarea cols="40" rows="8" name="speiseninfo" id="speiseninfo" data-theme="a" style='font-family:"monospace"'></textarea>
</div> <!-- Speisekarte --> </div> <!-- Speisekarte -->
<p> <p>
@ -2413,7 +2564,7 @@ $(document).on("pageinit", "#admin-page", function () {
</div> </div>
</div> </div>
</p>
<p> <p>
<div data-role="collapsible" data-collapsed="true" data-theme="f" data-content-theme="c" class="noprint" id="dbactionbakrest"> <div data-role="collapsible" data-collapsed="true" data-theme="f" data-content-theme="c" class="noprint" id="dbactionbakrest">
<p><h3><span id="bakrestxt">Sicherung und Import</span></h3></p> <p><h3><span id="bakrestxt">Sicherung und Import</span></h3></p>
@ -2434,28 +2585,29 @@ $(document).on("pageinit", "#admin-page", function () {
<div id=restorearea> <div id=restorearea>
<form id="restoreform" enctype="multipart/form-data" action="php/contenthandler.php?module=admin&command=restore" method="POST" data-ajax="false"> <form id="restoreform" enctype="multipart/form-data" action="php/contenthandler.php?module=admin&command=restore" method="POST" data-ajax="false">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" /> <input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<span id=uplfiletxt>Diese Datei hochladen:</span> <span id=uplfiletxt>Diese Datei hochladen (<i>importieren</i>):</span>
<input name="userfile" id="userfile" type="file" /> <input name="userfile" id="userfile" type="file" />
<div id=restinfoafterclick></div> <div id=restinfoafterclick></div>
<input type="submit" data-theme="d" value="Importieren" id="restorebtntxt" formaction="php/contenthandler.php?module=admin&command=restore"/> <input type="submit" data-theme="d" value="Importieren" id="restorebtntxt" formaction="php/contenthandler.php?module=admin&command=restore"/>
</form> </form>
</div> </div>
<p><button type="submit" data-theme="d" id="golive"><span id="golivetxt">Starte Produktivbetrieb</span></button>
</div> </div>
</p>
<p> <p>
<form action="dummy" method="GET"> <form action="dummy" method="GET">
<button type="submit" data-theme="d" id="shutdown_btn"><span id="shutdownbtntxt">Shutdown</span></button> <button type="submit" data-theme="d" id="shutdown_btn"><span id="shutdownbtntxt">Shutdown</span></button>
</form> </form>
<div id="shutdownhinttxt"></div> <div id="shutdownhinttxt"></div>
</p>
</div> <!-- collapsible Datenbank --> </div> <!-- collapsible Datenbank -->
<div id="tableforprint" class="printpart">Wenn dieser Text dargestellt wird, liegt ein Fehler vor!</div> <div id="tableforprint" class="printpart">Wenn dieser Text dargestellt wird, liegt ein Fehler vor!</div>
<div id="printserverdownloadpart" style="display:none;">
<a class="noprint" href="OrderSprinterPrintserver.exe" data-role="button" data-icon="arrow-d" data-ajax="false">Download Printserver</a> <a class="noprint" href="OrderSprinterPrintserver.exe" data-role="button" data-icon="arrow-d" data-ajax="false">Download Printserver</a>
</div> <!-- printerdownloadpart -->
<div data-role="footer" data-theme="b" id="thefooterr" class="noprint"> <div data-role="footer" data-theme="b" id="thefooterr" class="noprint">
<div class="ui-grid-a"> <div class="ui-grid-a">
<div class="ui-block-a userinfo" id="loggedinuser"></div> <div class="ui-block-a userinfo" id="loggedinuser"></div>
@ -2465,7 +2617,7 @@ $(document).on("pageinit", "#admin-page", function () {
</div> </div>
<div data-role="popup" id="nochangeddata" name="nochangeddata" data-overlay-theme="a" style="max-width:70%;" class="ui-corner-all"> <div data-role="popup" id="nochangeddata" data-overlay-theme="a" style="max-width:70%;" class="ui-corner-all">
<div data-role="header" class="ui-corner-top"> <div data-role="header" class="ui-corner-top">
<h1>Keine Datenänderung</h1> <h1>Keine Datenänderung</h1>
</div> </div>

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
<?php <?php
// Datenbank-Verbindungsparameter // Datenbank-Verbindungsparameter
require_once ('dbutils.php'); require_once ('dbutils.php');
require_once ('commonutils.php'); require_once ('commonutils.php');
require_once ('globals.php'); require_once ('globals.php');
require_once ('admin.php'); require_once ('admin.php');
@ -16,8 +16,8 @@ require_once 'translations.php';
} }
function handleCommand($command) { function handleCommand($command) {
// all commands require manager rights // all commands require closing,manager or admin rights
if (!($this->hasCurrentUserManagerOrAdminRights())) { if (!($this->hasCurrentUserManagerOrAdminOrClosingRights())) {
if ($command != 'exportCsv') { if ($command != 'exportCsv') {
echo json_encode(array("status" => "ERROR", "code" => ERROR_MANAGER_NOT_AUTHOTRIZED, "msg" => ERROR_MANAGER_NOT_AUTHOTRIZED_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_MANAGER_NOT_AUTHOTRIZED, "msg" => ERROR_MANAGER_NOT_AUTHOTRIZED_MSG));
} else { } else {
@ -32,7 +32,7 @@ if($command == 'createClosing') {
$this->createClosing($_POST['remark']); $this->createClosing($_POST['remark']);
} else if ($command == 'getClosings') { } else if ($command == 'getClosings') {
$this->getClosings($_GET['month'], $_GET['year']); $this->getClosings($_GET['month'], $_GET['year']);
} else if ($command == 'exportCsv') { } else if ($command == 'exportCsv') {
$this->exportCsv($_GET['closingid']); $this->exportCsv($_GET['closingid']);
} else if ($command == 'emailCsv') { } else if ($command == 'emailCsv') {
$this->emailCsv($_GET['closingid'],$_GET['emailaddress'],$_GET['topic']); $this->emailCsv($_GET['closingid'],$_GET['emailaddress'],$_GET['topic']);
@ -45,23 +45,23 @@ echo "Command not supported.";
} }
} }
private function hasCurrentUserManagerOrAdminRights() { private function hasCurrentUserManagerOrAdminOrClosingRights() {
session_start(); session_start();
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in // no user logged in
return false; return false;
} else { } else {
return ($_SESSION['right_manager'] || $_SESSION['is_admin']); return ($_SESSION['right_manager'] || $_SESSION['right_closing'] || $_SESSION['is_admin']);
} }
} }
private function getDecPoint() { private function getDecPoint() {
$sql = "SELECT name,setting FROM %config% WHERE name=?"; $sql = "SELECT name,setting FROM %config% WHERE name=?";
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array("decpoint")); $stmt->execute(array("decpoint"));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
return($row->setting); return($row->setting);
} }
private function createClosing ($remark) { private function createClosing ($remark) {
@ -73,14 +73,14 @@ $decpoint = $this->getDecPoint();
// first create a closing entry // 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'); $closingTime = date('Y-m-d H:i:s');
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction(); $pdo->beginTransaction();
$closingEntrySql = "INSERT INTO `%closing%` (`id` , `closingdate`,`remark`,`billcount`,`billsum`,`signature`) VALUES (NULL ,?,?,?,?,?)"; $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)); $stmt->execute(array($closingTime,$remark,0,0.0,null));
$newClosingId = $pdo->lastInsertId(); $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') "; $sql = "SELECT id FROM %bill% WHERE closingid is null AND (tableid >= '0' OR status='c') ";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
$result = $stmt->fetchAll(); $result = $stmt->fetchAll();
$utils = new CommonUtils(); $utils = new CommonUtils();
$ok = true; $ok = true;
foreach($result as $row) { foreach($result as $row) {
$aBillId = $row['id']; $aBillId = $row['id'];
if (!$utils->verifyBill($pdo, $aBillId)) { if (!$utils->verifyBill($pdo, $aBillId)) {
$ok=false; $ok=false;
break; break;
} }
} }
if (!$ok) { if (!$ok) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG));
return; return;
@ -110,17 +110,17 @@ $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($declareClose
$stmt->execute(); $stmt->execute();
$sql ="SELECT count(id) as billstotake FROM %bill% WHERE closingid=? AND (tableid >= '0' OR status='c')"; $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)); $stmt->execute(array($newClosingId));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$billsToTake = $row->billstotake; $billsToTake = $row->billstotake;
$pricesum = null; $pricesum = null;
// now calculate the sum of the prices of this closing // now calculate the sum of the prices of this closing
if ($billsToTake > 0) { if ($billsToTake > 0) {
$sql = "SELECT sum(brutto) as pricesum FROM %bill% WHERE closingid=? AND (tableid >= '0' OR status='c')"; $sql = "SELECT sum(brutto) as pricesum 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)); $stmt->execute(array($newClosingId));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$pricesum = $row->pricesum; $pricesum = $row->pricesum;
} }
@ -142,7 +142,7 @@ openssl_free_key($pkeyid);
// now add values to closing table to prepare for electronic signature // now add values to closing table to prepare for electronic signature
$sql = "UPDATE %closing% SET billcount=?, billsum=?,signature=? WHERE id=?"; $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)); $stmt->execute(array($billsToTake,$pricesum,$signature,$newClosingId));
// now clean the extras that are assigned to queue - we do not need them anymore // 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 = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $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 = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
@ -212,8 +212,8 @@ $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($closingid)); $stmt->execute(array($closingid));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$numberOfReturns = $row->countid; $numberOfReturns = $row->countid;
$sum = 0.0; $sum = 0.0;
if ($numberOfReturns > 0) { if ($numberOfReturns > 0) {
$sum = floatval($row->billsum); $sum = floatval($row->billsum);
} }
@ -269,7 +269,7 @@ $monthText = "0" . $month;
$lastDayInMonth = date("t", mktime(0, 0, 0, $month, 1, $year)); $lastDayInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
$dateStart = $year . $monthText . "01"; $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;"; $sql = "SELECT id,closingdate,remark FROM %closing% WHERE DATE(closingdate) BETWEEN ? AND ? ORDER BY closingdate DESC;";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($dateStart,$dateEnd)); $stmt->execute(array($dateStart,$dateEnd));
@ -286,7 +286,7 @@ $taxessums = $this->getTaxesGroupedOfClosing($pdo,$theId);
$cashops = $this->getCashOpsOfClosing($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); $closingEntry = array("id" => $theId, "closingDate" => $closingDate, "remark" => $remark, "totalsum" => $totalSum, "cashsum" => $cashSum, "usersums" => $userSums, "taxessums" => $taxessums,"cashops" => $cashops);
$resultarray[] = $closingEntry; $resultarray[] = $closingEntry;
} }
echo json_encode(array("status" => "OK", "msg" => $resultarray)); 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) { 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"; $topictxt = $topic . " " . $closingid . "\r\n";
if (Emailer::sendEmail($pdo, $msg, $toEmail, $topictxt)) { if (Emailer::sendEmail($pdo, $msg, $toEmail, $topictxt)) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
private function emailCsv($closingid,$toEmail,$topic) { private function emailCsv($closingid,$toEmail,$topic) {
// additional info to insert into email // additional info to insert into email
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint();
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$prevClosingDate = self::getDateOfPreviousClosing($pdo,$closingid); $prevClosingDate = self::getDateOfPreviousClosing($pdo,$closingid);
if (is_null($prevClosingDate)) { if (is_null($prevClosingDate)) {
$prevClosingDate = ""; $prevClosingDate = "";
} }
$sql = "SELECT closingdate, billcount, billsum FROM %closing% WHERE id=?"; $sql = "SELECT closingdate, billcount, billsum FROM %closing% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($closingid)); $stmt->execute(array($closingid));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$billsum = number_format($row->billsum, 2, $decpoint, ''); $billsum = number_format($row->billsum, 2, $decpoint, '');
$billcount = $row->billcount; $billcount = $row->billcount;
$closdate = $row->closingdate; $closdate = $row->closingdate;
if ($this->emailCsvCore($pdo,$closingid, $toEmail, $topic, $prevClosingDate,$closdate,$billsum,$billcount)) { if ($this->emailCsvCore($pdo,$closingid, $toEmail, $topic, $prevClosingDate,$closdate,$billsum,$billcount)) {
echo json_encode(array("status" => "OK")); echo json_encode(array("status" => "OK"));
} else { } else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_EMAIL_FAILURE, "msg" => ERROR_EMAIL_FAILURE_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_EMAIL_FAILURE, "msg" => ERROR_EMAIL_FAILURE_MSG));
} }
} }
private function getGeneralItemFromDb($field) { private function getGeneralItemFromDb($field) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$this->getGeneralItemFromDbWithPdo($pdo, $field); $this->getGeneralItemFromDbWithPdo($pdo, $field);
} }
private function getGeneralItemFromDbWithPdo($pdo,$field) { private function getGeneralItemFromDbWithPdo($pdo,$field) {
if (is_null($pdo)) { if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
} }
$aValue=""; $aValue="";
$sql = "SELECT setting FROM %config% where name='$field'"; $sql = "SELECT setting FROM %config% where name='$field'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$aValue = $row->setting; $aValue = $row->setting;
} }
return $aValue; return $aValue;
} }
public static function getDateOfPreviousClosing($pdoval,$closingid) { public static function getDateOfPreviousClosing($pdoval,$closingid) {
@ -380,43 +380,43 @@ $pdo = $pdoval;
// ids can be generated but not used in case of rollback // ids can be generated but not used in case of rollback
$sql = "SELECT MAX(id) as previousid FROM %closing% WHERE id<?"; $sql = "SELECT MAX(id) as previousid FROM %closing% WHERE id<?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($closingid)); $stmt->execute(array($closingid));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$previousId = intval($row->previousid); $previousId = intval($row->previousid);
$sql = "SELECT closingdate FROM %closing% WHERE id=?"; $sql = "SELECT closingdate FROM %closing% WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($previousId)); $stmt->execute(array($previousId));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
return $row->closingdate; return $row->closingdate;
} else { } else {
return null; return null;
} }
} else { } else {
return null; return null;
} }
} }
private function returnErrorInconsDB($doCsvExport,$onlyresultreturn) { private function returnErrorInconsDB($doCsvExport,$onlyresultreturn) {
if ($doCsvExport) { if ($doCsvExport) {
echo "ERROR - signatures do not fit"; echo "ERROR - signatures do not fit";
} else if ($onlyresultreturn) { } else if ($onlyresultreturn) {
return "Tagesabschluss-Datum: $closingdate\nBemerkung: $remark\nStatus: Inkonsistente Datenbank\n\ncsv-Daten:\n" . $csv; return "Tagesabschluss-Datum: $closingdate\nBemerkung: $remark\nStatus: Inkonsistente Datenbank\n\ncsv-Daten:\n" . $csv;
} else { } else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG));
} }
} }
private function retrieveClosingFromDb($pdo,$closingid,$doCsvExport,$onlyresultreturn) { private function retrieveClosingFromDb($pdo,$closingid,$doCsvExport,$onlyresultreturn) {
if(session_id() == '') { if(session_id() == '') {
session_start(); session_start();
} }
$l = $_SESSION['language']; $l = $_SESSION['language'];
$commonUtils = new CommonUtils(); $commonUtils = new CommonUtils();
$currency = $commonUtils->getCurrency(); $currency = $commonUtils->getCurrency();
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint();
@ -425,22 +425,22 @@ $previousClosingDate = self::getDateOfPreviousClosing(null,$closingid);
$csv = ""; $csv = "";
if ($doCsvExport || $onlyresultreturn) { if ($doCsvExport || $onlyresultreturn) {
$file_name = "tagesabschluss.csv"; $file_name = "tagesabschluss.csv";
header("Content-type: text/x-csv"); header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$file_name"); header("Content-Disposition: attachment; filename=$file_name");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache"); header("Pragma: no-cache");
header("Expires: 0"); header("Expires: 0");
$csv .= $this->t['ID'][$l] . ";" . $this->t['Date'][$l] . ";" . $this->t['Prod'][$l] . ";" . $this->t['Brutto'][$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['Netto'][$l] . "($currency);";
$csv .= $this->t['Tax'][$l] . ";"; $csv .= $this->t['Tax'][$l] . ";";
$csv .= $this->t['PayWay'][$l] . ";"; $csv .= $this->t['PayWay'][$l] . ";";
$csv .= $this->t['Userid'][$l] . ";"; $csv .= $this->t['Userid'][$l] . ";";
$csv .= $this->t['User'][$l] . ";"; $csv .= $this->t['User'][$l] . ";";
$csv .= $this->t['State'][$l] . ";"; $csv .= $this->t['State'][$l] . ";";
$csv .= $this->t['Ref'][$l] . "\n"; $csv .= $this->t['Ref'][$l] . "\n";
} }
$sql = "SELECT closingdate,remark,signature,billsum,billcount FROM %closing% WHERE id=?"; $sql = "SELECT closingdate,remark,signature,billsum,billcount FROM %closing% WHERE id=?";
@ -460,29 +460,29 @@ $billIdsAndPaymentsForThatClosing = $stmt->fetchAll();
$foundBillCount = count($billIdsAndPaymentsForThatClosing); $foundBillCount = count($billIdsAndPaymentsForThatClosing);
if (is_null($previousClosingDate)) { if (is_null($previousClosingDate)) {
$startDate = ""; $startDate = "";
} else { } else {
$startDate = $previousClosingDate; $startDate = $previousClosingDate;
} }
$billsumstr = number_format($billsum, 2, ".", ''); $billsumstr = number_format($billsum, 2, ".", '');
$data = "I($closingid)-S($startDate)-E($closingdate)-D($billcount)-S($billsumstr)"; $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); $ok = openssl_verify($data, $signature, $pubkeyid);
openssl_free_key($pubkeyid); openssl_free_key($pubkeyid);
if (($ok == 0) || ($billcount <> $foundBillCount)) { if (($ok == 0) || ($billcount <> $foundBillCount)) {
// something went wrong! // something went wrong!
$this->returnErrorInconsDB($doCsvExport, $onlyresultreturn); $this->returnErrorInconsDB($doCsvExport, $onlyresultreturn);
return; return;
} }
$retValues = array(); $retValues = array();
for ($index=0;$index < count($billIdsAndPaymentsForThatClosing);$index++) { for ($index=0;$index < count($billIdsAndPaymentsForThatClosing);$index++) {
$aBillId = $billIdsAndPaymentsForThatClosing[$index]['id']; $aBillId = $billIdsAndPaymentsForThatClosing[$index]['id'];
if (!$commonUtils->verifyBill($pdo, $aBillId)) { if (!$commonUtils->verifyBill($pdo, $aBillId)) {
$this->returnErrorInconsDB($doCsvExport, $onlyresultreturn); $this->returnErrorInconsDB($doCsvExport, $onlyresultreturn);
return; return;
} }
@ -497,46 +497,46 @@ $tax = $billIdsAndPaymentsForThatClosing[$index]['tax'];
$ref = $billIdsAndPaymentsForThatClosing[$index]['ref']; $ref = $billIdsAndPaymentsForThatClosing[$index]['ref'];
$ref = ($ref == null ? "" : $ref); $ref = ($ref == null ? "" : $ref);
if ($status == 'c') { if ($status == 'c') {
$statusTxt = $this->t['cashact'][$l]; // "Bareinlage/-entnahme"; $statusTxt = $this->t['cashact'][$l]; // "Bareinlage/-entnahme";
$brutto = number_format($brutto, 2, $decpoint, ''); $brutto = number_format($brutto, 2, $decpoint, '');
$netto = number_format($netto, 2, $decpoint, ''); $netto = number_format($netto, 2, $decpoint, '');
$tax = number_format($tax, 2, $decpoint, ''); $tax = number_format($tax, 2, $decpoint, '');
$retValues[] = array ( $retValues[] = array (
"billid" => $aBillId, "billid" => $aBillId,
"paidtime" => $billdate, "paidtime" => $billdate,
"productname" => $this->t['cashaction'][$l], // Kassenaktion "productname" => $this->t['cashaction'][$l], // Kassenaktion
"price" => $brutto, "price" => $brutto,
"netto" => $netto, "netto" => $netto,
"tax" => number_format(0.00, 2, $decpoint, ''), "tax" => number_format(0.00, 2, $decpoint, ''),
"payment" => $paymentArray[$paymentid], "payment" => $paymentArray[$paymentid],
"userid" => $userid, "userid" => $userid,
"username" => $username, "username" => $username,
"status" => $statusTxt, "status" => $statusTxt,
"ref" => $ref); "ref" => $ref);
if ($doCsvExport || $onlyresultreturn) { 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 { } else {
$sql = "SELECT DISTINCT productname,price,%queue%.tax as tax FROM %queue%,%billproducts% WHERE %billproducts%.billid=? AND %billproducts%.queueid=%queue%.id"; $sql = "SELECT DISTINCT productname,price,%queue%.tax as tax FROM %queue%,%billproducts% WHERE %billproducts%.billid=? AND %billproducts%.queueid=%queue%.id";
if ($status == 'x') { if ($status == 'x') {
$statusTxt = $this->t["laterCancelled"][$l]; $statusTxt = $this->t["laterCancelled"][$l];
} else if ($status == 's') { } else if ($status == 's') {
$statusTxt = $this->t["storno"][$l]; $statusTxt = $this->t["storno"][$l];
} else { } else {
$statusTxt = ""; $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 = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($aBillId)); $stmt->execute(array($aBillId));
$result = $stmt->fetchAll(); $result = $stmt->fetchAll();
foreach ($result as $zeile) { foreach ($result as $zeile) {
$productname = $zeile['productname']; $productname = $zeile['productname'];
$tax = $zeile['tax']; $tax = $zeile['tax'];
$paidtime = ($billdate == null ? "" : $billdate) ; $paidtime = ($billdate == null ? "" : $billdate) ;
$price = ($status == 's' ? 0.0-floatval($zeile['price']) : $zeile['price']); $price = ($status == 's' ? 0.0-floatval($zeile['price']) : $zeile['price']);
$netto = $price/(1 + $tax/100.0); $netto = $price/(1 + $tax/100.0);
@ -559,9 +559,9 @@ $retValues[] = array (
$productname = str_replace('"','""',$productname); $productname = str_replace('"','""',$productname);
if ($doCsvExport || $onlyresultreturn) { if ($doCsvExport || $onlyresultreturn) {
$csv .= "$aBillId; \"$paidtime\" ; \"$productname\" ; \"$price\" ; \"$netto\" ; \"$formattedtax\" ; \"$paymentArray[$paymentid]\"; $userid; \"$username\"; \"$statusTxt\"; $ref\n"; $csv .= "$aBillId; \"$paidtime\" ; \"$productname\" ; \"$price\" ; \"$netto\" ; \"$formattedtax\" ; \"$paymentArray[$paymentid]\"; $userid; \"$username\"; \"$statusTxt\"; $ref\n";
}
} }
} }
}
} }
if ($doCsvExport) { if ($doCsvExport) {
echo $csv; echo $csv;
@ -655,6 +655,6 @@ echo json_encode(array("status" => "OK", "msg" => $retVal));
return $retVal; return $retVal;
} }
} }
} }
?> ?>

View File

@ -59,31 +59,31 @@ class DbUtils {
return $pdo; return $pdo;
} }
function openDbAndReturnPdo () { function openDbAndReturnPdo () {
$dsn = 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB; $dsn = 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB;
$user = MYSQL_USER; $user = MYSQL_USER;
$password = MYSQL_PASSWORD; $password = MYSQL_PASSWORD;
$pdo = null; $pdo = null;
try { try {
$pdo = new PDO($dsn, $user, $password); $pdo = new PDO($dsn, $user, $password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} }
catch (PDOException $e) { catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage(); echo 'Connection failed: ' . $e->getMessage();
} }
return $pdo; return $pdo;
} }
function testDbAccess($host,$dbname,$user,$pass) { function testDbAccess($host,$dbname,$user,$pass) {
$dsn = 'mysql:host=' . $host . ';dbname=' . $dbname; $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;
$user = $user; $user = $user;
$password = $pass; $password = $pass;
$pdo = null; $pdo = null;
try { try {
$pdo = new PDO($dsn, $user, $password); $pdo = new PDO($dsn, $user, $password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} }
catch (PDOException $e) { catch (PDOException $e) {
// //
} }
if ($pdo != null) { if ($pdo != null) {
return true; return true;
@ -155,5 +155,54 @@ class DbUtils {
return self::$timezone; 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)
);
} }
?> ?>

View File

@ -8,13 +8,13 @@ define ( 'ERROR_NOT_AUTHOTRIZED', '2' );
define ( 'ERROR_BILL_NOT_AUTHOTRIZED', '3'); define ( 'ERROR_BILL_NOT_AUTHOTRIZED', '3');
define ( 'ERROR_BILL_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Bons)'); 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_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_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_PRODUCTS_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Produktangebot)');
define ( 'ERROR_BILL_NOT_STORNO_CODE', '7'); 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', '10');
define ( 'ERROR_BILL_ALREADY_CLOSED_MSG', 'Bon schon in Tagesabschluss'); 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_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_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_PAYDESK_SUM_MSG', 'Aktueller Kassenbestand nicht ermittelbar');
define ( 'ERROR_GENERAL_ID_TYPE', '14'); define ( 'ERROR_GENERAL_ID_TYPE', '14');
define ( 'ERROR_GENERAL_ID_TYPE_MSG', 'Falscher Typ des Referenzschluessels'); 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_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_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_EMAIL_FAILURE_MSG', 'Emailversand fehlgeschlagen');
define ( 'ERROR_INCONSISTENT_DB', '17'); define ( 'ERROR_INCONSISTENT_DB', '17');
define ( 'ERROR_INCONSISTENT_DB_MSG', 'Inkonsistente Datenbank'); 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_RES_NOT_AUTHOTRIZED_MSG', 'Fehlende Benutzerrechte (Reservierung)');
define ( 'ERROR_DB_PRIVS_MISSING', '19'); 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 ( 'FOOD_PRINT_TYPE', 1);
define ( 'DRINK_PRINT_TYPE', 2); define ( 'DRINK_PRINT_TYPE', 2);
define ( 'PAY_PRINT_TYPE', 3); 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');
?> ?>

View File

@ -7,18 +7,18 @@ require_once ('bill.php');
require_once ('closing.php'); require_once ('closing.php');
class PrintQueue { class PrintQueue {
var $dbutils; var $dbutils;
var $userrights; var $userrights;
var $admin; var $admin;
function __construct() { function __construct() {
$this->dbutils = new DbUtils(); $this->dbutils = new DbUtils();
$this->userrights = new Userrights(); $this->userrights = new Userrights();
$this->admin = new Admin(); $this->admin = new Admin();
} }
function handleCommand($command) { function handleCommand($command) {
// these command are only allowed for user with waiter rights // these command are only allowed for user with waiter rights
if ($command == 'getNextReceiptPrintJobs') { if ($command == 'getNextReceiptPrintJobs') {
// REM* feature level // REM* feature level
$fl = null; $fl = null;
@ -59,10 +59,16 @@ class PrintQueue {
} else if ($command == 'getLogoAsWbmp') { } else if ($command == 'getLogoAsWbmp') {
$this->getLogoAsWbmp(); $this->getLogoAsWbmp();
} else if ($command == 'getPrintJobOverview') { } 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 { } else {
echo "Kommando nicht erkannt!"; echo "Kommando nicht erkannt!";
} }
} }
function testConnection($md5pass) { function testConnection($md5pass) {
@ -96,7 +102,7 @@ class PrintQueue {
$stmt->execute(array($content,intval($kind) + 1,$printer)); $stmt->execute(array($content,intval($kind) + 1,$printer));
} }
function getPrintJobOverview() { function getPrintJobOverview($pdo) {
if (!($this->userrights->hasCurrentUserRight('right_manager')) && if (!($this->userrights->hasCurrentUserRight('right_manager')) &&
!($this->userrights->hasCurrentUserRight('is_admin')) !($this->userrights->hasCurrentUserRight('is_admin'))
) { ) {
@ -104,8 +110,6 @@ class PrintQueue {
return; return;
} }
$pdo = DbUtils::openDbAndReturnPdoStatic();
$jobs = array(); $jobs = array();
for ($printer=1;$printer<7;$printer++) { for ($printer=1;$printer<7;$printer++) {
// bills: // bills:
@ -128,6 +132,60 @@ class PrintQueue {
echo json_encode(array("status" => "OK", "msg" => $jobs)); 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) { function queueReceiptPrintJob($billid) {
// waiter, or manager, bill, admin rights required // waiter, or manager, bill, admin rights required
if (!($this->userrights->hasCurrentUserRight('right_paydesk')) && if (!($this->userrights->hasCurrentUserRight('right_paydesk')) &&
@ -162,6 +220,7 @@ class PrintQueue {
if (!($this->userrights->hasCurrentUserRight('right_paydesk')) && if (!($this->userrights->hasCurrentUserRight('right_paydesk')) &&
!($this->userrights->hasCurrentUserRight('right_manager')) && !($this->userrights->hasCurrentUserRight('right_manager')) &&
!($this->userrights->hasCurrentUserRight('right_bill')) && !($this->userrights->hasCurrentUserRight('right_bill')) &&
!($this->userrights->hasCurrentUserRight('right_closing')) &&
!($this->userrights->hasCurrentUserRight('right_waiter')) && !($this->userrights->hasCurrentUserRight('right_waiter')) &&
!($this->userrights->hasCurrentUserRight('is_admin')) !($this->userrights->hasCurrentUserRight('is_admin'))
) { ) {
@ -191,14 +250,14 @@ class PrintQueue {
} }
function isPasswordCorrect($pass,$verbose) { function isPasswordCorrect($pass,$verbose) {
$sql = "SELECT setting FROM %config% WHERE name=?"; $sql = "SELECT setting FROM %config% WHERE name=?";
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array("printpass")); $stmt->execute(array("printpass"));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$passInDb = $row->setting; $passInDb = $row->setting;
if ($passInDb != null) { if ($passInDb != null) {
// plain comparison // plain comparison
if ($pass == $passInDb) { if ($pass == $passInDb) {
@ -207,12 +266,12 @@ class PrintQueue {
if ($verbose) { if ($verbose) {
echo "Error: Falscher Printpass!"; echo "Error: Falscher Printpass!";
} }
} }
} else { } else {
if ($verbose) { if ($verbose) {
echo "Error: kein Printpass in DB gesetzt!"; echo "Error: kein Printpass in DB gesetzt!";
} }
} }
} }
if ($verbose) { if ($verbose) {
echo "Error: DB konnte nicht abgefragt werden!"; echo "Error: DB konnte nicht abgefragt werden!";
@ -400,11 +459,11 @@ class PrintQueue {
function deletePrintJob($pass,$id) { function deletePrintJob($pass,$id) {
$isCorrect = $this->isPasswordCorrect($pass,false); $isCorrect = $this->isPasswordCorrect($pass,false);
if ($isCorrect) { if ($isCorrect) {
$sql = "DELETE FROM %printjobs% WHERE id=?"; $sql = "DELETE FROM %printjobs% WHERE id=?";
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($id)); $stmt->execute(array($id));
echo json_encode(array("status" => "OK", "code" => OK, "msg" => "Druckauftrag erfolgreich gelöscht.")); echo json_encode(array("status" => "OK", "code" => OK, "msg" => "Druckauftrag erfolgreich gelöscht."));
} else { } else {

View File

@ -6,6 +6,7 @@ require_once ('commonutils.php');
require_once ('utilities/userrights.php'); require_once ('utilities/userrights.php');
require_once ('utilities/HistFiller.php'); require_once ('utilities/HistFiller.php');
require_once ('utilities/sorter.php'); require_once ('utilities/sorter.php');
require_once ('utilities/TypeAndProducts/ProductEntry.php');
class Products { class Products {
var $dbutils; var $dbutils;
@ -57,9 +58,10 @@ class Products {
$this->getMenuLevelUp($_GET['ref']); $this->getMenuLevelUp($_GET['ref']);
} else if ($command == 'getSpeisekarte') { } else if ($command == 'getSpeisekarte') {
if ($this->userrights->hasCurrentUserRight('is_admin') || ($this->userrights->hasCurrentUserRight('right_manager'))) { if ($this->userrights->hasCurrentUserRight('is_admin') || ($this->userrights->hasCurrentUserRight('right_manager'))) {
$this->getSpeisekarte(); $pdo = DbUtils::openDbAndReturnPdoStatic();
echo json_encode($this->getSpeisekarte($pdo));
} else { } 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') { } else if ($command == 'exportCsv') {
if (($this->userrights->hasCurrentUserRight('is_admin')) if (($this->userrights->hasCurrentUserRight('is_admin'))
@ -109,8 +111,6 @@ class Products {
$this->getPriceLevelInfo(); $this->getPriceLevelInfo();
} else if ($command == 'setPriceLevelInfo') { } else if ($command == 'setPriceLevelInfo') {
$this->setPriceLevelInfo($_POST['priceLevelId']); $this->setPriceLevelInfo($_POST['priceLevelId']);
} else if ($command == 'getSpeisekarte') {
$this->getSpeisekarte();
} else if ($command == 'getAudioFiles') { } else if ($command == 'getAudioFiles') {
$this->getAudioFiles(); $this->getAudioFiles();
} else if ($command == 'addGeneralComment') { } else if ($command == 'addGeneralComment') {
@ -389,7 +389,7 @@ class Products {
function readDbProducts($pdo) { function readDbProducts($pdo) {
$speisekarte = $this->readDbProductsWithRef_json_version($pdo,0,0); $speisekarte = $this->readDbProductsWithRef_json_version($pdo,0,0);
$speisekarte .= $this->readExtrasFromDb(null); $speisekarte .= $this->readExtrasFromDb($pdo);
return $speisekarte; return $speisekarte;
} }
@ -402,7 +402,7 @@ class Products {
$stmt->execute(); $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ); $result = $stmt->fetchAll(PDO::FETCH_OBJ);
$extrasTxt = ""; $extrasTxt = "";
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint($pdo);
foreach ($result as $aRes) { foreach ($result as $aRes) {
$extrasTxt .= "!" . $aRes->name . " (ID:" . $aRes->id . ") #" ; $extrasTxt .= "!" . $aRes->name . " (ID:" . $aRes->id . ") #" ;
$priceTxt = number_format($aRes->price, 2, $decpoint, ''); $priceTxt = number_format($aRes->price, 2, $decpoint, '');
@ -423,9 +423,8 @@ class Products {
return $extrasTxt; return $extrasTxt;
} }
private function getDecPoint() { private function getDecPoint($pdo) {
$sql = "SELECT name,setting FROM %config% WHERE name=?"; $sql = "SELECT name,setting FROM %config% WHERE name=?";
$pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array("decpoint")); $stmt->execute(array("decpoint"));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
@ -435,7 +434,7 @@ class Products {
private function exportCsv() { private function exportCsv() {
$pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo = DbUtils::openDbAndReturnPdoStatic();
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint($pdo);
$file_name = "datenexport-produkte.csv"; $file_name = "datenexport-produkte.csv";
header("Content-type: text/x-csv"); header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$file_name"); header("Content-Disposition: attachment; filename=$file_name");
@ -913,11 +912,8 @@ class Products {
if ($changeExtras == 1) { if ($changeExtras == 1) {
$this->changeExtraAssignment($pdo, $id, $extras); $this->changeExtraAssignment($pdo, $id, $extras);
} }
$histextra = self::getExtrasForProd($pdo,$id);
// now this has to be logged in the history tables... // now this has to be logged in the history tables...
$this->histfiller->updateProdInHist($pdo,$id, $shortname, $longname, $priceA, $priceB, $priceC, $tax, HistFiller::updateProdInHist($pdo,$id);
NULL, $available,$audioFile,$favorite,$histextra);
} else { } else {
$prodids = self::getAllProdIdOfSameTypeAndBelow($pdo,$id); $prodids = self::getAllProdIdOfSameTypeAndBelow($pdo,$id);
@ -934,14 +930,7 @@ class Products {
} }
private static function updateHistOnlyForExtrasOfProd($pdo,$aProdId,$histextra) { private static function updateHistOnlyForExtrasOfProd($pdo,$aProdId,$histextra) {
$sql = "SELECT shortname,longname,priceA,priceB,priceC,tax,available,audio,favorite FROM %products% WHERE id=?"; HistFiller::updateProdInHist($pdo, $aProdId);
$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);
} }
function changeExtraAssignment($pdo,$prodid,$extras) { function changeExtraAssignment($pdo,$prodid,$extras) {
@ -1037,9 +1026,7 @@ class Products {
$pdo->commit(); $pdo->commit();
// now this has to be logged in the history tables... // now this has to be logged in the history tables...
HistFiller::createProdInHist($pdo, $newProdId);
$this->histfiller->createProdInHist ($pdo,$newProdId, $shortname, $longname, $priceA, $priceB, $priceC,$tax,
NULL, $available,$audioFile,$favorite);
echo json_encode("OK: sql"); echo json_encode("OK: sql");
} }
@ -1119,9 +1106,8 @@ class Products {
// return in text format // return in text format
private function readDbProductsWithRef_json_version($pdo,$ref,$depth) { private function readDbProductsWithRef_json_version($pdo,$ref,$depth) {
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint($pdo);
$text = ""; $text = "";
$allProdsAndTypesInThisLevel = array();
$allProdsInThisLevel = $this->getProductsWithReferenz($pdo,$ref); $allProdsInThisLevel = $this->getProductsWithReferenz($pdo,$ref);
$allTypesInThisLevel = $this->getProdTypesWithReferenz($pdo,$ref); $allTypesInThisLevel = $this->getProdTypesWithReferenz($pdo,$ref);
@ -1130,33 +1116,8 @@ class Products {
$aProd = $allProdsInThisLevel[$index_prod]; $aProd = $allProdsInThisLevel[$index_prod];
// Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C) // Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C)
$shortname = $aProd['shortname'] . " (ID:" . $aProd['id'] . ")"; $prodText = ProductEntry::createProductStr($aProd,$decpoint);
$longname = $aProd['longname']; $text .= substr(" ", 0, $depth) . $prodText . "\n";
$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";
} }
for ($index_type=0;$index_type < count($allTypesInThisLevel);$index_type++) { for ($index_type=0;$index_type < count($allTypesInThisLevel);$index_type++) {
@ -1230,20 +1191,18 @@ class Products {
} }
} }
private function getSpeisekarte() { public function getSpeisekarte($pdo) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$legend = file_get_contents("../customer/menulegend.txt"); $legend = file_get_contents("../customer/menulegend.txt");
$decpoint = $this->getDecPoint(); $decpoint = $this->getDecPoint($pdo);
$pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT * FROM %products% WHERE removed is null"; $sql = "SELECT * FROM %products% WHERE removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(); $stmt->execute();
$numberOfProds = $stmt->rowCount(); $numberOfProds = $stmt->rowCount();
$sql = "SELECT * FROM %prodtype% WHERE removed is null"; $sql = "SELECT * FROM %prodtype% WHERE removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(); $stmt->execute();
$numberOfProdTypes = $stmt->rowCount(); $numberOfProdTypes = $stmt->rowCount();
@ -1256,7 +1215,7 @@ class Products {
$text = $legend . $this->readDbProducts($pdo); $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) private function endsWith($haystack, $needle)

View File

@ -19,9 +19,9 @@ class QueueContent {
} }
function handleCommand($command) { function handleCommand($command) {
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false); header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); header("Pragma: no-cache");
if ($command == "getJsonTableNameFromId") { if ($command == "getJsonTableNameFromId") {
$this->getJsonTableNameFromId($_GET['tableid']); $this->getJsonTableNameFromId($_GET['tableid']);
@ -29,7 +29,7 @@ class QueueContent {
} }
// these command are only allowed for user with supply rights // 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 (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_supply'))) { if (!($this->userrights->hasCurrentUserRight('right_supply'))) {
echo "Benutzerrechte nicht ausreichend!"; echo "Benutzerrechte nicht ausreichend!";
@ -39,29 +39,29 @@ class QueueContent {
// these command are only allowed for user with kitchen or bar rights // these command are only allowed for user with kitchen or bar rights
$cmdArray = array('declareProductBeCookingOrCooked', 'declareProductNOTBeCooked'); $cmdArray = array('declareProductBeCookingOrCooked', 'declareProductNOTBeCooked');
if (in_array($command, $cmdArray)) { if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_kitchen')) && !($this->userrights->hasCurrentUserRight('right_bar'))) { if (!($this->userrights->hasCurrentUserRight('right_kitchen')) && !($this->userrights->hasCurrentUserRight('right_bar'))) {
echo "Benutzerrechte nicht ausreichend!"; echo "Benutzerrechte nicht ausreichend!";
return false; return false;
} }
} }
// these command are only allowed for user with waiter rights // these command are only allowed for user with waiter rights
$cmdArray = array('addProductListToQueue', 'removeProductFromQueue', 'changeTable','getProdsForTableChange'); $cmdArray = array('addProductListToQueue', 'removeProductFromQueue', 'changeTable','getProdsForTableChange');
if (in_array($command, $cmdArray)) { if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_waiter'))) { if (!($this->userrights->hasCurrentUserRight('right_waiter'))) {
echo "Benutzerrechte nicht ausreichend!"; echo "Benutzerrechte nicht ausreichend!";
return false; return false;
} }
} }
// these command are only allowed for user with paydesk rights // these command are only allowed for user with paydesk rights
$cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId'); $cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId');
if (in_array($command, $cmdArray)) { if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_paydesk'))) { if (!($this->userrights->hasCurrentUserRight('right_paydesk'))) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_PAYDESK_NOT_AUTHOTRIZED, "msg" => ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_PAYDESK_NOT_AUTHOTRIZED, "msg" => ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG));
return false; return false;
} }
} }
if ($command == 'addProductListToQueue') { 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']); $this->declarePaidCreateBillReturnBillId($_POST['ids'],$_POST['brutto'],$_POST['netto'],$_POST['tableid'],$_POST['paymentid'],$_POST['tax'],$_POST['decpoint'],$_POST['declareready'],$_POST['host']);
} else { } else {
echo "Command not supported."; echo "Command not supported.";
} }
} }
// needed if paydesk gets the tableid by direct call // needed if paydesk gets the tableid by direct call
@ -124,13 +124,13 @@ class QueueContent {
} }
function getUserName($userid) { function getUserName($userid) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT username FROM %user% WHERE id=?"; $sql = "SELECT username FROM %user% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($userid)); $stmt->execute(array($userid));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
return($row->username); return($row->username);
} else { } else {
return ""; return "";
@ -161,8 +161,8 @@ class QueueContent {
* $kind=0 -> return only food elements, =1 -> return drinks * $kind=0 -> return only food elements, =1 -> return drinks
*/ */
private function getJsonAllQueueItemsToMake($kind) { private function getJsonAllQueueItemsToMake($kind) {
// current time // current time
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s'); $currentTime = date('Y-m-d H:i:s');
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
@ -514,17 +514,17 @@ class QueueContent {
} }
private function getJsonLastMadeItems($kind) { private function getJsonLastMadeItems($kind) {
$pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo = DbUtils::openDbAndReturnPdoStatic();
// first sort all non-ready products ordered by ordertime // first sort all non-ready products ordered by ordertime
if ($this->areBillExisting($pdo)) { 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% "; $sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables%,%bill% ";
} else { } else {
$sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables% "; $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 .= "WHERE (readytime <> '0000-00-00 00:00:00' AND ";
$sql .= "delivertime = '0000-00-00 00:00:00' AND "; $sql .= "delivertime = '0000-00-00 00:00:00' AND ";
$sql .= "ordertime is not null AND "; $sql .= "ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND "; $sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr = %resttables%.id AND "; $sql .= "%queue%.tablenr = %resttables%.id AND ";
$sql .= "%products%.category=%prodtype%.id AND "; $sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind=? AND "; $sql .= "%prodtype%.kind=? AND ";
@ -532,14 +532,14 @@ class QueueContent {
$sql .= "%queue%.workprinted='0') "; $sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) { if ($this->areBillExisting($pdo)) {
// now remove closed items // now remove closed items
$sql .= "AND (%queue%.billid is null OR ("; $sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
} }
$sql .= "ORDER BY readytime DESC LIMIT 10;"; $sql .= "ORDER BY readytime DESC LIMIT 10;";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind)); $stmt->execute(array($kind));
$result1 = $stmt->fetchAll(); $result1 = $stmt->fetchAll();
if ($this->areBillExisting($pdo)) { if ($this->areBillExisting($pdo)) {
@ -570,7 +570,7 @@ class QueueContent {
$result2 = $stmt->fetchAll(); $result2 = $stmt->fetchAll();
$result = array_merge($result1,$result2); $result = array_merge($result1,$result2);
$resultarray = array(); $resultarray = array();
foreach($result as $zeile) { foreach($result as $zeile) {
$extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']); $extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']);
@ -578,16 +578,16 @@ class QueueContent {
$productid = $zeile['prodid']; $productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usekitchen"] == 1) { if ($useConditions["usekitchen"] == 1) {
// yes, display it in kitchen view as cooked // yes, display it in kitchen view as cooked
$arr = array("id" => $zeile['id'], $arr = array("id" => $zeile['id'],
"tablename" => $zeile['tableno'], "tablename" => $zeile['tableno'],
"longname" => $zeile['longname'], "longname" => $zeile['longname'],
"option" => $zeile['anoption'], "option" => $zeile['anoption'],
"extras" => $extras, "extras" => $extras,
"readytime" => $zeile['readytime'] "readytime" => $zeile['readytime']
); );
$resultarray[] = $arr; $resultarray[] = $arr;
} }
} }
// now look for items that are made and auto-delivered // now look for items that are made and auto-delivered
@ -600,40 +600,40 @@ class QueueContent {
echo json_encode($resultarray); echo json_encode($resultarray);
} }
private function appendProdsForBarKitchenAndAutoDelivery($pdo,$kind,$resultarray) { private function appendProdsForBarKitchenAndAutoDelivery($pdo,$kind,$resultarray) {
$sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid "; $sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid ";
$sql .= "FROM %queue%,%resttables%,%products%,%bill%,%prodtype% "; $sql .= "FROM %queue%,%resttables%,%products%,%bill%,%prodtype% ";
$sql .= "WHERE (%queue%.productid=%products%.id "; $sql .= "WHERE (%queue%.productid=%products%.id ";
$sql .= "AND %queue%.tablenr=%resttables%.id "; $sql .= "AND %queue%.tablenr=%resttables%.id ";
$sql .= "AND %queue%.readytime <> '0000-00-00 00:00:00' "; $sql .= "AND %queue%.readytime <> '0000-00-00 00:00:00' ";
$sql .= "AND toremove <> '1' AND "; $sql .= "AND toremove <> '1' AND ";
$sql .= "ordertime is not null 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%.productid = %products%.id AND %products%.category = %prodtype%.id AND %prodtype%.kind=? AND %prodtype%.usesupplydesk='0' AND %prodtype%.usekitchen='1') AND ";
$sql .= "%queue%.workprinted='0') "; $sql .= "%queue%.workprinted='0') ";
// now remove closed items // now remove closed items
$sql .= "AND (%queue%.billid is null OR ("; $sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql = $sql . "ORDER BY delivertime DESC LIMIT 10"; $sql = $sql . "ORDER BY delivertime DESC LIMIT 10";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind)); $stmt->execute(array($kind));
$result = $stmt->fetchAll(); $result = $stmt->fetchAll();
foreach ($result as $zeile) { foreach ($result as $zeile) {
$productid = $zeile['prodid']; $productid = $zeile['prodid'];
$extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']); $extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']);
$deliveredProd = array( $deliveredProd = array(
"id" => $zeile['id'], "id" => $zeile['id'],
"tablename" => $zeile['tableno'], "tablename" => $zeile['tableno'],
"longname" => $zeile['longname'], "longname" => $zeile['longname'],
"option" => $zeile['anoption'], "option" => $zeile['anoption'],
"extras" => $extras, "extras" => $extras,
"readytime" => $zeile['delivertime'] "readytime" => $zeile['delivertime']
); );
$resultarray[] = $deliveredProd; $resultarray[] = $deliveredProd;
} }
return($resultarray); return($resultarray);
} }
/* /*
@ -641,17 +641,17 @@ class QueueContent {
*/ */
function declareProductBeCookingOrCooked($queueid,$action) { function declareProductBeCookingOrCooked($queueid,$action) {
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction(); $pdo->beginTransaction();
// is product already cooking or will it be set to cooking? // is product already cooking or will it be set to cooking?
$sql = "SELECT cooking,productid FROM %queue% WHERE id=?"; $sql = "SELECT cooking,productid FROM %queue% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid)); $stmt->execute(array($queueid));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$cooking = $row->cooking; $cooking = $row->cooking;
$productid = $row->productid; $productid = $row->productid;
if ($action == 'r') { if ($action == 'r') {
// product shall be declared ready // product shall be declared ready
@ -660,11 +660,11 @@ class QueueContent {
$pdo->rollBack(); $pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} else { } else {
$this->reallyDeclareAsCooked($pdo,$queueid); $this->reallyDeclareAsCooked($pdo,$queueid);
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usesupply"] == 0) { if ($useConditions["usesupply"] == 0) {
// can bypass the supplydesk // can bypass the supplydesk
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
} }
$pdo->commit(); $pdo->commit();
echo json_encode(array("status" => "OK")); echo json_encode(array("status" => "OK"));
@ -673,30 +673,30 @@ class QueueContent {
// product shall be declared as cooking (in progress) // product shall be declared as cooking (in progress)
if (!is_null($cooking)) { if (!is_null($cooking)) {
// a product must not be cooking before it can becomes 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)); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} else { } else {
$userid = $this->getUserId(); $userid = $this->getUserId();
$updSql = "UPDATE %queue% SET cooking=? WHERE id=?"; $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)); $stmt->execute(array($userid,$queueid));
$pdo->commit(); $pdo->commit();
echo json_encode(array("status" => "OK")); echo json_encode(array("status" => "OK"));
} }
} }
} else { } else {
$pdo->rollBack(); $pdo->rollBack();
} }
} else { } else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG));
} }
} }
private function reallyDeclareAsCooked($pdo,$queueid) { private function reallyDeclareAsCooked($pdo,$queueid) {
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$readytime = date('Y-m-d H:i:s'); $readytime = date('Y-m-d H:i:s');
$insertSql = "UPDATE %queue% SET readytime=? WHERE id=?"; $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)); $stmt->execute(array($readytime,$queueid));
} }
@ -705,15 +705,15 @@ class QueueContent {
*/ */
function declareProductNotBeCooked($queueid) { function declareProductNotBeCooked($queueid) {
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction(); $pdo->beginTransaction();
// first: is the product still declared as delivered? // first: is the product still declared as delivered?
$sql = "SELECT id FROM %queue% WHERE id=? AND readytime <> '0000-00-00 00:00:00'"; $sql = "SELECT id FROM %queue% WHERE id=? AND readytime <> '0000-00-00 00:00:00'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid)); $stmt->execute(array($queueid));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$foundid = $row->id; $foundid = $row->id;
if ($foundid == $queueid) { 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=?"; $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 { } else {
$pdo->rollBack(); $pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG)); echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} }
} else { } else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG)); 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) { 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 = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($prodid)); $stmt->execute(array($prodid));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
@ -767,12 +767,12 @@ class QueueContent {
} }
} }
/* /*
* Add a product list to the queue as if it was ordered by the waiter. * 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. * The ordertime is set by the time that this method is invoked.
* *
* If product shall not be run over kitchen or supplydesk this is * If product shall not be run over kitchen or supplydesk this is
* managed here as well * managed here as well
*/ */
function addProductListToQueue($theTableid,$prods,$doPrint,$payprinttype) { function addProductListToQueue($theTableid,$prods,$doPrint,$payprinttype) {
if (intval($theTableid) == 0) { if (intval($theTableid) == 0) {
@ -798,10 +798,10 @@ class QueueContent {
$stmt->execute(array('workflowconfig')); $stmt->execute(array('workflowconfig'));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$workflowconfig = $row->setting; $workflowconfig = $row->setting;
// get current pricelevel // get current pricelevel
$currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo); $currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo);
$currentPriceLevelId = $currentPriceLevel["id"]; $currentPriceLevelId = $currentPriceLevel["id"];
$insertedQueueIds = array(); $insertedQueueIds = array();
@ -812,29 +812,29 @@ class QueueContent {
$theOption = $aProd["option"]; $theOption = $aProd["option"];
$theChangedPrice = $aProd["changedPrice"]; $theChangedPrice = $aProd["changedPrice"];
$theChangedPrice = str_replace(',','.',$theChangedPrice); $theChangedPrice = str_replace(',','.',$theChangedPrice);
// now get the price for this pricelevel // now get the price for this pricelevel
$getPriceSql = "SELECT priceA,priceB,priceC,longname,tax FROM %products% where id=?"; $getPriceSql = "SELECT priceA,priceB,priceC,longname,tax FROM %products% where id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($getPriceSql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($getPriceSql));
$stmt->execute(array($productid)); $stmt->execute(array($productid));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
if ($row == null) { if ($row == null) {
echo "Fehler: Preise nicht vorhanden"; // error echo "Fehler: Preise nicht vorhanden"; // error
return; return;
} }
$productname = $row->longname; $productname = $row->longname;
if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) { if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) {
$price_for_level_A = $row->priceA; $price_for_level_A = $row->priceA;
$price_for_level_B = $row->priceB; $price_for_level_B = $row->priceB;
$price_for_level_C = $row->priceC; $price_for_level_C = $row->priceC;
$price = $price_for_level_A; // default - levl 1 $price = $price_for_level_A; // default - levl 1
if ($currentPriceLevelId == 2) { if ($currentPriceLevelId == 2) {
$price = $price_for_level_B; $price = $price_for_level_B;
} else if ($currentPriceLevelId == 3) { } else if ($currentPriceLevelId == 3) {
$price = $price_for_level_C; $price = $price_for_level_C;
} // else: use default price A } // else: use default price A
} else { } else {
$price = $theChangedPrice; $price = $theChangedPrice;
} }
@ -870,19 +870,19 @@ class QueueContent {
$price += floatval($row->price); $price += floatval($row->price);
} }
} }
if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) { if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) {
// first get category of product // first get category of product
$useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid); $useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid);
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$ordertime = date('Y-m-d H:i:s'); $ordertime = date('Y-m-d H:i:s');
$insertSql = "INSERT INTO `%queue%` ( $insertSql = "INSERT INTO `%queue%` (
`id` , `tablenr`,`productid`,`pricelevel`,`price`,`tax`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`) `id` , `tablenr`,`productid`,`pricelevel`,`price`,`tax`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`)
VALUES ( VALUES (
NULL , ?,?,?,?,?,?,?,?,?,?,?, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL,NULL,'0',NULL,'0');"; 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 = $pdo->prepare(DbUtils::substTableAlias($insertSql));
$stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$tax,$productname,$ordertime,$_SESSION['userid'],$theOption,($theChangedPrice == "NO" ? 0 : 1),$togo)); $stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$tax,$productname,$ordertime,$_SESSION['userid'],$theOption,($theChangedPrice == "NO" ? 0 : 1),$togo));
$queueid = $pdo->lastInsertId(); $queueid = $pdo->lastInsertId();
@ -895,26 +895,26 @@ class QueueContent {
$sql = "INSERT INTO %queueextras% (`id`,`queueid`,`extraid`,`name`) VALUES(NULL,?,?,?)"; $sql = "INSERT INTO %queueextras% (`id`,`queueid`,`extraid`,`name`) VALUES(NULL,?,?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid,$extraid,$extraname)); $stmt->execute(array($queueid,$extraid,$extraname));
} }
} }
if (($workflowconfig == 3) && ($doPrint == 0)) { if (($workflowconfig == 3) && ($doPrint == 0)) {
$this->reallyDeclareAsCooked($pdo,$queueid); $this->reallyDeclareAsCooked($pdo,$queueid);
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
} else { } else {
if ($useConditions["usekitchen"] == 0) { if ($useConditions["usekitchen"] == 0) {
// no - can bypass the kitchen // no - can bypass the kitchen
$this->reallyDeclareAsCooked($pdo,$queueid); $this->reallyDeclareAsCooked($pdo,$queueid);
// then also look for supplydesk, since kitchen action won't do this! // then also look for supplydesk, since kitchen action won't do this!
if ($useConditions["usesupply"] == 0) { if ($useConditions["usesupply"] == 0) {
// can bypass the supplydesk // can bypass the supplydesk
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid); $this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
// THIS autop declares as "prepared" (cooked)!!! // THIS autop declares as "prepared" (cooked)!!!
} }
} else { } else {
$insertedQueueIds[] = $queueid; $insertedQueueIds[] = $queueid;
} }
} }
} }
} }
@ -941,7 +941,7 @@ class QueueContent {
*/ */
function removeProductFromQueue($queueid,$isPaid,$isCooking,$isReady) { function removeProductFromQueue($queueid,$isPaid,$isCooking,$isReady) {
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT count(id) as countid FROM %bill%"; $sql = "SELECT count(id) as countid FROM %bill%";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
@ -949,7 +949,7 @@ class QueueContent {
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
$hasBills = ($row->countid > 0 ? true : false); $hasBills = ($row->countid > 0 ? true : false);
if ($hasBills) { if ($hasBills) {
$sql = "UPDATE %queue%,%bill% "; $sql = "UPDATE %queue%,%bill% ";
} else { } else {
$sql = "UPDATE %queue% "; $sql = "UPDATE %queue% ";
@ -976,9 +976,9 @@ class QueueContent {
$sql .= " billid = %bill%.id AND %bill%.closingid is null)) "; $sql .= " billid = %bill%.id AND %bill%.closingid is null)) ";
} }
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid)); $stmt->execute(array($queueid));
$rowsAffected = $stmt->rowCount(); $rowsAffected = $stmt->rowCount();
if ($rowsAffected == 1) { if ($rowsAffected == 1) {
echo json_encode(array("status" => "OK")); echo json_encode(array("status" => "OK"));
} else { } else {
@ -1016,7 +1016,7 @@ class QueueContent {
*/ */
function getJsonLongNamesOfProdsForTableNotDelivered($tableid) { function getJsonLongNamesOfProdsForTableNotDelivered($tableid) {
if (is_numeric($tableid)) { if (is_numeric($tableid)) {
$prods = array(); $prods = array();
$pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo = DbUtils::openDbAndReturnPdoStatic();
@ -1096,7 +1096,7 @@ class QueueContent {
$prods[] = $prodEntry; $prods[] = $prodEntry;
} }
echo json_encode($prods); echo json_encode($prods);
} }
} }
@ -1107,27 +1107,43 @@ class QueueContent {
$tableid = null; $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 .= "%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 .= "(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 = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid,$tableid)); $stmt->execute(array($tableid,$tableid));
$unpaidresult = $stmt->fetchAll(); $unpaidresultungrouped = $stmt->fetchAll();
$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% LEFT OUTER JOIN %bill% ON %queue%.billid=%bill%.id WHERE "; $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 .= "(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' OR ";
$sql .= "(%queue%.delivertime <> '0000-00-00 00:00:00' AND workprinted='1')) "; $sql .= "(%queue%.delivertime <> '0000-00-00 00:00:00' AND workprinted='1')) ";
$sql .= "GROUP BY productid";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid,$tableid)); $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) { function getJsonProductsOfTableToPay($tableid) {
$pdo = DbUtils::openDbAndReturnPdoStatic(); $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 $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% FROM %queue%
INNER JOIN %products% ON %queue%.productid = %products%.id INNER JOIN %products% ON %queue%.productid = %products%.id
INNER JOIN %pricelevel% ON %queue%.pricelevel = %pricelevel%.id "; INNER JOIN %pricelevel% ON %queue%.pricelevel = %pricelevel%.id ";
if ($tableid == 0) { if ($tableid == 0) {
$sql .= "WHERE tablenr is null "; $sql .= "WHERE tablenr is null ";
} else { } else {
$sql .= "WHERE tablenr = $tableid "; $sql .= "WHERE tablenr = $tableid ";
} }
$sql .= "AND paidtime is null AND toremove <> '1' AND ordertime is not null AND isclosed is null ORDER BY ordertime;"; $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(); $stmt->execute();
$result = $stmt->fetchAll(); $result = $stmt->fetchAll();
$prodsToPay = array(); $prodsToPay = array();
foreach ($result as $zeile) { foreach ($result as $zeile) {
$thePrice = $zeile['price']; $thePrice = $zeile['price'];
$theTax = $zeile['tax']; $theTax = $zeile['tax'];
$thePriceLevelName = $zeile['pricelevelname']; $thePriceLevelName = $zeile['pricelevelname'];
$longName = $zeile['longname']; $longName = $zeile['longname'];
$togo = $zeile["togo"]; $togo = $zeile["togo"];
$queueid = $zeile['id']; $queueid = $zeile['id'];
@ -1190,23 +1206,23 @@ class QueueContent {
// are listed up. It can be used as a receipt to print later // are listed up. It can be used as a receipt to print later
function displayBill($billtableitems,$totalPrice) { function displayBill($billtableitems,$totalPrice) {
$currency = $this->commonUtils->getCurrency(); $currency = $this->commonUtils->getCurrency();
$numberOfItemsToPay = count($billtableitems); $numberOfItemsToPay = count($billtableitems);
if ($numberOfItemsToPay > 0) { if ($numberOfItemsToPay > 0) {
echo "<br><br><table id=bill class=billtable>"; echo "<br><br><table id=bill class=billtable>";
echo "<tr><th>Speise/Getränk<th id=pricecolheader>Preis ($currency)</tr>"; echo "<tr><th>Speise/Getränk<th id=pricecolheader>Preis ($currency)</tr>";
for ($i=0;$i < $numberOfItemsToPay; $i++) { for ($i=0;$i < $numberOfItemsToPay; $i++) {
$aProductToPay = $billtableitems[$i]; $aProductToPay = $billtableitems[$i];
echo "<tr>"; echo "<tr>";
echo "<td>" . $aProductToPay['textOfButton'] . "<td id=pricecol>" . $aProductToPay['price'] . "</tr>"; echo "<td>" . $aProductToPay['textOfButton'] . "<td id=pricecol>" . $aProductToPay['price'] . "</tr>";
} }
echo "<tr><td id=totalprice colspan=2>Gesamtpreis: " . $totalPrice . " $currency </tr>"; echo "<tr><td id=totalprice colspan=2>Gesamtpreis: " . $totalPrice . " $currency </tr>";
} }
echo "</table>"; echo "</table>";
} }
// ********************************** // **********************************
// * Bereitstellung * // * Bereitstellung *
// ********************************** // **********************************
@ -1216,8 +1232,8 @@ class QueueContent {
$delivertime = date('Y-m-d H:i:s'); $delivertime = date('Y-m-d H:i:s');
$updateSql = "UPDATE %queue% SET delivertime=? WHERE id=?"; $updateSql = "UPDATE %queue% SET delivertime=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($delivertime,$queueid)); $stmt->execute(array($delivertime,$queueid));
// then it was probably already prepared // then it was probably already prepared
$updateSql = "UPDATE %queue% SET readytime=? WHERE id=?"; $updateSql = "UPDATE %queue% SET readytime=? WHERE id=?";
@ -1230,12 +1246,12 @@ class QueueContent {
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$this->declareProductBeDeliveredWithGivenPdo($pdo, $queueid); $this->declareProductBeDeliveredWithGivenPdo($pdo, $queueid);
} }
} }
function declareMultipleProductsDelivered($queueids) { function declareMultipleProductsDelivered($queueids) {
$ids = explode(",",$queueids); $ids = explode(",",$queueids);
$pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction(); $pdo->beginTransaction();
for ($i=0;$i < count($ids); $i++) { for ($i=0;$i < count($ids); $i++) {
@ -1250,12 +1266,12 @@ class QueueContent {
function declareProductNotBeDelivered($queueid) { function declareProductNotBeDelivered($queueid) {
$pdo = DbUtils::openDbAndReturnPdoStatic(); $pdo = DbUtils::openDbAndReturnPdoStatic();
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$delivertime = date('Y-m-d H:i:s'); $delivertime = date('Y-m-d H:i:s');
$updateSql = "UPDATE %queue% SET delivertime='0000-00-00 00:00:00' WHERE id=?"; $updateSql = "UPDATE %queue% SET delivertime='0000-00-00 00:00:00' WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql));
$stmt->execute(array($queueid)); $stmt->execute(array($queueid));
} }
} }
@ -1307,12 +1323,12 @@ class QueueContent {
$stmt->execute(); $stmt->execute();
$dbresult = $stmt->fetchAll(); $dbresult = $stmt->fetchAll();
// create a table that is optimal (sqrt-like size) // create a table that is optimal (sqrt-like size)
$numberOfIcons = count($dbresult); $numberOfIcons = count($dbresult);
$arrayOfProdsForTable = array(); $arrayOfProdsForTable = array();
$idsProdsOfTable = ''; // this is a hack! All queueids of a table redundant for "Deliver all" $idsProdsOfTable = ''; // this is a hack! All queueids of a table redundant for "Deliver all"
foreach($dbresult as $zeile) { foreach($dbresult as $zeile) {
$theAction= "deliver"; $theAction= "deliver";
$longname = $zeile['longname']; $longname = $zeile['longname'];
@ -1323,14 +1339,14 @@ class QueueContent {
"longname" => $zeile['longname'], "longname" => $zeile['longname'],
"option" => $zeile['anoption'], "option" => $zeile['anoption'],
"extras" => $extras, "extras" => $extras,
"status" => "ready_to_deliver"); "status" => "ready_to_deliver");
$arrayOfProdsForTable[] = $anProdElem; $arrayOfProdsForTable[] = $anProdElem;
if ($idsProdsOfTable == '') { if ($idsProdsOfTable == '') {
$idsProdsOfTable = $idsProdsOfTable . $zeile['id']; $idsProdsOfTable = $idsProdsOfTable . $zeile['id'];
} else { } else {
$idsProdsOfTable = $idsProdsOfTable . ',' . $zeile['id']; $idsProdsOfTable = $idsProdsOfTable . ',' . $zeile['id'];
} }
} }
return array("prods" => $arrayOfProdsForTable, "ids" => $idsProdsOfTable); return array("prods" => $arrayOfProdsForTable, "ids" => $idsProdsOfTable);
} }
@ -1384,8 +1400,8 @@ class QueueContent {
$sql .= "%queue%.workprinted='0') "; $sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) { if ($this->areBillExisting($pdo)) {
// now remove closed items // now remove closed items
$sql .= "AND (%queue%.billid is null OR ("; $sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
} }
$sql .= " ORDER BY tablenr"; $sql .= " ORDER BY tablenr";
@ -1440,18 +1456,18 @@ class QueueContent {
$tableheadeline = $commonUtils->getTableNameFromId($pdo,$tableid); $tableheadeline = $commonUtils->getTableNameFromId($pdo,$tableid);
$preparedProds[] = array( $preparedProds[] = array(
"tableheadline" => $tableheadeline, "tableheadline" => $tableheadeline,
"tableid" => $tableid, "tableid" => $tableid,
"tablestatus" => $tablestatus, "tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'], "ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable); "prodsOfTable" => $arrayOfProdsOfATable);
} else { } else {
$tablestatus = "incomplete"; $tablestatus = "incomplete";
$tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($pdo,$tableid); $tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($pdo,$tableid);
$preparedProds_incomplete_tables[] = array( $preparedProds_incomplete_tables[] = array(
"tableheadline" => $tableheadeline, "tableheadline" => $tableheadeline,
"tableid" => $tableid, "tableid" => $tableid,
"tablestatus" => $tablestatus, "tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'], "ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable); "prodsOfTable" => $arrayOfProdsOfATable);
} }
} }
@ -1473,7 +1489,7 @@ class QueueContent {
$sql .= "FROM %queue%,%resttables%,%products% "; $sql .= "FROM %queue%,%resttables%,%products% ";
} }
$sql .= "WHERE (delivertime <> '0000-00-00 00:00:00' "; $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 %queue%.tablenr=%resttables%.id ";
$sql .= "AND toremove <> '1' AND "; $sql .= "AND toremove <> '1' AND ";
$sql .= "ordertime is not null AND "; $sql .= "ordertime is not null AND ";
@ -1481,8 +1497,8 @@ class QueueContent {
$sql .= "%queue%.workprinted='0') "; $sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) { if ($this->areBillExisting($pdo)) {
// now remove closed items // now remove closed items
$sql .= "AND (%queue%.billid is null OR ("; $sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) "; $sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
} }
@ -1520,9 +1536,9 @@ class QueueContent {
$lastDeliveredProds = array(); $lastDeliveredProds = array();
foreach($result as $zeile) { foreach($result as $zeile) {
$productid = $zeile['prodid']; $productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid); $useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usesupply"] == 1) { if ($useConditions["usesupply"] == 1) {
// yes, display it in supplydesk view as cooked // yes, display it in supplydesk view as cooked
$extras = $this->getExtrasOfQueueItem(null,$zeile['id']); $extras = $this->getExtrasOfQueueItem(null,$zeile['id']);
@ -1533,17 +1549,17 @@ class QueueContent {
"option" => $zeile['anoption'], "option" => $zeile['anoption'],
"extras" => $extras, "extras" => $extras,
"delivertime" => $zeile['delivertime'], "delivertime" => $zeile['delivertime'],
"tablename" => $zeile['tableno']); "tablename" => $zeile['tableno']);
$lastDeliveredProds[] = $deliveredProd; $lastDeliveredProds[] = $deliveredProd;
} }
} }
echo json_encode($lastDeliveredProds); echo json_encode($lastDeliveredProds);
} }
// ********************************** // **********************************
// * Kasse * // * Kasse *
// ********************************** // **********************************
/* /*
* Test if all queue items with the given ids are not paid * Test if all queue items with the given ids are not paid
@ -1559,7 +1575,7 @@ class QueueContent {
$ids_array = explode ( ',', $ids ); $ids_array = explode ( ',', $ids );
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction(); $pdo->beginTransaction();
// check if all items are not paid yet! // check if all items are not paid yet!
@ -1568,10 +1584,10 @@ class QueueContent {
$anId = $ids_array[$i]; $anId = $ids_array[$i];
if (is_numeric($anId)) { if (is_numeric($anId)) {
$sql = "SELECT count(id) as countid FROM %queue% WHERE paidtime is not null AND id=?"; $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)); $stmt->execute(array($anId));
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$aCount = $row->countid; $aCount = $row->countid;
if (($aCount != null) && ($aCount == 1)) { if (($aCount != null) && ($aCount == 1)) {
$allNotPaid = false; $allNotPaid = false;
@ -1580,8 +1596,8 @@ class QueueContent {
} }
} }
// current time // current time
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s'); $currentTime = date('Y-m-d H:i:s');
$billid = (-1); $billid = (-1);
@ -1590,14 +1606,14 @@ class QueueContent {
// find highest bill id // find highest bill id
$sql = "SELECT id from %bill% ORDER BY id DESC"; $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(); $stmt->execute();
$numberOfIds = $stmt->rowCount(); $numberOfIds = $stmt->rowCount();
$newprevbrutto = 0; $newprevbrutto = 0;
$newprevnetto = 0; $newprevnetto = 0;
if ($numberOfIds > 0) { if ($numberOfIds > 0) {
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$billid = intval($row->id)+1; $billid = intval($row->id)+1;
$sql = "SELECT brutto,netto,prevbrutto,prevnetto FROM %bill% WHERE id=?"; $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)); $stmt->execute(array($billid,$currentTime,$brutto,$netto,$newprevbrutto,$newprevnetto,$tableid,$paymentId,$userid,$host,$signature));
// now declare them all to be paid: // now declare them all to be paid:
for ($i=0;$i<count($ids_array);$i++) { for ($i=0;$i<count($ids_array);$i++) {
$queueid = $ids_array[$i]; $queueid = $ids_array[$i];
if (is_numeric($queueid)) { if (is_numeric($queueid)) {
if ($declareready == 0) { if ($declareready == 0) {
$updateSql = "UPDATE %queue% SET paidtime=?, billid=? WHERE id=?"; $updateSql = "UPDATE %queue% SET paidtime=?, billid=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql));
$stmt->execute(array($currentTime,$billid,$queueid)); $stmt->execute(array($currentTime,$billid,$queueid));
} else { } else {
@ -1651,7 +1667,7 @@ class QueueContent {
} }
$billProdsSql = "INSERT INTO `%billproducts%` (`queueid`,`billid`) VALUES ( ?,?)"; $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)); $stmt->execute(array($queueid,$billid));
} }
} }
@ -1664,11 +1680,11 @@ class QueueContent {
} }
private function getUserId() { private function getUserId() {
if(session_id() == '') { if(session_id() == '') {
session_start(); session_start();
} }
return $_SESSION['userid']; return $_SESSION['userid'];
} }
} }

View File

@ -1,197 +1,145 @@
<?php <?php
require_once (__DIR__. '/../dbutils.php'); require_once (__DIR__. '/../dbutils.php');
require_once (__DIR__. '/../globals.php'); require_once (__DIR__. '/../globals.php');
class HistFiller { class HistFiller {
var $dbutils; var $dbutils;
function __construct() { function __construct() {
$this->dbutils = new DbUtils(); $this->dbutils = new DbUtils();
} }
public function defineHistActions () { public function defineHistActions () {
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)"; $sql = "INSERT INTO %histactions% (id,name,description) VALUES (?,?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle')); $stmt->execute(array('1', 'ProdInit', 'Initiales Befuellen der Produkttabelle'));
$stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle')); $stmt->execute(array('2', 'ConfigInit', 'Initiales Befuellen der Konfigurationstabelle'));
$stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle')); $stmt->execute(array('3', 'UserInit', 'Initiales Befuellen der Benutzertabelle'));
$stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten')); $stmt->execute(array('4', 'ProdChange', 'Modifikation der Produktdaten'));
$stmt->execute(array('5', 'ProdCreation', 'Neues Produkt')); $stmt->execute(array('5', 'ProdCreation', 'Neues Produkt'));
$stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration')); $stmt->execute(array('6', 'ConfigChange', 'Modifikation der Konfiguration'));
$stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer')); $stmt->execute(array('7', 'UserCreation', 'Neuer Benutzer'));
$stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers')); $stmt->execute(array('8', 'UserChange', 'Modifikation eines Benutzers'));
$stmt->execute(array('9', 'DbSave', 'Komplettsicherung der Datenbank')); $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) { private static function getColNamesForHistTable($tableDescr) {
$sql = "SELECT * FROM %user%"; $cols = array();
$this->readSqlUserTableAndSendToHist($pdo,$sql,'3'); 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) { public static function insertRestoreHistEntry($pdo) {
$sql = "SELECT * FROM %user% WHERE id='$userid'"; self::insertIntoHist($pdo, 10, null);
$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 function updateConfigInHist($pdo,$theItem, $theValue) { public function updateConfigInHist($pdo,$theItem, $theValue) {
$sql_find_id = "SELECT id FROM %config% WHERE name='$theItem'"; $sql_find_id = "SELECT id FROM %config% WHERE name='$theItem'";
$sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)"; $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (NULL,?,?)";
$pdo->beginTransaction(); $pdo->beginTransaction();
$stmt_query = $pdo->query(DbUtils::substTableAlias($sql_find_id)); $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 = $pdo->prepare(DbUtils::substTableAlias($sql_insert_histconfig));
$stmt_insert_histconfig->execute(array($theConfigId,"$theValue")); $stmt_insert_histconfig->execute(array($theConfigId,"$theValue"));
$newRefIdForHist = $pdo->lastInsertId(); $newRefIdForHist = $pdo->lastInsertId();
$this->insertIntoHist($pdo, '6', $newRefIdForHist); self::insertIntoHist($pdo, '6', $newRefIdForHist);
$pdo->commit(); $pdo->commit();
} }
/* /*
* Read the complete config table and fill in these values to the histtable * Read the complete config table and fill in these values to the histtable
*/ */
public function readConfigTableAndSendToHist() { public function readConfigTableAndSendToHist() {
$sql_query = "SELECT * FROM %config%"; $sql_query = "SELECT * FROM %config%";
$sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES ( $sql_insert_histconfig = "INSERT INTO %histconfig% (id,configid,setting) VALUES (
NULL,?,?)"; NULL,?,?)";
$pdo = $this->dbutils->openDbAndReturnPdo(); $pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction(); $pdo->beginTransaction();
$stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query)); $stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_query));
$stmt_insert_histconfig = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histconfig)); $stmt_insert_histconfig = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql_insert_histconfig));
$stmt_query->execute(); $stmt_query->execute();
$result = $stmt_query->fetchAll(); $result = $stmt_query->fetchAll();
foreach($result as $row){ foreach($result as $row){
$stmt_insert_histconfig->execute(array($row['id'],$row['setting'])); $stmt_insert_histconfig->execute(array($row['id'],$row['setting']));
$newRefIdForHist = $pdo->lastInsertId(); $newRefIdForHist = $pdo->lastInsertId();
$this->insertIntoHist($pdo, '2', $newRefIdForHist); $this->insertIntoHist($pdo, '2', $newRefIdForHist);
} }
$pdo->commit(); $pdo->commit();
} }
private function insertIntoHist($pdo,$action,$refIdForHist) { private static function insertIntoHist($pdo,$action,$refIdForHist) {
date_default_timezone_set(DbUtils::getTimeZone()); date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s'); $currentTime = date('Y-m-d H:i:s');
$sql_insert_hist = "INSERT INTO %hist% (id,date,action,refid) VALUES (NULL,?,?,?)"; $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 = $pdo->prepare(DbUtils::substTableAlias($sql_insert_hist));
$stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist)); $stmt_insert_hist->execute(array($currentTime, $action, $refIdForHist));
} }
} }

View File

@ -1,110 +1,158 @@
<?php <?php
// print_r(explode('|', $str, 2));
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;
// Constructor - gehts the line as it is in the Speisekarte
function parse($aTextLine) {
try {
// is there multiple price levels?
$numberOfPrices = 1;
$priceparts = explode('#', $aTextLine, 2);
$price_level_B = "0.00";
$price_level_C = "0.00";
$price_tax = null;
if (count($priceparts) == 2) {
// there is a # in the line --> 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); class ProductEntry {
$this->shortName = trim($parts[0]);
private $shortName; // the name that shall appear on the button of the waiter
$matches = array(); private $priceA; // the price of the product (default)
preg_match('/\(ID:([0-9]+)\)$/', $this->shortName,$matches,PREG_OFFSET_CAPTURE); private $priceB; // price level B
if (count($matches) > 0) { private $priceC; // price level C
$theMatch = $matches[0]; private $tax;
$this->prodid = intval(substr($theMatch[0],4,strlen($theMatch[0])-5)); private $longName; // the name that shall appear on the receipt
$theMatchPos = $theMatch[1]; private $prodid = null;
$this->shortName = trim(substr($this->shortName,0,$theMatchPos-1)); private $available = 1;
}
private static $PRICE_B = "PreisB";
$this->longName = $this->shortName; private static $PRICE_C = "PreisC";
$this->priceA = floatval(str_replace(",",".",(string) $parts[1])); private static $TAX = "Fixsteuersatz";
// default: all the same price private static $SHORTNAME = "Kurzname";
$this->priceB = $this->priceA; private static $AVAILABLE = "vorhanden";
$this->priceC = $this->priceA; private static $ID = "ID";
$this->tax = null;
if ($numberOfPrices == 2) { //
$this->priceB = $price_level_B; // A = C, only B is different public static function createProductStr($aProd, $decpoint) {
} else if ($numberOfPrices == 3) {
$this->priceB = $price_level_B; $shortname = $aProd['shortname'];
$this->priceC = $price_level_C; $longname = $aProd['longname'];
} else if ($numberOfPrices == 4) { $prodId = $aProd['id'];
$this->priceB = $price_level_B;
$this->priceC = $price_level_C; $available = $aProd['available'];
$this->tax = $price_tax; $priceA = str_replace('.', $decpoint, $aProd['priceA']);
} $priceB = str_replace('.', $decpoint, $aProd['priceB']);
$priceC = str_replace('.', $decpoint, $aProd['priceC']);
if (count($parts) > 2) { $tax = str_replace('.', $decpoint, $aProd['tax']);
$thirdpart = trim($parts[2]);
if ($thirdpart != "") { $prodText = "$longname; $priceA";
// in this case the button name is the not same as the name on the bill $extArr = array();
$this->longName = trim($parts[2]);
} if ($shortname != $longname) {
} $extArr[] = self::$SHORTNAME . ":" . $shortname;
return array("status" => "OK"); }
} catch (Exception $e) {
return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $aTextLine); 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() { function getShortName() {
return $this->shortName; return $this->shortName;
} }
function getPriceA() {
return $this->priceA; function getPriceA() {
} return $this->priceA;
function getPriceB() { }
return $this->priceB;
} function getPriceB() {
function getPriceC() { return $this->priceB;
return $this->priceC; }
}
function getTax() { function getPriceC() {
return $this->tax; return $this->priceC;
} }
function getLongName() {
return $this->longName; function getTax() {
} return $this->tax;
function getProdId() { }
return $this->prodid;
} function getLongName() {
function toString() { return $this->longName;
return "S:" . $this->shortName . " PA:" . $this->priceA . " PB:" . $this->priceB . " PC:" . $this->priceC . " Tax:" . $this->tax . " R:" . $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;
}
} }
?> ?>

View File

@ -47,26 +47,26 @@ class TypeAndProductFileManager {
private $nextIdOfProdType = 1; private $nextIdOfProdType = 1;
var $dbutils; var $dbutils;
function __construct() { function __construct() {
$this->dbutils = new DbUtils(); $this->dbutils = new DbUtils();
} }
/* /*
* Look at the beginning of a line and count the number of spaces or tabs * Look at the beginning of a line and count the number of spaces or tabs
*/ */
private function intendingOfText($text) { private function intendingOfText($text) {
$charCounter = 0; $charCounter = 0;
while (($text[$charCounter] == ' ') || ($text[$charCounter] == "\t")) { while (($text[$charCounter] == ' ') || ($text[$charCounter] == "\t")) {
$charCounter++; $charCounter++;
} }
return $charCounter; return $charCounter;
} }
private function startsWith($aText, $needle) private function startsWith($aText, $needle)
{ {
return $needle === "" || strpos($aText, $needle) === 0; return $needle === "" || strpos($aText, $needle) === 0;
} }
/* /*
@ -84,27 +84,27 @@ class TypeAndProductFileManager {
// now really read the file so that content starts at index 1 // now really read the file so that content starts at index 1
$index = 1; $index = 1;
$handle = fopen ($fileName, "r"); $handle = fopen ($fileName, "r");
while (!feof($handle)) { while (!feof($handle)) {
$textline = fgets($handle); $textline = fgets($handle);
if(!($this->startsWith($textline,'#'))) { if(!($this->startsWith($textline,'#'))) {
$depth = $this->intendingOfText($textline); $depth = $this->intendingOfText($textline);
$this->entries->add(new LineItem($depth,$index,$textline)); $this->entries->add(new LineItem($depth,$index,$textline));
$index++; $index++;
} }
} }
fclose ($handle); fclose ($handle);
} }
private function findNextIdOfProdType($pdo) { private function findNextIdOfProdType($pdo) {
$index = 1; $index = 1;
$sql = "SELECT id FROM %prodtype% ORDER BY id DESC LIMIT 1"; $sql = "SELECT id FROM %prodtype% ORDER BY id DESC LIMIT 1";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
$row =$stmt->fetchObject(); $row =$stmt->fetchObject();
if ($row != null) { if ($row != null) {
$index = intval($row->id) +1; $index = intval($row->id) +1;
} }
$this->nextIdOfProdType = $index; $this->nextIdOfProdType = $index;
} }
@ -119,30 +119,30 @@ class TypeAndProductFileManager {
$stmt->execute(array('1')); $stmt->execute(array('1'));
} }
/* /*
* read in the "Speisekarte.txt" * read in the "Speisekarte.txt"
* put the content in the array list "EntryList" as it is * put the content in the array list "EntryList" as it is
* without any modifications * without any modifications
*/ */
private function parseContent($pdo,$speisekarte) { private function parseContent($pdo,$speisekarte) {
// remove old content if any // remove old content if any
$this->entries = new EntryList(); $this->entries = new EntryList();
$this->extras = array(); $this->extras = array();
self::removeExtras($pdo); self::removeExtras($pdo);
// get max number of prodtype id -> the old ones will be kept! // get max number of prodtype id -> the old ones will be kept!
$index = $this->nextIdOfProdType; $index = $this->nextIdOfProdType;
$lines = explode("\n", $speisekarte); $lines = explode("\n", $speisekarte);
$previousDepth = 0; $previousDepth = 0;
for ($i=0;$i<count($lines);$i++) { for ($i=0;$i<count($lines);$i++) {
$textline = $lines[$i]; $textline = $lines[$i];
$cleanLine = str_replace(" ", "", $textline); $cleanLine = str_replace(" ", "", $textline);
if (($this->startsWith($textline,'!')) && (strlen($cleanLine) > 0)) { if (($this->startsWith($textline,'!')) && (strlen($cleanLine) > 0)) {
$this->extras[] = $textline; $this->extras[] = $textline;
} else if(!($this->startsWith($textline,'#')) && (strlen($cleanLine) > 0)) { } else if(!($this->startsWith($textline,'#')) && (strlen($cleanLine) > 0)) {
$depth = $this->intendingOfText($textline); $depth = $this->intendingOfText($textline);
if ($depth > ($previousDepth+1)) { if ($depth > ($previousDepth+1)) {
return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline); return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline);
@ -153,12 +153,12 @@ class TypeAndProductFileManager {
if (is_null($newLineItem)) { if (is_null($newLineItem)) {
return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline); return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $textline);
} else { } else {
$this->entries->add($newLineItem); $this->entries->add($newLineItem);
$index++; $index++;
} }
} }
} }
return array("status" => "OK"); return array("status" => "OK");
} }
/* /*
@ -207,8 +207,8 @@ class TypeAndProductFileManager {
$ref = intval($entry->getReference()); $ref = intval($entry->getReference());
$entry->setId($theId-1); $entry->setId($theId-1);
$theName = $entry->getName(); $theName = $entry->getName();
if ($ref >= $idOfEntryToRemove) { if ($ref >= $idOfEntryToRemove) {
$entry->setReference($ref-1); $entry->setReference($ref-1);
} }
} }
} }
@ -308,7 +308,7 @@ class TypeAndProductFileManager {
for ($i = 0;$i < $this->entries->size(); $i++) { for ($i = 0;$i < $this->entries->size(); $i++) {
$usekitchen = 1; // default $usekitchen = 1; // default
$usesupplydesk = 1; // default $usesupplydesk = 1; // default
$printer = 1; // default $printer = 1; // default
$theEntry = $this->entries->get($i); $theEntry = $this->entries->get($i);
$parts = explode(';', $theEntry->getName(), 2); $parts = explode(';', $theEntry->getName(), 2);
@ -323,23 +323,22 @@ class TypeAndProductFileManager {
$theRefId = $theEntry->getReference(); $theRefId = $theEntry->getReference();
$id = $theEntry->getId(); $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)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql));
try { try {
if ($theEntry->getDepth() > 0) { if ($theEntry->getDepth() > 0) {
$stmt->execute(array($id,$theProdTypeName,$theRefId,$usekitchen,$usesupplydesk,$kind,$printer)); $stmt->execute(array($id,$theProdTypeName,$theRefId,$usekitchen,$usesupplydesk,$kind,$printer));
} else { } else {
$stmt->execute(array($id,$theProdTypeName,null,$usekitchen,$usesupplydesk,$kind,$printer)); $stmt->execute(array($id,$theProdTypeName,null,$usekitchen,$usesupplydesk,$kind,$printer));
} }
} catch (Exception $e) { } catch (Exception $e) {
return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $theProdTypeName); return array("status" => "ERROR","code" => PARSE_ERROR,"msg" => PARSE_ERROR_MSG,"line" => $theProdTypeName);
} }
} }
return array("status" => "OK"); return array("status" => "OK");
} }
private function fillProductDbTable($pdo,$leafArray) { private function fillProductDbTable($pdo,$leafArray) {
$histFiller = new HistFiller();
for ($i=0;$i < $leafArray->size(); $i++) { for ($i=0;$i < $leafArray->size(); $i++) {
$theLeafEntry = $leafArray->get($i); $theLeafEntry = $leafArray->get($i);
$product = new ProductEntry(); $product = new ProductEntry();
@ -354,7 +353,7 @@ class TypeAndProductFileManager {
$shortName = $product->getShortName(); $shortName = $product->getShortName();
$longName = $product->getLongName(); $longName = $product->getLongName();
$prodid = $product->getProdId(); $prodid = $product->getProdId();
$available = 1; // default: product is available $available = $product->getAvailable();
$favorite = 0; $favorite = 0;
$category = $theLeafEntry->getReference(); $category = $theLeafEntry->getReference();
@ -375,10 +374,10 @@ class TypeAndProductFileManager {
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($shortName,$longName,$priceA,$priceB,$priceC,$tax, $category,$available,$favorite)); $stmt->execute(array($shortName,$longName,$priceA,$priceB,$priceC,$tax, $category,$available,$favorite));
$prodid = $pdo->lastInsertId(); $prodid = $pdo->lastInsertId();
$histFiller->createProdInHist($pdo, $prodid, $shortName, $longName, $priceA, $priceB, $priceC, $tax, 0, $available, null, $favorite); HistFiller::createProdInHist($pdo, $prodid);
} else { } 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 = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($prodid)); $stmt->execute(array($prodid));
$row = $stmt->fetchObject(); $row = $stmt->fetchObject();
@ -388,19 +387,20 @@ class TypeAndProductFileManager {
|| ($row->priceA != $priceA) || ($row->priceA != $priceA)
|| ($row->priceB != $priceB) || ($row->priceB != $priceB)
|| ($row->priceC != $priceC) || ($row->priceC != $priceC)
|| ($row->available != $available)
|| ($row->tax != $tax)); || ($row->tax != $tax));
if ($changed) { 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 = $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=?"; $sql = "SELECT sorting,available,favorite,audio FROM %products% WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql)); $stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($prodid)); $stmt->execute(array($prodid));
$row = $stmt->fetchObject(); $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=?"; $sql = "UPDATE %products% SET category=?,removed=? WHERE id=?";
@ -437,7 +437,7 @@ class TypeAndProductFileManager {
if ($theEntry->getReference() > 0) { if ($theEntry->getReference() > 0) {
$theRefEntry = $this->entries->get($theEntry->getReference()); $theRefEntry = $this->entries->get($theEntry->getReference());
$product = new ProductEntry($theEntry->getName()); $product = new ProductEntry($theEntry->getName());
// echo $theEntry->getName() . " -> " . $theRefEntry->getName() . " ---- "; // echo $theEntry->getName() . " -> " . $theRefEntry->getName() . " ---- ";
echo $product->toString() . " -> " . $theRefEntry->getName() . "<br>"; echo $product->toString() . " -> " . $theRefEntry->getName() . "<br>";
} else { } else {
echo $theEntry->getName() . " -> null<br>"; echo $theEntry->getName() . " -> null<br>";
@ -447,51 +447,51 @@ class TypeAndProductFileManager {
function manageSpeisekarte($pdo,$content) { function manageSpeisekarte($pdo,$content) {
$this->findNextIdOfProdType($pdo); $this->findNextIdOfProdType($pdo);
// first remove previous content // first remove previous content
$sql = "UPDATE %products% SET removed='1'"; $sql = "UPDATE %products% SET removed='1'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
$sql = "UPDATE `%prodtype%` SET removed='1'"; $sql = "UPDATE `%prodtype%` SET removed='1'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(); $stmt->execute();
// now fill in the new content // now fill in the new content
$ret = $this->parseContent($pdo,$content); $ret = $this->parseContent($pdo,$content);
if ($ret["status"] != "OK") { if ($ret["status"] != "OK") {
return $ret; return $ret;
} }
// now look on the first depth level (0). This level has // now look on the first depth level (0). This level has
// to be treated individually as staring point because later // to be treated individually as staring point because later
// on it will be iterated recursively // on it will be iterated recursively
// look at all elements at depth level 0 // 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); $anEntry = $this->entries->get($i);
if ($anEntry->getDepth() == 0) { if ($anEntry->getDepth() == 0) {
// highest level // highest level
$this->findAllSubItemsOfIndex($i,1,1,FOOD,null); $this->findAllSubItemsOfIndex($i,1,1,FOOD,null);
} }
} }
//Debug ausgabe //Debug ausgabe
for ($i=0;$i<$this->entries->size();$i++) { for ($i=0;$i<$this->entries->size();$i++) {
$anEntry = $this->entries->get($i); $anEntry = $this->entries->get($i);
$theId = $anEntry->getId(); $theId = $anEntry->getId();
$theName = $anEntry->getName(); $theName = $anEntry->getName();
$theRef = $anEntry->getReference(); $theRef = $anEntry->getReference();
} }
$this->sortOutLeafs(); $this->sortOutLeafs();
$ret = $this->fillProdTypeDbTable($pdo); $ret = $this->fillProdTypeDbTable($pdo);
if ($ret["status"] != "OK") { if ($ret["status"] != "OK") {
return $ret; return $ret;
} }
$ret = $this->fillProductDbTable($pdo,$this->leafArray); $ret = $this->fillProductDbTable($pdo,$this->leafArray);
// now add the extras // now add the extras
@ -501,7 +501,7 @@ class TypeAndProductFileManager {
$anExtra = new ExtraItem($pdo,$anExtraLine); $anExtra = new ExtraItem($pdo,$anExtraLine);
$prodInstance->createExtraCore($pdo, $anExtra->getName(), $anExtra->getPrice(), $anExtra->getAssignedProdIds()); $prodInstance->createExtraCore($pdo, $anExtra->getName(), $anExtra->getPrice(), $anExtra->getAssignedProdIds());
} }
return $ret; return $ret;
} }
} }
?> ?>

View File

@ -218,6 +218,7 @@ class Basedb {
`right_bill` INT (1) NOT NULL, `right_bill` INT (1) NOT NULL,
`right_products` INT (1) NOT NULL, `right_products` INT (1) NOT NULL,
`right_manager` INT (1) NOT NULL, `right_manager` INT (1) NOT NULL,
`right_closing` INT (1) NOT NULL,
`right_reservation` INT (1) NOT NULL, `right_reservation` INT (1) NOT NULL,
`right_rating` INT (1) NOT NULL, `right_rating` INT (1) NOT NULL,
`right_changeprice` INT (1) NOT NULL, `right_changeprice` INT (1) NOT NULL,
@ -469,10 +470,10 @@ class Basedb {
`host` INT(2) NULL, `host` INT(2) NULL,
`reason` VARCHAR ( 150 ) NULL, `reason` VARCHAR ( 150 ) NULL,
`signature`blob 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 (paymentid) REFERENCES %payment%(id),
FOREIGN KEY (userid) REFERENCES %user%(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 ; ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ;
"; ";
$stmt = $pdo->prepare($this->resolveTablenamesInSqlString($sql)); $stmt = $pdo->prepare($this->resolveTablenamesInSqlString($sql));
@ -510,7 +511,7 @@ class Basedb {
FOREIGN KEY (tablenr) REFERENCES %resttables%(id), FOREIGN KEY (tablenr) REFERENCES %resttables%(id),
FOREIGN KEY (pricelevel) REFERENCES %pricelevel%(id), FOREIGN KEY (pricelevel) REFERENCES %pricelevel%(id),
FOREIGN KEY (productid) REFERENCES %products%(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 (cooking) REFERENCES %user%(id),
FOREIGN KEY (orderuser) REFERENCES %user%(id) FOREIGN KEY (orderuser) REFERENCES %user%(id)
) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ; ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ;
@ -524,7 +525,7 @@ class Basedb {
`queueid` INT( 10 ) NOT NULL, `queueid` INT( 10 ) NOT NULL,
`billid` INT(10) NOT NULL, `billid` INT(10) NOT NULL,
FOREIGN KEY (queueid) REFERENCES %queue%(id), 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 ; ) CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = InnoDb ;
"; ";
$this->doSQL($pdo,$sql); $this->doSQL($pdo,$sql);
@ -586,6 +587,7 @@ class Basedb {
`right_bill` INT (1) NOT NULL, `right_bill` INT (1) NOT NULL,
`right_products` INT (1) NOT NULL, `right_products` INT (1) NOT NULL,
`right_manager` INT (1) NOT NULL, `right_manager` INT (1) NOT NULL,
`right_closing` INT (1) NOT NULL,
`right_reservation` INT (1) NOT NULL, `right_reservation` INT (1) NOT NULL,
`right_rating` INT (1) NOT NULL, `right_rating` INT (1) NOT NULL,
`right_changeprice` INT (1) NOT NULL, `right_changeprice` INT (1) NOT NULL,

View File

@ -16,13 +16,15 @@ define ( 'R_RES', 512);
define ( 'R_RAT', 1024); define ( 'R_RAT', 1024);
define ( 'R_MAN', 2048); define ( 'R_MAN', 2048);
define ( 'R_CP', 4096); define ( 'R_CP', 4096);
define ( 'R_CL', 8192);
class Userrights { 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_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; $_SESSION['allrights'] = $ret;
} }
@ -49,33 +51,33 @@ class Userrights {
* can the current call the currentCmd * can the current call the currentCmd
*/ */
function canUserCallCommands($currentCmd, $cmdArray,$right) { function canUserCallCommands($currentCmd, $cmdArray,$right) {
session_start(); session_start();
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in // no user logged in
return false; return false;
} else { } else {
// user is logged in // user is logged in
if (in_array($currentCmd, $cmdArray)) { 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]) { if ($_SESSION[$right]) {
return true; return true;
} }
} }
return false; return false;
} }
} }
function isCurrentUserAdmin() { function isCurrentUserAdmin() {
if(session_id() == '') { if(session_id() == '') {
session_start(); session_start();
} }
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) { if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in // no user logged in
return false; return false;
} else { } else {
return ($_SESSION['is_admin']); return ($_SESSION['is_admin']);
} }
} }

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -7,7 +7,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -7,7 +7,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -7,7 +7,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -5,7 +5,7 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="author" content="Stefan Pichel"> <meta name="author" content="Stefan Pichel">
<link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.1.30"> <link rel="stylesheet" type="text/css" href="css/bestformat.css?v=1.2.0">
<link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/orderstyle.min.css" />
<link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="php/3rdparty/orderstyle/jquery.mobile.icons.min.css" />

View File

@ -173,4 +173,11 @@ function handleTestForLoggedIn(answer) {
if (answer != "YES") { if (answer != "YES") {
setTimeout(function(){document.location.href = "index.html"},250); setTimeout(function(){document.location.href = "index.html"},250);
} }
}
function isInt(value) {
if(Math.floor(value) == value && $.isNumeric(value)) {
return true;
} else {
return false;
}
} }

File diff suppressed because one or more lines are too long