diff --git a/controllers/BaseApiController.php b/controllers/BaseApiController.php index 53cbac17..f6809d96 100644 --- a/controllers/BaseApiController.php +++ b/controllers/BaseApiController.php @@ -8,10 +8,18 @@ class BaseApiController extends BaseController public function __construct(\DI\Container $container) { parent::__construct($container); - $this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json')); } - protected $OpenApiSpec; + protected $OpenApiSpec = null; + + protected function getOpenApispec() + { + if($this->OpenApiSpec == null) + { + $this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json')); + } + return $this->OpenApiSpec; + } protected function ApiResponse(\Psr\Http\Message\ResponseInterface $response, $data) { diff --git a/controllers/BaseController.php b/controllers/BaseController.php index ecda17b8..0de7c51f 100644 --- a/controllers/BaseController.php +++ b/controllers/BaseController.php @@ -5,36 +5,46 @@ namespace Grocy\Controllers; use \Grocy\Services\DatabaseService; use \Grocy\Services\ApplicationService; use \Grocy\Services\LocalizationService; +use \Grocy\Services\StockService; use \Grocy\Services\UsersService; +use \Grocy\Services\UserfieldsService; +use \Grocy\Services\BatteriesService; +use \Grocy\Services\CalendarService; +use \Grocy\Services\SessionService; +use \Grocy\Services\RecipesService; +use \Grocy\Services\TasksService; +use \Grocy\Services\FilesService; +use \Grocy\Services\ChoresService; +use \Grocy\Services\ApiKeyService; class BaseController { public function __construct(\DI\Container $container) { - $databaseService = new DatabaseService(); - $this->Database = $databaseService->GetDbConnection(); - - $localizationService = new LocalizationService(GROCY_CULTURE); - $this->LocalizationService = $localizationService; - $applicationService = new ApplicationService(); - $versionInfo = $applicationService->GetInstalledVersion(); + $this->AppContainer = $container; + $this->View = $container->get('view'); + } - $view = $container->get('view'); - $this->View = $view; + protected function render($response, $page, $data = []) + { + $container = $this->AppContainer; - $view->set('version', $versionInfo->Version); - $view->set('releaseDate', $versionInfo->ReleaseDate); - $view->set('__t', function(string $text, ...$placeholderValues) use($localizationService) + $versionInfo = $this->getApplicationService()->GetInstalledVersion(); + $this->View->set('version', $versionInfo->Version); + $this->View->set('releaseDate', $versionInfo->ReleaseDate); + + $localizationService = $this->getLocalizationService(); + $this->View->set('__t', function(string $text, ...$placeholderValues) use($localizationService) { return $localizationService->__t($text, $placeholderValues); }); - $view->set('__n', function($number, $singularForm, $pluralForm) use($localizationService) + $this->View->set('__n', function($number, $singularForm, $pluralForm) use($localizationService) { return $localizationService->__n($number, $singularForm, $pluralForm); }); - $view->set('GettextPo', $localizationService->GetPoAsJsonString()); + $this->View->set('GettextPo', $localizationService->GetPoAsJsonString()); - $view->set('U', function($relativePath, $isResource = false) use($container) + $this->View->set('U', function($relativePath, $isResource = false) use($container) { return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource); }); @@ -44,7 +54,7 @@ class BaseController { $embedded = true; } - $view->set('embedded', $embedded); + $this->View->set('embedded', $embedded); $constants = get_defined_constants(); foreach ($constants as $constant => $value) @@ -54,20 +64,24 @@ class BaseController unset($constants[$constant]); } } - $view->set('featureFlags', $constants); + $this->View->set('featureFlags', $constants); - $view->set('userentitiesForSidebar', $this->Database->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name')); + return $this->View->render($response, $page, $data); + } + protected function renderPage($response, $page, $data = []) + { + $this->View->set('userentitiesForSidebar', $this->getDatabase()->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name')); try { - $usersService = new UsersService(); + $usersService = $this->getUsersService(); if (defined('GROCY_USER_ID')) { - $view->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID)); + $this->View->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID)); } else { - $view->set('userSettings', null); + $this->View->set('userSettings', null); } } catch (\Exception $ex) @@ -75,11 +89,83 @@ class BaseController // Happens when database is not initialised or migrated... } - $this->AppContainer = $container; + return $this->render($response, $page, $data); + } + + protected function getDatabaseService() + { + return DatabaseService::getInstance(); + } + + protected function getDatabase() + { + return $this->getDatabaseService()->GetDbConnection(); + } + + protected function getLocalizationService() + { + return LocalizationService::getInstance(GROCY_CULTURE); + } + + protected function getApplicationservice() + { + return ApplicationService::getInstance(); + } + + protected function getBatteriesService() + { + return BatteriesService::getInstance(); + } + + protected function getCalendarService() + { + return CalendarService::getInstance(); + } + + protected function getSessionService() + { + return SessionService::getInstance(); + } + + protected function getRecipesService() + { + return RecipesService::getInstance(); + } + + protected function getStockService() + { + return StockService::getInstance(); + } + + protected function getTasksService() + { + return TasksService::getInstance(); + } + + protected function getUsersService() + { + return UsersService::getInstance(); + } + + protected function getUserfieldsService() + { + return UserfieldsService::getInstance(); + } + + protected function getApiKeyService() + { + return ApiKeyService::getInstance(); + } + + protected function getChoresService() + { + return ChoresService::getInstance(); + } + + protected function getFilesService() + { + return FilesService::getInstance(); } protected $AppContainer; - protected $Database; - protected $LocalizationService; - protected $View; } diff --git a/controllers/BatteriesApiController.php b/controllers/BatteriesApiController.php index 7c0c193a..b0cc0700 100644 --- a/controllers/BatteriesApiController.php +++ b/controllers/BatteriesApiController.php @@ -2,18 +2,13 @@ namespace Grocy\Controllers; -use \Grocy\Services\BatteriesService; - class BatteriesApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->BatteriesService = new BatteriesService(); } - protected $BatteriesService; - public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { $requestBody = $request->getParsedBody(); @@ -26,8 +21,8 @@ class BatteriesApiController extends BaseApiController $trackedTime = $requestBody['tracked_time']; } - $chargeCycleId = $this->BatteriesService->TrackChargeCycle($args['batteryId'], $trackedTime); - return $this->ApiResponse($response, $this->Database->battery_charge_cycles($chargeCycleId)); + $chargeCycleId = $this->getBatteriesService()->TrackChargeCycle($args['batteryId'], $trackedTime); + return $this->ApiResponse($response, $this->getDatabase()->battery_charge_cycles($chargeCycleId)); } catch (\Exception $ex) { @@ -39,7 +34,7 @@ class BatteriesApiController extends BaseApiController { try { - return $this->ApiResponse($response, $this->BatteriesService->GetBatteryDetails($args['batteryId'])); + return $this->ApiResponse($response, $this->getBatteriesService()->GetBatteryDetails($args['batteryId'])); } catch (\Exception $ex) { @@ -49,14 +44,14 @@ class BatteriesApiController extends BaseApiController public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->BatteriesService->GetCurrent()); + return $this->ApiResponse($response, $this->getBatteriesService()->GetCurrent()); } public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - $this->ApiResponse($response, $this->BatteriesService->UndoChargeCycle($args['chargeCycleId'])); + $this->ApiResponse($response, $this->getBatteriesService()->UndoChargeCycle($args['chargeCycleId'])); return $this->EmptyApiResponse($response); } catch (\Exception $ex) diff --git a/controllers/BatteriesController.php b/controllers/BatteriesController.php index 9d6f4f7b..f0daa4fa 100644 --- a/controllers/BatteriesController.php +++ b/controllers/BatteriesController.php @@ -2,49 +2,40 @@ namespace Grocy\Controllers; -use \Grocy\Services\BatteriesService; -use \Grocy\Services\UsersService; -use \Grocy\Services\UserfieldsService; - class BatteriesController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->BatteriesService = new BatteriesService(); - $this->UserfieldsService = new UserfieldsService(); } - protected $BatteriesService; - protected $UserfieldsService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $usersService = new UsersService(); + $usersService = $this->getUsersService(); $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['batteries_due_soon_days']; - return $this->View->render($response, 'batteriesoverview', [ - 'batteries' => $this->Database->batteries()->orderBy('name'), - 'current' => $this->BatteriesService->GetCurrent(), + return $this->renderPage($response, 'batteriesoverview', [ + 'batteries' => $this->getDatabase()->batteries()->orderBy('name'), + 'current' => $this->getBatteriesService()->GetCurrent(), 'nextXDays' => $nextXDays, - 'userfields' => $this->UserfieldsService->GetFields('batteries'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('batteries') + 'userfields' => $this->getUserfieldsService()->GetFields('batteries'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries') ]); } public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'batterytracking', [ - 'batteries' => $this->Database->batteries()->orderBy('name') + return $this->renderPage($response, 'batterytracking', [ + 'batteries' => $this->getDatabase()->batteries()->orderBy('name') ]); } public function BatteriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'batteries', [ - 'batteries' => $this->Database->batteries()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('batteries'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('batteries') + return $this->renderPage($response, 'batteries', [ + 'batteries' => $this->getDatabase()->batteries()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('batteries'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries') ]); } @@ -52,31 +43,31 @@ class BatteriesController extends BaseController { if ($args['batteryId'] == 'new') { - return $this->View->render($response, 'batteryform', [ + return $this->renderPage($response, 'batteryform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('batteries') + 'userfields' => $this->getUserfieldsService()->GetFields('batteries') ]); } else { - return $this->View->render($response, 'batteryform', [ - 'battery' => $this->Database->batteries($args['batteryId']), + return $this->renderPage($response, 'batteryform', [ + 'battery' => $this->getDatabase()->batteries($args['batteryId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('batteries') + 'userfields' => $this->getUserfieldsService()->GetFields('batteries') ]); } } public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'batteriesjournal', [ - 'chargeCycles' => $this->Database->battery_charge_cycles()->orderBy('tracked_time', 'DESC'), - 'batteries' => $this->Database->batteries()->orderBy('name') + return $this->renderPage($response, 'batteriesjournal', [ + 'chargeCycles' => $this->getDatabase()->battery_charge_cycles()->orderBy('tracked_time', 'DESC'), + 'batteries' => $this->getDatabase()->batteries()->orderBy('name') ]); } public function BatteriesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'batteriessettings'); + return $this->renderPage($response, 'batteriessettings'); } } diff --git a/controllers/CalendarApiController.php b/controllers/CalendarApiController.php index bd96ca7e..183d6245 100644 --- a/controllers/CalendarApiController.php +++ b/controllers/CalendarApiController.php @@ -2,33 +2,25 @@ namespace Grocy\Controllers; -use \Grocy\Services\CalendarService; -use \Grocy\Services\ApiKeyService; - class CalendarApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->CalendarService = new CalendarService(); - $this->ApiKeyService = new ApiKeyService(); } - protected $CalendarService; - protected $ApiKeyService; - public function Ical(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { $vCalendar = new \Eluceo\iCal\Component\Calendar('grocy'); - $events = $this->CalendarService->GetEvents(); + $events = $this->getCalendarService()->GetEvents(); foreach($events as $event) { $date = new \DateTime($event['start']); $date->setTimezone(date_default_timezone_get()); - + if ($event['date_format'] === 'date') { $date->setTime(23, 59, 59); @@ -41,7 +33,7 @@ class CalendarApiController extends BaseApiController ->setDescription($event['description']) ->setNoTime($event['date_format'] === 'date') ->setUseTimezone(true); - + $vCalendar->addComponent($vEvent); } @@ -60,7 +52,7 @@ class CalendarApiController extends BaseApiController try { return $this->ApiResponse($response, array( - 'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . $this->ApiKeyService->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) + 'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . $this->getApiKeyService()->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) )); } catch (\Exception $ex) diff --git a/controllers/CalendarController.php b/controllers/CalendarController.php index bac0bf5e..48592404 100644 --- a/controllers/CalendarController.php +++ b/controllers/CalendarController.php @@ -2,22 +2,17 @@ namespace Grocy\Controllers; -use \Grocy\Services\CalendarService; - class CalendarController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->CalendarService = new CalendarService(); } - protected $CalendarService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'calendar', [ - 'fullcalendarEventSources' => $this->CalendarService->GetEvents() + return $this->renderPage($response, 'calendar', [ + 'fullcalendarEventSources' => $this->getCalendarService()->GetEvents() ]); } } diff --git a/controllers/ChoresApiController.php b/controllers/ChoresApiController.php index 81a71b08..e05495fa 100644 --- a/controllers/ChoresApiController.php +++ b/controllers/ChoresApiController.php @@ -2,18 +2,13 @@ namespace Grocy\Controllers; -use \Grocy\Services\ChoresService; - class ChoresApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->ChoresService = new ChoresService(); } - protected $ChoresService; - public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { $requestBody = $request->getParsedBody(); @@ -32,8 +27,8 @@ class ChoresApiController extends BaseApiController $doneBy = $requestBody['done_by']; } - $choreExecutionId = $this->ChoresService->TrackChore($args['choreId'], $trackedTime, $doneBy); - return $this->ApiResponse($response, $this->Database->chores_log($choreExecutionId)); + $choreExecutionId = $this->getChoresService()->TrackChore($args['choreId'], $trackedTime, $doneBy); + return $this->ApiResponse($response, $this->getDatabase()->chores_log($choreExecutionId)); } catch (\Exception $ex) { @@ -45,7 +40,7 @@ class ChoresApiController extends BaseApiController { try { - return $this->ApiResponse($response, $this->ChoresService->GetChoreDetails($args['choreId'])); + return $this->ApiResponse($response, $this->getChoresService()->GetChoreDetails($args['choreId'])); } catch (\Exception $ex) { @@ -55,14 +50,14 @@ class ChoresApiController extends BaseApiController public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->ChoresService->GetCurrent()); + return $this->ApiResponse($response, $this->getChoresService()->GetCurrent()); } public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - $this->ApiResponse($response, $this->ChoresService->UndoChoreExecution($args['executionId'])); + $this->ApiResponse($response, $this->getChoresService()->UndoChoreExecution($args['executionId'])); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -85,15 +80,15 @@ class ChoresApiController extends BaseApiController if ($choreId === null) { - $chores = $this->Database->chores(); + $chores = $this->getDatabase()->chores(); foreach ($chores as $chore) { - $this->ChoresService->CalculateNextExecutionAssignment($chore->id); + $this->getChoresService()->CalculateNextExecutionAssignment($chore->id); } } else { - $this->ChoresService->CalculateNextExecutionAssignment($choreId); + $this->getChoresService()->CalculateNextExecutionAssignment($choreId); } return $this->EmptyApiResponse($response); diff --git a/controllers/ChoresController.php b/controllers/ChoresController.php index ee9dba31..e9078926 100644 --- a/controllers/ChoresController.php +++ b/controllers/ChoresController.php @@ -2,95 +2,86 @@ namespace Grocy\Controllers; -use \Grocy\Services\ChoresService; -use \Grocy\Services\UsersService; -use \Grocy\Services\UserfieldsService; - class ChoresController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->ChoresService = new ChoresService(); - $this->UserfieldsService = new UserfieldsService(); } - protected $ChoresService; - protected $UserfieldsService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $usersService = new UsersService(); + $usersService = $this->getUsersService(); $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['chores_due_soon_days']; - return $this->View->render($response, 'choresoverview', [ - 'chores' => $this->Database->chores()->orderBy('name'), - 'currentChores' => $this->ChoresService->GetCurrent(), + return $this->renderPage($response, 'choresoverview', [ + 'chores' => $this->getDatabase()->chores()->orderBy('name'), + 'currentChores' => $this->getChoresService()->GetCurrent(), 'nextXDays' => $nextXDays, - 'userfields' => $this->UserfieldsService->GetFields('chores'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('chores'), + 'userfields' => $this->getUserfieldsService()->GetFields('chores'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores'), 'users' => $usersService->GetUsersAsDto() ]); } public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'choretracking', [ - 'chores' => $this->Database->chores()->orderBy('name'), - 'users' => $this->Database->users()->orderBy('username') + return $this->renderPage($response, 'choretracking', [ + 'chores' => $this->getDatabase()->chores()->orderBy('name'), + 'users' => $this->getDatabase()->users()->orderBy('username') ]); } public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'chores', [ - 'chores' => $this->Database->chores()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('chores'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('chores') + return $this->renderPage($response, 'chores', [ + 'chores' => $this->getDatabase()->chores()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('chores'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores') ]); } public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'choresjournal', [ - 'choresLog' => $this->Database->chores_log()->orderBy('tracked_time', 'DESC'), - 'chores' => $this->Database->chores()->orderBy('name'), - 'users' => $this->Database->users()->orderBy('username') + return $this->renderPage($response, 'choresjournal', [ + 'choresLog' => $this->getDatabase()->chores_log()->orderBy('tracked_time', 'DESC'), + 'chores' => $this->getDatabase()->chores()->orderBy('name'), + 'users' => $this->getDatabase()->users()->orderBy('username') ]); } public function ChoreEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $usersService = new UsersService(); + $usersService = getUsersService(); $users = $usersService->GetUsersAsDto(); if ($args['choreId'] == 'new') { - return $this->View->render($response, 'choreform', [ + return $this->renderPage($response, 'choreform', [ 'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'), 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('chores'), + 'userfields' => $this->getUserfieldsService()->GetFields('chores'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'users' => $users, - 'products' => $this->Database->products()->orderBy('name') + 'products' => $this->getDatabase()->products()->orderBy('name') ]); } else { - return $this->View->render($response, 'choreform', [ - 'chore' => $this->Database->chores($args['choreId']), + return $this->renderPage($response, 'choreform', [ + 'chore' => $this->getDatabase()->chores($args['choreId']), 'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('chores'), + 'userfields' => $this->getUserfieldsService()->GetFields('chores'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'users' => $users, - 'products' => $this->Database->products()->orderBy('name') + 'products' => $this->getDatabase()->products()->orderBy('name') ]); } } public function ChoresSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'choressettings'); + return $this->renderPage($response, 'choressettings'); } } diff --git a/controllers/EquipmentController.php b/controllers/EquipmentController.php index 841c3723..80dc7a19 100644 --- a/controllers/EquipmentController.php +++ b/controllers/EquipmentController.php @@ -2,24 +2,21 @@ namespace Grocy\Controllers; -use \Grocy\Services\UserfieldsService; - class EquipmentController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->UserfieldsService = new UserfieldsService(); } protected $UserfieldsService; public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'equipment', [ - 'equipment' => $this->Database->equipment()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('equipment'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('equipment') + return $this->renderPage($response, 'equipment', [ + 'equipment' => $this->getDatabase()->equipment()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('equipment'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('equipment') ]); } @@ -27,17 +24,17 @@ class EquipmentController extends BaseController { if ($args['equipmentId'] == 'new') { - return $this->View->render($response, 'equipmentform', [ + return $this->renderPage($response, 'equipmentform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('equipment') + 'userfields' => $this->getUserfieldsService()->GetFields('equipment') ]); } else { - return $this->View->render($response, 'equipmentform', [ - 'equipment' => $this->Database->equipment($args['equipmentId']), + return $this->renderPage($response, 'equipmentform', [ + 'equipment' => $this->getDatabase()->equipment($args['equipmentId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('equipment') + 'userfields' => $this->getUserfieldsService()->GetFields('equipment') ]); } } diff --git a/controllers/FilesApiController.php b/controllers/FilesApiController.php index 76064c7a..58aa1b70 100644 --- a/controllers/FilesApiController.php +++ b/controllers/FilesApiController.php @@ -2,18 +2,13 @@ namespace Grocy\Controllers; -use \Grocy\Services\FilesService; - class FilesApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->FilesService = new FilesService(); } - protected $FilesService; - public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try @@ -28,7 +23,7 @@ class FilesApiController extends BaseApiController } $data = $request->getBody()->getContents(); - file_put_contents($this->FilesService->GetFilePath($args['group'], $fileName), $data); + file_put_contents($this->getFilesService()->GetFilePath($args['group'], $fileName), $data); return $this->EmptyApiResponse($response); } @@ -71,11 +66,11 @@ class FilesApiController extends BaseApiController $bestFitWidth = $request->getQueryParams()['best_fit_width']; } - $filePath = $this->FilesService->DownscaleImage($args['group'], $fileName, $bestFitHeight, $bestFitWidth); + $filePath = $this->getFilesService()->DownscaleImage($args['group'], $fileName, $bestFitHeight, $bestFitWidth); } else { - $filePath = $this->FilesService->GetFilePath($args['group'], $fileName); + $filePath = $this->getFilesService()->GetFilePath($args['group'], $fileName); } if (file_exists($filePath)) @@ -109,7 +104,7 @@ class FilesApiController extends BaseApiController throw new \Exception('Invalid filename'); } - $filePath = $this->FilesService->GetFilePath($args['group'], $fileName); + $filePath = $this->getFilesService()->GetFilePath($args['group'], $fileName); if (file_exists($filePath)) { unlink($filePath); diff --git a/controllers/GenericEntityApiController.php b/controllers/GenericEntityApiController.php index 2f484c30..efbee609 100644 --- a/controllers/GenericEntityApiController.php +++ b/controllers/GenericEntityApiController.php @@ -2,23 +2,18 @@ namespace Grocy\Controllers; -use \Grocy\Services\UserfieldsService; - class GenericEntityApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->UserfieldsService = new UserfieldsService(); } - protected $UserfieldsService; - public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) { - return $this->ApiResponse($response, $this->Database->{$args['entity']}()); + return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}()); } else { @@ -30,7 +25,7 @@ class GenericEntityApiController extends BaseApiController { if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) { - return $this->ApiResponse($response, $this->Database->{$args['entity']}($args['objectId'])); + return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}($args['objectId'])); } else { @@ -51,11 +46,11 @@ class GenericEntityApiController extends BaseApiController throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); } - $newRow = $this->Database->{$args['entity']}()->createRow($requestBody); + $newRow = $this->getDatabase()->{$args['entity']}()->createRow($requestBody); $newRow->save(); $success = $newRow->isClean(); return $this->ApiResponse($response, array( - 'created_object_id' => $this->Database->lastInsertId() + 'created_object_id' => $this->getDatabase()->lastInsertId() )); } catch (\Exception $ex) @@ -82,7 +77,7 @@ class GenericEntityApiController extends BaseApiController throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); } - $row = $this->Database->{$args['entity']}($args['objectId']); + $row = $this->getDatabase()->{$args['entity']}($args['objectId']); $row->update($requestBody); $success = $row->isClean(); return $this->EmptyApiResponse($response); @@ -102,7 +97,7 @@ class GenericEntityApiController extends BaseApiController { if ($this->IsValidEntity($args['entity'])) { - $row = $this->Database->{$args['entity']}($args['objectId']); + $row = $this->getDatabase()->{$args['entity']}($args['objectId']); $row->delete(); $success = $row->isClean(); return $this->EmptyApiResponse($response); @@ -119,7 +114,7 @@ class GenericEntityApiController extends BaseApiController { try { - return $this->ApiResponse($response, $this->Database->{$args['entity']}()->where('name LIKE ?', '%' . $args['searchString'] . '%')); + return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}()->where('name LIKE ?', '%' . $args['searchString'] . '%')); } catch (\PDOException $ex) { @@ -136,7 +131,7 @@ class GenericEntityApiController extends BaseApiController { try { - return $this->ApiResponse($response, $this->UserfieldsService->GetValues($args['entity'], $args['objectId'])); + return $this->ApiResponse($response, $this->getUserfieldsService()->GetValues($args['entity'], $args['objectId'])); } catch (\Exception $ex) { @@ -155,7 +150,7 @@ class GenericEntityApiController extends BaseApiController throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); } - $this->UserfieldsService->SetValues($args['entity'], $args['objectId'], $requestBody); + $this->getUserfieldsService()->SetValues($args['entity'], $args['objectId'], $requestBody); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -166,11 +161,11 @@ class GenericEntityApiController extends BaseApiController private function IsValidEntity($entity) { - return in_array($entity, $this->OpenApiSpec->components->internalSchemas->ExposedEntity->enum); + return in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum); } private function IsEntityWithPreventedListing($entity) { - return !in_array($entity, $this->OpenApiSpec->components->internalSchemas->ExposedEntityButNoListing->enum); + return !in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntityButNoListing->enum); } } diff --git a/controllers/GenericEntityController.php b/controllers/GenericEntityController.php index 94b831de..e11edf5f 100644 --- a/controllers/GenericEntityController.php +++ b/controllers/GenericEntityController.php @@ -2,42 +2,37 @@ namespace Grocy\Controllers; -use \Grocy\Services\UserfieldsService; - class GenericEntityController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->UserfieldsService = new UserfieldsService(); } - protected $UserfieldsService; - public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'userfields', [ - 'userfields' => $this->UserfieldsService->GetAllFields(), - 'entities' => $this->UserfieldsService->GetEntities() + return $this->renderPage($response, 'userfields', [ + 'userfields' => $this->getUserfieldsService()->GetAllFields(), + 'entities' => $this->getUserfieldsService()->GetEntities() ]); } public function UserentitiesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'userentities', [ - 'userentities' => $this->Database->userentities()->orderBy('name') + return $this->renderPage($response, 'userentities', [ + 'userentities' => $this->getDatabase()->userentities()->orderBy('name') ]); } public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $userentity = $this->Database->userentities()->where('name = :1', $args['userentityName'])->fetch(); + $userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch(); - return $this->View->render($response, 'userobjects', [ + return $this->renderPage($response, 'userobjects', [ 'userentity' => $userentity, - 'userobjects' => $this->Database->userobjects()->where('userentity_id = :1', $userentity->id), - 'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('userentity-' . $args['userentityName']) + 'userobjects' => $this->getDatabase()->userobjects()->where('userentity_id = :1', $userentity->id), + 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('userentity-' . $args['userentityName']) ]); } @@ -45,19 +40,19 @@ class GenericEntityController extends BaseController { if ($args['userfieldId'] == 'new') { - return $this->View->render($response, 'userfieldform', [ + return $this->renderPage($response, 'userfieldform', [ 'mode' => 'create', - 'userfieldTypes' => $this->UserfieldsService->GetFieldTypes(), - 'entities' => $this->UserfieldsService->GetEntities() + 'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(), + 'entities' => $this->getUserfieldsService()->GetEntities() ]); } else { - return $this->View->render($response, 'userfieldform', [ + return $this->renderPage($response, 'userfieldform', [ 'mode' => 'edit', - 'userfield' => $this->UserfieldsService->GetField($args['userfieldId']), - 'userfieldTypes' => $this->UserfieldsService->GetFieldTypes(), - 'entities' => $this->UserfieldsService->GetEntities() + 'userfield' => $this->getUserfieldsService()->GetField($args['userfieldId']), + 'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(), + 'entities' => $this->getUserfieldsService()->GetEntities() ]); } } @@ -66,38 +61,38 @@ class GenericEntityController extends BaseController { if ($args['userentityId'] == 'new') { - return $this->View->render($response, 'userentityform', [ + return $this->renderPage($response, 'userentityform', [ 'mode' => 'create' ]); } else { - return $this->View->render($response, 'userentityform', [ + return $this->renderPage($response, 'userentityform', [ 'mode' => 'edit', - 'userentity' => $this->Database->userentities($args['userentityId']) + 'userentity' => $this->getDatabase()->userentities($args['userentityId']) ]); } } public function UserobjectEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $userentity = $this->Database->userentities()->where('name = :1', $args['userentityName'])->fetch(); + $userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch(); if ($args['userobjectId'] == 'new') { - return $this->View->render($response, 'userobjectform', [ + return $this->renderPage($response, 'userobjectform', [ 'userentity' => $userentity, 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']) + 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']) ]); } else { - return $this->View->render($response, 'userobjectform', [ + return $this->renderPage($response, 'userobjectform', [ 'userentity' => $userentity, 'mode' => 'edit', - 'userobject' => $this->Database->userobjects($args['userobjectId']), - 'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']) + 'userobject' => $this->getDatabase()->userobjects($args['userobjectId']), + 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']) ]); } } diff --git a/controllers/LoginController.php b/controllers/LoginController.php index 62ce10aa..21dbd956 100644 --- a/controllers/LoginController.php +++ b/controllers/LoginController.php @@ -2,20 +2,13 @@ namespace Grocy\Controllers; -use \Grocy\Services\SessionService; -use \Grocy\Services\DatabaseMigrationService; -use \Grocy\Services\DemoDataGeneratorService; - class LoginController extends BaseController { public function __construct(\DI\Container $container, string $sessionCookieName) { parent::__construct($container); - $this->SessionService = new SessionService(); $this->SessionCookieName = $sessionCookieName; } - - protected $SessionService; protected $SessionCookieName; public function ProcessLogin(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) @@ -23,13 +16,13 @@ class LoginController extends BaseController $postParams = $request->getParsedBody(); if (isset($postParams['username']) && isset($postParams['password'])) { - $user = $this->Database->users()->where('username', $postParams['username'])->fetch(); + $user = $this->getDatabase()->users()->where('username', $postParams['username'])->fetch(); $inputPassword = $postParams['password']; $stayLoggedInPermanently = $postParams['stay_logged_in'] == 'on'; if ($user !== null && password_verify($inputPassword, $user->password)) { - $sessionKey = $this->SessionService->CreateSession($user->id, $stayLoggedInPermanently); + $sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently); setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Cookie expires never, but session validity is up to SessionService if (password_needs_rehash($user->password, PASSWORD_DEFAULT)) @@ -54,12 +47,12 @@ class LoginController extends BaseController public function LoginPage(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'login'); + return $this->renderPage($response, 'login'); } public function Logout(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $this->SessionService->RemoveSession($_COOKIE[$this->SessionCookieName]); + $this->getSessionService()->RemoveSession($_COOKIE[$this->SessionCookieName]); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/')); } diff --git a/controllers/OpenApiController.php b/controllers/OpenApiController.php index 67b4b3bb..a312a48f 100644 --- a/controllers/OpenApiController.php +++ b/controllers/OpenApiController.php @@ -2,48 +2,42 @@ namespace Grocy\Controllers; -use \Grocy\Services\ApplicationService; -use \Grocy\Services\ApiKeyService; - class OpenApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->ApiKeyService = new ApiKeyService(); } - protected $ApiKeyService; - public function DocumentationUi(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'openapiui'); + return $this->render($response, 'openapiui'); } public function DocumentationSpec(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $applicationService = new ApplicationService(); + $applicationService = $this->getApplicationService(); $versionInfo = $applicationService->GetInstalledVersion(); - $this->OpenApiSpec->info->version = $versionInfo->Version; - $this->OpenApiSpec->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $this->OpenApiSpec->info->description); - $this->OpenApiSpec->servers[0]->url = $this->AppContainer->get('UrlManager')->ConstructUrl('/api'); + $this->getOpenApiSpec()->info->version = $versionInfo->Version; + $this->getOpenApiSpec()->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $this->getOpenApiSpec()->info->description); + $this->getOpenApiSpec()->servers[0]->url = $this->AppContainer->get('UrlManager')->ConstructUrl('/api'); - return $this->ApiResponse($response, $this->OpenApiSpec); + return $this->ApiResponse($response, $this->getOpenApiSpec()); } public function ApiKeysList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'manageapikeys', [ - 'apiKeys' => $this->Database->api_keys(), - 'users' => $this->Database->users() + return $this->renderPage($response, 'manageapikeys', [ + 'apiKeys' => $this->getDatabase()->api_keys(), + 'users' => $this->getDatabase()->users() ]); } public function CreateNewApiKey(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $newApiKey = $this->ApiKeyService->CreateApiKey(); - $newApiKeyId = $this->ApiKeyService->GetApiKeyId($newApiKey); + $newApiKey = $this->getApiKeyService()->CreateApiKey(); + $newApiKeyId = $this->getApiKeyService()->GetApiKeyId($newApiKey); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?CreatedApiKeyId=$newApiKeyId")); } } diff --git a/controllers/RecipesApiController.php b/controllers/RecipesApiController.php index 94a58db5..cb6f6c0f 100644 --- a/controllers/RecipesApiController.php +++ b/controllers/RecipesApiController.php @@ -2,18 +2,13 @@ namespace Grocy\Controllers; -use \Grocy\Services\RecipesService; - class RecipesApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->RecipesService = new RecipesService(); } - protected $RecipesService; - public function AddNotFulfilledProductsToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { $requestBody = $request->getParsedBody(); @@ -23,8 +18,8 @@ class RecipesApiController extends BaseApiController { $excludedProductIds = $requestBody['excludedProductIds']; } - - $this->RecipesService->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds); + + $this->getRecipesService()->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds); return $this->EmptyApiResponse($response); } @@ -32,7 +27,7 @@ class RecipesApiController extends BaseApiController { try { - $this->RecipesService->ConsumeRecipe($args['recipeId']); + $this->getRecipesService()->ConsumeRecipe($args['recipeId']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -44,13 +39,13 @@ class RecipesApiController extends BaseApiController public function GetRecipeFulfillment(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try - { + { if(!isset($args['recipeId'])) { - return $this->ApiResponse($response, $this->RecipesService->GetRecipesResolved()); + return $this->ApiResponse($response, $this->getRecipesService()->GetRecipesResolved()); } - $recipeResolved = FindObjectInArrayByPropertyValue($this->RecipesService->GetRecipesResolved(), 'recipe_id', $args['recipeId']); + $recipeResolved = FindObjectInArrayByPropertyValue($this->getRecipesService()->GetRecipesResolved(), 'recipe_id', $args['recipeId']); if(!$recipeResolved) { throw new \Exception('Recipe does not exist'); @@ -59,7 +54,7 @@ class RecipesApiController extends BaseApiController { return $this->ApiResponse($response, $recipeResolved); } - } + } catch (\Exception $ex) { return $this->GenericErrorResponse($response, $ex->getMessage()); diff --git a/controllers/RecipesController.php b/controllers/RecipesController.php index d8cbc23d..dffd0798 100644 --- a/controllers/RecipesController.php +++ b/controllers/RecipesController.php @@ -3,47 +3,38 @@ namespace Grocy\Controllers; use \Grocy\Services\RecipesService; -use \Grocy\Services\StockService; -use \Grocy\Services\UserfieldsService; class RecipesController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->RecipesService = new RecipesService(); - $this->StockService = new StockService(); - $this->UserfieldsService = new UserfieldsService(); } - protected $RecipesService; - protected $StockService; - protected $UserfieldsService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $recipes = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'); - $recipesResolved = $this->RecipesService->GetRecipesResolved(); + $recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'); + $recipesResolved = $this->getRecipesService()->GetRecipesResolved(); $selectedRecipe = null; $selectedRecipePositionsResolved = null; if (isset($request->getQueryParams()['recipe'])) { - $selectedRecipe = $this->Database->recipes($request->getQueryParams()['recipe']); - $selectedRecipePositionsResolved = $this->Database->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $request->getQueryParams()['recipe'])->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); + $selectedRecipe = $this->getDatabase()->recipes($request->getQueryParams()['recipe']); + $selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $request->getQueryParams()['recipe'])->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); } else { foreach ($recipes as $recipe) { $selectedRecipe = $recipe; - $selectedRecipePositionsResolved = $this->Database->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $recipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); + $selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $recipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); break; } } - $selectedRecipeSubRecipes = $this->Database->recipes()->where('id IN (SELECT includes_recipe_id FROM recipes_nestings_resolved WHERE recipe_id = :1 AND includes_recipe_id != :1)', $selectedRecipe->id)->orderBy('name')->fetchAll(); - $selectedRecipeSubRecipesPositions = $this->Database->recipes_pos_resolved()->where('recipe_id = :1', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC')->fetchAll(); + $selectedRecipeSubRecipes = $this->getDatabase()->recipes()->where('id IN (SELECT includes_recipe_id FROM recipes_nestings_resolved WHERE recipe_id = :1 AND includes_recipe_id != :1)', $selectedRecipe->id)->orderBy('name')->fetchAll(); + $selectedRecipeSubRecipesPositions = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC')->fetchAll(); $includedRecipeIdsAbsolute = array(); $includedRecipeIdsAbsolute[] = $selectedRecipe->id; @@ -52,22 +43,22 @@ class RecipesController extends BaseController $includedRecipeIdsAbsolute[] = $subRecipe->id; } - return $this->View->render($response, 'recipes', [ + return $this->renderPage($response, 'recipes', [ 'recipes' => $recipes, 'recipesResolved' => $recipesResolved, - 'recipePositionsResolved' => $this->Database->recipes_pos_resolved()->where('recipe_type', RecipesService::RECIPE_TYPE_NORMAL), + 'recipePositionsResolved' => $this->getDatabase()->recipes_pos_resolved()->where('recipe_type', RecipesService::RECIPE_TYPE_NORMAL), 'selectedRecipe' => $selectedRecipe, 'selectedRecipePositionsResolved' => $selectedRecipePositionsResolved, - 'products' => $this->Database->products(), - 'quantityUnits' => $this->Database->quantity_units(), + 'products' => $this->getDatabase()->products(), + 'quantityUnits' => $this->getDatabase()->quantity_units(), 'selectedRecipeSubRecipes' => $selectedRecipeSubRecipes, 'selectedRecipeSubRecipesPositions' => $selectedRecipeSubRecipesPositions, 'includedRecipeIdsAbsolute' => $includedRecipeIdsAbsolute, 'selectedRecipeTotalCosts' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->costs, 'selectedRecipeTotalCalories' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->calories, - 'userfields' => $this->UserfieldsService->GetFields('recipes'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('recipes'), - 'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() + 'userfields' => $this->getUserfieldsService()->GetFields('recipes'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('recipes'), + 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() ]); } @@ -76,26 +67,26 @@ class RecipesController extends BaseController $recipeId = $args['recipeId']; if ($recipeId == 'new') { - $newRecipe = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->createRow(array( - 'name' => $this->LocalizationService->__t('New recipe') + $newRecipe = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->createRow(array( + 'name' => $this->getLocalizationService()->__t('New recipe') )); $newRecipe->save(); - $recipeId = $this->Database->lastInsertId(); + $recipeId = $this->getDatabase()->lastInsertId(); } - - return $this->View->render($response, 'recipeform', [ - 'recipe' => $this->Database->recipes($recipeId), - 'recipePositions' => $this->Database->recipes_pos()->where('recipe_id', $recipeId), + + return $this->renderPage($response, 'recipeform', [ + 'recipe' => $this->getDatabase()->recipes($recipeId), + 'recipePositions' => $this->getDatabase()->recipes_pos()->where('recipe_id', $recipeId), 'mode' => 'edit', - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units(), - 'recipePositionsResolved' => $this->RecipesService->GetRecipesPosResolved(), - 'recipesResolved' => $this->RecipesService->GetRecipesResolved(), - 'recipes' => $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'), - 'recipeNestings' => $this->Database->recipes_nestings()->where('recipe_id', $recipeId), - 'userfields' => $this->UserfieldsService->GetFields('recipes'), - 'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units(), + 'recipePositionsResolved' => $this->getRecipesService()->GetRecipesPosResolved(), + 'recipesResolved' => $this->getRecipesService()->GetRecipesResolved(), + 'recipes' => $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'), + 'recipeNestings' => $this->getDatabase()->recipes_nestings()->where('recipe_id', $recipeId), + 'userfields' => $this->getUserfieldsService()->GetFields('recipes'), + 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() ]); } @@ -103,39 +94,39 @@ class RecipesController extends BaseController { if ($args['recipePosId'] == 'new') { - return $this->View->render($response, 'recipeposform', [ + return $this->renderPage($response, 'recipeposform', [ 'mode' => 'create', - 'recipe' => $this->Database->recipes($args['recipeId']), + 'recipe' => $this->getDatabase()->recipes($args['recipeId']), 'recipePos' => new \stdClass(), - 'products' => $this->Database->products()->orderBy('name'), - 'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), - 'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() ]); } else { - return $this->View->render($response, 'recipeposform', [ + return $this->renderPage($response, 'recipeposform', [ 'mode' => 'edit', - 'recipe' => $this->Database->recipes($args['recipeId']), - 'recipePos' => $this->Database->recipes_pos($args['recipePosId']), - 'products' => $this->Database->products()->orderBy('name'), - 'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), - 'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() + 'recipe' => $this->getDatabase()->recipes($args['recipeId']), + 'recipePos' => $this->getDatabase()->recipes_pos($args['recipePosId']), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() ]); } } public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'recipessettings'); + return $this->renderPage($response, 'recipessettings'); } public function MealPlan(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $recipes = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(); + $recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(); $events = array(); - foreach($this->Database->meal_plan() as $mealPlanEntry) + foreach($this->getDatabase()->meal_plan() as $mealPlanEntry) { $recipe = FindObjectInArrayByPropertyValue($recipes, 'id', $mealPlanEntry['recipe_id']); $title = ''; @@ -147,7 +138,7 @@ class RecipesController extends BaseController $productDetails = null; if ($mealPlanEntry['product_id'] !== null) { - $productDetails = $this->StockService->GetProductDetails($mealPlanEntry['product_id']); + $productDetails = $this->getStockService()->GetProductDetails($mealPlanEntry['product_id']); } $events[] = array( @@ -162,14 +153,14 @@ class RecipesController extends BaseController ); } - return $this->View->render($response, 'mealplan', [ + return $this->renderPage($response, 'mealplan', [ 'fullcalendarEventSources' => $events, 'recipes' => $recipes, - 'internalRecipes' => $this->Database->recipes()->whereNot('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(), - 'recipesResolved' => $this->RecipesService->GetRecipesResolved(), - 'products' => $this->Database->products()->orderBy('name'), - 'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), - 'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() + 'internalRecipes' => $this->getDatabase()->recipes()->whereNot('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(), + 'recipesResolved' => $this->getRecipesService()->GetRecipesResolved(), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() ]); } } diff --git a/controllers/StockApiController.php b/controllers/StockApiController.php index 14b5c86e..0a652329 100644 --- a/controllers/StockApiController.php +++ b/controllers/StockApiController.php @@ -9,16 +9,13 @@ class StockApiController extends BaseApiController public function __construct(\DI\Container $container) { parent::__construct($container); - $this->StockService = new StockService(); } - protected $StockService; - public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - return $this->ApiResponse($response, $this->StockService->GetProductDetails($args['productId'])); + return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($args['productId'])); } catch (\Exception $ex) { @@ -30,8 +27,8 @@ class StockApiController extends BaseApiController { try { - $productId = $this->StockService->GetProductIdFromBarcode($args['barcode']); - return $this->ApiResponse($response, $this->StockService->GetProductDetails($productId)); + $productId = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); + return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($productId)); } catch (\Exception $ex) { @@ -43,7 +40,7 @@ class StockApiController extends BaseApiController { try { - return $this->ApiResponse($response, $this->StockService->GetProductPriceHistory($args['productId'])); + return $this->ApiResponse($response, $this->getStockService()->GetProductPriceHistory($args['productId'])); } catch (\Exception $ex) { @@ -91,8 +88,8 @@ class StockApiController extends BaseApiController $transactionType = $requestBody['transactiontype']; } - $bookingId = $this->StockService->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, date('Y-m-d'), $price, $locationId); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, date('Y-m-d'), $price, $locationId); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { @@ -104,7 +101,7 @@ class StockApiController extends BaseApiController { try { - $args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); + $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); return $this->AddProduct($request, $response, $args); } catch (\Exception $ex) @@ -147,8 +144,8 @@ class StockApiController extends BaseApiController $locationId = $requestBody['location_id']; } - $bookingId = $this->StockService->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $price, $requestBody['open'], $requestBody['purchased_date']); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $price, $requestBody['open'], $requestBody['purchased_date']); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { @@ -188,8 +185,8 @@ class StockApiController extends BaseApiController $specificStockEntryId = $requestBody['stock_entry_id']; } - $bookingId = $this->StockService->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { @@ -201,7 +198,7 @@ class StockApiController extends BaseApiController { try { - $args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); + $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); return $this->TransferProduct($request, $response, $args); } catch (\Exception $ex) @@ -214,6 +211,8 @@ class StockApiController extends BaseApiController { $requestBody = $request->getParsedBody(); + $result = null; + try { if ($requestBody === null) @@ -256,20 +255,21 @@ class StockApiController extends BaseApiController $recipeId = $requestBody['recipe_id']; } - $bookingId = $this->StockService->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage()); + $result = $this->GenericErrorResponse($response, $ex->getMessage()); } + return $result; } public function ConsumeProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - $args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); + $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); return $this->ConsumeProduct($request, $response, $args); } catch (\Exception $ex) @@ -312,8 +312,8 @@ class StockApiController extends BaseApiController $price = $requestBody['price']; } - $bookingId = $this->StockService->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { @@ -325,7 +325,7 @@ class StockApiController extends BaseApiController { try { - $args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); + $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); return $this->InventoryProduct($request, $response, $args); } catch (\Exception $ex) @@ -356,8 +356,8 @@ class StockApiController extends BaseApiController $specificStockEntryId = $requestBody['stock_entry_id']; } - $bookingId = $this->StockService->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId); - return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); + $bookingId = $this->getStockService()->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId); + return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId)); } catch (\Exception $ex) { @@ -369,7 +369,7 @@ class StockApiController extends BaseApiController { try { - $args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); + $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); return $this->OpenProduct($request, $response, $args); } catch (\Exception $ex) @@ -380,7 +380,7 @@ class StockApiController extends BaseApiController public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->StockService->GetCurrentStock()); + return $this->ApiResponse($response, $this->getStockService()->GetCurrentStock()); } public function CurrentVolatileStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) @@ -391,9 +391,9 @@ class StockApiController extends BaseApiController $nextXDays = $request->getQueryParams()['expiring_days']; } - $expiringProducts = $this->StockService->GetExpiringProducts($nextXDays, true); - $expiredProducts = $this->StockService->GetExpiringProducts(-1); - $missingProducts = $this->StockService->GetMissingProducts(); + $expiringProducts = $this->getStockService()->GetExpiringProducts($nextXDays, true); + $expiredProducts = $this->getStockService()->GetExpiringProducts(-1); + $missingProducts = $this->getStockService()->GetMissingProducts(); return $this->ApiResponse($response, array( 'expiring_products' => $expiringProducts, 'expired_products' => $expiredProducts, @@ -413,7 +413,7 @@ class StockApiController extends BaseApiController $listId = intval($requestBody['list_id']); } - $this->StockService->AddMissingProductsToShoppingList($listId); + $this->getStockService()->AddMissingProductsToShoppingList($listId); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -434,7 +434,7 @@ class StockApiController extends BaseApiController $listId = intval($requestBody['list_id']); } - $this->StockService->ClearShoppingList($listId); + $this->getStockService()->ClearShoppingList($listId); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -476,7 +476,7 @@ class StockApiController extends BaseApiController throw new \Exception("No product id was supplied"); } - $this->StockService->AddProductToShoppingList($productId, $amount, $note, $listId); + $this->getStockService()->AddProductToShoppingList($productId, $amount, $note, $listId); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -512,7 +512,7 @@ class StockApiController extends BaseApiController throw new \Exception("No product id was supplied"); } - $this->StockService->RemoveProductFromShoppingList($productId, $amount, $listId); + $this->getStockService()->RemoveProductFromShoppingList($productId, $amount, $listId); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -531,7 +531,7 @@ class StockApiController extends BaseApiController $addFoundProduct = true; } - return $this->ApiResponse($response, $this->StockService->ExternalBarcodeLookup($args['barcode'], $addFoundProduct)); + return $this->ApiResponse($response, $this->getStockService()->ExternalBarcodeLookup($args['barcode'], $addFoundProduct)); } catch (\Exception $ex) { @@ -543,7 +543,7 @@ class StockApiController extends BaseApiController { try { - $this->ApiResponse($response, $this->StockService->UndoBooking($args['bookingId'])); + $this->ApiResponse($response, $this->getStockService()->UndoBooking($args['bookingId'])); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -556,7 +556,7 @@ class StockApiController extends BaseApiController { try { - $this->ApiResponse($response, $this->StockService->UndoTransaction($args['transactionId'])); + $this->ApiResponse($response, $this->getStockService()->UndoTransaction($args['transactionId'])); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -573,24 +573,24 @@ class StockApiController extends BaseApiController $allowSubproductSubstitution = true; } - return $this->ApiResponse($response, $this->StockService->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution)); + return $this->ApiResponse($response, $this->getStockService()->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution)); } public function ProductStockLocations(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->StockService->GetProductStockLocations($args['productId'])); + return $this->ApiResponse($response, $this->getStockService()->GetProductStockLocations($args['productId'])); } public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->StockService->GetStockEntry($args['entryId'])); + return $this->ApiResponse($response, $this->getStockService()->GetStockEntry($args['entryId'])); } public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - $stockLogRow = $this->Database->stock_log($args['bookingId']); + $stockLogRow = $this->getDatabase()->stock_log($args['bookingId']); if ($stockLogRow === null) { @@ -609,7 +609,7 @@ class StockApiController extends BaseApiController { try { - $transactionRows = $this->Database->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll(); + $transactionRows = $this->getDatabase()->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll(); if (count($transactionRows) === 0) { diff --git a/controllers/StockController.php b/controllers/StockController.php index 63f93eb2..8f3698a2 100644 --- a/controllers/StockController.php +++ b/controllers/StockController.php @@ -2,99 +2,90 @@ namespace Grocy\Controllers; -use \Grocy\Services\StockService; -use \Grocy\Services\UsersService; -use \Grocy\Services\UserfieldsService; - class StockController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->StockService = new StockService(); - $this->UserfieldsService = new UserfieldsService(); } - protected $StockService; - protected $UserfieldsService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $usersService = new UsersService(); + $usersService = $this->getUsersService(); $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days']; - return $this->View->render($response, 'stockoverview', [ - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name'), - 'currentStock' => $this->StockService->GetCurrentStock(true), - 'currentStockLocations' => $this->StockService->GetCurrentStockLocations(), - 'missingProducts' => $this->StockService->GetMissingProducts(), + return $this->renderPage($response, 'stockoverview', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'currentStock' => $this->getStockService()->GetCurrentStock(true), + 'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(), + 'missingProducts' => $this->getStockService()->GetMissingProducts(), 'nextXDays' => $nextXDays, - 'productGroups' => $this->Database->product_groups()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('products') + 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') ]); } public function Stockentries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $usersService = new UsersService(); + $usersService = $this->getUsersService(); $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days']; - return $this->View->render($response, 'stockentries', [ - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name'), - 'stockEntries' => $this->Database->stock()->orderBy('product_id'), - 'currentStockLocations' => $this->StockService->GetCurrentStockLocations(), + return $this->renderPage($response, 'stockentries', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'stockEntries' => $this->getDatabase()->stock()->orderBy('product_id'), + 'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(), 'nextXDays' => $nextXDays, - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('products') + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') ]); } public function Purchase(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'purchase', [ - 'products' => $this->Database->products()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name') + return $this->renderPage($response, 'purchase', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name') ]); } public function Consume(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'consume', [ - 'products' => $this->Database->products()->orderBy('name'), - 'recipes' => $this->Database->recipes()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name') + return $this->renderPage($response, 'consume', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'recipes' => $this->getDatabase()->recipes()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name') ]); } public function Transfer(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'transfer', [ - 'products' => $this->Database->products()->orderBy('name'), - 'recipes' => $this->Database->recipes()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name') + return $this->renderPage($response, 'transfer', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'recipes' => $this->getDatabase()->recipes()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name') ]); } public function Inventory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'inventory', [ - 'products' => $this->Database->products()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name') + return $this->renderPage($response, 'inventory', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name') ]); } public function StockEntryEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'stockentryform', [ - 'stockEntry' => $this->Database->stock()->where('id', $args['entryId'])->fetch(), - 'products' => $this->Database->products()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name') + return $this->renderPage($response, 'stockentryform', [ + 'stockEntry' => $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name') ]); } @@ -106,65 +97,65 @@ class StockController extends BaseController $listId = $request->getQueryParams()['list']; } - return $this->View->render($response, 'shoppinglist', [ - 'listItems' => $this->Database->shopping_list()->where('shopping_list_id = :1', $listId), - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'missingProducts' => $this->StockService->GetMissingProducts(), - 'productGroups' => $this->Database->product_groups()->orderBy('name'), - 'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), + return $this->renderPage($response, 'shoppinglist', [ + 'listItems' => $this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'missingProducts' => $this->getStockService()->GetMissingProducts(), + 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'), 'selectedShoppingListId' => $listId, - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('products') + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') ]); } public function ProductsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'products', [ - 'products' => $this->Database->products()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'productGroups' => $this->Database->product_groups()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('products') + return $this->renderPage($response, 'products', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') ]); } public function StockSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'stocksettings', [ - 'locations' => $this->Database->locations()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'productGroups' => $this->Database->product_groups()->orderBy('name') + return $this->renderPage($response, 'stocksettings', [ + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name') ]); } public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'locations', [ - 'locations' => $this->Database->locations()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('locations'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('locations') + return $this->renderPage($response, 'locations', [ + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('locations'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('locations') ]); } public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'productgroups', [ - 'productGroups' => $this->Database->product_groups()->orderBy('name'), - 'products' => $this->Database->products()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('product_groups'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('product_groups') + return $this->renderPage($response, 'productgroups', [ + 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('product_groups'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('product_groups') ]); } public function QuantityUnitsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'quantityunits', [ - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('quantity_units'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('quantity_units') + return $this->renderPage($response, 'quantityunits', [ + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('quantity_units') ]); } @@ -172,30 +163,30 @@ class StockController extends BaseController { if ($args['productId'] == 'new') { - return $this->View->render($response, 'productform', [ - 'locations' => $this->Database->locations()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'productgroups' => $this->Database->product_groups()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'products' => $this->Database->products()->where('parent_product_id IS NULL')->orderBy('name'), + return $this->renderPage($response, 'productform', [ + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'productgroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'products' => $this->getDatabase()->products()->where('parent_product_id IS NULL')->orderBy('name'), 'isSubProductOfOthers' => false, 'mode' => 'create' ]); } else { - $product = $this->Database->products($args['productId']); + $product = $this->getDatabase()->products($args['productId']); - return $this->View->render($response, 'productform', [ + return $this->renderPage($response, 'productform', [ 'product' => $product, - 'locations' => $this->Database->locations()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'productgroups' => $this->Database->product_groups()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('products'), - 'products' => $this->Database->products()->where('id != :1 AND parent_product_id IS NULL', $product->id)->orderBy('name'), - 'isSubProductOfOthers' => $this->Database->products()->where('parent_product_id = :1', $product->id)->count() !== 0, + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'productgroups' => $this->getDatabase()->product_groups()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('products'), + 'products' => $this->getDatabase()->products()->where('id != :1 AND parent_product_id IS NULL', $product->id)->orderBy('name'), + 'isSubProductOfOthers' => $this->getDatabase()->products()->where('parent_product_id = :1', $product->id)->count() !== 0, 'mode' => 'edit', - 'quConversions' => $this->Database->quantity_unit_conversions() + 'quConversions' => $this->getDatabase()->quantity_unit_conversions() ]); } } @@ -204,17 +195,17 @@ class StockController extends BaseController { if ($args['locationId'] == 'new') { - return $this->View->render($response, 'locationform', [ + return $this->renderPage($response, 'locationform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('locations') + 'userfields' => $this->getUserfieldsService()->GetFields('locations') ]); } else { - return $this->View->render($response, 'locationform', [ - 'location' => $this->Database->locations($args['locationId']), + return $this->renderPage($response, 'locationform', [ + 'location' => $this->getDatabase()->locations($args['locationId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('locations') + 'userfields' => $this->getUserfieldsService()->GetFields('locations') ]); } } @@ -223,17 +214,17 @@ class StockController extends BaseController { if ($args['productGroupId'] == 'new') { - return $this->View->render($response, 'productgroupform', [ + return $this->renderPage($response, 'productgroupform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('product_groups') + 'userfields' => $this->getUserfieldsService()->GetFields('product_groups') ]); } else { - return $this->View->render($response, 'productgroupform', [ - 'group' => $this->Database->product_groups($args['productGroupId']), + return $this->renderPage($response, 'productgroupform', [ + 'group' => $this->getDatabase()->product_groups($args['productGroupId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('product_groups') + 'userfields' => $this->getUserfieldsService()->GetFields('product_groups') ]); } } @@ -242,25 +233,25 @@ class StockController extends BaseController { if ($args['quantityunitId'] == 'new') { - return $this->View->render($response, 'quantityunitform', [ + return $this->renderPage($response, 'quantityunitform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('quantity_units'), - 'pluralCount' => $this->LocalizationService->GetPluralCount(), - 'pluralRule' => $this->LocalizationService->GetPluralDefinition() + 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), + 'pluralCount' => $this->getLocalizationService()->GetPluralCount(), + 'pluralRule' => $this->getLocalizationService()->GetPluralDefinition() ]); } else { - $quantityUnit = $this->Database->quantity_units($args['quantityunitId']); + $quantityUnit = $this->getDatabase()->quantity_units($args['quantityunitId']); - return $this->View->render($response, 'quantityunitform', [ + return $this->renderPage($response, 'quantityunitform', [ 'quantityUnit' => $quantityUnit, 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('quantity_units'), - 'pluralCount' => $this->LocalizationService->GetPluralCount(), - 'pluralRule' => $this->LocalizationService->GetPluralDefinition(), - 'defaultQuConversions' => $this->Database->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id), - 'quantityUnits' => $this->Database->quantity_units() + 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), + 'pluralCount' => $this->getLocalizationService()->GetPluralCount(), + 'pluralRule' => $this->getLocalizationService()->GetPluralDefinition(), + 'defaultQuConversions' => $this->getDatabase()->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id), + 'quantityUnits' => $this->getDatabase()->quantity_units() ]); } } @@ -269,18 +260,18 @@ class StockController extends BaseController { if ($args['itemId'] == 'new') { - return $this->View->render($response, 'shoppinglistitemform', [ - 'products' => $this->Database->products()->orderBy('name'), - 'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), + return $this->renderPage($response, 'shoppinglistitemform', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'), 'mode' => 'create' ]); } else { - return $this->View->render($response, 'shoppinglistitemform', [ - 'listItem' => $this->Database->shopping_list($args['itemId']), - 'products' => $this->Database->products()->orderBy('name'), - 'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), + return $this->renderPage($response, 'shoppinglistitemform', [ + 'listItem' => $this->getDatabase()->shopping_list($args['itemId']), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'), 'mode' => 'edit' ]); } @@ -290,14 +281,14 @@ class StockController extends BaseController { if ($args['listId'] == 'new') { - return $this->View->render($response, 'shoppinglistform', [ + return $this->renderPage($response, 'shoppinglistform', [ 'mode' => 'create' ]); } else { - return $this->View->render($response, 'shoppinglistform', [ - 'shoppingList' => $this->Database->shopping_lists($args['listId']), + return $this->renderPage($response, 'shoppinglistform', [ + 'shoppingList' => $this->getDatabase()->shopping_lists($args['listId']), 'mode' => 'edit' ]); } @@ -305,26 +296,26 @@ class StockController extends BaseController public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'shoppinglistsettings'); + return $this->renderPage($response, 'shoppinglistsettings'); } public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'stockjournal', [ - 'stockLog' => $this->Database->stock_log()->orderBy('row_created_timestamp', 'DESC'), - 'locations' => $this->Database->locations()->orderBy('name'), - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name') + return $this->renderPage($response, 'stockjournal', [ + 'stockLog' => $this->getDatabase()->stock_log()->orderBy('row_created_timestamp', 'DESC'), + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name') ]); } public function LocationContentSheet(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'locationcontentsheet', [ - 'products' => $this->Database->products()->orderBy('name'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), - 'locations' => $this->Database->locations()->orderBy('name'), - 'currentStockLocationContent' => $this->StockService->GetCurrentStockLocationContent() + return $this->renderPage($response, 'locationcontentsheet', [ + 'products' => $this->getDatabase()->products()->orderBy('name'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), + 'locations' => $this->getDatabase()->locations()->orderBy('name'), + 'currentStockLocationContent' => $this->getStockService()->GetCurrentStockLocationContent() ]); } @@ -333,32 +324,32 @@ class StockController extends BaseController $product = null; if (isset($request->getQueryParams()['product'])) { - $product = $this->Database->products($request->getQueryParams()['product']); + $product = $this->getDatabase()->products($request->getQueryParams()['product']); } $defaultQuUnit = null; if (isset($request->getQueryParams()['qu-unit'])) { - $defaultQuUnit = $this->Database->quantity_units($request->getQueryParams()['qu-unit']); + $defaultQuUnit = $this->getDatabase()->quantity_units($request->getQueryParams()['qu-unit']); } if ($args['quConversionId'] == 'new') { - return $this->View->render($response, 'quantityunitconversionform', [ + return $this->renderPage($response, 'quantityunitconversionform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('quantity_unit_conversions'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), 'product' => $product, 'defaultQuUnit' => $defaultQuUnit ]); } else { - return $this->View->render($response, 'quantityunitconversionform', [ - 'quConversion' => $this->Database->quantity_unit_conversions($args['quConversionId']), + return $this->renderPage($response, 'quantityunitconversionform', [ + 'quConversion' => $this->getDatabase()->quantity_unit_conversions($args['quConversionId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('quantity_unit_conversions'), - 'quantityunits' => $this->Database->quantity_units()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'), + 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'), 'product' => $product, 'defaultQuUnit' => $defaultQuUnit ]); @@ -367,8 +358,8 @@ class StockController extends BaseController public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'quantityunitpluraltesting', [ - 'quantityUnits' => $this->Database->quantity_units()->orderBy('name') + return $this->renderPage($response, 'quantityunitpluraltesting', [ + 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name') ]); } } diff --git a/controllers/SystemApiController.php b/controllers/SystemApiController.php index 371ceb7a..a293fd80 100644 --- a/controllers/SystemApiController.php +++ b/controllers/SystemApiController.php @@ -2,26 +2,18 @@ namespace Grocy\Controllers; -use \Grocy\Services\DatabaseService; -use \Grocy\Services\ApplicationService; - class SystemApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->DatabaseService = new DatabaseService(); - $this->ApplicationService = new ApplicationService(); } - protected $DatabaseService; - protected $ApplicationService; - public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, array( - 'changed_time' => $this->DatabaseService->GetDbChangedTime() - )); + return $this->ApiResponse($response, array( + 'changed_time' => $this->getDatabaseService()->GetDbChangedTime() + )); } public function LogMissingLocalization(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) @@ -32,18 +24,18 @@ class SystemApiController extends BaseApiController { $requestBody = $request->getParsedBody(); - $this->LocalizationService->CheckAndAddMissingTranslationToPot($requestBody['text']); + $this->getLocalizationService()->CheckAndAddMissingTranslationToPot($requestBody['text']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) { return $this->GenericErrorResponse($response, $ex->getMessage()); } - } + } } public function GetSystemInfo(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->ApplicationService->GetSystemInfo()); + return $this->ApiResponse($response, $this->getApplicationService()->GetSystemInfo()); } } diff --git a/controllers/SystemController.php b/controllers/SystemController.php index 1ce5a0f9..0b5a5a22 100644 --- a/controllers/SystemController.php +++ b/controllers/SystemController.php @@ -2,29 +2,26 @@ namespace Grocy\Controllers; -use \Grocy\Services\ApplicationService; use \Grocy\Services\DatabaseMigrationService; use \Grocy\Services\DemoDataGeneratorService; class SystemController extends BaseController { - protected $ApplicationService; public function __construct(\DI\Container $container) { parent::__construct($container); - $this->ApplicationService = new ApplicationService(); } public function Root(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { // Schema migration is done here - $databaseMigrationService = new DatabaseMigrationService(); + $databaseMigrationService = DatabaseMigrationService::getInstance(); $databaseMigrationService->MigrateDatabase(); if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease') { - $demoDataGeneratorService = new DemoDataGeneratorService(); + $demoDataGeneratorService = DemoDataGeneratorService::getInstance(); $demoDataGeneratorService->PopulateDemoData(); } @@ -85,7 +82,7 @@ class SystemController extends BaseController if ($entryPage === 'calendar' && constant('GROCY_FEATURE_FLAG_CALENDAR')) { return '/calendar'; } - + // Meal Plan if ($entryPage === 'mealplan' && constant('GROCY_FEATURE_FLAG_RECIPES')) { return '/mealplan'; @@ -96,14 +93,14 @@ class SystemController extends BaseController public function About(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'about', [ - 'system_info' => $this->ApplicationService->GetSystemInfo(), - 'changelog' => $this->ApplicationService->GetChangelog() + return $this->renderPage($response, 'about', [ + 'system_info' => $this->getApplicationService()->GetSystemInfo(), + 'changelog' => $this->getApplicationService()->GetChangelog() ]); } public function BarcodeScannerTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'barcodescannertesting'); + return $this->renderPage($response, 'barcodescannertesting'); } } diff --git a/controllers/TasksApiController.php b/controllers/TasksApiController.php index 53c85d81..fb8ad72a 100644 --- a/controllers/TasksApiController.php +++ b/controllers/TasksApiController.php @@ -2,21 +2,16 @@ namespace Grocy\Controllers; -use \Grocy\Services\TasksService; - class TasksApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->TasksService = new TasksService(); } - protected $TasksService; - public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, $this->TasksService->GetCurrent()); + return $this->ApiResponse($response, $this->getTasksService()->GetCurrent()); } public function MarkTaskAsCompleted(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) @@ -31,7 +26,7 @@ class TasksApiController extends BaseApiController $doneTime = $requestBody['done_time']; } - $this->TasksService->MarkTaskAsCompleted($args['taskId'], $doneTime); + $this->getTasksService()->MarkTaskAsCompleted($args['taskId'], $doneTime); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -44,7 +39,7 @@ class TasksApiController extends BaseApiController { try { - $this->TasksService->UndoTask($args['taskId']); + $this->getTasksService()->UndoTask($args['taskId']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) diff --git a/controllers/TasksController.php b/controllers/TasksController.php index 5260681d..ab57c547 100644 --- a/controllers/TasksController.php +++ b/controllers/TasksController.php @@ -2,43 +2,34 @@ namespace Grocy\Controllers; -use \Grocy\Services\TasksService; -use \Grocy\Services\UsersService; -use \Grocy\Services\UserfieldsService; - class TasksController extends BaseController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->TasksService = new TasksService(); - $this->UserfieldsService = new UserfieldsService(); } - protected $TasksService; - protected $UserfieldsService; - public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { if (isset($request->getQueryParams()['include_done'])) { - $tasks = $this->Database->tasks()->orderBy('name'); + $tasks = $this->getDatabase()->tasks()->orderBy('name'); } else { - $tasks = $this->TasksService->GetCurrent(); + $tasks = $this->getTasksService()->GetCurrent(); } - $usersService = new UsersService(); + $usersService = $this->getUsersService(); $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['tasks_due_soon_days']; - return $this->View->render($response, 'tasks', [ + return $this->renderPage($response, 'tasks', [ 'tasks' => $tasks, 'nextXDays' => $nextXDays, - 'taskCategories' => $this->Database->task_categories()->orderBy('name'), - 'users' => $this->Database->users(), - 'userfields' => $this->UserfieldsService->GetFields('tasks'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('tasks') + 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'), + 'users' => $this->getDatabase()->users(), + 'userfields' => $this->getUserfieldsService()->GetFields('tasks'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('tasks') ]); } @@ -46,31 +37,31 @@ class TasksController extends BaseController { if ($args['taskId'] == 'new') { - return $this->View->render($response, 'taskform', [ + return $this->renderPage($response, 'taskform', [ 'mode' => 'create', - 'taskCategories' => $this->Database->task_categories()->orderBy('name'), - 'users' => $this->Database->users()->orderBy('username'), - 'userfields' => $this->UserfieldsService->GetFields('tasks') + 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'), + 'users' => $this->getDatabase()->users()->orderBy('username'), + 'userfields' => $this->getUserfieldsService()->GetFields('tasks') ]); } else { - return $this->View->render($response, 'taskform', [ - 'task' => $this->Database->tasks($args['taskId']), + return $this->renderPage($response, 'taskform', [ + 'task' => $this->getDatabase()->tasks($args['taskId']), 'mode' => 'edit', - 'taskCategories' => $this->Database->task_categories()->orderBy('name'), - 'users' => $this->Database->users()->orderBy('username'), - 'userfields' => $this->UserfieldsService->GetFields('tasks') + 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'), + 'users' => $this->getDatabase()->users()->orderBy('username'), + 'userfields' => $this->getUserfieldsService()->GetFields('tasks') ]); } } public function TaskCategoriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'taskcategories', [ - 'taskCategories' => $this->Database->task_categories()->orderBy('name'), - 'userfields' => $this->UserfieldsService->GetFields('task_categories'), - 'userfieldValues' => $this->UserfieldsService->GetAllValues('task_categories') + return $this->renderPage($response, 'taskcategories', [ + 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'), + 'userfields' => $this->getUserfieldsService()->GetFields('task_categories'), + 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('task_categories') ]); } @@ -78,23 +69,23 @@ class TasksController extends BaseController { if ($args['categoryId'] == 'new') { - return $this->View->render($response, 'taskcategoryform', [ + return $this->renderPage($response, 'taskcategoryform', [ 'mode' => 'create', - 'userfields' => $this->UserfieldsService->GetFields('task_categories') + 'userfields' => $this->getUserfieldsService()->GetFields('task_categories') ]); } else { - return $this->View->render($response, 'taskcategoryform', [ - 'category' => $this->Database->task_categories($args['categoryId']), + return $this->renderPage($response, 'taskcategoryform', [ + 'category' => $this->getDatabase()->task_categories($args['categoryId']), 'mode' => 'edit', - 'userfields' => $this->UserfieldsService->GetFields('task_categories') + 'userfields' => $this->getUserfieldsService()->GetFields('task_categories') ]); } } public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'taskssettings'); + return $this->renderPage($response, 'taskssettings'); } } diff --git a/controllers/UsersApiController.php b/controllers/UsersApiController.php index 8933f1e1..00625bf2 100644 --- a/controllers/UsersApiController.php +++ b/controllers/UsersApiController.php @@ -2,23 +2,18 @@ namespace Grocy\Controllers; -use \Grocy\Services\UsersService; - class UsersApiController extends BaseApiController { public function __construct(\DI\Container $container) { parent::__construct($container); - $this->UsersService = new UsersService(); } - protected $UsersService; - public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { try { - return $this->ApiResponse($response, $this->UsersService->GetUsersAsDto()); + return $this->ApiResponse($response, $this->getUsersService()->GetUsersAsDto()); } catch (\Exception $ex) { @@ -37,7 +32,7 @@ class UsersApiController extends BaseApiController throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); } - $this->UsersService->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); + $this->getUsersService()->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -50,7 +45,7 @@ class UsersApiController extends BaseApiController { try { - $this->UsersService->DeleteUser($args['userId']); + $this->getUsersService()->DeleteUser($args['userId']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -65,7 +60,7 @@ class UsersApiController extends BaseApiController try { - $this->UsersService->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); + $this->getUsersService()->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -78,7 +73,7 @@ class UsersApiController extends BaseApiController { try { - $value = $this->UsersService->GetUserSetting(GROCY_USER_ID, $args['settingKey']); + $value = $this->getUsersService()->GetUserSetting(GROCY_USER_ID, $args['settingKey']); return $this->ApiResponse($response, array('value' => $value)); } catch (\Exception $ex) @@ -93,7 +88,7 @@ class UsersApiController extends BaseApiController { $requestBody = $request->getParsedBody(); - $value = $this->UsersService->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']); + $value = $this->getUsersService()->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']); return $this->EmptyApiResponse($response); } catch (\Exception $ex) diff --git a/controllers/UsersController.php b/controllers/UsersController.php index 72450711..01894a66 100644 --- a/controllers/UsersController.php +++ b/controllers/UsersController.php @@ -6,8 +6,8 @@ class UsersController extends BaseController { public function UsersList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->View->render($response, 'users', [ - 'users' => $this->Database->users()->orderBy('username') + return $this->renderPage($response, 'users', [ + 'users' => $this->getDatabase()->users()->orderBy('username') ]); } @@ -15,14 +15,14 @@ class UsersController extends BaseController { if ($args['userId'] == 'new') { - return $this->View->render($response, 'userform', [ + return $this->renderPage($response, 'userform', [ 'mode' => 'create' ]); } else { - return $this->View->render($response, 'userform', [ - 'user' => $this->Database->users($args['userId']), + return $this->renderPage($response, 'userform', [ + 'user' => $this->getDatabase()->users($args['userId']), 'mode' => 'edit' ]); } diff --git a/middleware/ApiKeyAuthMiddleware.php b/middleware/ApiKeyAuthMiddleware.php index 61e6ef12..462d3d55 100644 --- a/middleware/ApiKeyAuthMiddleware.php +++ b/middleware/ApiKeyAuthMiddleware.php @@ -38,8 +38,8 @@ class ApiKeyAuthMiddleware extends BaseMiddleware $validSession = true; $validApiKey = true; $usedApiKey = null; - - $sessionService = new SessionService(); + + $sessionService = SessionService::getInstance(); if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName])) { $validSession = false; diff --git a/middleware/BaseMiddleware.php b/middleware/BaseMiddleware.php index a582a53a..3b38a957 100644 --- a/middleware/BaseMiddleware.php +++ b/middleware/BaseMiddleware.php @@ -9,7 +9,7 @@ class BaseMiddleware public function __construct(\DI\Container $container) { $this->AppContainer = $container; - $this->ApplicationService = new ApplicationService(); + $this->ApplicationService = ApplicationService::getInstance(); } protected $AppContainer; diff --git a/middleware/SessionAuthMiddleware.php b/middleware/SessionAuthMiddleware.php index 1f9fb618..2a6b4ce3 100644 --- a/middleware/SessionAuthMiddleware.php +++ b/middleware/SessionAuthMiddleware.php @@ -25,7 +25,7 @@ class SessionAuthMiddleware extends BaseMiddleware $routeContext = RouteContext::fromRequest($request); $route = $routeContext->getRoute(); $routeName = $route->getName(); - $sessionService = new SessionService(); + $sessionService = SessionService::getInstance(); if ($routeName === 'root') { diff --git a/migrations/0027.php b/migrations/0027.php index 3f294cd7..8d9079f1 100644 --- a/migrations/0027.php +++ b/migrations/0027.php @@ -2,7 +2,7 @@ // This is executed inside DatabaseMigrationService class/context -$db = $this->DatabaseService->GetDbConnection(); +$db = $this->getDatabaseService()->GetDbConnection(); if (defined('GROCY_HTTP_USER')) { diff --git a/migrations/0031.php b/migrations/0031.php index 043c0002..03dfcd18 100644 --- a/migrations/0031.php +++ b/migrations/0031.php @@ -3,9 +3,9 @@ // This is executed inside DatabaseMigrationService class/context use \Grocy\Services\LocalizationService; -$localizationService = new LocalizationService(GROCY_CULTURE); +$localizationService = $this->getLocalizationService(); -$db = $this->DatabaseService->GetDbConnection(); +$db = $this->getDatabaseService()->GetDbConnection(); if ($db->quantity_units()->count() === 0) { diff --git a/migrations/0063.php b/migrations/0063.php index 1a9bb94b..6aaac16d 100644 --- a/migrations/0063.php +++ b/migrations/0063.php @@ -3,11 +3,11 @@ // This is executed inside DatabaseMigrationService class/context use \Grocy\Services\LocalizationService; -$localizationService = new LocalizationService(GROCY_CULTURE); +$localizationService = $this->getLocalizationService(); -$db = $this->DatabaseService->GetDbConnection(); +$db = $this->getDatabaseService()->GetDbConnection(); -$defaultShoppingList = $this->Database->shopping_lists()->where('id = 1')->fetch(); +$defaultShoppingList = $db->shopping_lists()->where('id = 1')->fetch(); $defaultShoppingList->update(array( 'name' => $localizationService->__t('Shopping list') )); diff --git a/routes.php b/routes.php index 385c45d9..d6a7cddf 100644 --- a/routes.php +++ b/routes.php @@ -9,6 +9,7 @@ use Grocy\Middleware\ApiKeyAuthMiddleware; $app->group('', function(RouteCollectorProxy $group) { + // System routes $group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root'); $group->get('/about', '\Grocy\Controllers\SystemController:About'); @@ -113,7 +114,7 @@ $app->group('', function(RouteCollectorProxy $group) $group->get('/equipment', '\Grocy\Controllers\EquipmentController:Overview'); $group->get('/equipment/{equipmentId}', '\Grocy\Controllers\EquipmentController:EditForm'); } - + // Calendar routes if (GROCY_FEATURE_FLAG_CALENDAR) { 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/ApplicationService.php b/services/ApplicationService.php index d7604ef0..13137dd0 100644 --- a/services/ApplicationService.php +++ b/services/ApplicationService.php @@ -5,17 +5,18 @@ namespace Grocy\Services; class ApplicationService extends BaseService { private $InstalledVersion; + public function GetInstalledVersion() { if ($this->InstalledVersion == null) { $this->InstalledVersion = json_decode(file_get_contents(__DIR__ . '/../version.json')); - + if (GROCY_MODE === 'prerelease') { $commitHash = trim(exec('git log --pretty="%h" -n1 HEAD')); $commitDate = trim(exec('git log --date=iso --pretty="%cd" -n1 HEAD')); - + $this->InstalledVersion->Version = "pre-release-$commitHash"; $this->InstalledVersion->ReleaseDate = substr($commitDate, 0, 19); } diff --git a/services/BaseService.php b/services/BaseService.php index cc6afeeb..8962f54e 100644 --- a/services/BaseService.php +++ b/services/BaseService.php @@ -2,20 +2,64 @@ namespace Grocy\Services; -use \Grocy\Services\DatabaseService; -use \Grocy\Services\LocalizationService; +#use \Grocy\Services\DatabaseService; +#use \Grocy\Services\LocalizationService; class BaseService { public function __construct() { - $this->DatabaseService = new DatabaseService(); - $this->Database = $this->DatabaseService->GetDbConnection(); - - $localizationService = new LocalizationService(GROCY_CULTURE); - $this->LocalizationService = $localizationService; } - protected $DatabaseService; - protected $Database; - protected $LocalizationService; + private static $instances = array(); + + public static function getInstance() + { + $className = get_called_class(); + if(!isset(self::$instances[$className])) + { + self::$instances[$className] = new $className(); + } + + return self::$instances[$className]; + } + + protected function getDatabaseService() + { + return DatabaseService::getInstance(); + } + + protected function getDatabase() + { + return $this->getDatabaseService()->GetDbConnection(); + } + + protected function getLocalizationService() + { + return LocalizationService::getInstance(GROCY_CULTURE); + } + + protected function getStockservice() + { + return StockService::getInstance(); + } + + protected function getTasksService() + { + return TasksService::getInstance(); + } + + protected function getChoresService() + { + return ChoresService::getInstance(); + } + + protected function getBatteriesService() + { + return BatteriesService::getInstance(); + } + + protected function getUsersService() + { + return UsersService::getInstance(); + } } 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/CalendarService.php b/services/CalendarService.php index a73566e1..d60002a6 100644 --- a/services/CalendarService.php +++ b/services/CalendarService.php @@ -2,11 +2,11 @@ namespace Grocy\Services; -use \Grocy\Services\StockService; -use \Grocy\Services\TasksService; -use \Grocy\Services\ChoresService; -use \Grocy\Services\BatteriesService; -use \Grocy\Services\UsersService; +#use \Grocy\Services\StockService; +#use \Grocy\Services\TasksService; +#use \Grocy\Services\ChoresService; +#use \Grocy\Services\BatteriesService; +#use \Grocy\Services\UsersService; use \Grocy\Helpers\UrlManager; class CalendarService extends BaseService @@ -14,27 +14,17 @@ class CalendarService extends BaseService public function __construct() { parent::__construct(); - $this->StockService = new StockService(); - $this->TasksService = new TasksService(); - $this->ChoresService = new ChoresService(); - $this->BatteriesService = new BatteriesService(); $this->UrlManager = new UrlManager(GROCY_BASE_URL); } - protected $StockService; - protected $TasksService; - protected $ChoresService; - protected $BatteriesService; - protected $UrlManager; - public function GetEvents() { $stockEvents = array(); if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) { - $products = $this->Database->products(); - $titlePrefix = $this->LocalizationService->__t('Product expires') . ': '; - foreach($this->StockService->GetCurrentStock() as $currentStockEntry) + $products = $this->getDatabase()->products(); + $titlePrefix = $this->getLocalizationService()->__t('Product expires') . ': '; + foreach($this->getStockService()->GetCurrentStock() as $currentStockEntry) { if ($currentStockEntry->amount > 0) { @@ -50,8 +40,8 @@ class CalendarService extends BaseService $taskEvents = array(); if (GROCY_FEATURE_FLAG_TASKS) { - $titlePrefix = $this->LocalizationService->__t('Task due') . ': '; - foreach($this->TasksService->GetCurrent() as $currentTaskEntry) + $titlePrefix = $this->getLocalizationService()->__t('Task due') . ': '; + foreach($this->getTasksService()->GetCurrent() as $currentTaskEntry) { $taskEvents[] = array( 'title' => $titlePrefix . $currentTaskEntry->name, @@ -64,19 +54,18 @@ class CalendarService extends BaseService $choreEvents = array(); if (GROCY_FEATURE_FLAG_CHORES) { - $usersService = new UsersService(); - $users = $usersService->GetUsersAsDto(); + $users = $this->getUsersService()->GetUsersAsDto(); - $chores = $this->Database->chores(); - $titlePrefix = $this->LocalizationService->__t('Chore due') . ': '; - foreach($this->ChoresService->GetCurrent() as $currentChoreEntry) + $chores = $this->getDatabase()->chores(); + $titlePrefix = $this->getLocalizationService()->__t('Chore due') . ': '; + foreach($this->getChoresService()->GetCurrent() as $currentChoreEntry) { $chore = FindObjectInArrayByPropertyValue($chores, 'id', $currentChoreEntry->chore_id); $assignedToText = ''; if (!empty($currentChoreEntry->next_execution_assigned_to_user_id)) { - $assignedToText = ' (' . $this->LocalizationService->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')'; + $assignedToText = ' (' . $this->getLocalizationService()->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')'; } $choreEvents[] = array( @@ -90,9 +79,9 @@ class CalendarService extends BaseService $batteryEvents = array(); if (GROCY_FEATURE_FLAG_BATTERIES) { - $batteries = $this->Database->batteries(); - $titlePrefix = $this->LocalizationService->__t('Battery charge cycle due') . ': '; - foreach($this->BatteriesService->GetCurrent() as $currentBatteryEntry) + $batteries = $this->getDatabase()->batteries(); + $titlePrefix = $this->getLocalizationService()->__t('Battery charge cycle due') . ': '; + foreach($this->getBatteriesService()->GetCurrent() as $currentBatteryEntry) { $batteryEvents[] = array( 'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name, @@ -105,13 +94,13 @@ class CalendarService extends BaseService $mealPlanRecipeEvents = array(); if (GROCY_FEATURE_FLAG_RECIPES) { - $recipes = $this->Database->recipes(); - $mealPlanDayRecipes = $this->Database->recipes()->where('type', 'mealplan-day'); - $titlePrefix = $this->LocalizationService->__t('Meal plan recipe') . ': '; + $recipes = $this->getDatabase()->recipes(); + $mealPlanDayRecipes = $this->getDatabase()->recipes()->where('type', 'mealplan-day'); + $titlePrefix = $this->getLocalizationService()->__t('Meal plan recipe') . ': '; foreach($mealPlanDayRecipes as $mealPlanDayRecipe) { - $recipesOfCurrentDay = $this->Database->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id); + $recipesOfCurrentDay = $this->getDatabase()->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id); foreach ($recipesOfCurrentDay as $recipeOfCurrentDay) { $mealPlanRecipeEvents[] = array( @@ -123,8 +112,8 @@ class CalendarService extends BaseService } } - $mealPlanDayNotes = $this->Database->meal_plan()->where('type', 'note'); - $titlePrefix = $this->LocalizationService->__t('Meal plan note') . ': '; + $mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note'); + $titlePrefix = $this->getLocalizationService()->__t('Meal plan note') . ': '; $mealPlanNotesEvents = array(); foreach($mealPlanDayNotes as $mealPlanDayNote) { @@ -135,9 +124,9 @@ class CalendarService extends BaseService ); } - $products = $this->Database->products(); - $mealPlanDayProducts = $this->Database->meal_plan()->where('type', 'product'); - $titlePrefix = $this->LocalizationService->__t('Meal plan product') . ': '; + $products = $this->getDatabase()->products(); + $mealPlanDayProducts = $this->getDatabase()->meal_plan()->where('type', 'product'); + $titlePrefix = $this->getLocalizationService()->__t('Meal plan product') . ': '; $mealPlanProductEvents = array(); foreach($mealPlanDayProducts as $mealPlanDayProduct) { diff --git a/services/ChoresService.php b/services/ChoresService.php index fef9e0a5..65c49699 100644 --- a/services/ChoresService.php +++ b/services/ChoresService.php @@ -2,7 +2,7 @@ namespace Grocy\Services; -use \Grocy\Services\StockService; +#use \Grocy\Services\StockService; class ChoresService extends BaseService { @@ -21,15 +21,12 @@ class ChoresService extends BaseService public function __construct() { parent::__construct(); - $this->StockService = new StockService(); } - protected $StockService; - public function GetCurrent() { $sql = 'SELECT * from chores_current'; - return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); + return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); } public function GetChoreDetails(int $choreId) @@ -38,16 +35,15 @@ class ChoresService extends BaseService { throw new \Exception('Chore does not exist'); } - - $usersService = new UsersService(); - $users = $usersService->GetUsersAsDto(); - - $chore = $this->Database->chores($choreId); - $choreTrackedCount = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count(); - $choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); - $nextExecutionTime = $this->Database->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time'); - $lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); + $users = $this->getUsersService()->GetUsersAsDto(); + + $chore = $this->getDatabase()->chores($choreId); + $choreTrackedCount = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count(); + $choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); + $nextExecutionTime = $this->getDatabase()->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time'); + + $lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); $lastDoneByUser = null; if ($lastChoreLogRow !== null && !empty($lastChoreLogRow)) { @@ -77,31 +73,31 @@ class ChoresService extends BaseService throw new \Exception('Chore does not exist'); } - $userRow = $this->Database->users()->where('id = :1', $doneBy)->fetch(); + $userRow = $this->getDatabase()->users()->where('id = :1', $doneBy)->fetch(); if ($userRow === null) { throw new \Exception('User does not exist'); } - $chore = $this->Database->chores($choreId); + $chore = $this->getDatabase()->chores($choreId); if ($chore->track_date_only == 1) { $trackedTime = substr($trackedTime, 0, 10) . ' 00:00:00'; } - - $logRow = $this->Database->chores_log()->createRow(array( + + $logRow = $this->getDatabase()->chores_log()->createRow(array( 'chore_id' => $choreId, 'tracked_time' => $trackedTime, 'done_by_user_id' => $doneBy )); $logRow->save(); - $lastInsertId = $this->Database->lastInsertId(); + $lastInsertId = $this->getDatabase()->lastInsertId(); $this->CalculateNextExecutionAssignment($choreId); if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id)) { - $this->StockService->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME); + $this->getStockService()->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME); } return $lastInsertId; @@ -109,13 +105,13 @@ class ChoresService extends BaseService private function ChoreExists($choreId) { - $choreRow = $this->Database->chores()->where('id = :1', $choreId)->fetch(); + $choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch(); return $choreRow !== null; } public function UndoChoreExecution($executionId) { - $logRow = $this->Database->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch(); + $logRow = $this->getDatabase()->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch(); if ($logRow == null) { throw new \Exception('Execution does not exist or was already undone'); @@ -135,13 +131,12 @@ class ChoresService extends BaseService throw new \Exception('Chore does not exist'); } - $chore = $this->Database->chores($choreId); - $choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); - $lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); + $chore = $this->getDatabase()->chores($choreId); + $choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); + $lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); $lastDoneByUserId = $lastChoreLogRow->done_by_user_id; - - $usersService = new UsersService(); - $users = $usersService->GetUsersAsDto(); + + $users = $this->getUsersService()->GetUsersAsDto(); $assignedUsers = array(); foreach ($users as $user) { @@ -198,7 +193,7 @@ class ChoresService extends BaseService } else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST) { - $row = $this->Database->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch(); + $row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch(); if ($row != null) { $nextExecutionUserId = $row->user_id; 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/DatabaseService.php b/services/DatabaseService.php index 252aaec8..23fc7b9d 100644 --- a/services/DatabaseService.php +++ b/services/DatabaseService.php @@ -2,10 +2,22 @@ namespace Grocy\Services; -use \Grocy\Services\ApplicationService; +#use \Grocy\Services\ApplicationService; class DatabaseService { + private static $instance = null; + + public static function getInstance() + { + if (self::$instance == null) + { + self::$instance = new self(); + } + + return self::$instance; + } + private function GetDbFilePath() { if (GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease') @@ -16,34 +28,34 @@ class DatabaseService return GROCY_DATAPATH . '/grocy.db'; } - private $DbConnectionRaw; + private static $DbConnectionRaw = null; /** * @return \PDO */ public function GetDbConnectionRaw() { - if ($this->DbConnectionRaw == null) + if (self::$DbConnectionRaw == null) { $pdo = new \PDO('sqlite:' . $this->GetDbFilePath()); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->DbConnectionRaw = $pdo; + self::$DbConnectionRaw = $pdo; } - return $this->DbConnectionRaw; + return self::$DbConnectionRaw; } - private $DbConnection; + private static $DbConnection = null; /** * @return \LessQL\Database */ public function GetDbConnection() { - if ($this->DbConnection == null) + if (self::$DbConnection == null) { - $this->DbConnection = new \LessQL\Database($this->GetDbConnectionRaw()); + self::$DbConnection = new \LessQL\Database($this->GetDbConnectionRaw()); } - return $this->DbConnection; + return self::$DbConnection; } /** diff --git a/services/DemoDataGeneratorService.php b/services/DemoDataGeneratorService.php index 3d3106c6..6a32b9e3 100644 --- a/services/DemoDataGeneratorService.php +++ b/services/DemoDataGeneratorService.php @@ -2,7 +2,7 @@ namespace Grocy\Services; -use \Grocy\Services\LocalizationService; +#use \Grocy\Services\LocalizationService; class DemoDataGeneratorService extends BaseService { @@ -12,11 +12,11 @@ class DemoDataGeneratorService extends BaseService $this->LocalizationService = new LocalizationService(GROCY_CULTURE); } - protected $LocalizationService; + 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.'; @@ -183,7 +183,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()); @@ -319,13 +319,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/FilesService.php b/services/FilesService.php index cd9ebd6d..cecdae3c 100644 --- a/services/FilesService.php +++ b/services/FilesService.php @@ -11,9 +11,9 @@ class FilesService extends BaseService public function __construct() { parent::__construct(); - + $this->StoragePath = GROCY_DATAPATH . '/storage'; - + if (!file_exists($this->StoragePath)) { mkdir($this->StoragePath); diff --git a/services/LocalizationService.php b/services/LocalizationService.php index 8478510c..e11c7f85 100644 --- a/services/LocalizationService.php +++ b/services/LocalizationService.php @@ -2,24 +2,44 @@ namespace Grocy\Services; -use \Grocy\Services\DatabaseService; +#use \Grocy\Services\DatabaseService; use \Gettext\Translation; use \Gettext\Translations; use \Gettext\Translator; class LocalizationService { + + private static $instanceMap = array(); + public function __construct(string $culture) { $this->Culture = $culture; - $this->DatabaseService = new DatabaseService(); - $this->Database = $this->DatabaseService->GetDbConnection(); $this->LoadLocalizations($culture); } - protected $DatabaseService; - protected $Database; + + 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); + } + + return self::$instanceMap[$culture]; + } + protected $Pot; protected $PotMain; protected $Po; @@ -57,7 +77,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 2cbd3865..0c1f9b52 100644 --- a/services/RecipesService.php +++ b/services/RecipesService.php @@ -2,7 +2,7 @@ namespace Grocy\Services; -use \Grocy\Services\StockService; +#use \Grocy\Services\StockService; class RecipesService extends BaseService { @@ -13,46 +13,43 @@ class RecipesService extends BaseService public function __construct() { parent::__construct(); - $this->StockService = new StockService(); } - protected $StockService; - 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(); } @@ -68,26 +65,26 @@ class RecipesService extends BaseService } $transactionId = uniqid(); - $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) { - $this->StockService->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true); + $this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true); } } - $recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch(); + $recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch(); if (!empty($recipeRow->product_id)) { - $recipeResolvedRow = $this->Database->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch(); - $this->StockService->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs)); + $recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch(); + $this->getStockService()->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs)); } } 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 4759f4c5..a1b547aa 100644 --- a/services/SessionService.php +++ b/services/SessionService.php @@ -4,6 +4,7 @@ namespace Grocy\Services; class SessionService extends BaseService { + /** * @return boolean */ @@ -15,16 +16,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; } @@ -41,14 +42,14 @@ class SessionService extends BaseService public function CreateSession($userId, $stayLoggedInPermanently = false) { $newSessionKey = $this->GenerateSessionKey(); - + $expires = date('Y-m-d H:i:s', intval(time() + 2592000)); // Default is that sessions expire in 30 days if ($stayLoggedInPermanently === true) { $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 @@ -60,22 +61,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 1bfd41c7..ec9a3934 100644 --- a/services/StockService.php +++ b/services/StockService.php @@ -27,9 +27,9 @@ 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)'; } - $currentStockMapped = $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ); + $currentStockMapped = $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ); - $relevantProducts = $this->Database->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)'); + $relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)'); foreach ($relevantProducts as $product) { $currentStockMapped[$product->id][0]->product_id = $product->id; @@ -42,19 +42,19 @@ class StockService extends BaseService 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() @@ -65,17 +65,17 @@ 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 GetProductStockLocations($productId) { - return $this->Database->stock_current_locations()->where('product_id', $productId)->fetchAll(); + return $this->getDatabase()->stock_current_locations()->where('product_id', $productId)->fetchAll(); } 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) { @@ -117,24 +117,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; @@ -168,7 +168,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( @@ -181,7 +181,7 @@ class StockService extends BaseService public function GetStockEntry($entryId) { - return $this->Database->stock()->where('id', $entryId)->fetch(); + return $this->getDatabase()->stock()->where('id', $entryId)->fetch(); } public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false) @@ -201,7 +201,7 @@ class StockService extends BaseService $sqlWhereAndOpen = 'AND open = 0'; } - return $this->Database->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); + return $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); } public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false) @@ -257,7 +257,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, @@ -270,9 +270,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, @@ -319,6 +319,7 @@ class StockService extends BaseService if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) { + if ($locationId === null) // Consume from any location { $potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution); @@ -353,7 +354,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, @@ -377,7 +378,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, @@ -401,7 +402,7 @@ class StockService extends BaseService } } - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } else { @@ -443,7 +444,7 @@ class StockService extends BaseService $amount = abs($amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight)); } - $productStockAmountAtFromLocation = $this->Database->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount'); + $productStockAmountAtFromLocation = $this->getDatabase()->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount'); $potentialStockEntriesAtFromLocation = $this->GetProductStockEntriesForLocation($productId, $locationIdFrom); if ($amount > $productStockAmountAtFromLocation) @@ -472,8 +473,8 @@ class StockService extends BaseService if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING) { - $locationFrom = $this->Database->locations()->where('id', $locationIdFrom)->fetch(); - $locationTo = $this->Database->locations()->where('id', $locationIdTo)->fetch(); + $locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch(); + $locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch(); // Product was moved from a non-freezer to freezer location -> freeze if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0) @@ -491,7 +492,7 @@ class StockService extends BaseService $correlationId = uniqid(); if ($amount >= $stockEntry->amount) // Take the whole stock entry { - $logRowForLocationFrom = $this->Database->stock_log()->createRow(array( + $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $stockEntry->amount * -1, 'best_before_date' => $stockEntry->best_before_date, @@ -506,7 +507,7 @@ class StockService extends BaseService )); $logRowForLocationFrom->save(); - $logRowForLocationTo = $this->Database->stock_log()->createRow(array( + $logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $stockEntry->amount, 'best_before_date' => $newBestBeforeDate, @@ -532,7 +533,7 @@ class StockService extends BaseService { $restStockAmount = $stockEntry->amount - $amount; - $logRowForLocationFrom = $this->Database->stock_log()->createRow(array( + $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $amount * -1, 'best_before_date' => $stockEntry->best_before_date, @@ -547,7 +548,7 @@ class StockService extends BaseService )); $logRowForLocationFrom->save(); - $logRowForLocationTo = $this->Database->stock_log()->createRow(array( + $logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $amount, 'best_before_date' => $newBestBeforeDate, @@ -568,7 +569,7 @@ class StockService extends BaseService )); // The transfered amount gets into a new stock entry - $stockEntryNew = $this->Database->stock()->createRow(array( + $stockEntryNew = $this->getDatabase()->stock()->createRow(array( 'product_id' => $stockEntry->product_id, 'amount' => $amount, 'best_before_date' => $newBestBeforeDate, @@ -585,13 +586,13 @@ class StockService extends BaseService } } - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } public function EditStockEntry(int $stockRowId, int $amount, $bestBeforeDate, $locationId, $price, $open, $purchasedDate) { - $stockRow = $this->Database->stock()->where('id = :1', $stockRowId)->fetch(); + $stockRow = $this->getDatabase()->stock()->where('id = :1', $stockRowId)->fetch(); if ($stockRow === null) { @@ -600,7 +601,7 @@ class StockService extends BaseService $correlationId = uniqid(); $transactionId = uniqid(); - $logOldRowForStockUpdate = $this->Database->stock_log()->createRow(array( + $logOldRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockRow->product_id, 'amount' => $stockRow->amount, 'best_before_date' => $stockRow->best_before_date, @@ -636,7 +637,7 @@ class StockService extends BaseService 'purchased_date' => $purchasedDate )); - $logNewRowForStockUpdate = $this->Database->stock_log()->createRow(array( + $logNewRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array( 'product_id' => $stockRow->product_id, 'amount' => $amount, 'best_before_date' => $bestBeforeDate, @@ -652,7 +653,7 @@ class StockService extends BaseService )); $logNewRowForStockUpdate->save(); - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null) @@ -713,9 +714,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) { @@ -742,7 +743,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, @@ -766,7 +767,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, @@ -776,7 +777,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, @@ -799,7 +800,7 @@ class StockService extends BaseService } } - return $this->Database->lastInsertId(); + return $this->getDatabase()->lastInsertId(); } public function AddMissingProductsToShoppingList($listId = 1) @@ -812,10 +813,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) @@ -828,7 +829,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 @@ -845,7 +846,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(); } @@ -856,7 +857,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)) @@ -886,7 +887,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( @@ -897,7 +898,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, @@ -909,19 +910,19 @@ 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 LocationExists($locationId) { - $locationRow = $this->Database->locations()->where('id = :1', $locationId)->fetch(); + $locationRow = $this->getDatabase()->locations()->where('id = :1', $locationId)->fetch(); return $locationRow !== 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; } @@ -937,7 +938,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->getDatabase()->quantity_units()->fetchAll()); } else { @@ -955,7 +956,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; @@ -967,7 +968,7 @@ class StockService extends BaseService public function UndoBooking($bookingId, $skipCorrelatedBookings = false) { - $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'); @@ -976,7 +977,7 @@ class StockService extends BaseService // Undo all correlated bookings first, in order from newest first to the oldest if (!$skipCorrelatedBookings && !empty($logRow->correlation_id)) { - $correlatedBookings = $this->Database->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll(); + $correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll(); foreach ($correlatedBookings as $correlatedBooking) { $this->UndoBooking($correlatedBooking->id, true); @@ -984,7 +985,7 @@ class StockService extends BaseService return; } - $hasSubsequentBookings = $this->Database->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0; + $hasSubsequentBookings = $this->getDatabase()->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0; if ($hasSubsequentBookings) { throw new \Exception('Booking has subsequent dependent bookings, undo not possible'); @@ -993,7 +994,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 @@ -1005,7 +1006,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, @@ -1024,7 +1025,7 @@ class StockService extends BaseService } elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_TO) { - $stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); + $stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); if ($stockRow === null) { throw new \Exception('Booking does not exist or was already undone'); @@ -1051,10 +1052,10 @@ class StockService extends BaseService { // Add corresponding amount back to stock or // create a row if missing - $stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); + $stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); if ($stockRow === null) { - $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, @@ -1079,7 +1080,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 @@ -1102,7 +1103,7 @@ class StockService extends BaseService elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_STOCK_EDIT_OLD) { // Make sure there is a stock row still - $stockRow = $this->Database->stock()->where('id = :1', $logRow->stock_row_id)->fetch(); + $stockRow = $this->getDatabase()->stock()->where('id = :1', $logRow->stock_row_id)->fetch(); if ($stockRow == null) { throw new \Exception('Booking does not exist or was already undone'); @@ -1139,7 +1140,7 @@ class StockService extends BaseService public function UndoTransaction($transactionId) { - $transactionBookings = $this->Database->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll(); + $transactionBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll(); if (count($transactionBookings) === 0) { 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; } } diff --git a/services/UserfieldsService.php b/services/UserfieldsService.php index 619bc602..1ff1e417 100644 --- a/services/UserfieldsService.php +++ b/services/UserfieldsService.php @@ -18,11 +18,19 @@ class UserfieldsService extends BaseService public function __construct() { parent::__construct(); - $this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json')); } - protected $OpenApiSpec; - + protected $OpenApiSpec = null; + + protected function getOpenApispec() + { + if($this->OpenApiSpec == null) + { + $this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json')); + } + return $this->OpenApiSpec; + } + public function GetFields($entity) { if (!$this->IsValidEntity($entity)) @@ -30,17 +38,17 @@ class UserfieldsService extends BaseService throw new \Exception('Entity does not exist or is not exposed'); } - return $this->Database->userfields()->where('entity', $entity)->orderBy('name')->fetchAll(); + return $this->getDatabase()->userfields()->where('entity', $entity)->orderBy('name')->fetchAll(); } public function GetField($fieldId) { - return $this->Database->userfields($fieldId); + return $this->getDatabase()->userfields($fieldId); } public function GetAllFields() { - return $this->Database->userfields()->orderBy('name')->fetchAll(); + return $this->getDatabase()->userfields()->orderBy('name')->fetchAll(); } public function GetValues($entity, $objectId) @@ -50,7 +58,7 @@ class UserfieldsService extends BaseService throw new \Exception('Entity does not exist or is not exposed'); } - $userfields = $this->Database->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll(); + $userfields = $this->getDatabase()->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll(); $userfieldKeyValuePairs = array(); foreach ($userfields as $userfield) { @@ -67,7 +75,7 @@ class UserfieldsService extends BaseService throw new \Exception('Entity does not exist or is not exposed'); } - return $this->Database->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll(); + return $this->getDatabase()->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll(); } public function SetValues($entity, $objectId, $userfields) @@ -79,7 +87,7 @@ class UserfieldsService extends BaseService foreach ($userfields as $key => $value) { - $fieldRow = $this->Database->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch(); + $fieldRow = $this->getDatabase()->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch(); if ($fieldRow === null) { @@ -88,7 +96,7 @@ class UserfieldsService extends BaseService $fieldId = $fieldRow->id; - $alreadyExistingEntry = $this->Database->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch(); + $alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch(); if ($alreadyExistingEntry) // Update { $alreadyExistingEntry->update(array( @@ -97,7 +105,7 @@ class UserfieldsService extends BaseService } else // Insert { - $newRow = $this->Database->userfield_values()->createRow(array( + $newRow = $this->getDatabase()->userfield_values()->createRow(array( 'field_id' => $fieldId, 'object_id' => $objectId, 'value' => $value @@ -109,10 +117,10 @@ class UserfieldsService extends BaseService public function GetEntities() { - $exposedDefaultEntities = $this->OpenApiSpec->components->internalSchemas->ExposedEntity->enum; - + $exposedDefaultEntities = $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum; + $userentities = array(); - foreach ($this->Database->userentities()->orderBy('name') as $userentity) + foreach ($this->getDatabase()->userentities()->orderBy('name') as $userentity) { $userentities[] = 'userentity-' . $userentity->name; } diff --git a/services/UsersService.php b/services/UsersService.php index 2b431cbe..14810db0 100644 --- a/services/UsersService.php +++ b/services/UsersService.php @@ -6,7 +6,7 @@ class UsersService extends BaseService { public function CreateUser(string $username, string $firstName, string $lastName, string $password) { - $newUserRow = $this->Database->users()->createRow(array( + $newUserRow = $this->getDatabase()->users()->createRow(array( 'username' => $username, 'first_name' => $firstName, 'last_name' => $lastName, @@ -22,7 +22,7 @@ class UsersService extends BaseService throw new \Exception('User does not exist'); } - $user = $this->Database->users($userId); + $user = $this->getDatabase()->users($userId); $user->update(array( 'username' => $username, 'first_name' => $firstName, @@ -33,13 +33,13 @@ class UsersService extends BaseService public function DeleteUser($userId) { - $row = $this->Database->users($userId); + $row = $this->getDatabase()->users($userId); $row->delete(); } public function GetUsersAsDto() { - $users = $this->Database->users(); + $users = $this->getDatabase()->users(); $returnUsers = array(); foreach ($users as $user) { @@ -52,7 +52,7 @@ class UsersService extends BaseService public function GetUserSetting($userId, $settingKey) { - $settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); + $settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); if ($settingRow !== null) { return $settingRow->value; @@ -67,7 +67,7 @@ class UsersService extends BaseService { $settings = array(); - $settingRows = $this->Database->user_settings()->where('user_id = :1', $userId)->fetchAll(); + $settingRows = $this->getDatabase()->user_settings()->where('user_id = :1', $userId)->fetchAll(); foreach ($settingRows as $settingRow) { $settings[$settingRow->key] = $settingRow->value; @@ -80,7 +80,7 @@ class UsersService extends BaseService public function SetUserSetting($userId, $settingKey, $settingValue) { - $settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); + $settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); if ($settingRow !== null) { $settingRow->update(array( @@ -90,7 +90,7 @@ class UsersService extends BaseService } else { - $settingRow = $this->Database->user_settings()->createRow(array( + $settingRow = $this->getDatabase()->user_settings()->createRow(array( 'user_id' => $userId, 'key' => $settingKey, 'value' => $settingValue @@ -101,7 +101,7 @@ class UsersService extends BaseService private function UserExists($userId) { - $userRow = $this->Database->users()->where('id = :1', $userId)->fetch(); + $userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch(); return $userRow !== null; } } diff --git a/views/consume.blade.php b/views/consume.blade.php index 3f96f209..a7fd0da5 100644 --- a/views/consume.blade.php +++ b/views/consume.blade.php @@ -86,7 +86,7 @@ @endif - + @if(GROCY_FEATURE_FLAG_STOCK_PRODUCT_OPENED_TRACKING) @endif