ordersprinter/php/products.php

609 lines
21 KiB
PHP
Raw Normal View History

2020-11-19 22:44:19 +01:00
<?php
// Datenbank-Verbindungsparameter
require_once ('dbutils.php');
require_once ('queuecontent.php');
require_once ('commonutils.php');
require_once ('utilities/userrights.php');
require_once ('utilities/HistFiller.php');
class Products {
var $dbutils;
var $queue;
var $commonUtils;
var $userrights;
var $histfiller;
function __construct() {
$this->dbutils = new DbUtils();
$this->queue = new QueueContent();
$this->commonUtils = new CommonUtils();
$this->userrights = new Userrights();
$this->histfiller = new HistFiller();
}
function handleCommand($command) {
// canUserCallCommands($currentCmd, $cmdArray,$right)
$cmdArray = array('showDbProducts', 'applySingleProdData', 'reassign', 'applyType', 'getSingleProdData','getPriceLevelInfo','setPriceLevelInfo', 'createProduct','createProdType');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_products'))) {
if ($command == 'createProdType') {
echo json_encode(array("status" => "ERROR", "code" => ERROR_PRODUCTS_NOT_AUTHOTRIZED, "msg" => ERROR_PRODUCTS_NOT_AUTHOTRIZED_MSG));
} else {
echo "Benutzerrechte nicht ausreichend!";
}
return false;
}
}
if($command == 'showDbProducts') {
$this->showDbProducts();
} else if ($command == 'getSpeisekarte') {
if ($this->userrights->hasCurrentUserRight('is_admin') || ($this->userrights->hasCurrentUserRight('right_manager'))) {
$this->getSpeisekarte();
} else {
echo "Fehlende Benutzerechte";
}
} else if ($command == 'exportCsv') {
if (($this->userrights->hasCurrentUserRight('is_admin'))
|| ($this->userrights->hasCurrentUserRight('right_manager'))) {
$this->exportCsv();
}
} else if ($command == 'getAllTypesAndAvailProds') {
$this->getAllTypesAndAvailProds();
} else if ($command == 'getAllAvailProdsAlphaSorted') {
$this->getAllAvailProdsAlphaSorted();
} else if ($command == 'getSingleProdData') {
$this->getSingleProdData($_GET['id']);
} else if ($command == 'applySingleProdData') {
$this->applySingleProdData($_POST['id'],$_POST['longname'],$_POST['shortname'],$_POST['priceA'],$_POST['priceB'],$_POST['priceC'],$_POST['available'],$_POST['audioFile']);
} else if ($command == 'createProduct') {
$this->createProduct($_POST['longname'],$_POST['shortname'],$_POST['priceA'],$_POST['priceB'],$_POST['priceC'],$_POST['available'],$_POST['prodTypeId'],$_POST['audioFile']);
} else if ($command == 'reassign') {
$this->reassign($_POST['productid'],$_POST['typeid']);
} else if ($command == 'createProdType') {
$this->createProdType($_POST['refid'],$_POST['name']);
} else if ($command == 'applyType') {
$this->applyType($_POST['id'],$_POST['name'],$_POST['kind'],$_POST['usekitchen'],$_POST['usesupply']);
} else if ($command == 'getPriceLevelInfo') {
$this->getPriceLevelInfo();
} else if ($command == 'setPriceLevelInfo') {
$this->setPriceLevelInfo($_POST['priceLevelId']);
} else if ($command == 'getSpeisekarte') {
$this->getSpeisekarte();
} else if ($command == 'getAudioFiles') {
$this->getAudioFiles();
} else {
echo "Command not supported.";
}
}
function getDateValueAsBoolInterpretatedIcon($aValue) {
if ($aValue != '0' ) {
$imgFile = "ok.png";
} else {
$imgFile = "notavailable.png";
}
return $imgFile;
}
private function getAllTypesAndAvailProds() {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$sql = "select id,name,reference from %prodtype% where removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$typeArray = array();
foreach($result as $row) {
$ref = $row['reference'];
if ($ref == null) {
$ref = 0;
}
$typeArray[] = array("id" => $row['id'], "name" => $row['name'], "ref" => $ref);
}
$sql = "select id,shortname,longname,audio,category as ref from %products% where available='1' AND removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$prodArray = array();
foreach($result as $row) {
$ref = $row['ref'];
if ($ref == null) {
$ref = 0;
}
$audio = $row['audio'];
if ($audio == null) {
$audio = "";
}
$prodArray[] = array("id" => $row['id'], "name" => $row['shortname'], "longname" => $row['longname'], "audio" => $audio, "ref" => $ref);
}
$pdo->commit();
$retArray = array("types" => $typeArray, "prods" => $prodArray);
echo json_encode($retArray);
}
/*
* Return all available product with id and name that are not in given type.
* (used for re-assignment to type)
*/
function getAllAvailProdsAlphaSorted() {
$pdo = $this->dbutils->openDbAndReturnPdo();
// find categories with available products in them
$sql = "select distinct category from %products% WHERE available='1' AND removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$typeArr = array();
foreach($result as $row) {
$cat = $row['category'];
// find all prods not in this array (for later re-assignment into this cat)
$sql = "select id,longname from %products% WHERE available='1' AND removed is null AND category <> ? ORDER BY longname";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($cat));
$prodresult = $stmt->fetchAll();
$prodArray = array();
foreach($prodresult as $prow) {
$prodArray[] = array("id" => $prow['id'], "name" => $prow['longname']);
}
$typeArr[] = array("type" => $cat, "prods" => $prodArray);
}
echo json_encode($typeArr);
}
// ************************************************************
// * Start OLD part
// ************************************************************
// Utility function: find the roomid if the tableid is known
function getRoomFromTableid($tableid) {
// Find roomid for table (variable roomid works in the one direction, but if called by back-button, not)
$sql = "select " . DB_ROOM_TABLE . ".id as id from " . DB_ROOM_TABLE . ", " . DB_RESTTABLES_TABLE . " where " . DB_RESTTABLES_TABLE . ".id = '" . $tableid . "' and " . DB_ROOM_TABLE . ".id = " . DB_RESTTABLES_TABLE . ".roomid;";
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$roomid = $zeile['id'];
mysqli_free_result( $dbresult );
return $roomid;
}
function areThereProductsInTheCategory($categoryid) {
$sql = "SELECT id FROM " . DB_PRODUCTS_TABLE . " WHERE category = " . $categoryid . " AND available='1';";
$dbresult = $this->dbutils->performSqlCommand($sql);
$numberOfEnttry = mysqli_num_rows($dbresult);
mysqli_free_result( $dbresult );
if ($numberOfEnttry > 0) {
return true;
} else {
return false;
}
}
function areThereCategoriesInTheCategory($categoryid) {
$sql = "SELECT id FROM %prodtype% WHERE removed is null AND reference = $categoryid";
$dbresult = $this->dbutils->performSqlCommand($sql);
$numberOfEntry = mysqli_num_rows($dbresult);
mysqli_free_result( $dbresult );
if ($numberOfEntry > 0) {
return true;
} else {
return false;
}
}
/*
* Return in array all products with their id and longname that have a reference to
* the given category.
*
* The output is this:
* ["id" => 1, "longname" => "Whatever Product"],
* ["id" => 2, "longname" => "Whatever Other Product"], ...
*/
private function getProductsWithReferenz($ref) {
$prods = array();
$sql = "SELECT id,shortname,longname,priceA,priceB,priceC,available,audio from %products% where removed is null AND category is null";
if ($ref > 0) {
$sql = "SELECT id,shortname,longname,priceA,priceB,priceC,available,audio from %products% where removed is null AND category=$ref";
}
$dbresult = $this->dbutils->performSqlCommand($sql);
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$prod_entry = array(
"id" => $zeile['id'],
"shortname" => $zeile['shortname'],
"longname" => $zeile['longname'],
"available" => $zeile['available'],
"priceA" => $zeile['priceA'],
"priceB" => $zeile['priceB'],
"priceC" => $zeile['priceC'],
"audio" => ($zeile['audio'] == null ? '' : $zeile['audio']),
"type" => "p");
$prods[] = $prod_entry;
}
mysqli_free_result( $dbresult );
return $prods;
}
/*
* Return in array all types with their id and name that have a reference to
* the given category.
*
* The output is this:
* ["id" => 1, "name" => "Meal"],
* ["id" => 2, "name" => "Drinks"], ...
*/
private function getProdTypesWithReferenz($ref) {
$types = array();
$sql = "SELECT id,name,kind,usekitchen,usesupplydesk from %prodtype% where removed is null AND reference is null";
if ($ref > 0) {
$sql = "SELECT id,name,kind,usekitchen,usesupplydesk from %prodtype% where removed is null AND reference=$ref";
}
$dbresult = $this->dbutils->performSqlCommand($sql);
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$prod_entry = array(
"id" => $zeile['id'],
"name" => $zeile['name'],
"kind" => $zeile['kind'],
"usekitchen" => $zeile['usekitchen'],
"usesupplydesk" => $zeile['usesupplydesk'],
"type" => "t");
$types[] = $prod_entry;
}
mysqli_free_result( $dbresult );
return $types;
}
function showDbProducts() {
$productArray = $this->getDbProductsWithRef_json_version(0,0);
echo json_encode($productArray);
}
function readDbProducts() {
$speisekarte = $this->readDbProductsWithRef_json_version(0,0);
return $speisekarte;
}
private function exportCsv() {
$file_name = "datenexport-produkte.csv";
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$file_name");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Expires: 0");
echo("Eintragsid; Datum ; Produktid; Kurzname; Langname; Preis (Stufe A); Preis (Stufe B);");
echo("Preis (Stufe C); Verf<72>gbarkeit; Beschreibung");
echo("\n");
$sql = "SELECT DISTINCT %hist%.id as id,date,";
$sql .= "prodid,shortname,longname,priceA,priceB,priceC,available, description ";
$sql .= " FROM %hist%, %histprod%, %histactions% ";
$sql .= " WHERE (refid=%histprod%.id) ";
$sql .= " AND (action='1' OR action='4' OR action='5') ";
$sql .= " AND (action=%histactions%.id) ";
$sql .= " ORDER BY date,id";
$dbresult = $this->dbutils->performSqlCommand($sql);
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$val1 = $zeile['id'];
$val2 = $zeile['date'];
$val3 = $zeile['prodid'];
$val4 = str_replace('"','""',$zeile['shortname']);
$val5 = str_replace('"','""',$zeile['longname']);
$val6 = $zeile['priceA'];
$val7 = $zeile['priceB'];
$val8 = $zeile['priceC'];
$val9 = ($zeile['available'] == '1' ? "Ja" : "Nein");
$val10 = $zeile['description'];
echo "$val1; $val2; $val3; \"$val4\"; \"$val5\"; $val6; $val7; $val8; $val9; $val10\n";
}
mysqli_free_result( $dbresult );
}
function getSingleProdData($id) {
if (is_numeric($id)) {
$sql = "SELECT shortname,longname,priceA,priceB,priceC,available,audio from %products% where id=$id";
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$prod_entry = array(
"shortname" => $zeile['shortname'],
"longname" => $zeile['longname'],
"available" => $zeile['available'],
"priceA" => $zeile['priceA'],
"priceB" => $zeile['priceB'],
"priceC" => $zeile['priceC'],
"audio" => $zeile['audio']
);
mysqli_free_result( $dbresult );
echo json_encode($prod_entry);
}
}
function reassign($prodid,$typeid) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$sql = "UPDATE %products% SET category=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($typeid,$prodid));
$affectedRows = $stmt->rowCount();
$pdo->commit();
if ($affectedRows == 1) {
echo json_encode("OK");
} else {
echo json_encode("Failed");
}
}
function applySingleProdData($id,$longname,$shortname,$priceA,$priceB,$priceC,$available,$audioFile) {
if (!is_numeric($id) || !is_numeric($available) || !is_numeric($priceA) || !is_numeric($priceB) || !is_numeric($priceC)) {
return;
}
$priceA = $this->dbutils->filterString($priceA);
$priceB = $this->dbutils->filterString($priceB);
$priceC = $this->dbutils->filterString($priceC);
if ($audioFile == '') {
$audioFile = null;
}
$updateSql = "UPDATE %products% SET shortname=?, longname=?, priceA=?, priceB=?, priceC=?, available=?, audio=? WHERE id=?";
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($shortname,$longname,$priceA,$priceB,$priceC,$available,$audioFile,$id));
$pdo->commit();
echo json_encode("OK: $updateSql");
// now this has to be logged in the history tables...
$this->histfiller->updateProdInHist($id, $shortname, $longname, $priceA, $priceB, $priceC,
NULL, $available,$audioFile);
}
function createProdType($id,$prodTypeName) {
if (!is_numeric($id)) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_ID_TYPE, "msg" => ERROR_GENERAL_ID_TYPE_MSG));
return;
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
// which kind is the referenced type?
$sql = "SELECT kind FROM %prodtype% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($id));
$row =$stmt->fetchObject();
if ($row == null) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_GENERAL_DB_NOT_READABLE, "msg" => ERROR_GENERAL_DB_NOT_READABLE_MSG));
return;
}
$kind = $row->kind;
$sql = "INSERT INTO `%prodtype%` (`id`,`name`,`usekitchen`,`usesupplydesk`,`kind`,`sorting`,`reference`) ";
$sql .= " VALUES(NULL,?,1,1,?,NULL,?)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($prodTypeName,$kind,$id));
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
function createProduct($longname,$shortname,$priceA,$priceB,$priceC,$available,$typeId,$audioFile) {
if (!is_numeric($typeId) || !is_numeric($available) || !is_numeric($priceA) || !is_numeric($priceB) || !is_numeric($priceC)) {
return;
}
if ($audioFile == '') {
$audioFile = null;
}
$sql = "INSERT INTO `%products%` (`id`, `shortname`, `longname`, `priceA`, `priceB`, `priceC`, `category`,`available`,`audio`) VALUES (NULL,?,?,?,?,?,?,?,?)";
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($shortname,$longname,$priceA,$priceB,$priceC,$typeId,$available,$audioFile));
$newProdId = $pdo->lastInsertId();
$pdo->commit();
// now this has to be logged in the history tables...
$this->histfiller->createProdInHist ($newProdId['id'], $shortname, $longname, $priceA, $priceB, $priceC,
NULL, $available,$audioFile);
echo json_encode("OK: sql");
}
/*
* Change the properties of a type of products
*/
function applyType($id,$name,$kind,$usekitchen,$usesupply) {
if (!is_numeric($id) || !is_numeric($kind) || !is_numeric($usekitchen) || !is_numeric($usesupply)) {
return;
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$updateSql = "UPDATE %prodtype% SET kind=?, name=?, usekitchen=?, usesupplydesk=? WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($updateSql));
$stmt->execute(array($kind,$name,$usekitchen,$usesupply,$id));
echo json_encode("OK: $updateSql");
}
/*
* Return a html table with all products in a structured way
*/
private function getDbProductsWithRef_json_version($ref,$depth) {
$allProdsAndTypesInThisLevel = array();
$allProdsInThisLevel = $this->getProductsWithReferenz($ref);
$allTypesInThisLevel = $this->getProdTypesWithReferenz($ref);
for ($index_prod=0;$index_prod<count($allProdsInThisLevel);$index_prod++) {
$aProd = $allProdsInThisLevel[$index_prod];
$allProdsAndTypesInThisLevel[] = array("entry" => $aProd, "content" => '');
}
for ($index_type=0;$index_type < count($allTypesInThisLevel);$index_type++) {
$aProdType = $allTypesInThisLevel[$index_type];
$typeRef = $aProdType['id'];
$allProdsAndTypesInThisLevel[] = array("entry" => $aProdType,"content" => $this->getDbProductsWithRef_json_version($typeRef,$depth+1));
}
return $allProdsAndTypesInThisLevel;
}
// return in text format
private function readDbProductsWithRef_json_version($ref,$depth) {
$text = "";
$allProdsAndTypesInThisLevel = array();
$allProdsInThisLevel = $this->getProductsWithReferenz($ref);
$allTypesInThisLevel = $this->getProdTypesWithReferenz($ref);
for ($index_prod=0;$index_prod<count($allProdsInThisLevel);$index_prod++) {
$aProd = $allProdsInThisLevel[$index_prod];
// Kurzname ; NormalPreis (Stufe A); Langname # Preis (Stufe B); Preis (Stufe C)
$shortname = $aProd['shortname'];
$longname = $aProd['longname'];
$available = $aProd['available'];
$priceA = $aProd['priceA'];
$priceB = $aProd['priceB'];
$priceC = $aProd['priceC'];
$prodText = "$shortname ; $priceA ; $longname # $priceB ; $priceC";
$text .= substr ( " " , 0 ,$depth) . $prodText . "\n";
}
for ($index_type=0;$index_type < count($allTypesInThisLevel);$index_type++) {
$aProdType = $allTypesInThisLevel[$index_type];
$typeRef = $aProdType['id'];
$indent = substr ( " " , 0 ,$depth);
$prod_entry = array(
"id" => $zeile['id'],
"name" => $zeile['name'],
"kind" => $zeile['kind'],
"usekitchen" => $zeile['usekitchen'],
"usesupplydesk" => $zeile['usesupplydesk'],
"type" => "t");
$prodTypeName = $aProdType['name'];
$kind = ($aProdType['kind'] == 0 ? "F" : "D");
$usekitchen = ($aProdType['usekitchen'] == 1 ? "K" : "");
$usesupplydesk = ($aProdType['usesupplydesk'] == 1 ? "B" : "");
$text .= $indent . $prodTypeName . " = $usekitchen$usesupplydesk$kind\n";
$text .= $this->readDbProductsWithRef_json_version($typeRef,$depth+1);
}
return $text;
}
private function numberOfProdsInProdType($theId) {
// how many prods are related to this type?
$sql = "SELECT COUNT(id) FROM %products% WHERE removed is null AND category=$theId";
$dbresult = $this->dbutils->performSqlCommand($sql);
$zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC);
$noProdsInThisProdType = $zeile['COUNT(id)'];
mysqli_free_result( $dbresult );
// iterate over all prodtypes in this prodtype
$prodtypesInside = $this->getProdTypesWithReferenz($theId);
for ($i=0;$i < count($prodtypesInside);$i++) {
$anInsideProdType = $prodtypesInside[i];
// recursive
$noProdsInThisProdType += $this->numberOfProdsInProdType($anInsideProdType["id"]);
}
return $noProdsInThisProdType;
}
private function getPriceLevelInfo() {
$currentPriceLevel = $this->commonUtils->getCurrentPriceLevel();
$currentPriceLevelId = $currentPriceLevel["id"];
$currentPriceLevelName = $currentPriceLevel["name"];
$pricelevels = array();
$sql = "SELECT * FROM %pricelevel%";
$dbresult = $this->dbutils->performSqlCommand($sql);
while ($zeile = mysqli_fetch_array( $dbresult, MYSQL_ASSOC)) {
$theId = $zeile['id'];
$selected = "0";
if ($theId == $currentPriceLevelId) {
$selected = "1";
}
$levels_entry = array(
"id" => $theId,
"name" => $zeile['name'],
"info" => $zeile['info'],
"selected" => $selected);
$pricelevels[] = $levels_entry;
}
mysqli_free_result( $dbresult );
$retArray = array("currentId" => $currentPriceLevelId, "currentName" => $currentPriceLevelName, "levels" => $pricelevels);
echo json_encode($retArray);
}
private function setPriceLevelInfo($levelId) {
if (is_numeric($levelId)) {
$updateSql = "UPDATE %config% SET setting=$levelId WHERE name='pricelevel'";
$dbresult = $this->dbutils->performSqlCommand($updateSql);
echo json_encode("OK");
}
}
private function getSpeisekarte() {
$pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT * FROM %products% WHERE removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$numberOfProds = $stmt->rowCount();
$sql = "SELECT * FROM %prodtype% WHERE removed is null";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$numberOfProdTypes = $stmt->rowCount();
if (($numberOfProds == 0) && ($numberOfProdTypes == 0)) {
// no products defined yet - present Beispiel
$text = file_get_contents ("../customer/speisekarte.txt");
} else {
$text = $this->readDbProducts();
}
echo json_encode($text);
}
private function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
private function getAudioFiles() {
$dir = '../customer';
$fileList = scandir($dir);
$audioFiles = array();
foreach ($fileList as $aFile) {
if ($this->endsWith($aFile, '.mp3') || $this->endsWith($aFile, '.ogg') || $this->endsWith($aFile, '.wav')) {
$audioFiles[] = $aFile;
}
}
echo json_encode($audioFiles);
}
}
?>