ordersprinter/webapp/php/queuecontent.php

1984 lines
70 KiB
PHP

<?php
require_once ('dbutils.php');
require_once ('products.php');
require_once ('commonutils.php');
require_once ('printqueue.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', 'changeTable','getProdsForTableChange');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_waiter'))) {
echo "Benutzerrechte nicht ausreichend!";
return false;
}
}
// these command are only allowed for user with paydesk rights
$cmdArray = array('getJsonProductsOfTableToPay', 'declarePaidCreateBillReturnBillId');
if (in_array($command, $cmdArray)) {
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"],$_POST["print"],$_POST["payprinttype"]);
} else if ($command == 'getRecords') {
$this->getRecords($_GET["tableid"]);
} 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 == 'getUnpaidTables') {
$this->getUnpaidTables();
} else if ($command == 'getProdsForTableChange') {
$this->getProdsForTableChange($_GET['tableId']);
} else if ($command == 'changeTable') {
$this->changeTable($_POST['fromTableId'],$_POST['toTableId'],$_POST['queueids']);
} else if ($command == 'removeProductFromQueue') {
$this->removeProductFromQueue($_POST["queueid"],$_POST["isPaid"],$_POST["isCooking"],$_POST["isReady"]);
} 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') {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$this->declarePaidCreateBillReturnBillId($pdo,$_POST['ids'],$_POST['tableid'],$_POST['paymentid'],$_POST['declareready'],$_POST['host'],false,$_POST['reservationid'],$_POST['guestinfo'],$_POST['intguestid']);
} else {
echo "Command not supported.";
}
}
private static function setNewProductsToServe($pdo,$val) {
$sql = "SELECT count(id) as countid FROM %work% WHERE item=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array("newproductstoserve"));
if ($row->countid == 0) {
$sql = "INSERT INTO %work% (item,value,signature) VALUES (?,?,?)";
CommonUtils::execSql($pdo, $sql, array("newproductstoserve",$val,null));
} else {
$sql = "UPDATE %work% SET value=? WHERE item=?";
CommonUtils::execSql($pdo, $sql, array($val,"newproductstoserve"));
}
}
private static function getNewProductsToServe($pdo) {
$sql = "SELECT count(id) as countid FROM %work% WHERE item=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array("newproductstoserve"));
if ($row->countid == 0) {
return 0;
} else {
$sql = "SELECT value FROM %work% WHERE item=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array("newproductstoserve"));
return $row->value;
}
}
function getJsonTableNameFromId($tableid) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$commonUtils = new CommonUtils();
echo json_encode($commonUtils->getTableNameFromId($pdo,$tableid));
}
function getUserName($userid) {
$pdo = $this->dbutils->openDbAndReturnPdo();
if (is_null($userid)) {
return "";
}
$sql = "SELECT username FROM %user% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($userid));
if ($row != null) {
return($row->username);
} else {
return "";
}
}
private function areBillExisting($pdo) {
$sql = "SELECT count(id) as countid FROM %bill%";
$row = CommonUtils::getRowSqlObject($pdo, $sql, null);
$count = intval($row->countid);
if ($count > 0) {
return true;
} else {
return false;
}
}
/*
* 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) {
date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s');
$pdo = $this->dbutils->openDbAndReturnPdo();
Guestsync::sync($pdo);
if ($this->areBillExisting($pdo)) {
$sql = "SELECT DISTINCT %queue%.id as id,%resttables%.id as tableid,tablenr,longname,anoption,tableno,date_format(ordertime,'%Y-%m-%d %H:%i:00') as ordertime,cooking,TIMESTAMPDIFF(MINUTE,ordertime,?) AS waittime FROM %queue%,%products%,%prodtype%,%resttables%,%bill% ";
} else {
$sql = "SELECT DISTINCT %queue%.id as id,%resttables%.id as tableid,tablenr,longname,anoption,tableno,date_format(ordertime,'%Y-%m-%d %H:%i:00') as ordertime,cooking,TIMESTAMPDIFF(MINUTE,ordertime,?) AS waittime FROM %queue%,%products%,%prodtype%,%resttables% ";
}
$sql .= "WHERE (readytime IS NULL AND ";
$sql .= " ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr = %resttables%.id AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind=? AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql .= "ORDER BY ordertime,longname,anoption,cooking DESC,%queue%.id";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentTime,$kind));
$result1 = $stmt->fetchAll();
$sql = "SELECT DISTINCT q.id as id,'-' as tableid,'-' as tablenr,longname,anoption,'-' as tableno,date_format(ordertime,'%Y-%m-%d %H:%i:00') as ordertime,cooking,TIMESTAMPDIFF(MINUTE,ordertime,?) AS waittime FROM %products%,%prodtype%,%queue% q LEFT OUTER JOIN %bill% b ";
$sql .= " ON q.billid=b.id ";
$sql .= "WHERE (readytime IS NULL AND ";
$sql .= " ordertime is not null AND ";
$sql .= "q.productid=%products%.id AND ";
$sql .= "q.tablenr is null AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind=? AND ";
$sql .= "q.isclosed is null AND ";
$sql .= "q.workprinted='0') ";
$sql .= "AND (q.billid is null OR ( ";
$sql .= "b.closingid is null)) ";
$sql .= "ORDER BY ordertime,longname,anoption,cooking DESC";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentTime,$kind));
$result2 = $stmt->fetchAll();
$result = array_merge($result1,$result2);
$resultarray = array();
foreach($result as $zeile) {
$waitTime = $zeile['waittime'];
$cook = $zeile['cooking'];
if (is_null($cook)) {
$cook = 0;
}
$arr = array("id" => $zeile['id'],
"tableid" => $zeile['tableid'],
"tablenr" => $zeile['tableno'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"cooking" => $cook,
"waittime" => $waitTime
);
$resultarray[] = $arr;
}
$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)) {
$table = $aTable;
$tableid = $resultarray[$queue_index]['tableid'];
$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']);
$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';
$extras = $this->getExtrasOfQueueItem($pdo,$foundItem['id']);
$anEntryForThisTable = array("id" => $foundItem['id'],
"longname" => $foundItem['longname'],
"option" => $foundItem['option'],
"extras" => $extras,
"cooking" => $this->getUserName($foundItem['cooking']),
"waiticon" => $waitIconMinStep,
"waittime" => $waittimeofentry
);
$tableArr[] = $anEntryForThisTable;
}
}
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, "tableid" => $tableid,"count" => count($tableArr), "queueitems" => $tableArr, "maxwaittime" => $maxWaitTime);
$insertedTables[] = $aTable;
}
}
}
echo json_encode($tablearray);
}
private function getExtrasOfQueueItem($pdo,$queueid) {
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$sql = "SELECT name FROM %queueextras% WHERE queueid=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid));
$extras = $stmt->fetchAll();
$extrasarr = array();
foreach($extras as $anExtra) {
$extrasarr[] = $anExtra["name"];
}
return $extrasarr;
}
private function getExtrasWithIdsOfQueueItem($pdo,$queueid) {
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$sql = "SELECT name,extraid FROM %queueextras% WHERE queueid=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid));
$extras = $stmt->fetchAll();
$extrasnames = array();
$extrasids = array();
foreach($extras as $anExtra) {
$extrasnames[] = $anExtra["name"];
$extrasids[] = $anExtra["extraid"];
}
return array("extrasnames" => $extrasnames,"extrasids" => $extrasids);
}
private function getJobsToPrint($pdo,$kind,$printer,$queueIds) {
if (is_null($queueIds) || (count($queueIds) == 0)) {
return array();
}
$queueStr = implode(',',$queueIds);
$decpoint = CommonUtils::getConfigValue($pdo, 'decpoint', '.');
$groupWorkItems = 'groupworkitemsf';
if ($kind == 1) {
$groupWorkItems = 'groupworkitemsd';
}
$sql = "SELECT setting FROM %config% where name=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($groupWorkItems));
$groupworkitems = $row->setting;
if (is_null($groupworkitems)) {
$groupworkitems = 1;
}
$sql = "SELECT %queue%.id as id,%queue%.tablenr as tableid, %queue%.productid,%queue%.productname as longname,%queue%.price as price,%queue%.togo as togo,anoption,%prodtype%.kind as kind,%prodtype%.printer as printer FROM %queue%,%products%,%prodtype% WHERE %prodtype%.kind=? AND %queue%.id IN ($queueStr) AND productid=%products%.id AND %products%.category=%prodtype%.id ORDER BY longname";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind));
$queueItems = $stmt->fetchAll();
$jobs = array();
foreach($queueItems as $aQueueItem) {
$thePrinter = $aQueueItem["printer"];
$queueid = $aQueueItem["id"];
$tableid = $aQueueItem["tableid"];
if (!is_null($tableid) && ($tableid != 0)) {
$sql = "SELECT DISTINCT %room%.printer as printer FROM %queue%,%resttables%,%room% WHERE %resttables%.id=? AND %resttables%.roomid=%room%.id LIMIT 1";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($tableid));
$roomPrinter = $row->printer;
if (!is_null($roomPrinter)) {
$thePrinter = $roomPrinter;
}
}
if ($thePrinter == $printer) {
$extras = $this->getExtrasOfQueueItem($pdo,$queueid);
$formattedPrice = number_format($aQueueItem["price"], 2, $decpoint, '');
$theEntry = array(
"id" => $queueid,
"productid" => $aQueueItem["productid"],
"longname" => $aQueueItem["longname"],
"singleprod" => $aQueueItem["longname"],
"price" => $formattedPrice,
"togo" => $aQueueItem["togo"],
"anoption" => $aQueueItem["anoption"],
"kind" => $aQueueItem["kind"],
"printer" => $aQueueItem["printer"],
"extras" => $extras
);
if ($groupworkitems) {
$this->grouping($jobs, $theEntry);
} else {
$jobs[] = $theEntry;
}
}
}
if ($groupworkitems == 1) {
foreach($jobs as &$aJob) {
$aJob["singleprod"] = $aJob["longname"];
$cnt = $aJob["count"];
$aJob["longname"] = $cnt . "x " . $aJob["longname"];
$aJob["allqueueids"] = $queueIds;
}
}
return $jobs;
}
private function grouping(&$collection,$entry) {
$extrasTxt = join(",",$entry["extras"]);
$found = false;
foreach($collection as &$anEntry) {
if (($anEntry["longname"] == $entry["longname"]) && ($anEntry["price"] == $entry["price"]) && ($anEntry["togo"] == $entry["togo"]) && ($anEntry["anoption"] == $entry["anoption"]) && (join(",",$anEntry["extras"]) == $extrasTxt)) {
$found = true;
$anEntry["count"] = $anEntry["count"] + 1;
}
}
if (!$found) {
$collection[] = array("id" => $entry["id"],
"productid" => $entry["productid"],
"longname" => $entry["longname"],
"singleprod" => $entry["singleprod"],
"printer" => $entry["printer"],
"anoption" => $entry["anoption"],
"price" => $entry["price"],
"togo" => $entry["togo"],
"kind" => $entry["kind"],
"extras" => $entry["extras"],
"count" => 1
);
}
}
private function filterKindQueueIds($pdo,$idArr,$kind) {
$retArr = array();
if (is_null($idArr) || (count($idArr) == 0)) {
return $retArr;
}
$sql = "SELECT %queue%.id as id,kind from %prodtype%,%products%,%queue% where %queue%.id=? AND productid=%products%.id AND category=%prodtype%.id";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
foreach($idArr as $id) {
$stmt->execute(array($id));
$row = $stmt->fetchObject();
if ($row->kind == $kind) {
$retArr[] = $id;
}
}
return $retArr;
}
private function doWorkPrint($pdo,$theTableid,$insertedQueueIds,$username,$payPrintType,$lang,$declareReadyDelivered = true) {
$oneProdForEachWorkRecf = CommonUtils::getConfigValue($pdo, 'oneprodworkrecf', 0);
$oneProdForEachWorkRecd = CommonUtils::getConfigValue($pdo, 'oneprodworkrecd', 0);
$foodIds = $this->filterKindQueueIds($pdo, $insertedQueueIds, 0);
$drinkIds = $this->filterKindQueueIds($pdo, $insertedQueueIds, 1);
if (($payPrintType != "s") || ($oneProdForEachWorkRecf == 0)) {
$this->doWorkPrintCore($pdo,$theTableid,$foodIds,$username,$payPrintType,$lang,$declareReadyDelivered);
}
if (($payPrintType != "s") || ($oneProdForEachWorkRecd == 0)) {
$this->doWorkPrintCore($pdo,$theTableid,$drinkIds,$username,$payPrintType,$lang,$declareReadyDelivered);
}
if ($payPrintType != 's') {
return;
}
if ($oneProdForEachWorkRecf == 1) {
foreach($foodIds as $aQueueId) {
$this->doWorkPrintCore($pdo,$theTableid,array($aQueueId),$username,$payPrintType,$lang,$declareReadyDelivered);
}
}
if ($oneProdForEachWorkRecd == 1) {
foreach($drinkIds as $aQueueId) {
$this->doWorkPrintCore($pdo,$theTableid,array($aQueueId),$username,$payPrintType,$lang,$declareReadyDelivered);
}
}
}
private function doWorkPrintCore($pdo,$theTableid,$insertedQueueIds,$username,$payPrintType,$lang,$declareReadyDelivered = true) {
$foodJobsPrinter1 = $this->getJobsToPrint($pdo, 0, 1, $insertedQueueIds);
$foodJobsPrinter2 = $this->getJobsToPrint($pdo, 0, 2, $insertedQueueIds);
$drinkJobsPrinter1 = $this->getJobsToPrint($pdo, 1, 1, $insertedQueueIds);
$drinkJobsPrinter2 = $this->getJobsToPrint($pdo, 1, 2, $insertedQueueIds);
if ($payPrintType == "s") {
$this->createAWorkReceiptAndQueueWorkPrint($pdo,$foodJobsPrinter1,$theTableid,0,1,$username,$lang);
$this->createAWorkReceiptAndQueueWorkPrint($pdo,$foodJobsPrinter2,$theTableid,0,2,$username,$lang);
$this->createAWorkReceiptAndQueueWorkPrint($pdo,$drinkJobsPrinter1,$theTableid,1,1,$username,$lang);
$this->createAWorkReceiptAndQueueWorkPrint($pdo,$drinkJobsPrinter2,$theTableid,1,2,$username,$lang);
}
if ($declareReadyDelivered) {
$printAndQueueJobs = CommonUtils::getConfigValue($pdo, "printandqueuejobs", 0);
if ($printAndQueueJobs == 0) {
$this->declareReadyAndDelivered($pdo, $insertedQueueIds);
}
}
$result = array_merge($foodJobsPrinter1,$foodJobsPrinter2,$drinkJobsPrinter1,$drinkJobsPrinter2);
return $result;
}
private function declareReadyAndDelivered($pdo,$queueids) {
date_default_timezone_set(DbUtils::getTimeZone());
$now = date('Y-m-d H:i:s');
$germanTime = date('H:i');
$sql = "UPDATE %queue% SET workprinted='1',readytime=?,delivertime=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
foreach($queueids as $anId) {
$stmt->execute(array($now,$now,$anId));
}
}
private function createAWorkReceiptAndQueueWorkPrint($pdo,$jobs,$theTableid,$kind,$printer,$user,$lang) {
if (count($jobs) < 1) {
return;
}
date_default_timezone_set(DbUtils::getTimeZone());
$germanTime = date('H:i');
$resultarray = array();
foreach($jobs as $aJob) {
$queueId = $aJob["id"];
$extras = $this->getExtrasOfQueueItem($pdo,$queueId);
$togo = "";
if ($aJob['togo'] == 1) {
$togo = "To-Go";
}
$arr = array("id" => $queueId,
"longname" => $aJob['longname'],
"singleprod" => $aJob['singleprod'],
"price" => $aJob['price'],
"togo" => $togo,
"option" => $aJob['anoption'],
"extras" => $extras,
"ordertime" => $germanTime,
"kind" => $kind,
"printer" => $printer,
"allqueueids" => $aJob["allqueueids"]
);
$resultarray[] = $arr;
}
if (is_null($theTableid) || ($theTableid == 0)) {
$takeAwayStr = array("Zum Mitnehmen","Take away","Para llevar");
$tablename = $takeAwayStr[$lang];
} else {
$sql = "SELECT tableno,%room%.abbreviation FROM %resttables%,%room% WHERE %resttables%.id=? AND %resttables%.roomid=%room%.id";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($theTableid));
if (is_null($row->abbreviation) || ($row->abbreviation == '')) {
$tablename = $row->tableno;
} else {
$tablename = $row->abbreviation . "-" . $row->tableno;
}
}
PrintQueue::queueWorkPrintJob($pdo, $tablename, $germanTime, $resultarray, $kind, $printer, $user);
}
private function getJsonLastMadeItems($kind) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
if ($this->areBillExisting($pdo)) {
$sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables%,%bill% ";
} else {
$sql = "SELECT DISTINCT %queue%.id as id,tablenr,longname,anoption,tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%resttables% ";
}
$sql .= "WHERE (readytime IS NOT NULL AND ";
$sql .= "delivertime IS NULL AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr = %resttables%.id AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind=? AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql .= "ORDER BY readytime DESC LIMIT 10;";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind));
$result1 = $stmt->fetchAll();
if ($this->areBillExisting($pdo)) {
$sql = "SELECT DISTINCT %queue%.id as id,0 as tablenr,longname,anoption,'-' as tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype%,%bill% ";
} else {
$sql = "SELECT DISTINCT %queue%.id as id,0 as tablenr,longname,anoption,'-' as tableno,readytime,%products%.id as prodid FROM %queue%,%products%,%prodtype% ";
}
$sql .= "WHERE (readytime IS NOT NULL AND ";
$sql .= "delivertime IS NULL AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.productid=%products%.id AND ";
$sql .= "%queue%.tablenr is null AND ";
$sql .= "%products%.category=%prodtype%.id AND ";
$sql .= "%prodtype%.kind=? AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql .= "ORDER BY readytime DESC LIMIT 10;";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind));
$result2 = $stmt->fetchAll();
$result = array_merge($result1,$result2);
$resultarray = array();
foreach($result as $zeile) {
$extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']);
$productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usekitchen"] == 1) {
$arr = array("id" => $zeile['id'],
"tablename" => $zeile['tableno'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"extras" => $extras,
"readytime" => $zeile['readytime']
);
$resultarray[] = $arr;
}
}
$resultarray = $this->appendProdsForBarKitchenAndAutoDelivery($pdo,$kind, $resultarray);
echo json_encode($resultarray);
}
private function appendProdsForBarKitchenAndAutoDelivery($pdo,$kind,$resultarray) {
$sql = "SELECT DISTINCT q.id as id,tableno as tablename,longname,delivertime,anoption,p.id as prodid ";
$sql .= "FROM %queue% q ";
$sql .= "LEFT JOIN %bill% b ON q.billid=b.id ";
$sql .= "INNER JOIN %products% p ON q.productid=p.id ";
$sql .= "INNER JOIN %prodtype% t ON p.category=t.id AND t.kind=? AND t.usesupplydesk='0' AND t.usekitchen='1' ";
$sql .= "LEFT JOIN %resttables% r ON q.tablenr=r.id ";
$sql .= "WHERE q.workprinted='0' AND toremove <> '1' AND q.readytime IS NOT NULL AND ordertime is not null ";
$sql .= " AND (q.billid is null OR (q.billid=b.id AND b.closingid is null)) ";
$sql .= "ORDER BY q.delivertime DESC LIMIT 50";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($kind));
$result = $stmt->fetchAll();
foreach ($result as $zeile) {
$extras = $this->getExtrasOfQueueItem($pdo,$zeile['id']);
$deliveredProd = array(
"id" => $zeile['id'],
"tablename" => $zeile['tablename'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"extras" => $extras,
"readytime" => $zeile['delivertime']
);
$resultarray[] = $deliveredProd;
}
return($resultarray);
}
function getTableIdOfQueue($pdo,$queueid) {
$sql = "SELECT tablenr as tableid FROM %queue% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($queueid));
return $row->tableid;
}
/*
* Kitchen can delare a product as being cooked
*/
function declareProductBeCookingOrCooked($queueid,$action) {
if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$sql = "SELECT cooking,productid FROM %queue% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($queueid));
if ($row != null) {
$cooking = $row->cooking;
$productid = $row->productid;
if ($action == 'r') {
if (is_null($cooking)) {
$pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => ERROR_DB_PAR_ACCESS, "msg" => ERROR_DB_PAR_ACCESS_MSG));
} else {
$this->reallyDeclareAsCooked($pdo,$queueid);
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usesupply"] == 0) {
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
} else {
self::setNewProductsToServe($pdo, 1);
}
$payprinttype = CommonUtils::getConfigValue($pdo, 'payprinttype', "l");
$digiprintwork = CommonUtils::getConfigValue($pdo, 'digiprintwork', 1);
if (($payprinttype === 's') && ($digiprintwork == 1)) {
$theTableid = $this->getTableIdOfQueue($pdo, $queueid);
if (is_null($theTableid)) {
$theTableid = 0;
}
$this->doWorkPrint($pdo,$theTableid,array($queueid),$_SESSION['currentuser'],$payprinttype, $_SESSION['language'],false);
}
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
} else if ($action == 'c') {
if (!is_null($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(DbUtils::getTimeZone());
$readytime = date('Y-m-d H:i:s');
$insertSql = "UPDATE %queue% SET readytime=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($insertSql));
$stmt->execute(array($readytime,$queueid));
}
/*
* Product is not cooked (undo of kitchen)
*/
function declareProductNotBeCooked($queueid) {
if (is_numeric($queueid)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$sql = "SELECT id FROM %queue% WHERE id=? AND readytime IS NOT NULL";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($queueid));
if ($row != null) {
$foundid = $row->id;
if ($foundid == $queueid) {
$sql = "UPDATE %queue% SET readytime=?, delivertime=?, cooking=NULL WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array(null,null,$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($pdo,$prodid) {
$sql = "SELECT category FROM %products% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($prodid));
return $row->category;
}
private function getUseKitchenAndSupplyForProdInCat($pdo,$catid) {
$sql = "SELECT usekitchen, usesupplydesk FROM %prodtype% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($catid));
return array("usekitchen" => $row->usekitchen, "usesupply" => $row->usesupplydesk);
}
private function getUseKitchenAndSupplyForProd($pdo,$prodid) {
$catid = $this->findCategoryOfProd($pdo,$prodid);
return $this->getUseKitchenAndSupplyForProdInCat($pdo,$catid);
}
private function getUseKitchenAndSupplyForProdWithPdo($pdo,$prodid) {
$sql = "SELECT usekitchen, usesupplydesk FROM %prodtype%,%products% WHERE %products%.category=%prodtype%.id AND %products%.id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($prodid));
if ($row != null) {
return array("usekitchen" => $row->usekitchen, "usesupply" => $row->usesupplydesk);
} else {
return array("usekitchen" => "1", "usesupply" => "1");
}
}
function getRecords($tableid) {
if (!($this->userrights->hasCurrentUserRight('right_waiter')) && !($this->userrights->hasCurrentUserRight('right_paydesk'))) {
echo json_encode(array("status" => "ERROR","msg" => "Benutzerrechte nicht ausreichend"));
return false;
}
$pdo = DbUtils::openDbAndReturnPdoStatic();
if ($tableid != 0) {
$sql = "SELECT id,TIME(date) as time,(IF(userid is null,'-',(SELECT username FROM %user% WHERE %user%.id=userid))) as username,action,tableid FROM %records% WHERE tableid=? ORDER BY time DESC";
$entries = CommonUtils::fetchSqlAll($pdo, $sql, array($tableid));
} else {
$sql = "SELECT id,TIME(date) as time,(IF(userid is null,'-',(SELECT username FROM %user% WHERE %user%.id=userid))) as username,action,tableid FROM %records% WHERE tableid is null ORDER BY time DESC";
$entries = CommonUtils::fetchSqlAll($pdo, $sql, null);
}
$records = array();
foreach($entries as $anEntry) {
$sql = "SELECT queueid FROM %recordsqueue% WHERE recordid=?";
$queueids = CommonUtils::fetchSqlAll($pdo, $sql, array($anEntry["id"]));
$prods = array();
foreach($queueids as $queueid) {
$sql = "SELECT productid,longname FROM %products%,%queue% WHERE %queue%.id=? AND %queue%.productid=%products%.id";
$prodInfo = CommonUtils::fetchSqlAll($pdo, $sql, array($queueid["queueid"]));
if (count($prodInfo) == 0) {
break;
}
$sql = "SELECT extraid,name FROM %queueextras% WHERE queueid=?";
$extras = CommonUtils::fetchSqlAll($pdo, $sql, array($queueid["queueid"]));
$extrasArr = array();
foreach($extras as $e) {
$extrasArr[] = $e["name"];
}
$extrasStr = implode(',', $extrasArr);
$prods[] = array("name" => $prodInfo[0]["longname"],"extras" => $extrasStr);
}
$records[] = array("id" => $anEntry["id"],"time" => $anEntry["time"],"username" => $anEntry["username"],"action" => $anEntry["action"],"prods" => $prods);
}
echo json_encode(array("status" => "OK","msg" => $records));
}
/*
* Add a product list to the queue as if it was ordered by the waiter.
* The ordertime is set by the time that this method is invoked.
*
* If product shall not be run over kitchen or supplydesk this is
* managed here as well
*/
function addProductListToQueue($theTableid,$prods,$doPrint,$payprinttype) {
if (intval($theTableid) == 0) {
$theTableid = null; // togo room
}
if(session_id() == '') {
session_start();
}
date_default_timezone_set(DbUtils::getTimeZone());
$ordertime = date('Y-m-d H:i:s');
$pdo = $this->dbutils->openDbAndReturnPdo();
$printAndQueueJobs = CommonUtils::getConfigValue($pdo, "printandqueuejobs", 0);
if ($printAndQueueJobs == 1) {
$doPrint = 1;
}
$pdo->beginTransaction();
$togotax = CommonUtils::getExistingConfigValue($pdo, 'togotax');
$normaltax = CommonUtils::getExistingConfigValue($pdo, 'tax');
$workflowconfig = CommonUtils::getExistingConfigValue($pdo, 'workflowconfig');
$austria = CommonUtils::getExistingConfigValue($pdo, 'austria');
$currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo);
$currentPriceLevelId = $currentPriceLevel["id"];
$insertedQueueIds = array();
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($ordertime,$_SESSION['userid'],$theTableid,T_ORDER));
$recordid = $pdo->lastInsertId();
$i = 0;
for ($i=0;$i<count($prods);$i++) {
$aProd = $prods[$i];
$productid = intval($aProd["prodid"]);
$theOption = $aProd["option"];
$theChangedPrice = $aProd["changedPrice"];
$theChangedPrice = str_replace(',','.',$theChangedPrice);
$getPriceSql = "SELECT priceA,priceB,priceC,longname,tax,taxaustria,amount FROM %products% where id=?";
$row = CommonUtils::getRowSqlObject($pdo, $getPriceSql, array($productid));
if ($row == null) {
echo "Fehler: Preise nicht vorhanden"; // error
return;
}
if (!is_null($row->amount)) {
$amount = max(($row->amount -1),0);
$sql = "UPDATE %products% SET amount=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($amount,$productid));
}
$productname = $row->longname;
if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) {
$price_for_level_A = $row->priceA;
$price_for_level_B = $row->priceB;
$price_for_level_C = $row->priceC;
$price = $price_for_level_A; // default - levl 1
if ($currentPriceLevelId == 2) {
$price = $price_for_level_B;
} else if ($currentPriceLevelId == 3) {
$price = $price_for_level_C;
} // else: use default price A
} else {
$price = $theChangedPrice;
}
$togo = $aProd["togo"];
$tax = $normaltax;
if (is_null($theTableid)) {
$tax = $togotax;
}
if ($togo == 1) {
$tax = $togotax;
}
if ($austria == 1) {
$taxaustrianumber = $row->taxaustria;
$configItem = "";
switch($taxaustrianumber) {
case 1:
$configItem = "taxaustrianormal";
break;
case 2:
$configItem = "taxaustriaerm1";
break;
case 3:
$configItem = "taxaustriaerm2";
break;
case 4:
$configItem = "taxaustriaspecial";
break;
default:
$configItem = "taxaustrianormal";
}
$tax = CommonUtils::getExistingConfigValue($pdo, $configItem);
} else {
$taxaustrianumber = null;
if (!is_null($row->tax)) {
$tax = $row->tax;
}
}
$extras = null;
if (array_key_exists("extras",$aProd)) {
$extras = $aProd["extras"];
}
if (($theChangedPrice == "NO") || (!is_numeric($theChangedPrice))) {
if (!is_null($extras) && ($extras != "")) {
for ($j=0;$j<count($extras);$j++) {
$anExtra = $extras[$j];
$extraid = $anExtra["id"];
$extraname = $anExtra["name"];
$sql = "SELECT price FROM %extras% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($extraid));
$price += floatval($row->price);
}
}
}
if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) {
$useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid);
$insertSql = "INSERT INTO `%queue%` (
`id` , `tablenr`,`productid`,`pricelevel`,`price`,`tax`,`taxaustria`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`)
VALUES (
NULL , ?,?,?,?,?,?,?,?,?,?,?,?, null, null, NULL,NULL,'0',NULL,'0');";
$stmt = $pdo->prepare(DbUtils::substTableAlias($insertSql));
$stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$tax,$taxaustrianumber,$productname,$ordertime,$_SESSION['userid'],$theOption,($theChangedPrice == "NO" ? 0 : 1),$togo));
$queueid = $pdo->lastInsertId();
$sql = "INSERT INTO %recordsqueue% (recordid,queueid) VALUES(?,?)";
CommonUtils::execSql($pdo, $sql, array($recordid,$queueid));
if (!is_null($extras) && ($extras != "")) {
for ($j=0;$j<count($extras);$j++) {
$anExtra = $extras[$j];
$extraid = $anExtra["id"];
$extraname = $anExtra["name"];
$sql = "INSERT INTO %queueextras% (`id`,`queueid`,`extraid`,`name`) VALUES(NULL,?,?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($queueid,$extraid,$extraname));
}
}
if (($workflowconfig == 3) && ($doPrint == 0)) {
$this->reallyDeclareAsCooked($pdo,$queueid);
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
} else {
if ($useConditions["usekitchen"] == 0) {
$this->reallyDeclareAsCooked($pdo,$queueid);
if ($useConditions["usesupply"] == 0) {
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
}
} else {
$insertedQueueIds[] = $queueid;
}
}
}
}
$cashenabled = CommonUtils::getConfigValue($pdo, "cashenabled", 1);
if ($cashenabled == 0) {
$idStr = join(',',$insertedQueueIds);
$this->declarePaidCreateBillReturnBillId($pdo,$idStr, $theTableid, 1, 0, 0, true,'','','');
}
if ($doPrint == 1) {
if ($payprinttype == "s") {
$this->doWorkPrint($pdo,$theTableid,$insertedQueueIds,$_SESSION['currentuser'],$payprinttype, $_SESSION['language']);
echo json_encode(array("status" => "OK"));
} else {
$result = $this->doWorkPrint($pdo,$theTableid,$insertedQueueIds,$_SESSION['currentuser'],$payprinttype, $_SESSION['language']);
echo json_encode(array("status" => "OK", "msg" => $result));
}
} else {
echo json_encode(array("status" => "OK"));
}
$pdo->commit();
}
function addProductListToQueueForGuest($pdo,$ordertime,$theTableid,$prodid,$doPrint) {
if(session_id() == '') {
session_start();
}
date_default_timezone_set(DbUtils::getTimeZone());
$pdo->beginTransaction();
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($ordertime,null,$theTableid,T_ORDER));
$recordid = $pdo->lastInsertId();
$tax = CommonUtils::getExistingConfigValue($pdo, 'tax');
$workflowconfig = CommonUtils::getExistingConfigValue($pdo, 'workflowconfig');
$currentPriceLevel = $this->commonUtils->getCurrentPriceLevel($pdo);
$currentPriceLevelId = $currentPriceLevel["id"];
$insertedQueueIds = array();
$productid = $prodid;
$theOption = '';
$theChangedPrice = "NO";
$getPriceSql = "SELECT priceA,priceB,priceC,longname,tax,taxaustria,amount FROM %products% where id=?";
$row = CommonUtils::getRowSqlObject($pdo, $getPriceSql, array($productid));
if ($row == null) {
echo "Fehler: Preise nicht vorhanden"; // error
return;
}
if (!is_null($row->amount)) {
$amount = max(($row->amount -1),0);
$sql = "UPDATE %products% SET amount=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($amount,$productid));
}
$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
$taxaustrianumber = null;
if (!is_null($row->tax)) {
$tax = $row->tax;
}
if (is_null($theTableid) || (is_numeric($theTableid) && is_numeric($productid))) {
$useConditions = $this->getUseKitchenAndSupplyForProdWithPdo($pdo,$productid);
$insertSql = "INSERT INTO `%queue%` (
`tablenr`,`productid`,`pricelevel`,`price`,`tax`,`taxaustria`,`productname`,`ordertime`,`orderuser`,`anoption`,`pricechanged`,`togo`,`readytime`,`delivertime`,`paidtime`,`billid`,`toremove`,`cooking`,`workprinted`)
VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?, null, null, NULL,NULL,'0',NULL,'0');";
$stmt = $pdo->prepare(DbUtils::substTableAlias($insertSql));
$stmt->execute(array($theTableid,$productid,$currentPriceLevelId,$price,$tax,$taxaustrianumber,$productname,$ordertime,null,$theOption,($theChangedPrice == "NO" ? 0 : 1),0));
$queueid = $pdo->lastInsertId();
$sql = "INSERT INTO %recordsqueue% (recordid,queueid) VALUES(?,?)";
CommonUtils::execSql($pdo, $sql, array($recordid,$queueid));
if (($workflowconfig == 3) && ($doPrint == 0)) {
$this->reallyDeclareAsCooked($pdo,$queueid);
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
} else {
if ($useConditions["usekitchen"] == 0) {
$this->reallyDeclareAsCooked($pdo,$queueid);
if ($useConditions["usesupply"] == 0) {
$this->declareProductBeDeliveredWithGivenPdo($pdo,$queueid);
}
} else {
$insertedQueueIds[] = $queueid;
}
}
}
$cashenabled = CommonUtils::getConfigValue($pdo, "cashenabled", 1);
if ($cashenabled == 0) {
$idStr = join(',',$insertedQueueIds);
$this->declarePaidCreateBillReturnBillId($pdo,$idStr, $theTableid, 1, 0, 0, true,'','','');
}
if ($doPrint == 1) {
$this->doWorkPrint($pdo,$theTableid,$insertedQueueIds,'Gastbestellung','s', $_SESSION['language']);
}
$pdo->commit();
}
/*
* 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,$isPaid,$isCooking,$isReady) {
if (is_numeric($queueid)) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s');
$userid = $this->getUserId();
$sql = "SELECT tablenr FROM %queue% WHERE id=?";
$result = CommonUtils::fetchSqlAll($pdo, $sql, array($queueid));
if (count($result) == 0) {
echo json_encode(array("status" => "OK"));
return;
}
$tableid = $result[0]["tablenr"];
$sql = "SELECT count(id) as countid FROM %bill%";
$row = CommonUtils::getRowSqlObject($pdo, $sql, null);
$hasBills = ($row->countid > 0 ? true : false);
if ($hasBills) {
$sql = "UPDATE %queue%,%bill% ";
} else {
$sql = "UPDATE %queue% ";
}
$sql .= "SET ordertime=null WHERE %queue%.id=? AND ordertime IS NOT NULL ";
if ($isPaid == '1') {
$sql .= " AND paidtime IS NOT NULL ";
} else {
$sql .= " AND (paidtime IS NULL or paidtime is null) ";
}
if ($isCooking == '1') {
$sql .= " AND cooking is not null ";
} else {
$sql .= " AND cooking is null ";
}
if ($isReady == '1') {
$sql .= " AND readytime IS NOT NULL ";
} else {
$sql .= " AND (readytime IS NULL or readytime is null) ";
}
if ($hasBills) {
$sql .= " AND (billid is null OR (";
$sql .= " billid = %bill%.id AND %bill%.closingid is null)) ";
}
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($queueid));
$rowsAffected = $stmt->rowCount();
if ($rowsAffected == 1) {
Workreceipts::createCancelWorkReceipt($pdo, $queueid);
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($currentTime,$userid,$tableid,T_REMOVE));
$recordid = $pdo->lastInsertId();
$sql = "INSERT INTO %recordsqueue% (recordid,queueid) VALUES(?,?)";
CommonUtils::execSql($pdo, $sql, array($recordid,$queueid));
echo json_encode(array("status" => "OK"));
} else {
echo json_encode(array("status" => "Failed", "msg" => "Affected rows: $rowsAffected"));
}
}
}
function getUnpaidTables() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT DISTINCT %resttables%.tableno as tablename FROM %queue%,%resttables% WHERE paidtime is null AND ordertime is not null and tablenr=%resttables%.id AND isclosed is null";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$unpaidTables = array();
foreach ($result as $anUnpaidTable) {
$unpaidTables[] = $anUnpaidTable["tablename"];
}
echo json_encode(array("status" => "OK","msg" => join(",",$unpaidTables)));
}
/*
* 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();
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT count(id) as countid FROM %bill%";
$row = CommonUtils::getRowSqlObject($pdo, $sql, null);
if ($row->countid == 0) {
$sql = "SELECT DISTINCT %queue%.id as quid, ordertime FROM %queue% WHERE ordertime is not null AND isclosed is null AND ";
} else {
$sql = "SELECT DISTINCT %queue%.id as quid, ordertime FROM %queue%,%bill% WHERE ordertime is not null AND isclosed is null AND ((%queue%.billid is null AND %queue%.paidtime is null) OR (%queue%.billid=%bill%.id AND %bill%.closingid is null)) AND ";
}
if ($tableid == 0) {
$sql .= "%queue%.tablenr is null ORDER BY ordertime, quid";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
} else {
$sql .= "%queue%.tablenr=? ORDER BY ordertime, quid";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid));
}
$allNotClosedQueueIds = $stmt->fetchAll();
$resultids = array();
$sql = "SELECT count(id) as countid FROM %queue% WHERE %queue%.id=? AND (%queue%.delivertime IS NULL ";
$sql .= " OR %queue%.readytime IS NULL ";
$sql .= " OR (%queue%.billid is null AND %queue%.paidtime is null)) ";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
foreach($allNotClosedQueueIds as $aQueueId) {#
$aQId = $aQueueId["quid"];
$stmt->execute(array($aQId));
$row = $stmt->fetchObject();
if ($row->countid > 0) {
$resultids[] = $aQId;
}
}
$prods = array();
$sql = "SELECT productid,readytime,paidtime,cooking,productname,anoption,productname,togo,pricechanged,price FROM %queue% WHERE id=? ORDER BY productid ";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
foreach ($resultids as $anId) {
$stmt->execute(array($anId));
$row = $stmt->fetchObject();
$isReady = "1";
$isDelivered = "1";
$isPaid = "1";
$isCooking = '1';
if ($row->readytime == null) {
$isReady = "0"; // not yet prepared by the kitchen
}
if ($row->paidtime == null) {
$isPaid = "0"; // not yet paid
}
if (is_null($row->cooking)) {
$isCooking = '0';
}
$extras = $this->getExtrasWithIdsOfQueueItem($pdo,$anId);
$prodEntry = array(
"id" =>$anId,
"prodid" => $row->productid,
"longname" => $row->productname,
"option" => $row->anoption,
"pricechanged" => $row->pricechanged,
"togo" => $row->togo,
"price" => $row->price,
"extras" => $extras["extrasnames"],
"extrasids" => $extras["extrasids"],
"isready" => $isReady,
"isPaid" => $isPaid,
"isCooking" => $isCooking);
$prods[] = $prodEntry;
}
echo json_encode($prods);
}
}
function getProdsForTableChange($tableid) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
if ($tableid == 0) {
$tableid = null;
}
$sql = "SELECT %queue%.id as queueid,productname FROM ";
$sql .= "%queue% WHERE ";
$sql .= "(tablenr=? OR (tablenr IS NULL AND ? IS NULL)) AND ordertime is not null AND isclosed is null AND billid is null ";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid,$tableid));
$unpaidresultungrouped = $stmt->fetchAll();
$sql = "SELECT %queue%.id as queueid,productname FROM ";
$sql .= "%queue% LEFT OUTER JOIN %bill% ON %queue%.billid=%bill%.id WHERE ";
$sql .= "(tablenr=? OR (tablenr IS NULL AND ? IS NULL)) AND ordertime is not null AND isclosed is null AND billid is null AND (";
$sql .= "%queue%.delivertime IS NULL OR ";
$sql .= "(%queue%.delivertime IS NOT NULL AND workprinted='1')) ";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid,$tableid));
$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","msg" => $merged));
}
function isQueueIdInList($queueid,$list) {
foreach($list as $entry) {
if ($entry['queueid'] == $queueid) {
return true;
}
}
return false;
}
function changeTable($fromTableId, $toTableId, $queueids) {
$ids = explode(",",$queueids);
foreach($ids as $id) {
if (!is_numeric($id)) {
echo json_encode(array("status" => "ERROR", "code" => NUMBERFORMAT_ERROR, "msg" => NUMBERFORMAT_ERROR_MSG));
return;
}
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s');
$userid = $this->getUserId();
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($currentTime,$userid,$fromTableId,T_FROM_TABLE));
$recordidFromTable = $pdo->lastInsertId();
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($currentTime,$userid,$toTableId,T_TO_TABLE));
$recordidToTable = $pdo->lastInsertId();
$sql = "INSERT INTO %recordsqueue% (recordid,queueid) VALUES(?,?)";
foreach($ids as $id) {
CommonUtils::execSql($pdo, $sql, array($recordidFromTable,$id));
CommonUtils::execSql($pdo, $sql, array($recordidToTable,$id));
}
$sql = "UPDATE %queue% SET tablenr=? WHERE id IN($queueids) AND tablenr=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($toTableId,$fromTableId));
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
function getJsonProductsOfTableToPay($tableid) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT %queue%.id as id,longname,%queue%.price as price,%queue%.tax,%prodtype%.kind as kind,%pricelevel%.name as pricelevelname,%products%.id as prodid,%queue%.togo as togo, ordertime
FROM %queue%
INNER JOIN %products% ON %queue%.productid = %products%.id
INNER JOIN %pricelevel% ON %queue%.pricelevel = %pricelevel%.id
INNER JOIN %prodtype% ON %products%.category = %prodtype%.id ";
if ($tableid == 0) {
$sql .= "WHERE tablenr is null ";
} else {
$sql .= "WHERE tablenr = $tableid ";
}
$sql .= "AND paidtime is null AND toremove <> '1' AND ordertime is not null AND isclosed is null ORDER BY kind,ordertime, id;";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$prodsToPay = array();
foreach ($result as $zeile) {
$thePrice = $zeile['price'];
$theTax = $zeile['tax'];
$thePriceLevelName = $zeile['pricelevelname'];
$longName = $zeile['longname'];
$togo = $zeile["togo"];
$queueid = $zeile['id'];
$extras = $this->getExtrasOfQueueItem($pdo,$queueid);
$prodId = $zeile['prodid'];
$prodsToPay[] = array("id" => $queueid, "prodid" => $prodId, "longname" => $longName, "pricelevelname" => $thePriceLevelName, "price" => $thePrice, "tax" => $theTax, "togo" => $togo, "extras" => $extras);
}
echo json_encode(array("status" => "OK", "msg" => $prodsToPay));
}
function displayBill($billtableitems,$totalPrice) {
$currency = $this->commonUtils->getCurrency();
$numberOfItemsToPay = count($billtableitems);
if ($numberOfItemsToPay > 0) {
echo "<br><br><table id=bill class=billtable>";
echo "<tr><th>Speise/Getränk<th id=pricecolheader>Preis ($currency)</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 . " $currency </tr>";
}
echo "</table>";
}
function declareProductBeDeliveredWithGivenPdo($pdo,$queueid) {
if (is_numeric($queueid)) {
date_default_timezone_set(DbUtils::getTimeZone());
$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));
$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();
$this->declareProductBeDeliveredWithGivenPdo($pdo, $queueid);
}
}
function declareMultipleProductsDelivered($queueids) {
$ids = explode(",",$queueids);
$pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction();
for ($i=0;$i < count($ids); $i++) {
$aQueueId = $ids[$i];
if (is_numeric($aQueueId)) {
$this->declareProductBeDeliveredWithGivenPdo($pdo,$aQueueId);
}
}
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
function declareProductNotBeDelivered($queueid) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
if (is_numeric($queueid)) {
date_default_timezone_set(DbUtils::getTimeZone());
$delivertime = date('Y-m-d H:i:s');
$updateSql = "UPDATE %queue% SET delivertime=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql));
$stmt->execute(array(null,$queueid));
}
}
public function getAllPreparedProductsForTableidAsArray($pdo,$tableid) {
if (!is_null($tableid)) {
$sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,anoption,readytime ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%products%,%resttables%,%bill% ";
} else {
$sql .= "FROM %queue%,%products%,%resttables% ";
}
$sql .= "WHERE (readytime IS NOT NULL and delivertime IS NULL ";
$sql .= "AND %queue%.productid=%products%.id ";
$sql .= "AND %queue%.tablenr=%resttables%.id ";
$sql .= "AND %queue%.isclosed is null ";
$sql .= "AND ordertime is not null ";
$sql .= "AND %resttables%.id=" . $tableid . " ";
$sql .= "AND toremove <> '1') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql .= " ORDER BY tableno";
} else {
$sql = "SELECT DISTINCT %queue%.id as id,'' as tableno,longname,anoption,readytime ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%products%,%bill% ";
} else {
$sql .= "FROM %queue%,%products% ";
}
$sql .= "WHERE (readytime IS NOT NULL and delivertime IS NULL ";
$sql .= "AND %queue%.productid=%products%.id ";
$sql .= "AND %queue%.tablenr is null ";
$sql .= "AND ordertime is not null ";
$sql .= "AND %queue%.isclosed is null ";
$sql .= "AND toremove <> '1') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql = $sql . " ORDER BY tableno";
}
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$dbresult = $stmt->fetchAll();
$numberOfIcons = count($dbresult);
$arrayOfProdsForTable = array();
$idsProdsOfTable = ''; // this is a hack! All queueids of a table redundant for "Deliver all"
foreach($dbresult as $zeile) {
$theAction= "deliver";
$longname = $zeile['longname'];
$extras = $this->getExtrasOfQueueItem(null,$zeile['id']);
$anProdElem = array(
"id" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"extras" => $extras,
"status" => "ready_to_deliver");
$arrayOfProdsForTable[] = $anProdElem;
if ($idsProdsOfTable == '') {
$idsProdsOfTable = $idsProdsOfTable . $zeile['id'];
} else {
$idsProdsOfTable = $idsProdsOfTable . ',' . $zeile['id'];
}
}
return array("prods" => $arrayOfProdsForTable, "ids" => $idsProdsOfTable);
}
public function numberOfProductsForTableNotDelivered($pdo,$tableid) {
$sql = "SELECT DISTINCT %queue%.id as id ";
if (!is_null($tableid)) {
$sql .= "FROM %queue%,%resttables% ";
} else {
$sql .= "FROM %queue% ";
}
$sql .= "WHERE delivertime IS NULL ";
$sql .= "AND ordertime is not null ";
$sql .= "AND %queue%.isclosed is null ";
$sql .= "AND workprinted='0' ";
$sql .= "AND toremove <> '1' ";
if (!is_null($tableid)) {
$sql .= "AND %queue%.tablenr=%resttables%.id ";
$sql .= "AND %resttables%.id=" . $tableid;
} else {
$sql .= "AND %queue%.tablenr is null ";
}
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$dbresult = $stmt->fetchAll();
$numberOfProducts = count($dbresult);
return $numberOfProducts;
}
function getJsonAllPreparedProducts() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT DISTINCT tablenr ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%resttables%,%bill% ";
} else {
$sql .= "FROM %queue%,%resttables% ";
}
$sql .= "WHERE (readytime IS NOT NULL and delivertime IS NULL ";
$sql .= "AND toremove <> '1' ";
$sql .= "AND %queue%.tablenr=%resttables%.id AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql .= " ORDER BY tablenr";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result1 = $stmt->fetchAll();
$sql = "SELECT DISTINCT tablenr ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%bill% ";
} else {
$sql .= "FROM %queue% ";
}
$sql .= "WHERE (readytime IS NOT NULL and delivertime IS NULL ";
$sql .= "AND toremove <> '1' ";
$sql .= "AND %queue%.tablenr is null AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result2 = $stmt->fetchAll();
$result = array_merge($result1,$result2);
$tablesToServe = array();
foreach($result as $zeile) {
$tablesToServe[] = $zeile['tablenr'];
}
$preparedProds_incomplete_tables = array();
$preparedProds = array();
$commonUtils = new CommonUtils();
foreach ($tablesToServe as $tableid) {
$arrayOfProdsAndIdsOfATable = $this->getAllPreparedProductsForTableidAsArray($pdo,$tableid);
$arrayOfProdsOfATable = $arrayOfProdsAndIdsOfATable['prods'];
$numberOfProductsTotalToServe = $this->numberOfProductsForTableNotDelivered($pdo,$tableid);
$numberOfReadyProducts = count($arrayOfProdsOfATable);
if ($numberOfReadyProducts >= $numberOfProductsTotalToServe) {
$tablestatus = "complete";
$tableheadeline = $commonUtils->getTableNameFromId($pdo,$tableid);
$preparedProds[] = array(
"tableheadline" => $tableheadeline,
"tableid" => $tableid,
"tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable);
} else {
$tablestatus = "incomplete";
$tableheadeline = "Tisch: " . $commonUtils->getTableNameFromId($pdo,$tableid);
$preparedProds_incomplete_tables[] = array(
"tableheadline" => $tableheadeline,
"tableid" => $tableid,
"tablestatus" => $tablestatus,
"ids" => $arrayOfProdsAndIdsOfATable['ids'],
"prodsOfTable" => $arrayOfProdsOfATable);
}
}
$newProdsToServe = self::getNewProductsToServe($pdo);
self::setNewProductsToServe($pdo, 0);
$items = array_merge($preparedProds,$preparedProds_incomplete_tables);
echo json_encode(array("items" => $items, "newproductstoserve" => $newProdsToServe));
}
/*
* Return as JSON object a list of max 10 entries of products that
* have been delivered to a table
*/
function getJsonLastDeliveredProducts() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT DISTINCT %queue%.id as id,tableno,longname,delivertime,anoption,%products%.id as prodid ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%resttables%,%products%,%bill% ";
} else {
$sql .= "FROM %queue%,%resttables%,%products% ";
}
$sql .= "WHERE (delivertime IS NOT NULL ";
$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%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql = $sql . "ORDER BY delivertime DESC LIMIT 10";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result1 = $stmt->fetchAll();
$sql = "SELECT DISTINCT %queue%.id as id,'' as tableno,longname,delivertime,anoption,%products%.id as prodid ";
if ($this->areBillExisting($pdo)) {
$sql .= "FROM %queue%,%products%,%bill% ";
} else {
$sql .= "FROM %queue%,%products% ";
}
$sql .= "WHERE (delivertime IS NOT NULL ";
$sql .= "AND %queue%.productid=%products%.id ";
$sql .= "AND %queue%.tablenr is null ";
$sql .= "AND toremove <> '1' AND ";
$sql .= "ordertime is not null AND ";
$sql .= "%queue%.isclosed is null AND ";
$sql .= "%queue%.workprinted='0') ";
if ($this->areBillExisting($pdo)) {
$sql .= "AND (%queue%.billid is null OR (";
$sql .= "%queue%.billid=%bill%.id AND %bill%.closingid is null)) ";
}
$sql = $sql . "ORDER BY delivertime DESC LIMIT 10";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result2 = $stmt->fetchAll();
$result = array_merge($result1,$result2);
$lastDeliveredProds = array();
foreach($result as $zeile) {
$productid = $zeile['prodid'];
$useConditions = $this->getUseKitchenAndSupplyForProd($pdo,$productid);
if ($useConditions["usesupply"] == 1) {
$extras = $this->getExtrasOfQueueItem(null,$zeile['id']);
$deliveredProd = array(
"id" => $zeile['id'],
"longname" => $zeile['longname'],
"option" => $zeile['anoption'],
"extras" => $extras,
"delivertime" => $zeile['delivertime'],
"tablename" => $zeile['tableno']);
$lastDeliveredProds[] = $deliveredProd;
}
}
echo json_encode($lastDeliveredProds);
}
/*
* 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($pdo,$ids,$tableid,$paymentId,$declareready,$host,$calledInternally = false,$reservationid='',$guestinfo='',$intguestid='') {
date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s');
if ($intguestid == '') {
$intguestid = null;
}
if ($reservationid != "") {
$reservationid = substr($reservationid, 0, 30);
}
if ($guestinfo != "") {
$guestinfo = substr($guestinfo, 0, 30);
}
$printextras = CommonUtils::getConfigValue($pdo, 'printextras', 0);
$userid = $this->getUserId();
$ids = trim($ids, ",");
$ids_array = explode ( ',', $ids );
if (CommonUtils::callPlugin($pdo, "createBill", "replace")) {
return;
}
CommonUtils::callPlugin($pdo, "createBill", "before");
if (!$calledInternally) {
$pdo->beginTransaction();
}
$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=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($anId));
if ($row != null) {
$aCount = $row->countid;
if (($aCount != null) && ($aCount == 1)) {
$allNotPaid = false;
}
}
} else {
$allNotPaid = false;
}
}
$billid = (-1);
if ($allNotPaid == true) {
$billid = -1;
$sql = "SELECT id from %bill% ORDER BY id DESC";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$numberOfIds = $stmt->rowCount();
$newprevbrutto = 0;
$newprevnetto = 0;
if ($numberOfIds > 0) {
$row =$stmt->fetchObject();
if ($row != null) {
$billid = intval($row->id)+1;
$sql = "SELECT brutto,ROUND(netto,2) as netto,prevbrutto,prevnetto FROM %bill% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($row->id));
$newprevbrutto = $row->prevbrutto + $row->brutto;
$newprevnetto = $row->prevnetto + $row->netto;
} else {
if (!$calledInternally) {
echo " - row ist null - ";
$pdo->rollBack();
}
return;
}
} else {
$billid = 1;
}
if (!$this->commonUtils->verifyLastBillId($pdo, $billid)) {
if (!$calledInternally) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_INCONSISTENT_DB, "msg" => ERROR_INCONSISTENT_DB_MSG));
$pdo->rollBack();
}
return;
} else {
$this->commonUtils->setLastBillIdInWorkTable($pdo, $billid);
}
if (is_null($tableid)) {
$tableid = 0;
}
if (!$calledInternally) {
$sql = "INSERT INTO %records% (date,userid,tableid,action) VALUES(?,?,?,?)";
CommonUtils::execSql($pdo, $sql, array($currentTime,$userid,($tableid == 0 ? null : $tableid),T_BILL));
$recordid = $pdo->lastInsertId();
}
$idlist = join("','",$ids_array);
$sql = "SELECT SUM(price) as brutto,ROUND(SUM(price/(1 + %queue%.tax/100.0)),6) as netto FROM %queue% WHERE id IN ('$idlist')";
$row = CommonUtils::getRowSqlObject($pdo, $sql, null);
$brutto = $row->brutto;
$netto = $row->netto;
$signature = $this->commonUtils->calcSignatureForBill($pdo,$currentTime, $brutto, $netto, '0.00', $userid);
$billInsertSql = "INSERT INTO `%bill%` (`id` , `billdate`,`brutto`,`netto`,`prevbrutto`,`prevnetto`,`tableid`,`paymentid`,`userid`,`ref`,`tax`,`host`,`reservationid`,`guestinfo`,`intguestid`,`printextras`,`signature`) VALUES (?,?,?,?,?,?,?,?,?,NULL,NULL,?,?,?,?,?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billInsertSql));
$stmt->execute(array($billid,$currentTime,$brutto,$netto,$newprevbrutto,$newprevnetto,$tableid,$paymentId,$userid,$host,$reservationid,$guestinfo,$intguestid,$printextras,$signature));
for ($i=0;$i<count($ids_array);$i++) {
$queueid = $ids_array[$i];
if (is_numeric($queueid)) {
if ($declareready == 0) {
$updateSql = "UPDATE %queue% SET paidtime=?, billid=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql));
$stmt->execute(array($currentTime,$billid,$queueid));
} else {
$updateSql = "UPDATE %queue% SET paidtime=?, billid=?,readytime=?,delivertime=? WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($updateSql));
$stmt->execute(array($currentTime,$billid,$currentTime,$currentTime,$queueid));
}
$billProdsSql = "INSERT INTO `%billproducts%` (`queueid`,`billid`) VALUES ( ?,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($billProdsSql));
$stmt->execute(array($queueid,$billid));
if (!$calledInternally) {
$sql = "INSERT INTO %recordsqueue% (recordid,queueid) VALUES(?,?)";
CommonUtils::execSql($pdo, $sql, array($recordid,$queueid));
}
}
}
Hotelinterface::insertIntoHsin($pdo,$billid);
}
if (!$calledInternally) {
$pdo->commit();
}
$billInfo = array("billid" => $billid, "date" => $currentTime);
// Rksv::signBill($pdo, $billid);
CommonUtils::callPlugin($pdo, "createBill", "after");
CommonUtils::log($pdo, "QUEUE", "Created bill with id=$billid from user $userid");
if (!$calledInternally) {
echo json_encode(array("status" => "OK", "msg" => $billInfo));
}
}
private function getUserId() {
if(session_id() == '') {
session_start();
}
return $_SESSION['userid'];
}
}