diff --git a/services/ApiKeyService.php b/services/ApiKeyService.php index 66b6fa74..2e8f76cd 100644 --- a/services/ApiKeyService.php +++ b/services/ApiKeyService.php @@ -18,16 +18,16 @@ class ApiKeyService extends BaseService } else { - $apiKeyRow = $this->Database->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch(); + $apiKeyRow = $this->getDatabase()->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch(); if ($apiKeyRow !== null) { // This should not change the database file modification time as this is used // to determine if REALLY something has changed - $dbModTime = $this->DatabaseService->GetDbChangedTime(); + $dbModTime = $this->getDatabaseService()->GetDbChangedTime(); $apiKeyRow->update(array( 'last_used' => date('Y-m-d H:i:s', time()) )); - $this->DatabaseService->SetDbChangedTime($dbModTime); + $this->getDatabaseService()->SetDbChangedTime($dbModTime); return true; } @@ -44,8 +44,8 @@ class ApiKeyService extends BaseService public function CreateApiKey($keyType = self::API_KEY_TYPE_DEFAULT) { $newApiKey = $this->GenerateApiKey(); - - $apiKeyRow = $this->Database->api_keys()->createRow(array( + + $apiKeyRow = $this->getDatabase()->api_keys()->createRow(array( 'api_key' => $newApiKey, 'user_id' => GROCY_USER_ID, 'expires' => '2999-12-31 23:59:59', // Default is that API keys expire never @@ -58,21 +58,21 @@ class ApiKeyService extends BaseService public function RemoveApiKey($apiKey) { - $this->Database->api_keys()->where('api_key', $apiKey)->delete(); + $this->getDatabase()->api_keys()->where('api_key', $apiKey)->delete(); } public function GetApiKeyId($apiKey) { - $apiKey = $this->Database->api_keys()->where('api_key', $apiKey)->fetch(); + $apiKey = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch(); return $apiKey->id; } public function GetUserByApiKey($apiKey) { - $apiKeyRow = $this->Database->api_keys()->where('api_key', $apiKey)->fetch(); + $apiKeyRow = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch(); if ($apiKeyRow !== null) { - return $this->Database->users($apiKeyRow->user_id); + return $this->getDatabase()->users($apiKeyRow->user_id); } return null; } @@ -87,7 +87,7 @@ class ApiKeyService extends BaseService } else { - $apiKeyRow = $this->Database->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch(); + $apiKeyRow = $this->getDatabase()->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch(); if ($apiKeyRow !== null) { return $apiKeyRow->api_key; diff --git a/services/BaseService.php b/services/BaseService.php index a9ddffa5..f7474631 100644 --- a/services/BaseService.php +++ b/services/BaseService.php @@ -8,14 +8,20 @@ use \Grocy\Services\LocalizationService; class BaseService { public function __construct() { - $this->DatabaseService = DatabaseService::getInstance(); - $this->Database = $this->DatabaseService->GetDbConnection(); - - $localizationService = LocalizationService::getInstance(GROCY_CULTURE); - $this->LocalizationService = $localizationService; } - protected $DatabaseService; - protected $Database; - protected $LocalizationService; + protected function getDatabaseService() + { + return DatabaseService::getInstance(); + } + + protected function getdatabase() + { + return $this->DatabaseService->GetDbConnection(); + } + + protected function getLocalizationService() + { + return LocalizationService::getInstance(GROCY_CULTURE); + } } diff --git a/services/BatteriesService.php b/services/BatteriesService.php index e7c879fa..1e3da503 100644 --- a/services/BatteriesService.php +++ b/services/BatteriesService.php @@ -7,7 +7,7 @@ class BatteriesService extends BaseService public function GetCurrent() { $sql = 'SELECT * from batteries_current'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetBatteryDetails(int $batteryId) @@ -17,10 +17,10 @@ class BatteriesService extends BaseService throw new \Exception('Battery does not exist'); } - $battery = $this->Database->batteries($batteryId); - $batteryChargeCyclesCount = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count(); - $batteryLastChargedTime = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time'); - $nextChargeTime = $this->Database->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time'); + $battery = $this->getDatabase()->batteries($batteryId); + $batteryChargeCyclesCount = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count(); + $batteryLastChargedTime = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time'); + $nextChargeTime = $this->getDatabase()->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time'); return array( 'battery' => $battery, @@ -37,24 +37,24 @@ class BatteriesService extends BaseService throw new \Exception('Battery does not exist'); } - $logRow = $this->Database->battery_charge_cycles()->createRow(array( + $logRow = $this->getDatabase()->battery_charge_cycles()->createRow(array( 'battery_id' => $batteryId, 'tracked_time' => $trackedTime )); $logRow->save(); - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } private function BatteryExists($batteryId) { - $batteryRow = $this->Database->batteries()->where('id = :1', $batteryId)->fetch(); + $batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch(); return $batteryRow !== null; } public function UndoChargeCycle($chargeCycleId) { - $logRow = $this->Database->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch(); + $logRow = $this->getDatabase()->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch(); if ($logRow == null) { throw new \Exception('Charge cycle does not exist or was already undone'); diff --git a/services/DatabaseMigrationService.php b/services/DatabaseMigrationService.php index 77ecabde..104bba80 100644 --- a/services/DatabaseMigrationService.php +++ b/services/DatabaseMigrationService.php @@ -6,7 +6,7 @@ class DatabaseMigrationService extends BaseService { public function MigrateDatabase() { - $this->DatabaseService->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); + $this->getDatabaseService()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); $sqlMigrationFiles = array(); foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file) @@ -41,21 +41,21 @@ class DatabaseMigrationService extends BaseService private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql) { - $rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); + $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); if (intval($rowCount) === 0) { - $this->DatabaseService->ExecuteDbStatement($sql); - $this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); + $this->getDatabaseService()->ExecuteDbStatement($sql); + $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); } } private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile) { - $rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); + $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); if (intval($rowCount) === 0) { include $phpFile; - $this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); + $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); } } } diff --git a/services/DemoDataGeneratorService.php b/services/DemoDataGeneratorService.php index 76d217ac..2a141c45 100644 --- a/services/DemoDataGeneratorService.php +++ b/services/DemoDataGeneratorService.php @@ -9,14 +9,14 @@ class DemoDataGeneratorService extends BaseService public function __construct() { parent::__construct(); - $this->LocalizationService = new LocalizationService(GROCY_CULTURE); + $this->getLocalizationService() = new LocalizationService(GROCY_CULTURE); } protected $LocalizationService; public function PopulateDemoData() { - $rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); + $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); if (intval($rowCount) === 0) { $loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'; @@ -181,7 +181,7 @@ class DemoDataGeneratorService extends BaseService INSERT INTO migrations (migration) VALUES (-1); "; - $this->DatabaseService->ExecuteDbStatement($sql); + $this->getDatabaseService()->ExecuteDbStatement($sql); $stockService = new StockService(); $stockService->AddProduct(3, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime('-10 days')), $this->RandomPrice()); @@ -317,13 +317,13 @@ class DemoDataGeneratorService extends BaseService private function __t_sql(string $text) { - $localizedText = $this->LocalizationService->__t($text, null); + $localizedText = $this->getLocalizationService()->__t($text, null); return str_replace("'", "''", $localizedText); } private function __n_sql($number, string $singularForm, string $pluralForm) { - $localizedText = $this->LocalizationService->__n($number, $singularForm, $pluralForm); + $localizedText = $this->getLocalizationService()->__n($number, $singularForm, $pluralForm); return str_replace("'", "''", $localizedText); } diff --git a/services/LocalizationService.php b/services/LocalizationService.php index 0c3dce11..d8c90744 100644 --- a/services/LocalizationService.php +++ b/services/LocalizationService.php @@ -15,29 +15,31 @@ class LocalizationService public function __construct(string $culture) { $this->Culture = $culture; - $this->DatabaseService = DatabaseService::getInstance(); - $this->Database = $this->DatabaseService->GetDbConnection(); $this->LoadLocalizations($culture); } + + protected function getDatabaseService() + { + return DatabaseService::getInstance(); + } + + protected function getdatabase() + { + return $this->getDatabaseService()->GetDbConnection(); + } + public static function getInstance(string $culture) { if (!in_array($culture, self::$instanceMap)) { self::$instanceMap[$culture] = new self($culture); } - #if (!apcu_exists("grocy_LocalizationService_".$culture)) - #{ - # apcu_store("grocy_LocalizationService_".$culture, new self($culture)); - #} - #return apcu_fetch("grocy_LocalizationService_".$culture); return self::$instanceMap[$culture]; } - protected $DatabaseService; - protected $Database; protected $Pot; protected $PotMain; protected $Po; @@ -85,7 +87,7 @@ class LocalizationService $quantityUnits = null; try { - $quantityUnits = $this->Database->quantity_units()->fetchAll(); + $quantityUnits = $this->getDatabase()->quantity_units()->fetchAll(); } catch (\Exception $ex) { diff --git a/services/RecipesService.php b/services/RecipesService.php index 966e1f5c..9782f780 100644 --- a/services/RecipesService.php +++ b/services/RecipesService.php @@ -21,38 +21,38 @@ class RecipesService extends BaseService public function GetRecipesPosResolved() { $sql = 'SELECT * FROM recipes_pos_resolved'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetRecipesResolved() { $sql = 'SELECT * FROM recipes_resolved'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null) { - $recipe = $this->Database->recipes($recipeId); + $recipe = $this->getDataBase()->recipes($recipeId); $recipePositions = $this->GetRecipesPosResolved(); foreach ($recipePositions as $recipePosition) { if($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds)) { - $product = $this->Database->products($recipePosition->product_id); - + $product = $this->getDataBase()->products($recipePosition->product_id); + $toOrderAmount = ceil(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list) / $product->qu_factor_purchase_to_stock); if ($recipe->not_check_shoppinglist == 1) { $toOrderAmount = ceil($recipePosition->missing_amount / $product->qu_factor_purchase_to_stock); } - + if($toOrderAmount > 0) { - $shoppinglistRow = $this->Database->shopping_list()->createRow(array( + $shoppinglistRow = $this->getDataBase()->shopping_list()->createRow(array( 'product_id' => $recipePosition->product_id, 'amount' => $toOrderAmount, - 'note' => $this->LocalizationService->__t('Added for recipe %s', $recipe->name) + 'note' => $this->getLocalizationService()->__t('Added for recipe %s', $recipe->name) )); $shoppinglistRow->save(); } @@ -67,7 +67,7 @@ class RecipesService extends BaseService throw new \Exception('Recipe does not exist'); } - $recipePositions = $this->Database->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll(); + $recipePositions = $this->getDataBase()->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll(); foreach ($recipePositions as $recipePosition) { if ($recipePosition->only_check_single_unit_in_stock == 0) @@ -79,7 +79,7 @@ class RecipesService extends BaseService private function RecipeExists($recipeId) { - $recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch(); + $recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch(); return $recipeRow !== null; } } diff --git a/services/SessionService.php b/services/SessionService.php index b98d8973..9f02e1e5 100644 --- a/services/SessionService.php +++ b/services/SessionService.php @@ -27,16 +27,16 @@ class SessionService extends BaseService } else { - $sessionRow = $this->Database->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch(); + $sessionRow = $this->getDatabase()->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch(); if ($sessionRow !== null) { // This should not change the database file modification time as this is used // to determine if REALLY something has changed - $dbModTime = $this->DatabaseService->GetDbChangedTime(); + $dbModTime = $this->getDatabaseService()->GetDbChangedTime(); $sessionRow->update(array( 'last_used' => date('Y-m-d H:i:s', time()) )); - $this->DatabaseService->SetDbChangedTime($dbModTime); + $this->getDatabaseService()->SetDbChangedTime($dbModTime); return true; } @@ -60,7 +60,7 @@ class SessionService extends BaseService $expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Never } - $sessionRow = $this->Database->sessions()->createRow(array( + $sessionRow = $this->getDatabase()->sessions()->createRow(array( 'user_id' => $userId, 'session_key' => $newSessionKey, 'expires' => $expires @@ -72,22 +72,22 @@ class SessionService extends BaseService public function RemoveSession($sessionKey) { - $this->Database->sessions()->where('session_key', $sessionKey)->delete(); + $this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete(); } public function GetUserBySessionKey($sessionKey) { - $sessionRow = $this->Database->sessions()->where('session_key', $sessionKey)->fetch(); + $sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch(); if ($sessionRow !== null) { - return $this->Database->users($sessionRow->user_id); + return $this->getDatabase()->users($sessionRow->user_id); } return null; } public function GetDefaultUser() { - return $this->Database->users(1); + return $this->getDatabase()->users(1); } private function GenerateSessionKey() diff --git a/services/StockService.php b/services/StockService.php index 13db241c..54546bde 100644 --- a/services/StockService.php +++ b/services/StockService.php @@ -23,25 +23,25 @@ class StockService extends BaseService $sql = 'SELECT * FROM stock_current WHERE best_before_date IS NOT NULL UNION SELECT id, 0, 0, null, 0, 0, 0 FROM ' . $missingProductsView . ' WHERE id NOT IN (SELECT product_id FROM stock_current)'; } - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetCurrentStockLocationContent() { $sql = 'SELECT * FROM stock_current_location_content'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetCurrentStockLocations() { $sql = 'SELECT * FROM stock_current_locations'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetCurrentProductPrices() { $sql = 'SELECT * FROM products_current_price'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetMissingProducts() @@ -52,12 +52,12 @@ class StockService extends BaseService $sql = 'SELECT * FROM stock_missing_products'; } - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetProductIdFromBarcode(string $barcode) { - $potentialProduct = $this->Database->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch(); + $potentialProduct = $this->getDatabase()->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch(); if ($potentialProduct === null) { @@ -99,24 +99,24 @@ class StockService extends BaseService $stockCurrentRow->is_aggregated_amount = 0; } - $product = $this->Database->products($productId); - $productLastPurchased = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date'); - $productLastUsed = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date'); - $nextBestBeforeDate = $this->Database->stock()->where('product_id', $productId)->min('best_before_date'); - $quPurchase = $this->Database->quantity_units($product->qu_id_purchase); - $quStock = $this->Database->quantity_units($product->qu_id_stock); - $location = $this->Database->locations($product->location_id); - $averageShelfLifeDays = intval($this->Database->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days); - + $product = $this->getDatabase()->products($productId); + $productLastPurchased = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date'); + $productLastUsed = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date'); + $nextBestBeforeDate = $this->getDatabase()->stock()->where('product_id', $productId)->min('best_before_date'); + $quPurchase = $this->getDatabase()->quantity_units($product->qu_id_purchase); + $quStock = $this->getDatabase()->quantity_units($product->qu_id_stock); + $location = $this->getDatabase()->locations($product->location_id); + $averageShelfLifeDays = intval($this->getDatabase()->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days); + $lastPrice = null; - $lastLogRow = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch(); + $lastLogRow = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch(); if ($lastLogRow !== null && !empty($lastLogRow)) { $lastPrice = $lastLogRow->price; } - $consumeCount = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1; - $consumeCountSpoiled = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1; + $consumeCount = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1; + $consumeCountSpoiled = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1; if ($consumeCount == 0) { $consumeCount = 1; @@ -150,7 +150,7 @@ class StockService extends BaseService } $returnData = array(); - $rows = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC'); + $rows = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC'); foreach ($rows as $row) { $returnData[] = array( @@ -168,11 +168,11 @@ class StockService extends BaseService if ($excludeOpened) { - return $this->Database->stock()->where('product_id = :1 AND open = 0', $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); + return $this->getDatabase()->stock()->where('product_id = :1 AND open = 0', $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); } else { - return $this->Database->stock()->where('product_id', $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); + return $this->getDatabase()->stock()->where('product_id', $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); } } @@ -218,7 +218,7 @@ class StockService extends BaseService { $stockId = uniqid(); - $logRow = $this->Database->stock_log()->createRow(array( + $logRow = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $productId, 'amount' => $amount, 'best_before_date' => $bestBeforeDate, @@ -230,9 +230,9 @@ class StockService extends BaseService )); $logRow->save(); - $returnValue = $this->Database->lastInsertId(); + $returnValue = $this->getDatabase()->lastInsertId(); - $stockRow = $this->Database->stock()->createRow(array( + $stockRow = $this->getDatabase()->stock()->createRow(array( 'product_id' => $productId, 'amount' => $amount, 'best_before_date' => $bestBeforeDate, @@ -274,7 +274,7 @@ class StockService extends BaseService if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) { - $productStockAmount = $this->Database->stock()->where('product_id', $productId)->sum('amount'); + $productStockAmount = $this->getDatabase()->stock()->where('product_id', $productId)->sum('amount'); $potentialStockEntries = $this->GetProductStockEntries($productId); if ($amount > $productStockAmount) @@ -296,7 +296,7 @@ class StockService extends BaseService if ($amount >= $stockEntry->amount) // Take the whole stock entry { - $logRow = $this->Database->stock_log()->createRow(array( + $logRow = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $stockEntry->amount * -1, 'best_before_date' => $stockEntry->best_before_date, @@ -319,7 +319,7 @@ class StockService extends BaseService { $restStockAmount = $stockEntry->amount - $amount; - $logRow = $this->Database->stock_log()->createRow(array( + $logRow = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $amount * -1, 'best_before_date' => $stockEntry->best_before_date, @@ -342,7 +342,7 @@ class StockService extends BaseService } } - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } else { @@ -408,9 +408,9 @@ class StockService extends BaseService throw new \Exception('Product does not exist'); } - $productStockAmountUnopened = $this->Database->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount'); + $productStockAmountUnopened = $this->getDatabase()->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount'); $potentialStockEntries = $this->GetProductStockEntries($productId, true); - $product = $this->Database->products($productId); + $product = $this->getDatabase()->products($productId); if ($amount > $productStockAmountUnopened) { @@ -437,7 +437,7 @@ class StockService extends BaseService if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened { - $logRow = $this->Database->stock_log()->createRow(array( + $logRow = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $stockEntry->amount, 'best_before_date' => $stockEntry->best_before_date, @@ -461,7 +461,7 @@ class StockService extends BaseService { $restStockAmount = $stockEntry->amount - $amount; - $newStockRow = $this->Database->stock()->createRow(array( + $newStockRow = $this->getDatabase()->stock()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $restStockAmount, 'best_before_date' => $stockEntry->best_before_date, @@ -471,7 +471,7 @@ class StockService extends BaseService )); $newStockRow->save(); - $logRow = $this->Database->stock_log()->createRow(array( + $logRow = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $amount, 'best_before_date' => $stockEntry->best_before_date, @@ -494,7 +494,7 @@ class StockService extends BaseService } } - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } public function AddMissingProductsToShoppingList($listId = 1) @@ -507,10 +507,10 @@ class StockService extends BaseService $missingProducts = $this->GetMissingProducts(); foreach ($missingProducts as $missingProduct) { - $product = $this->Database->products()->where('id', $missingProduct->id)->fetch(); + $product = $this->getDatabase()->products()->where('id', $missingProduct->id)->fetch(); $amountToAdd = ceil($missingProduct->amount_missing / $product->qu_factor_purchase_to_stock); - $alreadyExistingEntry = $this->Database->shopping_list()->where('product_id', $missingProduct->id)->fetch(); + $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch(); if ($alreadyExistingEntry) // Update { if ($alreadyExistingEntry->amount < $amountToAdd) @@ -523,7 +523,7 @@ class StockService extends BaseService } else // Insert { - $shoppinglistRow = $this->Database->shopping_list()->createRow(array( + $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array( 'product_id' => $missingProduct->id, 'amount' => $amountToAdd, 'shopping_list_id' => $listId @@ -540,7 +540,7 @@ class StockService extends BaseService throw new \Exception('Shopping list does not exist'); } - $this->Database->shopping_list()->where('shopping_list_id = :1', $listId)->delete(); + $this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId)->delete(); } @@ -551,7 +551,7 @@ class StockService extends BaseService throw new \Exception('Shopping list does not exist'); } - $productRow = $this->Database->shopping_list()->where('product_id = :1', $productId)->fetch(); + $productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch(); //If no entry was found with for this product, we return gracefully if ($productRow != null && !empty($productRow)) @@ -581,7 +581,7 @@ class StockService extends BaseService throw new \Exception('Product does not exist'); } - $alreadyExistingEntry = $this->Database->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch(); + $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch(); if ($alreadyExistingEntry) // Update { $alreadyExistingEntry->update(array( @@ -592,7 +592,7 @@ class StockService extends BaseService } else // Insert { - $shoppinglistRow = $this->Database->shopping_list()->createRow(array( + $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array( 'product_id' => $productId, 'amount' => $amount, 'shopping_list_id' => $listId, @@ -604,13 +604,13 @@ class StockService extends BaseService private function ProductExists($productId) { - $productRow = $this->Database->products()->where('id = :1', $productId)->fetch(); + $productRow = $this->getDatabase()->products()->where('id = :1', $productId)->fetch(); return $productRow !== null; } private function ShoppingListExists($listId) { - $shoppingListRow = $this->Database->shopping_lists()->where('id = :1', $listId)->fetch(); + $shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch(); return $shoppingListRow !== null; } @@ -626,7 +626,7 @@ class StockService extends BaseService if (file_exists($path)) { require_once $path; - return new $pluginName($this->Database->locations()->fetchAll(), $this->Database->quantity_units()->fetchAll()); + return new $pluginName($this->getDatabase()->locations()->fetchAll(), $this->Database->quantity_units()->fetchAll()); } else { @@ -644,7 +644,7 @@ class StockService extends BaseService if ($addFoundProduct === true) { // Add product to database and include new product id in output - $newRow = $this->Database->products()->createRow($pluginOutput); + $newRow = $this->getDatabase()->products()->createRow($pluginOutput); $newRow->save(); $pluginOutput['id'] = $newRow->id; @@ -656,13 +656,13 @@ class StockService extends BaseService public function UndoBooking($bookingId) { - $logRow = $this->Database->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch(); + $logRow = $this->getDatabase()->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch(); if ($logRow == null) { throw new \Exception('Booking does not exist or was already undone'); } - $hasSubsequentBookings = $this->Database->stock_log()->where('stock_id = :1 AND id != :2 AND id > :2', $logRow->stock_id, $logRow->id)->count() > 0; + $hasSubsequentBookings = $this->getDatabase()->stock_log()->where('stock_id = :1 AND id != :2 AND id > :2', $logRow->stock_id, $logRow->id)->count() > 0; if ($hasSubsequentBookings) { throw new \Exception('Booking has subsequent dependent bookings, undo not possible'); @@ -671,7 +671,7 @@ class StockService extends BaseService if ($logRow->transaction_type === self::TRANSACTION_TYPE_PURCHASE || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount > 0)) { // Remove corresponding stock entry - $stockRows = $this->Database->stock()->where('stock_id', $logRow->stock_id); + $stockRows = $this->getDatabase()->stock()->where('stock_id', $logRow->stock_id); $stockRows->delete(); // Update log entry @@ -683,7 +683,7 @@ class StockService extends BaseService elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_CONSUME || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount < 0)) { // Add corresponding amount back to stock - $stockRow = $this->Database->stock()->createRow(array( + $stockRow = $this->getDatabase()->stock()->createRow(array( 'product_id' => $logRow->product_id, 'amount' => $logRow->amount * -1, 'best_before_date' => $logRow->best_before_date, @@ -703,7 +703,7 @@ class StockService extends BaseService elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_PRODUCT_OPENED) { // Remove opened flag from corresponding log entry - $stockRows = $this->Database->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1); + $stockRows = $this->getDatabase()->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1); $stockRows->update(array( 'open' => 0, 'opened_date' => null diff --git a/services/TasksService.php b/services/TasksService.php index 1219b4eb..61244de0 100644 --- a/services/TasksService.php +++ b/services/TasksService.php @@ -7,7 +7,7 @@ class TasksService extends BaseService public function GetCurrent() { $sql = 'SELECT * from tasks_current'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function MarkTaskAsCompleted($taskId, $doneTime) @@ -17,7 +17,7 @@ class TasksService extends BaseService throw new \Exception('Task does not exist'); } - $taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); + $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow->update(array( 'done' => 1, 'done_timestamp' => $doneTime @@ -33,7 +33,7 @@ class TasksService extends BaseService throw new \Exception('Task does not exist'); } - $taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); + $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow->update(array( 'done' => 0, 'done_timestamp' => null @@ -44,7 +44,7 @@ class TasksService extends BaseService private function TaskExists($taskId) { - $taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); + $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); return $taskRow !== null; } }