ordersprinter/php/queuecontent.php

1030 lines
38 KiB
PHP

<?php
require_once ('dbutils.php');
require_once ('products.php');
require_once ('commonutils.php');
require_once ('utilities/userrights.php');
class QueueContent {
var $dbutils;
var $commonUtils;
var $userrights;
public static $lastSettingOfDisplayMode = 'all';
function __construct() {
$this->dbutils = new DbUtils();
$this->commonUtils = new CommonUtils();
$this->userrights = new Userrights();
}
function handleCommand($command) {
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
if ($command == "getJsonTableNameFromId") {
$this->getJsonTableNameFromId($_GET['tableid']);
return;
}
// these command are only allowed for user with supply rights
$cmdArray = array('getJsonAllPreparedProducts', 'getJsonLastDeliveredProducts', 'declareProductBeDelivered', 'declareMultipleProductsDelivered','declareProductNotBeDelivered');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_supply'))) {
echo "Benutzerrechte nicht ausreichend!";
return false;
}
}
// these command are only allowed for user with kitchen or bar rights
$cmdArray = array('declareProductBeCookingOrCooked', 'declareProductNOTBeCooked');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_kitchen')) && !($this->userrights->hasCurrentUserRight('right_bar'))) {
echo "Benutzerrechte nicht ausreichend!";
return false;
}
}
// these command are only allowed for user with waiter rights
$cmdArray = array('addProductListToQueue', 'removeProductFromQueue', 'getNotPrintedWorkItemsAndDeclareThemPrinted', 'changeTable');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_waiter'))) {
echo "Benutzerrechte nicht ausreichend!";
return false;
}
}
// these command are only allowed for user with paydesk rights
$cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_paydesk'))) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_PAYDESK_NOT_AUTHOTRIZED, "msg" => ERROR_PAYDESK_NOT_AUTHOTRIZED_MSG));
return false;
}
}
if ($command == 'addProductListToQueue') {
$this->addProductListToQueue($_POST["tableid"],$_POST["prods"]);
} else if ($command == 'kitchenToCook') {
$this->kitchenToCook();
} else if ($command == 'declareProductBeCookingOrCooked') {
$this->declareProductBeCookingOrCooked($_POST['queueid'],$_POST['action']);
} else if ($command == 'declareProductNotBeCooked') {
$this->declareProductNotBeCooked($_POST['queueid']);
} else if ($command == 'showProductsOfTableToPay') {
$this->showProductsOfTableToPay($_GET['tableid']);
} else if ($command == 'getJsonAllPreparedProducts') {
$this->getJsonAllPreparedProducts();
} else if ($command == 'declareProductBeDelivered') {
$this->declareProductBeDelivered($_POST['queueid']);
} else if ($command == 'declareMultipleProductsDelivered') {
$this->declareMultipleProductsDelivered($_POST['queueids']);
} else if ($command == 'declareProductNotBeDelivered') {
$this->declareProductNotBeDelivered($_POST['queueid']);
} else if ($command == 'getJsonLongNamesOfProdsForTableNotDelivered') {
$this->getJsonLongNamesOfProdsForTableNotDelivered($_GET["tableid"]);
} else if ($command == 'changeTable') {
$this->changeTable($_POST['fromTableId'],$_POST['toTableId'],$_POST['alsoNotPayed'],$_POST['queueids']);
} else if ($command == 'removeProductFromQueue') {
$this->removeProductFromQueue($_POST["queueid"]);
} else if ($command == 'getJsonAllQueueItemsToMake') {
$this->getJsonAllQueueItemsToMake(intval($_GET["kind"]));
} else if ($command == 'getJsonLastMadeItems') {
$this->getJsonLastMadeItems(intval($_GET["kind"]));
} else if ($command == 'getJsonLastDeliveredProducts') {
$this->getJsonLastDeliveredProducts();
} else if ($command == 'getJsonProductsOfTableToPay') {
$this->getJsonProductsOfTableToPay($_GET['tableid']);
} else if ($command == 'declarePaidCreateBillReturnBillId') {
$this->declarePaidCreateBillReturnBillId($_POST['ids'],$_POST['html'],$_POST['brutto'],$_POST['netto'],$_POST['tableid'],$_POST['paymentid'],$_POST['tax']);
} else if ($command == 'getNotPrintedWorkItemsAndDeclareThemPrinted') {
$this->getNotPrintedWorkItemsAndDeclareThemPrinted($_GET['tableid']);
} else {
echo "Command not supported.";
}
}
function getTableNameFromId($tableid) {
$sql = "SELECT tableno FROM " . DB_RESTTABLES_TABLE . " WHERE id=". $tableid;
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$tablename = $zeile['tableno'];
mysqli_free_result( $dbresult );
return $tablename;
}
// needed if paydesk gets the tableid by direct call
function getJsonTableNameFromId($tableid) {
echo json_encode($this->getTableNameFromId($tableid));
}
function getDateValueAsBoolInterpretatedIcon($aValue) {
if ($aValue != '0000-00-00 00:00:00' ) {
$imgFile = "ok.png";
} else {
$imgFile = "wait.png";
}
return "<img src=img/" . $imgFile . " />";
}
function getUserName($userid) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT username FROM %user% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($userid));
$row =$stmt->fetchObject();
if ($row != null) {
return($row->username);
} else {
return "";
}
}
/*
* Get the queue items for the kitchen view that have to be still be cooked
* as a json element array
*
* 1. It is sorted for ordertime
* 2. From this ordertime search for the distinct tables
* 3. Sort it that way that tables are grouped together
*
* $kind=0 -> return only food elements, =1 -> return drinks
*/
private function getJsonAllQueueItemsToMake($kind) {
// current time
date_default_timezone_set('Europe/Berlin');
$currentTime = date('Y-m-d H:i:s');
// first sort all non-ready products ordered by ordertime
$sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,ordertime,cooking FROM %queue%,%products%,%prodtype%,%resttables%,%bill% ";
$sql .= "WHERE (readytime = '0000-00-00 00:00:00' AND ";
$sql .= " ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr = %resttables%.id AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind='$kind' AND ";
$sql .= "%queue%.workprinted='0') ";
// now remove closed items
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql .= "ORDER BY ordertime";
$dbresult = $this->dbutils->performSqlCommand($sql);
$resultarray = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC))
{
$waitTime = round(abs(strtotime($currentTime) - strtotime($zeile['ordertime'])) / 60,0);
$cook = $zeile['cooking'];
if (is_null($cook)) {
$cook = 0;
}
$arr = array("id" => $zeile['id'],
"tablenr" => $zeile['tableno'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"cooking" => $cook,
"waittime" => $waitTime
);
$resultarray[] = $arr;
}
mysqli_free_result( $dbresult );
$tablearray = array();
$insertedTables = array();
$table = (-1);
if (count($resultarray) <> 0) {
for ($queue_index=0;$queue_index < count($resultarray);$queue_index++) {
$aTable = $resultarray[$queue_index]['tablenr'];
if (($table <> $aTable) && !in_array($aTable,$insertedTables)) {
// sort all entries for this table
$table = $aTable;
$maxWaitTime = $resultarray[$queue_index]['waittime'];
$tableArr = array();
for ($i=0;$i<count($resultarray);$i++) {
if ($resultarray[$i]['tablenr'] == $table) {
$foundItem = $resultarray[$i];
$waittimeofentry = intval($foundItem['waittime']);
// icons of waittime
// 1-20 in 1 min steps
// 25,30,40,50,60min
$waitIconMinStep = 1;
if ($waittimeofentry <= 1) {
$waitIconMinStep = 1;
} else if ($waittimeofentry <= 20) {
$waitIconMinStep = strval($waittimeofentry);
} else if ($waittimeofentry <= 25) {
$waitIconMinStep = 25;
} else if ($waittimeofentry <= 30) {
$waitIconMinStep = 30;
} else if ($waittimeofentry <= 40) {
$waitIconMinStep = 40;
} else if ($waittimeofentry <= 50) {
$waitIconMinStep = 50;
} else {
$waitIconMinStep = 60;
}
$waitIconMinStep = $waitIconMinStep . 'min.png';
$anEntryForThisTable = array("id" => $foundItem['id'],
"longname" => $foundItem['longname'],
"option" => $foundItem['option'],
"cooking" => $this->getUserName($foundItem['cooking']),
"waiticon" => $waitIconMinStep,
"waittime" => $waittimeofentry);
$tableArr[] = $anEntryForThisTable;
}
}
// Now fit max wait time of table to entry wait time steps:
if (($maxWaitTime > 20) && ($maxWaitTime < 60)) {
if ($maxWaitTime >= 50) {
$maxWaitTime = "> 50";
} else if ($maxWaitTime >= 40) {
$maxWaitTime = "> 40";
} else if ($maxWaitTime >= 30) {
$maxWaitTime = "> 30";
} else if ($maxWaitTime >= 25) {
$maxWaitTime = "> 25";
} else {
$maxWaitTime = "> 20";
}
} else if ($maxWaitTime <= 1) {
$maxWaitTime = "1";
}
$tablearray[] = array("table" => $table, "count" => count($tableArr), "queueitems" => $tableArr, "maxwaittime" => $maxWaitTime);
$insertedTables[] = $aTable;
}
}
}
echo json_encode($tablearray);
}
/*
* Return in an JSON element declared by kind - product - option all work items that haven't been printed.
* In the next step declare them all printed
*/
private function getNotPrintedWorkItemsAndDeclareThemPrinted($tableid) {
// which elements are not printed yet?
$whereClause = "WHERE ";
$whereClause .= "%queue%.productid=%products%.id AND ";
$whereClause .= "%queue%.tablenr = %resttables%.id AND ";
$whereClause .= "%products%.category=%prodtype%.id AND ";
$whereClause .= "workprinted='0' AND ";
$whereClause .= "ordertime is not null AND ";
$whereClause .= "%resttables%.id='$tableid' AND ";
$whereClause .= "%queue%.readytime = '0000-00-00 00:00:00' AND ";
$whereClause .= "%queue%.cooking is null AND ";
$whereClause .= "%queue%.delivertime = '0000-00-00 00:00:00' ";
$sql = "SELECT %queue%.id as id,longname,anoption,ordertime,kind FROM %queue%,%products%,%prodtype%,%resttables% ";
$sql .= $whereClause;
$sql .= "ORDER BY ordertime";
$dbresult = $this->dbutils->performSqlCommand($sql);
$resultarray = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC))
{
$arr = array("id" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"ordertime" => $zeile['ordertime'],
"kind" => $zeile['kind']
);
$resultarray[] = $arr;
}
mysqli_free_result( $dbresult );
// then declare them as printed
$sql = "UPDATE %queue%,%products%,%prodtype%,%resttables% SET %queue%.workprinted='1' $whereClause";
$dbresult = $this->dbutils->performSqlCommand($sql);
// return result to print
echo json_encode(array("status" => "OK", "msg" => $resultarray));
}
private function getJsonLastMadeItems($kind) {
// first sort all non-ready products ordered by ordertime
$sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables%,%bill% ";
$sql .= "WHERE (readytime <> '0000-00-00 00:00:00' AND ";
$sql .= "delivertime = '0000-00-00 00:00:00' AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr = %resttables%.id AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind='$kind' AND ";
$sql .= "%queue%.workprinted='0') ";
// now remove closed items
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql .= "ORDER BY readytime DESC LIMIT 10;";
$dbresult = $this->dbutils->performSqlCommand($sql);
$resultarray = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC))
{
$productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($productid);
if ($useConditions["usekitchen"] == 1) {
// yes, display it in kitchen view as cooked
$arr = array("id" => $zeile['id'],
"tablename" => $zeile['tableno'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"readytime" => $zeile['readytime']
);
$resultarray[] = $arr;
}
}
mysqli_free_result( $dbresult );
echo json_encode($resultarray);
}
/*
* Kitchen can delare a product as being cooked
*/
function declareProductBeCookingOrCooked($queueid,$action) {
if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
// is product already cooking or will it be set to cooking?
$sql = "SELECT cooking,productid FROM %queue% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid));
$row =$stmt->fetchObject();
if ($row != null) {
$cooking = $row->cooking;
$productid = $row->productid;
if ($action == 'r') {
// product shall be declared ready
if (is_null($cooking)) {
// a product must be cooking before it can be ready!
$pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} else {
$this->reallyDeclareAsCooked($pdo,$queueid);
$useConditions = $this->getUseKitchenAndSupplyForProd($productid);
if ($useConditions["usesupply"] == 0) {
// can bypass the supplydesk
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
}
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
} else if ($action == 'c') {
// product shall be declared as cooking (in progress)
if (!is_null($cooking)) {
// a product must not be cooking before it can becomes cooking
$pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} else {
$userid = $this->getUserId();
$updSql = "UPDATE %queue% SET cooking=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updSql));
$stmt->execute(array($userid,$queueid));
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
}
} else {
$pdo->rollBack();
}
} else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG));
}
}
private function reallyDeclareAsCooked($pdo,$queueid) {
date_default_timezone_set('Europe/Berlin');
$readytime = date('Y-m-d H:i:s');
$insertSql = "UPDATE %queue% SET readytime=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql));
$stmt->execute(array($readytime,$queueid));
}
/*
* Product is not cooked (undo of kitchen)
*/
function declareProductNotBeCooked($queueid) {
if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
// first: is the product still declared as delivered?
$sql = "SELECT id FROM %queue% WHERE id=? AND readytime <> '0000-00-00 00:00:00'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid));
$row =$stmt->fetchObject();
if ($row != null) {
$foundid = $row->id;
if ($foundid == $queueid) {
$sql = "UPDATE %queue% SET readytime='0000-00-00 00:00:00', cooking=NULL WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid));
$pdo->commit();
echo json_encode(array("status" => "OK"));
} else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
$pdo->rollBack();
}
} else {
$pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
}
} else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG));
}
}
private function findCategoryOfProd($prodid) {
$sql = "SELECT category FROM %products% WHERE id=$prodid";
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$categoryid = $zeile['category'];
mysqli_free_result( $dbresult );
return $categoryid;
}
private function getUseKitchenAndSupplyForProdInCat($catid) {
$sql = "SELECT usekitchen, usesupplydesk FROM %prodtype% WHERE id=$catid";
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$useKit = $zeile['usekitchen'];
$useSupply = $zeile['usesupplydesk'];
mysqli_free_result( $dbresult );
return array("usekitchen" => $useKit, "usesupply" => $useSupply);
}
private function getUseKitchenAndSupplyForProd($prodid) {
$catid = $this->findCategoryOfProd($prodid);
return $this->getUseKitchenAndSupplyForProdInCat($catid);
}
private function getUseKitchenAndSupplyForProdWithPdo($pdo,$prodid) {
$sql = "SELECT usekitchen, usesupplydesk FROM %prodtype%,%products% WHERE %products%.category=%prodtype%.id AND %products%.id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($prodid));
$row = $stmt->fetchObject();
if ($row != null) {
return array("usekitchen" => $row->usekitchen, "usesupply" => $row->usesupplydesk);
} else {
return array("usekitchen" => "1", "usesupply" => "1");
}
}
/*
* Add a product list to the queue as if it was ordered by the waiter.
* The ordertime is set by the time that this method is invoked.
*
* If product shall not be run over kitchen or supplydesk this is
* managed here as well
*/
function addProductListToQueue($theTableid,$prods) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
// get current pricelevel
$currentPriceLevel = $this->commonUtils->getCurrentPriceLevel();
$currentPriceLevelId = $currentPriceLevel["id"];
$i = 0;
for ($i=0;$i<count($prods);$i++) {
$aProd = $prods[$i];
$productid = intval($aProd[0]);
$theOption = $aProd[1];
// now get the price for this pricelevel
$getPriceSql = "SELECT priceA,priceB,priceC,longname FROM %products% where id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($getPriceSql));
$stmt->execute(array($productid));
$row = $stmt->fetchObject();
if ($row == null) {
echo "Fehler: Preise nicht vorhanden"; // error
return;
}
$productname = $row->longname;
$price_for_level_A = $row->priceA;
$price_for_level_B = $row->priceB;
$price_for_level_C = $row->priceC;
$price = $price_for_level_A; // default - levl 1
if ($currentPriceLevelId == 2) {
$price = $price_for_level_B;
} else if ($currentPriceLevelId == 3) {
$price = $price_for_level_C;
} // else: use default price A
if (is_numeric($theTableid) && is_numeric($productid)) {
// first get category of product
$useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid);
date_default_timezone_set('Europe/Berlin');
$ordertime = date('Y-m-d H:i:s');
$insertSql = "INSERT INTO `%queue%` (
`id` , `tablenr`,`productid`,`pricelevel`,`price`,`productname`,`ordertime`,`anoption`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`,`action`)
VALUES (
NULL , ?,?,?,?,?,?,?, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL,NULL,'0',NULL,'0','P');";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql));
$stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$productname,$ordertime,$theOption));
$queueid = $pdo->lastInsertId();
if ($useConditions["usekitchen"] == 0) {
// no - can bypass the kitchen
$this->reallyDeclareAsCooked($pdo,$queueid);
// then also look for supplydesk, since kitchen action won't do this!
if ($useConditions["usesupply"] == 0) {
// can bypass the supplydesk
$this->declareProductBeDelivered($queueid);
// THIS autop declares as "prepared" (cooked)!!!
}
}
}
}
$pdo->commit();
echo json_encode("OK");
}
/*
* Do as if the product would have been removed from queue - but don't do it exactly,
* because then it would not appear in the reports any more. Instead declare the
* ordertime = null (was never ordered...)
*/
function removeProductFromQueue($queueid) {
if (is_numeric($queueid)) {
$sql = "UPDATE %queue% SET ordertime=null WHERE id=$queueid";
$dbresult = $this->dbutils->performSqlCommand($sql);
}
}
/*
* Return as JSON structure all products that are assigned to a specified table, with the
* specification that they are not delivered yet.
*
* ordertime must not be null, because =null means that is is paid but was cancelled later
* by the waiter! (in a previous version such entries were deleted from queue, but then
* they won't appear in reports any more)
*
* Return is: [
* {"queueid":"2","longname":"EL Greco 1 Person", "isReady":"1"},
* {"queueid":"5","longname":"Souvlaki","isReady":"0"}]
* (a sample)
*
*/
function getJsonLongNamesOfProdsForTableNotDelivered($tableid) {
if (is_numeric($tableid)) {
$prods = array();
$sql = "SELECT DISTINCT %queue%.id as id,longname,anoption,readytime,delivertime,paidtime ";
$sql .= "FROM %queue%,%products%,%bill% ";
$sql .= "WHERE (%queue%.productid = %products%.id ";
$sql .= "AND tablenr=$tableid AND delivertime = '0000-00-00 00:00:00') ";
$sql .= "AND ordertime is not null ";
$sql .= " AND ";
$sql .= "(%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql .= "ORDER BY ordertime";
$dbresult = $this->dbutils->performSqlCommand($sql);
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$isReady = "1";
$isDelivered = "1";
$isPaid = "1";
if ($zeile['readytime'] == '0000-00-00 00:00:00') {
$isReady = "0"; // not yet prepared by the kitchen
}
if ($zeile['paidtime'] == null) {
$isPaid = "0"; // not yet paid
}
$prodEntry = array(
"queueid" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"isready" => $isReady,
"isPaid" => $isPaid);
$prods[] = $prodEntry;
}
mysqli_free_result( $dbresult );
echo json_encode($prods);
}
}
function changeTable($fromTableId, $toTableId, $doAlsoNotPayed,$queueidsNotDelivered) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$sql = "SELECT DISTINCT %queue%.id as id,longname,anoption,readytime,delivertime,paidtime ";
$sql .= "FROM %queue%,%products%,%bill% ";
$whereClause = "WHERE (%queue%.productid = %products%.id ";
$whereClause .= "AND tablenr=? AND delivertime = '0000-00-00 00:00:00') ";
$whereClause .= "AND ordertime is not null ";
$whereClause .= " AND ";
$whereClause .= "(%queue%.billid is null OR (";
$whereClause .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql .= $whereClause . "ORDER BY ordertime";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($fromTableId));
$result = $stmt->fetchAll();
$queueIdArray = array();
foreach($result as $row) {
$queueIdArray[] = $row['id'];
}
if ($queueIdArray != $queueidsNotDelivered) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
$pdo->rollBack();
} else {
$sql = "UPDATE %queue%,%products%,%bill% SET %queue%.tablenr = ? ";
$sql .= $whereClause;
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($toTableId,$fromTableId));
if ($doAlsoNotPayed == 1) {
$sql = "UPDATE %queue%,%products%,%pricelevel% SET %queue%.tablenr=?
WHERE tablenr = ? AND paidtime is null AND toremove <> '1'
AND %queue%.productid = %products%.id
AND %queue%.pricelevel = %pricelevel%.id
AND ordertime is not null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($toTableId,$fromTableId));
}
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
}
// **********************************
// * Kassenfunktionen *
// **********************************
function getJsonProductsOfTableToPay($tableid) {
$sql = "SELECT %queue%.id as id,longname,%queue%.price as price,%pricelevel%.name as pricelevelname,%products%.id as prodid
FROM %queue%
INNER JOIN %products% ON %queue%.productid = %products%.id
INNER JOIN %pricelevel% ON %queue%.pricelevel = %pricelevel%.id
WHERE tablenr = $tableid AND paidtime is null AND toremove <> '1'
AND ordertime is not null
ORDER BY ordertime;";
$dbresult = $this->dbutils->performSqlCommand($sql);
$prodsToPay = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$thePrice = $zeile['price'];
$thePriceLevelName = $zeile['pricelevelname'];
$longName = $zeile['longname'];
$queueid = $zeile['id'];
$prodId = $zeile['prodid'];
$prodsToPay[] = array("id" => $queueid, "prodid" => $prodId, "longname" => $longName, "pricelevelname" => $thePriceLevelName, "price" => $thePrice);
}
mysqli_free_result( $dbresult );
echo json_encode(array("status" => "OK", "msg" => $prodsToPay));
}
// This function gets the items to pay and creates a table, in which these items
// are listed up. It can be used as a receipt to print later
function displayBill($billtableitems,$totalPrice) {
$numberOfItemsToPay = count($billtableitems);
if ($numberOfItemsToPay > 0) {
echo "<br><br><table id=bill class=billtable>";
echo "<tr><th>Speise/Getränk<th id=pricecolheader>Preis (Euro)</tr>";
for ($i=0;$i < $numberOfItemsToPay; $i++) {
$aProductToPay = $billtableitems[$i];
echo "<tr>";
echo "<td>" . $aProductToPay['textOfButton'] . "<td id=pricecol>" . $aProductToPay['price'] . "</tr>";
}
echo "<tr><td id=totalprice colspan=2>Gesamtpreis: " . $totalPrice . " Euro </tr>";
}
echo "</table>";
}
// **********************************
// * Bereitstellung *
// **********************************
function declareProductBeDeliveredWithGivenPdo($pdo,$queueid) {
if (is_numeric($queueid)) {
date_default_timezone_set('Europe/Berlin');
$delivertime = date('Y-m-d H:i:s');
$updateSql = "UPDATE %queue% SET delivertime=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($delivertime,$queueid));
// then it was probably already prepared
$updateSql = "UPDATE %queue% SET readytime=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($delivertime,$queueid));
}
}
function declareProductBeDelivered($queueid) {
if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$this->declareProductBeDeliveredWithGivenPdo($pdo, $queueid);
$pdo->commit();
}
}
function declareMultipleProductsDelivered($queueids) {
$ids = explode(",",$queueids);
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
for ($i=0;$i < count($ids); $i++) {
$aQueueId = $ids[$i];
if (is_numeric($aQueueId)) {
$this->declareProductBeDeliveredWithGivenPdo($pdo,$aQueueId);
}
}
$pdo->commit();
}
function declareProductNotBeDelivered($queueid) {
if (is_numeric($queueid)) {
date_default_timezone_set('Europe/Berlin');
$delivertime = date('Y-m-d H:i:s');
$updateSql = "UPDATE %queue% SET delivertime='0000-00-00 00:00:00' WHERE id='" . $queueid . "';";
$dbresult = $this->dbutils->performSqlCommand($updateSql);
}
}
private function getAllPreparedProductsForTableidAsArray($tableid) {
$sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,anoption,readytime ";
$sql = $sql . "FROM %queue%,%products%,%resttables%,%bill% ";
$sql = $sql . "WHERE (readytime <> '0000-00-00 00:00:00' and delivertime = '0000-00-00 00:00:00' ";
$sql = $sql . "AND %queue%.productid=%products%.id ";
$sql = $sql . "AND %queue%.tablenr=%resttables%.id ";
$sql = $sql . "AND %resttables%.id=" . $tableid . " ";
$sql = $sql . "AND toremove <> '1') ";
// now remove closed items
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql = $sql . " ORDER BY tableno";
$dbresult = $this->dbutils->performSqlCommand($sql);
// create a table that is optimal (sqrt-like size)
$numberOfIcons = mysqli_num_rows($dbresult);
$arrayOfProdsForTable = array();
$idsProdsOfTable = ''; // this is a hack! All queueids of a table redundant for "Deliver all"
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$theAction= "deliver";
$longname = $zeile['longname'];
$anProdElem = array(
"id" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"status" => "ready_to_deliver");
$arrayOfProdsForTable[] = $anProdElem;
if ($idsProdsOfTable == '') {
$idsProdsOfTable = $idsProdsOfTable . $zeile['id'];
} else {
$idsProdsOfTable = $idsProdsOfTable . ',' . $zeile['id'];
}
}
mysqli_free_result( $dbresult );
return array("prods" => $arrayOfProdsForTable, "ids" => $idsProdsOfTable);
}
// total number of products for table
// can later be used for color indication if products can be delivered completly for a table
private function numberOfProductsForTableNotDelivered($tableid) {
$sql = "SELECT %queue%.id as id ";
$sql = $sql . "FROM %queue%,%resttables% ";
$sql = $sql . "WHERE delivertime = '0000-00-00 00:00:00' ";
$sql = $sql . "AND %queue%.tablenr=%resttables%.id ";
$sql = $sql . "AND toremove <> '1' ";
$sql = $sql . "AND %resttables%.id=" . $tableid;
$dbresult = $this->dbutils->performSqlCommand($sql);
$numberOfProducts = mysqli_num_rows($dbresult);
mysqli_free_result( $dbresult );
return $numberOfProducts;
}
function getJsonAllPreparedProducts() {
// find out the tables that are relevant
$sql = "SELECT DISTINCT tablenr ";
$sql .= "FROM %queue%,%resttables%,%bill% ";
$sql .= "WHERE (readytime <> '0000-00-00 00:00:00' and delivertime = '0000-00-00 00:00:00' ";
$sql .= "AND toremove <> '1' ";
$sql .= "AND %queue%.tablenr=%resttables%.id AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.workprinted='0') ";
// now remove closed items
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql .= " ORDER BY tableno";
$dbresult = $this->dbutils->performSqlCommand($sql);
$tablesToServe = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$tablesToServe[] = $zeile['tablenr'];
}
mysqli_free_result( $dbresult );
// to sort complete prepared tables use two arrays:
$preparedProds_incomplete_tables = array();
$preparedProds = array();
$commonUtils = new CommonUtils();
foreach ($tablesToServe as $tableid) {
$arrayOfProdsAndIdsOfATable = $this->getAllPreparedProductsForTableidAsArray($tableid);
$arrayOfProdsOfATable = $arrayOfProdsAndIdsOfATable['prods'];
$numberOfProductsTotalToServe = $this->numberOfProductsForTableNotDelivered($tableid);
$numberOfReadyProducts = count($arrayOfProdsOfATable);
if ($numberOfReadyProducts >= $numberOfProductsTotalToServe) {
$tablestatus = "complete";
$tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($tableid);
$preparedProds[] = array(
"tableheadline" => $tableheadeline,
"tableid" => $tableid,
"tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable);
} else {
$tablestatus = "incomplete";
$tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($tableid);
$preparedProds_incomplete_tables[] = array(
"tableheadline" => $tableheadeline,
"tableid" => $tableid,
"tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable);
}
}
echo json_encode(array_merge($preparedProds,$preparedProds_incomplete_tables));
}
/*
* Return as JSON object a list of max 10 entries of products that
* have been delivered to a table
*/
function getJsonLastDeliveredProducts() {
$sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid ";
$sql .= "FROM %queue%,%resttables%,%products%,%bill% ";
$sql .= "WHERE (delivertime <> '0000-00-00 00:00:00' ";
$sql .= "AND %queue%.productid=%products%.id ";
$sql .= "AND %queue%.tablenr=%resttables%.id ";
$sql .= "AND toremove <> '1' AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.workprinted='0') ";
// now remove closed items
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
$sql = $sql . "ORDER BY delivertime DESC LIMIT 10";
$dbresult = $this->dbutils->performSqlCommand($sql);
$lastDeliveredProds = array();
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($productid);
if ($useConditions["usesupply"] == 1) {
// yes, display it in supplydesk view as cooked
$deliveredProd = array(
"id" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"delivertime" => $zeile['delivertime'],
"tablename" => $zeile['tableno']);
$lastDeliveredProds[] = $deliveredProd;
}
}
mysqli_free_result( $dbresult );
echo json_encode($lastDeliveredProds);
}
// **********************************
// * Kasse *
// **********************************
/*
* Test if all queue items with the given ids are not paid
* -> if there are paid items --> report error by return negative value
*
* Set paid column with the given date
* Create bill
* Return a bill id
*/
function declarePaidCreateBillReturnBillId($ids,$html,$brutto,$netto,$tableid,$paymentId,$tax) {
$userid = $this->getUserId();
$ids_array = explode ( ',', $ids );
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
// check if all items are not paid yet!
$allNotPaid = true;
for ($i=0;$i<count($ids_array);$i++) {
$anId = $ids_array[$i];
if (is_numeric($anId)) {
$sql = "SELECT count(id) as countid FROM %queue% WHERE paidtime is not null AND id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($anId));
$row =$stmt->fetchObject();
if ($row != null) {
$aCount = $row->countid;
if (($aCount != null) && ($aCount == 1)) {
$allNotPaid = false;
}
}
}
}
// current time
date_default_timezone_set('Europe/Berlin');
$currentTime = date('Y-m-d H:i:s');
$billid = (-1);
if ($allNotPaid == true) {
$billid = -1;
// find highest bill id
$sql = "SELECT id from %bill% ORDER BY id DESC";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$numberOfIds = $stmt->rowCount();
if ($numberOfIds > 0) {
$row =$stmt->fetchObject();
if ($row != null) {
$billid = intval($row->id)+1;
} else {
echo " - row ist null - ";
$pdo->rollBack();
return;
}
} else {
$billid = 1;
}
$html = $this->dbutils->filterString($html);
$brutto = $this->dbutils->filterString($brutto);
$tableid = $this->dbutils->filterString($tableid);
$billInsertSql = "INSERT INTO `%bill%` (`id` , `billdate`,`content`,`brutto`,`netto`,`tableid`,`paymentid`,`userid`,`ref`,`tax`) VALUES (?,?,?,?,?,?,?,?,NULL,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billInsertSql));
$stmt->execute(array($billid,$currentTime,$html,$brutto,$netto,$tableid,$paymentId,$userid,$tax));
// now declare them all to be paid:
for ($i=0;$i<count($ids_array);$i++) {
$queueid = $ids_array[$i];
if (is_numeric($queueid)) {
$updateSql = "UPDATE %queue% SET paidtime=?, billid=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($currentTime,$billid,$queueid));
$billProdsSql = "INSERT INTO `%billproducts%` (`queueid`,`billid`) VALUES ( ?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billProdsSql));
$stmt->execute(array($queueid,$billid));
}
}
}
$pdo->commit();
$billInfo = array("billid" => $billid, "date" => $currentTime);
echo json_encode(array("status" => "OK", "msg" => $billInfo));
}
private function getUserId() {
if(session_id() == '') {
session_start();
}
return $_SESSION['userid'];
}
}
?>